-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvf_cae.c
More file actions
1902 lines (1627 loc) · 74.5 KB
/
Copy pathvf_cae.c
File metadata and controls
1902 lines (1627 loc) · 74.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CAE (Complexity-Aware Encoding) Filter for FFmpeg
*
* Enhanced to include additional metrics (Entropy and Color Variance), advanced normalization,
* performance optimizations using ARM NEON, enhanced logging, dynamic parameter tuning,
* and scene change handling.
*
* Author: Zaki Ahmed
* Date: 2024-10-31
*/
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <float.h>
#include <stddef.h> // For offsetof
#include "libavutil/internal.h"
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include "avfilter.h"
#include "filters.h"
#include "video.h"
#include <libavutil/log.h>
#include <libavutil/frame.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libswscale/swscale.h>
#include <libavutil/mem.h>
#include <pthread.h> // For POSIX threads and mutex
#include <omp.h> // For OpenMP
#include <time.h>
#include <fftw3.h> // For DCT computations
#ifdef __ARM_NEON
#include <arm_neon.h>
#endif
#define START_TIMER(name) \
struct timespec start_##name, end_##name; \
clock_gettime(CLOCK_MONOTONIC, &start_##name);
#define END_TIMER(name, description) \
clock_gettime(CLOCK_MONOTONIC, &end_##name); \
double elapsed_##name = (end_##name.tv_sec - start_##name.tv_sec) * 1e3 + \
(end_##name.tv_nsec - start_##name.tv_nsec) / 1e6; \
av_log(ctx, AV_LOG_DEBUG, "%s: %.3f ms\n", description, elapsed_##name);
#define BLOCK_SIZE 16 // BLOCK SIZE
typedef struct CaeContext {
const AVClass *class;
int frame_counter; // Counts the number of frames processed
int frame_interval; // Interval at which frames are processed
// User-configurable options
double alpha_complexity; // Threshold multiplier for complexity
double alpha_ssim; // Threshold multiplier for SSIM
double alpha_hist; // Threshold multiplier for Histogram Difference
double alpha_dct; // Threshold multiplier for DCT Energy
double alpha_sobel; // Threshold multiplier for Sobel Energy
int window_size; // Sliding window size
int threshold_mode; // Mode for thresholding (e.g., 0: Median + alpha*MAD)
int cooldown_frames; // Number of frames to ignore after a scene change
int required_consecutive_changes; // Number of consecutive detections to confirm scene change
double k_threshold; // Multiplier for MAD in adaptive threshold calculation
double max_weight; // Maximum allowable weight to prevent domination
// Internal variables
double *complexity_window; // Sliding window for complexity scores (delta_complexity)
double *ssim_window; // Sliding window for SSIM scores (delta_ssim)
double *hist_window; // Sliding window for histogram differences (delta_hist)
double *dct_window; // Sliding window for DCT Energy (delta_dct)
double *sobel_window; // Sliding window for Sobel Energy (delta_sobel)
double *entropy_window; // Sliding window for Entropy
double *color_var_window; // Sliding window for Color Variance
int window_index; // Current index in the window
bool window_filled; // Indicates if the window is fully populated
double previous_complexity; // Complexity of the previous frame
// Scene Change Detection Enhancements
int current_cooldown; // Current cooldown counter
int consecutive_detected; // Counter for consecutive detections
// Dynamic Weights for Metrics
double weight_complexity;
double weight_ssim;
double weight_hist;
double weight_dct;
double weight_sobel;
double weight_entropy;
double weight_color_var;
// For Dynamic Adaptive Threshold
double *weighted_sum_window; // Sliding window for weighted_sum
double median_weighted_sum; // Median of weighted_sum_window
double mad_weighted_sum; // MAD of weighted_sum_window
int weighted_sum_window_size; // Size of weighted_sum_window
int weighted_sum_window_index; // Current index in weighted_sum_window
bool weighted_sum_window_filled; // Indicates if weighted_sum_window is fully populated
// FFTW Plan
fftw_plan dct_plan; // FFTW plan for DCT computations
double *dct_input; // Input buffer for DCT
fftw_complex *dct_output; // Output buffer for DCT
// For color space conversion
struct SwsContext *sws_ctx;
enum AVPixelFormat src_pix_fmt;
enum AVPixelFormat dst_pix_fmt;
int width;
int height;
// Previous grayscale frame
AVFrame *prev_gray_frame; // AVFrame to store previous grayscale data
// Additional structures for Histogram
int hist_prev[256];
int hist_curr[256];
// **Adaptive Frame Interval Variables**
int min_frame_interval; // Minimum frame interval
int max_frame_interval; // Maximum frame interval
double activity_score; // Combined activity score based on metrics
// **New Variables for Normalization**
double min_complexity, max_complexity;
double min_ssim, max_ssim;
double min_hist, max_hist;
double min_dct, max_dct;
double min_sobel, max_sobel;
double min_entropy, max_entropy;
double min_color_var, max_color_var;
double crf_exponent; // Exponent for CRF scaling
double sigmoid_slope;
double sigmoid_midpoint;
AVFilterContext *ctx; // Reference to the filter context for logging
} CaeContext;
// Function prototypes
static int init_cae_context(AVFilterContext *ctx);
static void uninit_cae_context(AVFilterContext *ctx);
static av_cold int init_filter(AVFilterContext *ctx);
static av_cold void uninit_filter(AVFilterContext *ctx);
static int filter_frame(AVFilterLink *inlink, AVFrame *frame);
static double compute_SAD(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride);
static double compute_SAD_NEON(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride);
static double compute_SSIM(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride);
static double compute_SSIM_NEON(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride);
static double compute_hist_diff(int *hist1, int *hist2);
static void compute_histogram(const uint8_t *data, int width, int height, int stride, int *hist);
static void compute_histogram_NEON(const uint8_t *data, int width, int height, int stride, int *hist);
static double compute_DCT_energy(CaeContext *s, const uint8_t *data, int width, int height, int stride);
static double compute_Sobel_energy(const uint8_t *data, int width, int height, int stride);
static double compute_Sobel_energy_NEON(const uint8_t *src, int width, int height, int stride);
static double compute_entropy(const uint8_t *data, int width, int height, int stride);
static double compute_entropy_NEON(const uint8_t *data, int width, int height, int stride);
static double compute_color_variance(const uint8_t *data, int width, int height, int stride);
static double compute_color_variance_NEON(const uint8_t *data, int width, int height, int stride);
static bool calculate_mad(const double *data, int size, double median, double *mad);
static bool calculate_median(const double *data, int size, double *median);
static int compare_doubles(const void *a, const void *b);
static int cae_config_props(AVFilterLink *inlink);
static void adjust_weights(CaeContext *s, double delta_complexity, double delta_ssim, double delta_hist, double delta_dct, double delta_sobel, double delta_entropy, double delta_color_var);
static bool calculate_adaptive_threshold(CaeContext *s);
static bool is_finite_double(double value);
static int calculate_dynamic_crf(CaeContext *s, double activity_score);
static int attach_crf_metadata(AVFrame *frame, int crf);
/**
* @brief Validate if a double value is finite (not NaN or Inf).
*
* @param value The value to validate.
* @return true if finite, false otherwise.
*/
static bool is_finite_double(double value) {
return !isnan(value) && !isinf(value);
}
/**
* @brief Comparator for qsort (ascending order)
*/
static int compare_doubles(const void *a, const void *b) {
double da = *(const double*)a;
double db = *(const double*)b;
// Handle NaN cases
if (isnan(da) && isnan(db)) return 0;
if (isnan(da)) return 1; // NaNs are considered greater
if (isnan(db)) return -1;
// Handle Infinities
if (da == db) return 0;
if (da == INFINITY) return 1;
if (db == INFINITY) return -1;
if (da == -INFINITY) return -1;
if (db == -INFINITY) return 1;
// Regular comparison
return (da < db) ? -1 : (da > db) ? 1 : 0;
}
/**
* @brief Function to calculate median with explicit error handling
*/
static bool calculate_median(const double *data, int size, double *median) {
if (size <= 0 || median == NULL)
return false;
double *sorted = malloc(size * sizeof(double));
if (!sorted)
return false; // Memory allocation failed
memcpy(sorted, data, size * sizeof(double));
qsort(sorted, size, sizeof(double), compare_doubles);
if (size % 2 == 0)
*median = (sorted[size / 2 - 1] + sorted[size / 2]) / 2.0;
else
*median = sorted[size / 2];
free(sorted);
return true;
}
/**
* @brief Function to calculate Median Absolute Deviation (MAD) with error handling
*/
static bool calculate_mad(const double *data, int size, double median, double *mad) {
if (size <= 0 || mad == NULL)
return false;
double *deviations = malloc(size * sizeof(double));
if (!deviations)
return false; // Memory allocation failed
for (int i = 0; i < size; i++) {
deviations[i] = fabs(data[i] - median);
}
bool success = calculate_median(deviations, size, mad);
free(deviations);
return success;
}
/**
* @brief Function to compute histogram
*/
static void compute_histogram(const uint8_t *data, int width, int height, int stride, int *hist) {
memset(hist, 0, 256 * sizeof(int));
#pragma omp parallel for
for (int y = 0; y < height; y++) {
const uint8_t *row = data + y * stride;
for (int x = 0; x < width; x++) {
#pragma omp atomic
hist[row[x]]++;
}
}
}
/**
* @brief Function to compute histogram using NEON and private histograms
*/
static void compute_histogram_NEON(const uint8_t *data, int width, int height, int stride, int *hist) {
#ifdef __ARM_NEON
memset(hist, 0, 256 * sizeof(int));
int num_threads = omp_get_max_threads();
int **private_hists = malloc(num_threads * sizeof(int*));
if (!private_hists) {
av_log(NULL, AV_LOG_ERROR, "Failed to allocate memory for private histograms.\n");
compute_histogram(data, width, height, stride, hist); // Fallback to standard histogram
return;
}
for (int i = 0; i < num_threads; i++) {
private_hists[i] = calloc(256, sizeof(int));
if (!private_hists[i]) {
av_log(NULL, AV_LOG_ERROR, "Failed to allocate memory for private histogram %d.\n", i);
// Free previously allocated histograms
for (int j = 0; j < i; j++) {
free(private_hists[j]);
}
free(private_hists);
compute_histogram(data, width, height, stride, hist); // Fallback
return;
}
}
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
int *local_hist = private_hists[thread_id];
#pragma omp for nowait
for (int y = 0; y < height; y++) {
const uint8_t *row = data + y * stride;
for (int x = 0; x < width; x++) {
local_hist[row[x]]++;
}
}
}
// Aggregate private histograms into the shared histogram
for (int i = 0; i < num_threads; i++) {
for (int j = 0; j < 256; j++) {
hist[j] += private_hists[i][j];
}
free(private_hists[i]);
}
free(private_hists);
#else
compute_histogram(data, width, height, stride, hist);
#endif
}
/**
* @brief Function to compute Histogram Difference (Chi-Square)
*/
static double compute_hist_diff(int *hist1, int *hist2) {
double chi_sq = 0.0;
for (int i = 0; i < 256; i++) {
double numerator = (double)(hist1[i] - hist2[i]) * (double)(hist1[i] - hist2[i]);
double denominator = (double)(hist1[i] + hist2[i] + 1e-6); // Avoid division by zero
chi_sq += numerator / denominator;
}
return chi_sq;
}
/**
* @brief Function to compute SSIM
*/
static double compute_SSIM(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride) {
// Constants for SSIM
const double C1 = 6.5025, C2 = 58.5225;
double mean_prev = 0.0, mean_curr = 0.0;
double variance_prev = 0.0, variance_curr = 0.0, covariance = 0.0;
// First pass: Compute means
#pragma omp parallel for reduction(+:mean_prev, mean_curr)
for (int y = 0; y < height; y++) {
const uint8_t *prev_row = prev + y * stride;
const uint8_t *curr_row = curr + y * stride;
for (int x = 0; x < width; x++) {
mean_prev += prev_row[x];
mean_curr += curr_row[x];
}
}
mean_prev /= (width * height);
mean_curr /= (width * height);
// Second pass: Compute variances and covariance
#pragma omp parallel for reduction(+:variance_prev, variance_curr, covariance)
for (int y = 0; y < height; y++) {
const uint8_t *prev_row = prev + y * stride;
const uint8_t *curr_row = curr + y * stride;
for (int x = 0; x < width; x++) {
double diff_prev = prev_row[x] - mean_prev;
double diff_curr = curr_row[x] - mean_curr;
variance_prev += diff_prev * diff_prev;
variance_curr += diff_curr * diff_curr;
covariance += diff_prev * diff_curr;
}
}
variance_prev /= (width * height - 1);
variance_curr /= (width * height - 1);
covariance /= (width * height - 1);
// Compute SSIM
double numerator = (2 * mean_prev * mean_curr + C1) * (2 * covariance + C2);
double denominator = (mean_prev * mean_prev + mean_curr * mean_curr + C1) * (variance_prev + variance_curr + C2);
return numerator / denominator;
}
/**
* @brief Optimized and Multi-Threaded SSIM Computation Using NEON Intrinsics
*
* @param prev_data Pointer to the previous grayscale frame data
* @param curr_data Pointer to the current grayscale frame data
* @param width Width of the frame
* @param height Height of the frame
* @param stride Stride of the frame data
* @return double SSIM value
*/
static double compute_SSIM_NEON(const uint8_t *prev_data, const uint8_t *curr_data, int width, int height, int stride) {
#ifdef __ARM_NEON
double ssim_total = 0.0;
// Define window size (e.g., 8x8)
const int window_size = 8;
const int num_windows_x = width / window_size;
const int num_windows_y = height / window_size;
#pragma omp parallel for reduction(+:ssim_total) schedule(dynamic)
for (int y = 0; y < num_windows_y; y++) {
for (int x = 0; x < num_windows_x; x++) {
const uint8_t *prev_window = prev_data + y * window_size * stride + x * window_size;
const uint8_t *curr_window = curr_data + y * window_size * stride + x * window_size;
uint8x8_t prev_vec = vld1_u8(prev_window);
uint8x8_t curr_vec = vld1_u8(curr_window);
uint16x8_t prev_extended = vmovl_u8(prev_vec);
uint16x8_t curr_extended = vmovl_u8(curr_vec);
// Sum using vaddvq_u16 for the full vector
double mean_prev = (double)vaddvq_u16(prev_extended) / (window_size * window_size);
double mean_curr = (double)vaddvq_u16(curr_extended) / (window_size * window_size);
double variance_prev = 0.0, variance_curr = 0.0, covariance = 0.0;
for (int i = 0; i < window_size * window_size; i += 8) {
uint8x8_t p = vld1_u8(prev_window + i);
uint8x8_t c = vld1_u8(curr_window + i);
uint16x8_t p16 = vmovl_u8(p);
uint16x8_t c16 = vmovl_u8(c);
float32x4_t p_f_low = vcvtq_f32_u32(vmovl_u16(vget_low_u16(p16)));
float32x4_t p_f_high = vcvtq_f32_u32(vmovl_u16(vget_high_u16(p16)));
float32x4_t c_f_low = vcvtq_f32_u32(vmovl_u16(vget_low_u16(c16)));
float32x4_t c_f_high = vcvtq_f32_u32(vmovl_u16(vget_high_u16(c16)));
float32x4_t diff_p_low = vsubq_f32(p_f_low, vdupq_n_f32((float)mean_prev));
float32x4_t diff_p_high = vsubq_f32(p_f_high, vdupq_n_f32((float)mean_prev));
float32x4_t diff_c_low = vsubq_f32(c_f_low, vdupq_n_f32((float)mean_curr));
float32x4_t diff_c_high = vsubq_f32(c_f_high, vdupq_n_f32((float)mean_curr));
float32x4_t var_p_low = vmulq_f32(diff_p_low, diff_p_low);
float32x4_t var_p_high = vmulq_f32(diff_p_high, diff_p_high);
float32x4_t var_c_low = vmulq_f32(diff_c_low, diff_c_low);
float32x4_t var_c_high = vmulq_f32(diff_c_high, diff_c_high);
float32x4_t cov_low = vmulq_f32(diff_p_low, diff_c_low);
float32x4_t cov_high = vmulq_f32(diff_p_high, diff_c_high);
variance_prev += (double)(vaddvq_f32(var_p_low) + vaddvq_f32(var_p_high));
variance_curr += (double)(vaddvq_f32(var_c_low) + vaddvq_f32(var_c_high));
covariance += (double)(vaddvq_f32(cov_low) + vaddvq_f32(cov_high));
}
variance_prev /= (window_size * window_size - 1);
variance_curr /= (window_size * window_size - 1);
covariance /= (window_size * window_size - 1);
double C1 = 6.5025, C2 = 58.5225;
double ssim_window = ((2 * mean_prev * mean_curr + C1) * (2 * covariance + C2)) /
((mean_prev * mean_prev + mean_curr * mean_curr + C1) * (variance_prev + variance_curr + C2));
ssim_total += ssim_window;
}
}
return ssim_total / (num_windows_x * num_windows_y);
#else
return compute_SSIM(prev_data, curr_data, width, height, stride);
#endif
}
/**
* @brief Function to compute SAD
*/
static double compute_SAD(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride) {
double sad = 0.0;
#pragma omp parallel for reduction(+:sad)
for (int y = 0; y < height; y++) {
const uint8_t *p = prev + y * stride;
const uint8_t *c = curr + y * stride;
for (int x = 0; x < width; x++) {
sad += fabs((double)p[x] - (double)c[x]);
}
}
return sad;
}
/**
* @brief Function to compute SAD using NEON intrinsics
*/
static double compute_SAD_NEON(const uint8_t *prev, const uint8_t *curr, int width, int height, int stride) {
#ifdef __ARM_NEON
uint64_t sad = 0;
// Iterate over blocks
for (int y = 0; y < height; y += BLOCK_SIZE) {
for (int x = 0; x < width; x += BLOCK_SIZE) {
// Process each row within the block
for (int by = 0; by < BLOCK_SIZE && (y + by) < height; by++) {
const uint8_t *prev_row = prev + (y + by) * stride + x;
const uint8_t *curr_row = curr + (y + by) * stride + x;
// Prefetch the rows for caching
__builtin_prefetch(prev_row, 0, 3);
__builtin_prefetch(curr_row, 0, 3);
int bx = 0;
for (; bx <= BLOCK_SIZE - 16 && (x + bx) < width; bx += 16) {
uint8x16_t prev_vals = vld1q_u8(prev_row + bx);
uint8x16_t curr_vals = vld1q_u8(curr_row + bx);
// Calculate absolute differences and accumulate SAD
uint8x16_t abs_diff = vabdq_u8(prev_vals, curr_vals);
sad += vaddvq_u16(vpaddlq_u8(abs_diff));
}
// Process any remaining pixels in the row
for (; bx < BLOCK_SIZE && (x + bx) < width; bx++) {
sad += abs((int32_t)prev_row[bx] - (int32_t)curr_row[bx]);
}
}
}
}
return (double)sad;
#else
return compute_SAD(prev, curr, width, height, stride);
#endif
}
/**
* @brief Function to compute DCT Energy
*/
static double compute_DCT_energy(CaeContext *s, const uint8_t *data, int width, int height, int stride) {
// Populate input with normalized pixel values
#pragma omp parallel for
for (int y = 0; y < height; y++) {
const uint8_t *row = data + y * stride;
for (int x = 0; x < width; x++) {
s->dct_input[y * width + x] = (double)row[x] / 255.0;
}
}
// Execute DCT
fftw_execute(s->dct_plan);
// Compute energy
double energy = 0.0;
int fft_size = height * (width / 2 + 1); // FFTW R2C output size
#pragma omp parallel for reduction(+:energy)
for (int i = 0; i < fft_size; i++) {
double real = s->dct_output[i][0];
double imag = s->dct_output[i][1];
energy += real * real + imag * imag;
}
return energy;
}
/**
* @brief Optimized Sobel Filter Using NEON Intrinsics and OpenMP
*
* This function computes the total Sobel energy (sum of gradient magnitudes)
* for a given grayscale image using ARM NEON vectorization and OpenMP parallelization.
* It processes 16 pixels per iteration to maximize SIMD throughput.
*
* @param src Pointer to the input grayscale image data (16-byte aligned)
* @param width Width of the image (must be >=3)
* @param height Height of the image (must be >=3)
* @param stride Stride (bytes per row) of the input image
* @return double Total Sobel energy for the frame
*/
static double compute_Sobel_energy_NEON(const uint8_t *restrict src, int width, int height, int stride) {
#ifdef __ARM_NEON
if (width < 3 || height < 3) return 0.0;
// Calculate SIMD processing width (16 pixels per iteration)
int simd_width = (width - 2) / 16 * 16;
double total_sobel_energy = 0.0;
// Define constants for Sobel
const int8x16_t neg2 = vdupq_n_s8(-2);
const int8x16_t pos2 = vdupq_n_s8(2);
const int8x16_t neg1 = vdupq_n_s8(-1);
const int8x16_t pos1 = vdupq_n_s8(1);
#pragma omp parallel for reduction(+:total_sobel_energy) schedule(static)
for (int y = 1; y < height - 1; y++) {
const uint8_t *prev_row = src + (y - 1) * stride;
const uint8_t *curr_row = src + y * stride;
const uint8_t *next_row = src + (y + 1) * stride;
double row_sobel_energy = 0.0;
for (int x = 1; x <= simd_width; x += 16) {
// Load 16 pixels from each relevant position
uint8x16_t prev_left_u8 = vld1q_u8(prev_row + x - 1);
uint8x16_t prev_right_u8 = vld1q_u8(prev_row + x + 1);
uint8x16_t curr_left_u8 = vld1q_u8(curr_row + x - 1);
uint8x16_t curr_right_u8 = vld1q_u8(curr_row + x + 1);
uint8x16_t next_left_u8 = vld1q_u8(next_row + x - 1);
uint8x16_t next_right_u8 = vld1q_u8(next_row + x + 1);
uint8x16_t prev_center_u8 = vld1q_u8(prev_row + x);
uint8x16_t next_center_u8 = vld1q_u8(next_row + x);
// Reinterpret as signed integers
int8x16_t p_prev_left = vreinterpretq_s8_u8(prev_left_u8);
int8x16_t p_prev_right = vreinterpretq_s8_u8(prev_right_u8);
int8x16_t p_curr_left = vreinterpretq_s8_u8(curr_left_u8);
int8x16_t p_curr_right = vreinterpretq_s8_u8(curr_right_u8);
int8x16_t p_next_left = vreinterpretq_s8_u8(next_left_u8);
int8x16_t p_next_right = vreinterpretq_s8_u8(next_right_u8);
int8x16_t p_prev_center = vreinterpretq_s8_u8(prev_center_u8);
int8x16_t p_next_center = vreinterpretq_s8_u8(next_center_u8);
// Initialize gx and gy vectors
int16x8_t gx_low = vmull_s8(vget_low_s8(p_prev_left), vget_low_s8(neg1));
gx_low = vmlal_s8(gx_low, vget_low_s8(p_curr_left), vget_low_s8(neg2));
gx_low = vmlal_s8(gx_low, vget_low_s8(p_next_left), vget_low_s8(neg1));
gx_low = vmlal_s8(gx_low, vget_low_s8(p_prev_right), vget_low_s8(pos1));
gx_low = vmlal_s8(gx_low, vget_low_s8(p_curr_right), vget_low_s8(pos2));
gx_low = vmlal_s8(gx_low, vget_low_s8(p_next_right), vget_low_s8(pos1));
int16x8_t gx_high = vmull_s8(vget_high_s8(p_prev_left), vget_high_s8(neg1));
gx_high = vmlal_s8(gx_high, vget_high_s8(p_curr_left), vget_high_s8(neg2));
gx_high = vmlal_s8(gx_high, vget_high_s8(p_next_left), vget_high_s8(neg1));
gx_high = vmlal_s8(gx_high, vget_high_s8(p_prev_right), vget_high_s8(pos1));
gx_high = vmlal_s8(gx_high, vget_high_s8(p_curr_right), vget_high_s8(pos2));
gx_high = vmlal_s8(gx_high, vget_high_s8(p_next_right), vget_high_s8(pos1));
// Calculate gy
int16x8_t gy_low = vmull_s8(vget_low_s8(p_prev_left), vget_low_s8(pos1));
gy_low = vmlal_s8(gy_low, vget_low_s8(p_prev_center), vdup_n_s8(2)); // p_prev_center * 2
gy_low = vmlal_s8(gy_low, vget_low_s8(p_prev_right), vget_low_s8(pos1));
gy_low = vmlal_s8(gy_low, vget_low_s8(p_next_left), vget_low_s8(neg1));
gy_low = vmlal_s8(gy_low, vget_low_s8(p_next_center), vdup_n_s8(-2)); // p_next_center * -2
gy_low = vmlal_s8(gy_low, vget_low_s8(p_next_right), vget_low_s8(neg1));
int16x8_t gy_high = vmull_s8(vget_high_s8(p_prev_left), vget_high_s8(pos1));
gy_high = vmlal_s8(gy_high, vget_high_s8(p_prev_center), vdup_n_s8(2)); // p_prev_center * 2
gy_high = vmlal_s8(gy_high, vget_high_s8(p_prev_right), vget_high_s8(pos1));
gy_high = vmlal_s8(gy_high, vget_high_s8(p_next_left), vget_high_s8(neg1));
gy_high = vmlal_s8(gy_high, vget_high_s8(p_next_center), vdup_n_s8(-2)); // p_next_center * -2
gy_high = vmlal_s8(gy_high, vget_high_s8(p_next_right), vget_high_s8(neg1));
// Sum of absolute values of gx and gy
uint16x8_t abs_gx_low = vqabsq_s16(gx_low);
uint16x8_t abs_gy_low = vqabsq_s16(gy_low);
uint16x8_t sum_gx_gy_low = vaddq_u16(abs_gx_low, abs_gy_low);
uint16x8_t abs_gx_high = vqabsq_s16(gx_high);
uint16x8_t abs_gy_high = vqabsq_s16(gy_high);
uint16x8_t sum_gx_gy_high = vaddq_u16(abs_gx_high, abs_gy_high);
// Accumulate the sum
// Convert to unsigned integers and then to integers for accumulation
// vaddvq_u16 sums all elements in the vector
uint32_t sum_low = vaddvq_u16(sum_gx_gy_low);
uint32_t sum_high = vaddvq_u16(sum_gx_gy_high);
row_sobel_energy += (double)(sum_low + sum_high);
}
// Handle any remaining pixels not processed by SIMD
for (int x = simd_width + 1; x < width - 1; x++) {
int gx = -1 * prev_row[x - 1] + 1 * prev_row[x + 1]
-2 * curr_row[x - 1] + 2 * curr_row[x + 1]
-1 * next_row[x - 1] + 1 * next_row[x + 1];
int gy = -1 * prev_row[x - 1] - 2 * prev_row[x] -1 * prev_row[x + 1]
+1 * next_row[x - 1] + 2 * next_row[x] +1 * next_row[x + 1];
// Use |gx| + |gy| as an approximation for magnitude to avoid sqrt
double magnitude = fabs((double)gx) + fabs((double)gy);
row_sobel_energy += magnitude;
}
// Accumulate row_sobel_energy to total_sobel_energy
total_sobel_energy += row_sobel_energy;
}
return total_sobel_energy / ((double)(width - 2) * (double)(height - 2));
#else
return compute_Sobel_energy(src, width, height, stride);
#endif
}
/**
* @brief Function to compute Sobel Energy
*/
static double compute_Sobel_energy(const uint8_t *data, int width, int height, int stride) {
double sobel_energy = 0.0;
// Define Sobel kernels
const int sobel_x[3][3] = {
{ -1, 0, 1 },
{ -2, 0, 2 },
{ -1, 0, 1 }
};
const int sobel_y[3][3] = {
{ -1, -2, -1 },
{ 0, 0, 0 },
{ 1, 2, 1 }
};
// Compute gradients
#pragma omp parallel for reduction(+:sobel_energy)
for (int y = 1; y < height - 1; y++) {
for (int x = 1; x < width - 1; x++) {
int gx = 0;
int gy = 0;
for (int ky = -1; ky <=1; ky++) {
for (int kx = -1; kx <=1; kx++) {
gx += sobel_x[ky + 1][kx + 1] * data[(y + ky) * stride + (x + kx)];
gy += sobel_y[ky + 1][kx + 1] * data[(y + ky) * stride + (x + kx)];
}
}
double magnitude = sqrt((double)(gx * gx + gy * gy));
sobel_energy += magnitude;
}
}
return sobel_energy;
}
/**
* @brief Function to compute Entropy
*/
static double compute_entropy(const uint8_t *data, int width, int height, int stride) {
int hist[256] = {0};
compute_histogram_NEON(data, width, height, stride, hist);
double entropy = 0.0;
double total = (double)(width * height);
for (int i = 0; i < 256; i++) {
if (hist[i] > 0) {
double p = hist[i] / total;
entropy -= p * log(p);
}
}
return entropy;
}
/**
* @brief Optimized Entropy Computation Using NEON Intrinsics and OpenMP
*
* This function computes the entropy of a grayscale image using NEON vectorization and OpenMP parallelization.
*
* @param data Pointer to the input grayscale image data
* @param width Width of the image
* @param height Height of the image
* @param stride Stride (bytes per row) of the input image
* @return double Entropy of the image
*/
static double compute_entropy_NEON(const uint8_t *data, int width, int height, int stride) {
#ifdef __ARM_NEON
// Initialize a histogram array
uint32_t histogram[256] = {0};
double entropy = 0.0;
// Parallelize the loop over blocks using OpenMP
#pragma omp parallel
{
// Each thread maintains its own local histogram to avoid race conditions
uint32_t local_histogram[256] = {0};
#pragma omp for nowait schedule(static)
for (int y = 0; y < height; y += BLOCK_SIZE) {
for (int x = 0; x < width; x += BLOCK_SIZE) {
// Iterate through each row in the block
for (int by = 0; by < BLOCK_SIZE && (y + by) < height; by++) {
const uint8_t *row = data + (y + by) * stride + x;
// Prefetch row data to improve cache performance
__builtin_prefetch(row, 0, 3);
int bx = 0;
// Process 8 pixels at a time
for (; bx <= BLOCK_SIZE - 8 && (x + bx + 7) < width; bx += 8) {
// Load 8 pixels
uint8x8_t pixels = vld1_u8(row + bx);
// Convert to uint16x8_t
uint16x8_t pixels_16 = vmovl_u8(pixels); // Zero-extend to 16 bits
// Split into lower and higher 4 pixels each
uint16x4_t pixels_low = vget_low_u16(pixels_16);
uint16x4_t pixels_high = vget_high_u16(pixels_16);
// Convert to uint32x4_t
uint32x4_t pixels_low32 = vmovl_u16(pixels_low);
uint32x4_t pixels_high32 = vmovl_u16(pixels_high);
// Convert to float32x4_t
float32x4_t p1 = vcvtq_f32_u32(pixels_low32);
float32x4_t p2 = vcvtq_f32_u32(pixels_high32);
// Accumulate histogram bins
for (int i = 0; i < 4; i++) {
uint8_t pixel = (uint8_t)p1[i];
local_histogram[pixel]++;
}
for (int i = 0; i < 4; i++) {
uint8_t pixel = (uint8_t)p2[i];
local_histogram[pixel]++;
}
}
// Handle any remaining pixels
for (; bx < BLOCK_SIZE && (x + bx) < width; bx++) {
uint8_t pixel = row[bx];
local_histogram[pixel]++;
}
}
}
}
// Combine local histograms into the global histogram
#pragma omp critical
{
for (int i = 0; i < 256; i++) {
histogram[i] += local_histogram[i];
}
}
} // End of parallel region
// Compute entropy from the global histogram
for (int i = 0; i < 256; i++) {
if (histogram[i] > 0) {
double p = (double)histogram[i] / (double)(width * height);
entropy -= p * log2(p);
}
}
return entropy;
#else
return compute_entropy(data, width, height, stride);
#endif
}
/**
* @brief Function to compute Color Variance
*
* Assumes grayscale for simplicity. For color images, handle each channel separately.
*/
static double compute_color_variance(const uint8_t *data, int width, int height, int stride) {
double mean = 0.0;
double variance = 0.0;
// First pass: compute mean
#pragma omp parallel for reduction(+:mean)
for (int y = 0; y < height; y++) {
const uint8_t *row = data + y * stride;
for (int x = 0; x < width; x++) {
mean += row[x];
}
}
mean /= (width * height);
// Second pass: compute variance
#pragma omp parallel for reduction(+:variance)
for (int y = 0; y < height; y++) {
const uint8_t *row = data + y * stride;
for (int x = 0; x < width; x++) {
double diff = row[x] - mean;
variance += diff * diff;
}
}
variance /= (width * height - 1);
return variance;
}
/**
* @brief Compute color variance in BLOCK_SIZE x BLOCK_SIZE blocks using NEON
*
* @param data Pointer to the input image data
* @param width Width of the image
* @param height Height of the image
* @param stride Stride of the image (number of bytes per row)
* @return double The total color variance for the entire image
*/
static double compute_color_variance_NEON(const uint8_t *data, int width, int height, int stride) {
#ifdef __ARM_NEON
double sum = 0.0;
double sum_sq = 0.0;
// Parallelize the loop over blocks using OpenMP
#pragma omp parallel for reduction(+:sum, sum_sq) schedule(static)
for (int y = 0; y < height; y += BLOCK_SIZE) {
for (int x = 0; x < width; x += BLOCK_SIZE) {
// Iterate through each row in the block
for (int by = 0; by < BLOCK_SIZE && (y + by) < height; by++) {
const uint8_t *row = data + (y + by) * stride + x;
// Prefetch row data to improve cache performance
__builtin_prefetch(row, 0, 3);
int bx = 0;
// Initialize NEON vectors for sum and sum of squares
float32x4_t v_sum = vdupq_n_f32(0.0f);
float32x4_t v_sum_sq = vdupq_n_f32(0.0f);
// Process 8 pixels at a time
for (; bx <= BLOCK_SIZE - 8 && (x + bx + 7) < width; bx += 8) {
// Load 8 pixels
uint8x8_t pixels = vld1_u8(row + bx);
// Convert to uint16x8_t
uint16x8_t pixels_16 = vmovl_u8(pixels); // Zero-extend to 16 bits
// Split into lower and higher 4 pixels each
uint16x4_t pixels_low = vget_low_u16(pixels_16);
uint16x4_t pixels_high = vget_high_u16(pixels_16);
// Convert to uint32x4_t
uint32x4_t pixels_low32 = vmovl_u16(pixels_low);
uint32x4_t pixels_high32 = vmovl_u16(pixels_high);
// Convert to float32x4_t
float32x4_t p1 = vcvtq_f32_u32(pixels_low32);
float32x4_t p2 = vcvtq_f32_u32(pixels_high32);
// Accumulate sum
v_sum = vaddq_f32(v_sum, vaddq_f32(p1, p2));
// Accumulate sum of squares
float32x4_t p1_sq = vmulq_f32(p1, p1);
float32x4_t p2_sq = vmulq_f32(p2, p2);
v_sum_sq = vaddq_f32(v_sum_sq, vaddq_f32(p1_sq, p2_sq));
}
// Horizontal add to accumulate NEON vectors
sum += vaddvq_f32(v_sum); // Sum all elements in v_sum
sum_sq += vaddvq_f32(v_sum_sq); // Sum all elements in v_sum_sq
// Handle any remaining pixels
for (; bx < BLOCK_SIZE && (x + bx) < width; bx++) {
float pixel = (float)row[bx];
sum += pixel;
sum_sq += pixel * pixel;
}
}
}
}
// Compute mean and variance
double total_pixels = (double)(width * height);
double mean = sum / total_pixels;
double variance = (sum_sq / total_pixels) - (mean * mean);
return variance;
#else
return compute_color_variance(data, width, height, stride);
#endif
}
/**
* @brief Function to adjust weights dynamically based on recent frame impacts
*/
static void adjust_weights(CaeContext *s, double delta_complexity, double delta_ssim, double delta_hist, double delta_dct, double delta_sobel, double delta_entropy, double delta_color_var) {
// Adjust weights based on whether each metric exceeds its threshold
if (delta_complexity > s->alpha_complexity)
s->weight_complexity += 0.1;
else
s->weight_complexity = fmax(s->weight_complexity - 0.05, 0.1);
if (delta_ssim > s->alpha_ssim)
s->weight_ssim += 0.1;
else
s->weight_ssim = fmax(s->weight_ssim - 0.05, 0.1);
if (delta_hist > s->alpha_hist)
s->weight_hist += 0.1;
else
s->weight_hist = fmax(s->weight_hist - 0.05, 0.1);
if (delta_dct > s->alpha_dct)
s->weight_dct += 0.1;
else
s->weight_dct = fmax(s->weight_dct - 0.05, 0.1);
if (delta_sobel > s->alpha_sobel)
s->weight_sobel += 0.1;
else
s->weight_sobel = fmax(s->weight_sobel - 0.05, 0.1);
if (delta_entropy > 0.5) // Example threshold for entropy
s->weight_entropy += 0.1;
else
s->weight_entropy = fmax(s->weight_entropy - 0.05, 0.1);
if (delta_color_var > 100.0) // Example threshold for color variance
s->weight_color_var += 0.1;
else
s->weight_color_var = fmax(s->weight_color_var - 0.05, 0.1);
// Normalize weights to sum to max_weight (e.g., 10.0 to prevent domination)
double total_weight = s->weight_complexity + s->weight_ssim + s->weight_hist + s->weight_dct + s->weight_sobel + s->weight_entropy + s->weight_color_var;
if (total_weight > s->max_weight) {
double scaling_factor = s->max_weight / total_weight;
s->weight_complexity *= scaling_factor;