-
Notifications
You must be signed in to change notification settings - Fork 45
/
display.cpp
1806 lines (1456 loc) · 72.4 KB
/
display.cpp
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
#include "display.h"
#include <libgen.h>
#include <algorithm>
#include <atomic>
#include <iomanip>
#include <iostream>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include "controls.h"
#include "ffmpeg.h"
#include "format_converter.h"
#include "png_saver.h"
#include "source_code_pro_regular_ttf.h"
#include "string_utils.h"
#include "version.h"
#include "video_compare_icon.h"
#include "vmaf_calculator.h"
extern "C" {
#include <libavfilter/avfilter.h>
#include <libavutil/imgutils.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
}
static const SDL_Color BACKGROUND_COLOR = {54, 69, 79, 0};
static const SDL_Color LOOP_OFF_LABEL_COLOR = {0, 0, 0, 0};
static const SDL_Color LOOP_FW_LABEL_COLOR = {80, 127, 255, 0};
static const SDL_Color LOOP_PP_LABEL_COLOR = {191, 95, 60, 0};
static const SDL_Color TEXT_COLOR = {255, 255, 255, 0};
static const SDL_Color HELP_TEXT_PRIMARY_COLOR = {255, 255, 255, 0};
static const SDL_Color HELP_TEXT_ALTERNATE_COLOR = {255, 255, 192, 0};
static const SDL_Color POSITION_COLOR = {255, 255, 192, 0};
static const SDL_Color TARGET_COLOR = {200, 200, 140, 0};
static const SDL_Color ZOOM_COLOR = {255, 165, 0, 0};
static const SDL_Color PLAYBACK_SPEED_COLOR = {0, 192, 160, 0};
static const SDL_Color BUFFER_COLOR = {160, 225, 192, 0};
static const int BACKGROUND_ALPHA = 100;
static const int MOUSE_WHEEL_SCROLL_STEPS_TO_DOUBLE = 12;
static const float ZOOM_STEP_SIZE = pow(2.0F, 1.0F / float(MOUSE_WHEEL_SCROLL_STEPS_TO_DOUBLE));
static const int PLAYBACK_SPEED_KEY_PRESSES_TO_DOUBLE = 6;
static const float PLAYBACK_SPEED_STEP_SIZE = pow(2.0F, 1.0F / float(PLAYBACK_SPEED_KEY_PRESSES_TO_DOUBLE));
static const int HELP_TEXT_LINE_SPACING = 1;
static const int HELP_TEXT_HORIZONTAL_MARGIN = 26;
auto frame_deleter = [](AVFrame* frame) {
av_freep(&frame->data[0]);
av_frame_free(&frame);
};
using AVFramePtr = std::unique_ptr<AVFrame, decltype(frame_deleter)>;
template <typename T>
inline T check_sdl(T value, const std::string& message) {
if (!value) {
throw std::runtime_error{"SDL " + message + " - " + SDL_GetError()};
}
return value;
}
inline int clamp_int_to_byte_range(int value) {
return value > 255 ? 255 : value < 0 ? 0 : value;
}
inline int clamp_int_to_10_bpc_range(int value) {
return value > 1023 ? 1023 : value < 0 ? 0 : value;
}
inline uint8_t clamp_int_to_byte(int value) {
return static_cast<uint8_t>(clamp_int_to_byte_range(value));
}
inline uint16_t clamp_int_to_10_bpc(int value) {
return static_cast<uint16_t>(clamp_int_to_10_bpc_range(value));
}
// Credits to Kemin Zhou for this approach which does not require Boost or C++17
// https://stackoverflow.com/questions/4430780/how-can-i-extract-the-file-name-and-extension-from-a-path-in-c
std::string get_file_name_and_extension(const std::string& file_path) {
char* buff = new char[file_path.size() + 1];
strcpy(buff, file_path.c_str());
const std::string result = std::string(basename(buff));
delete[] buff;
return result;
}
std::string get_file_stem(const std::string& file_path) {
std::string tmp = get_file_name_and_extension(file_path);
const std::string::size_type i = tmp.rfind('.');
if (i != std::string::npos) {
tmp = tmp.substr(0, i);
}
return tmp;
}
std::string strip_ffmpeg_patterns(const std::string& input) {
static const std::regex pattern_regex(R"(%\d*d|\*|\?)");
return std::regex_replace(input, pattern_regex, "");
};
inline float round_3(float value) {
return std::round(value * 1000.0F) / 1000.0F;
}
static std::string format_position_difference(const float position1, const float position2) {
// round both for the sake of consistency with the displayed positions
const float position1_rounded = round_3(position1);
const float position2_rounded = round_3(position2);
// absolute difference very close to 0.001 -> we are in sync!
if (std::abs(position1_rounded - position2_rounded) < 9.99e-4) {
return "";
} else if (position1 < position2) {
return " (-" + format_position(position2_rounded - position1_rounded, true) + ")";
}
return " (+" + format_position(position1_rounded - position2_rounded, true) + ")";
}
static std::string to_hex(const uint32_t value, const int width) {
std::stringstream sstream;
sstream << std::setfill('0') << std::setw(width) << std::hex << value;
return sstream.str();
}
static std::string format_libav_version(unsigned version) {
int major = (version >> 16) & 0xff;
int minor = (version >> 8) & 0xff;
int micro = version & 0xff;
return string_sprintf("%2u.%2u.%3u", major, minor, micro);
}
auto get_metadata_int_value = [](const AVFrame* frame, const std::string& key, const int default_value) -> int {
const AVDictionaryEntry* entry = av_dict_get(frame->metadata, key.c_str(), nullptr, 0);
return entry ? std::atoi(entry->value) : default_value;
};
SDL::SDL() {
check_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == 0, "SDL init");
check_sdl(TTF_Init() == 0, "TTF init");
}
SDL::~SDL() {
SDL_Quit();
}
Display::Display(const int display_number,
const Mode mode,
const bool verbose,
const bool fit_window_to_usable_bounds,
const bool high_dpi_allowed,
const bool use_10_bpc,
const bool fast_input_alignment,
const std::tuple<int, int> window_size,
const unsigned width,
const unsigned height,
const double duration,
const float wheel_sensitivity,
const std::string& left_file_name,
const std::string& right_file_name)
: display_number_{display_number},
mode_{mode},
fit_window_to_usable_bounds_{fit_window_to_usable_bounds},
high_dpi_allowed_{high_dpi_allowed},
use_10_bpc_{use_10_bpc},
fast_input_alignment_{fast_input_alignment},
video_width_{static_cast<int>(width)},
video_height_{static_cast<int>(height)},
duration_{duration},
wheel_sensitivity_{wheel_sensitivity},
left_file_stem_{strip_ffmpeg_patterns(get_file_stem(left_file_name))},
right_file_stem_{strip_ffmpeg_patterns(get_file_stem(right_file_name))} {
const int auto_width = mode == Mode::hstack ? width * 2 : width;
const int auto_height = mode == Mode::vstack ? height * 2 : height;
int window_x;
int window_y;
int window_width;
int window_height;
constexpr int min_width = 4;
constexpr int min_height = 1;
if (!fit_window_to_usable_bounds) {
if (std::get<0>(window_size) < 0 && std::get<1>(window_size) < 0) {
window_width = auto_width;
window_height = auto_height;
} else {
if (std::get<0>(window_size) < 0) {
window_height = std::get<1>(window_size);
window_width = static_cast<float>(auto_width) / static_cast<float>(auto_height) * window_height;
} else if (std::get<1>(window_size) < 0) {
window_width = std::get<0>(window_size);
window_height = static_cast<float>(auto_height) / static_cast<float>(auto_width) * window_width;
} else {
window_width = std::get<0>(window_size);
window_height = std::get<1>(window_size);
}
}
window_x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display_number);
window_y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display_number);
if (high_dpi_allowed_) {
window_width /= 2;
window_height /= 2;
}
} else {
SDL_Rect bounds;
check_sdl(SDL_GetDisplayUsableBounds(display_number, &bounds) == 0, "get display usable bounds");
// account for window frame and title bar
constexpr int border_width = 10;
#ifdef __linux__
constexpr int border_height = 40;
#else
constexpr int border_height = 34;
#endif
const int usable_width = std::max(bounds.w - border_width, min_width);
const int usable_height = std::max(bounds.h - border_height, min_height);
const float aspect_ratio = static_cast<float>(auto_width) / static_cast<float>(auto_height);
const float usable_aspect_ratio = static_cast<float>(usable_width) / static_cast<float>(usable_height);
if (usable_aspect_ratio > aspect_ratio) {
window_height = usable_height;
window_width = static_cast<int>(window_height * aspect_ratio);
} else {
window_width = usable_width;
window_height = static_cast<int>(window_width / aspect_ratio);
}
window_x = bounds.x + (usable_width - window_width + border_width) / 2;
window_y = bounds.y + (usable_height - window_height + border_height) / 2 + border_width;
#ifdef __linux__
window_y -= 2 * border_width + 4;
#endif
}
if (window_width < min_width) {
throw std::runtime_error{"Window width cannot be less than " + std::to_string(min_width)};
}
if (window_height < min_height) {
throw std::runtime_error{"Window height cannot be less than " + std::to_string(min_height)};
}
const int create_window_flags = SDL_WINDOW_SHOWN;
window_ = check_sdl(SDL_CreateWindow(string_sprintf("%s | %s", get_file_name_and_extension(left_file_name).c_str(), get_file_name_and_extension(right_file_name).c_str()).c_str(), window_x, window_y, window_width, window_height,
high_dpi_allowed_ ? create_window_flags | SDL_WINDOW_ALLOW_HIGHDPI : create_window_flags),
"window");
SDL_RWops* embedded_icon = check_sdl(SDL_RWFromConstMem(VIDEO_COMPARE_ICON_BMP, VIDEO_COMPARE_ICON_BMP_LEN), "get pointer to icon");
SDL_Surface* icon_surface = check_sdl(SDL_LoadBMP_RW(embedded_icon, 1), "load icon");
#ifdef _WIN32
SDL_Surface* resized_icon_surface = SDL_CreateRGBSurface(0, 64, 64, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
SDL_BlitScaled(icon_surface, nullptr, resized_icon_surface, nullptr);
SDL_SetWindowIcon(window_, resized_icon_surface);
SDL_FreeSurface(resized_icon_surface);
#else
SDL_SetWindowIcon(window_, icon_surface);
#endif
SDL_FreeSurface(icon_surface);
renderer_ = check_sdl(SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), "renderer");
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
SDL_RenderClear(renderer_);
SDL_RenderPresent(renderer_);
SDL_GL_GetDrawableSize(window_, &drawable_width_, &drawable_height_);
SDL_GetWindowSize(window_, &window_width_, &window_height_);
drawable_to_window_width_factor_ = static_cast<float>(drawable_width_) / static_cast<float>(window_width_);
drawable_to_window_height_factor_ = static_cast<float>(drawable_height_) / static_cast<float>(window_height_);
video_to_window_width_factor_ = static_cast<float>(video_width_) / static_cast<float>(window_width_) * ((mode_ == Mode::hstack) ? 2.F : 1.F);
video_to_window_height_factor_ = static_cast<float>(video_height_) / static_cast<float>(window_height_) * ((mode_ == Mode::vstack) ? 2.F : 1.F);
font_scale_ = (drawable_to_window_width_factor_ + drawable_to_window_height_factor_) / 2.0F;
border_extension_ = 3 * font_scale_;
double_border_extension_ = border_extension_ * 2;
line1_y_ = 20;
line2_y_ = line1_y_ + 30 * font_scale_;
if (mode_ != Mode::vstack) {
max_text_width_ = drawable_width_ / 2 - double_border_extension_ - line1_y_;
} else {
max_text_width_ = drawable_width_ - double_border_extension_ - line1_y_;
}
SDL_RWops* embedded_font = check_sdl(SDL_RWFromConstMem(SOURCE_CODE_PRO_REGULAR_TTF, SOURCE_CODE_PRO_REGULAR_TTF_LEN), "get pointer to font");
small_font_ = check_sdl(TTF_OpenFontRW(embedded_font, 0, 16 * font_scale_), "font open");
big_font_ = check_sdl(TTF_OpenFontRW(embedded_font, 0, 24 * font_scale_), "font open");
normal_mode_cursor_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
pan_mode_cursor_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
SDL_RenderSetLogicalSize(renderer_, drawable_width_, drawable_height_);
auto create_video_texture = [&](const std::string& scale_quality) {
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, scale_quality.c_str());
return check_sdl(SDL_CreateTexture(renderer_, use_10_bpc ? SDL_PIXELFORMAT_ARGB2101010 : SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STREAMING, mode == Mode::hstack ? width * 2 : width, mode == Mode::vstack ? height * 2 : height),
"video texture " + scale_quality);
};
video_texture_linear_ = create_video_texture("linear");
video_texture_nn_ = create_video_texture("nearest");
if (verbose) {
print_verbose_info();
}
auto render_text_with_fallback = [&](const std::string& text) {
SDL_Surface* surface = TTF_RenderUTF8_Blended(small_font_, text.c_str(), TEXT_COLOR);
if (!surface) {
std::cerr << "Falling back to lower-quality rendering for '" << text << "'" << std::endl;
surface = check_sdl(TTF_RenderUTF8_Solid(small_font_, text.c_str(), TEXT_COLOR), "text surface");
}
return surface;
};
SDL_Surface* text_surface = render_text_with_fallback(left_file_name);
left_text_texture_ = SDL_CreateTextureFromSurface(renderer_, text_surface);
left_text_width_ = text_surface->w;
left_text_height_ = text_surface->h;
SDL_FreeSurface(text_surface);
text_surface = render_text_with_fallback(right_file_name);
right_text_texture_ = SDL_CreateTextureFromSurface(renderer_, text_surface);
right_text_width_ = text_surface->w;
right_text_height_ = text_surface->h;
SDL_FreeSurface(text_surface);
diff_buffer_ = new uint8_t[video_width_ * video_height_ * 3 * (use_10_bpc ? sizeof(uint16_t) : sizeof(uint8_t))];
uint8_t* diff_plane_0 = diff_buffer_;
diff_planes_ = {diff_plane_0, nullptr, nullptr};
diff_pitches_ = {video_width_ * 3 * (use_10_bpc ? sizeof(uint16_t) : sizeof(uint8_t)), 0, 0};
// initialize help texts
bool primary_color = true;
auto add_help_texture = [&](TTF_Font* font, const std::string& text) {
int h;
SDL_Surface* surface = TTF_RenderUTF8_Blended_Wrapped(font, text.c_str(), primary_color ? HELP_TEXT_PRIMARY_COLOR : HELP_TEXT_ALTERNATE_COLOR, drawable_width_ - HELP_TEXT_HORIZONTAL_MARGIN * 2);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer_, surface);
SDL_FreeSurface(surface);
SDL_QueryTexture(texture, nullptr, nullptr, nullptr, &h);
help_total_height_ += h;
help_textures_.push_back(texture);
};
add_help_texture(small_font_, " ");
TTF_SetFontStyle(big_font_, TTF_STYLE_BOLD | TTF_STYLE_UNDERLINE);
add_help_texture(big_font_, "CONTROLS");
TTF_SetFontStyle(big_font_, TTF_STYLE_NORMAL);
add_help_texture(small_font_, " ");
for (auto& key_description_pair : get_controls()) {
primary_color = !primary_color;
add_help_texture(small_font_, string_sprintf(" %-12s %s", key_description_pair.first.c_str(), key_description_pair.second.c_str()));
}
add_help_texture(big_font_, " ");
for (auto& text : get_instructions()) {
primary_color = !primary_color;
add_help_texture(small_font_, text);
add_help_texture(small_font_, " ");
}
}
Display::~Display() {
SDL_DestroyTexture(video_texture_linear_);
SDL_DestroyTexture(video_texture_nn_);
SDL_DestroyTexture(left_text_texture_);
SDL_DestroyTexture(right_text_texture_);
if (message_texture_ != nullptr) {
SDL_DestroyTexture(message_texture_);
}
for (auto help_texture : help_textures_) {
SDL_DestroyTexture(help_texture);
}
TTF_CloseFont(small_font_);
TTF_CloseFont(big_font_);
SDL_FreeCursor(normal_mode_cursor_);
SDL_FreeCursor(pan_mode_cursor_);
delete[] diff_buffer_;
if (left_buffer_ != nullptr) {
delete[] left_buffer_;
}
if (right_buffer_ != nullptr) {
delete[] right_buffer_;
}
SDL_DestroyRenderer(renderer_);
SDL_DestroyWindow(window_);
}
void Display::print_verbose_info() {
std::cout << "Main program version: " << VersionInfo::version << std::endl;
std::cout << "Video size: " << video_width_ << "x" << video_height_ << std::endl;
std::cout << "Video duration: " << format_duration(duration_) << std::endl;
std::cout << "Display mode: " << modeToString(mode_) << std::endl;
std::cout << "Fit to usable bounds: " << std::boolalpha << fit_window_to_usable_bounds_ << std::endl;
std::cout << "High-DPI allowed: " << std::boolalpha << high_dpi_allowed_ << std::endl;
std::cout << "Use 10 bpc: " << std::boolalpha << use_10_bpc_ << std::endl;
std::cout << "Fast input alignment: " << std::boolalpha << fast_input_alignment_ << std::endl;
std::cout << "Mouse whl sensitivity: " << wheel_sensitivity_ << std::endl;
SDL_version sdl_linked_version;
SDL_GetVersion(&sdl_linked_version);
std::cout << "SDL version: " << string_sprintf("%u.%u.%u", sdl_linked_version.major, sdl_linked_version.minor, sdl_linked_version.patch) << std::endl;
const SDL_version* sdl_ttf_linked_version = TTF_Linked_Version();
std::cout << "SDL_ttf version: " << string_sprintf("%u.%u.%u", sdl_ttf_linked_version->major, sdl_ttf_linked_version->minor, sdl_ttf_linked_version->patch) << std::endl;
SDL_RendererInfo info;
SDL_GetRendererInfo(renderer_, &info);
std::cout << "SDL renderer: " << info.name << std::endl;
int current_display_number = SDL_GetWindowDisplayIndex(window_);
std::cout << "SDL display number: " << current_display_number << std::endl;
SDL_DisplayMode desktop_display_mode;
SDL_GetDesktopDisplayMode(current_display_number, &desktop_display_mode);
std::cout << "SDL desktop size: " << desktop_display_mode.w << "x" << desktop_display_mode.h << std::endl;
std::cout << "SDL GL drawable size: " << drawable_width_ << "x" << drawable_height_ << std::endl;
std::cout << "SDL window size: " << window_width_ << "x" << window_height_ << std::endl;
auto stringify_format_and_bpp = [&](Uint32 pixel_format) -> std::string { return string_sprintf("%s (%d bpp)", SDL_GetPixelFormatName(pixel_format), SDL_BITSPERPIXEL(pixel_format)); };
Uint32 window_pixel_format = SDL_GetWindowPixelFormat(window_);
std::cout << "SDL window px format: " << stringify_format_and_bpp(window_pixel_format) << std::endl;
Uint32 video_pixel_format;
SDL_QueryTexture(video_texture_linear_, &video_pixel_format, nullptr, nullptr, nullptr);
std::cout << "SDL video px format: " << stringify_format_and_bpp(video_pixel_format) << std::endl;
std::cout << "FFmpeg version: " << av_version_info() << std::endl;
std::cout << "libavutil version: " << format_libav_version(avutil_version()) << std::endl;
std::cout << "libavcodec version: " << format_libav_version(avcodec_version()) << std::endl;
std::cout << "libavformat version: " << format_libav_version(avformat_version()) << std::endl;
std::cout << "libavfilter version: " << format_libav_version(avfilter_version()) << std::endl;
std::cout << "libswscale version: " << format_libav_version(swscale_version()) << std::endl;
std::cout << "libswresample version: " << format_libav_version(swresample_version()) << std::endl;
std::cout << "libavcodec configuration: " << avcodec_configuration() << std::endl << std::endl;
}
void Display::convert_to_packed_10_bpc(std::array<uint8_t*, 3> in_planes, std::array<size_t, 3> in_pitches, std::array<uint32_t*, 3> out_planes, std::array<size_t, 3> out_pitches, const SDL_Rect& roi) {
uint16_t* p_in = reinterpret_cast<uint16_t*>(in_planes[0] + roi.x * 6 + in_pitches[0] * roi.y);
uint32_t* p_out = out_planes[0] + roi.x + out_pitches[0] * roi.y / 4;
for (int y = 0; y < roi.h; y++) {
for (int in_x = 0, out_x = 0; out_x < roi.w; in_x += 3, out_x++) {
const uint32_t r = p_in[in_x] >> 6;
const uint32_t g = p_in[in_x + 1] >> 6;
const uint32_t b = p_in[in_x + 2] >> 6;
p_out[out_x] = (r << 20) | (g << 10) | (b);
}
p_in += in_pitches[0] / 2;
p_out += out_pitches[0] / 4;
}
}
void Display::update_difference(std::array<uint8_t*, 3> planes_left, std::array<size_t, 3> pitches_left, std::array<uint8_t*, 3> planes_right, std::array<size_t, 3> pitches_right, int split_x) {
const int amplification = 2;
if (use_10_bpc_) {
uint16_t* p_left = reinterpret_cast<uint16_t*>(planes_left[0] + split_x * 6);
uint16_t* p_right = reinterpret_cast<uint16_t*>(planes_right[0] + split_x * 6);
uint16_t* p_diff = reinterpret_cast<uint16_t*>(diff_planes_[0] + split_x * 6);
for (int y = 0; y < video_height_; y++) {
for (int in_x = 0, out_x = 0; out_x < (video_width_ - split_x) * 3; in_x += 3, out_x += 3) {
const int rl = p_left[in_x] >> 6;
const int gl = p_left[in_x + 1] >> 6;
const int bl = p_left[in_x + 2] >> 6;
const int rr = p_right[in_x] >> 6;
const int gr = p_right[in_x + 1] >> 6;
const int br = p_right[in_x + 2] >> 6;
const int r_diff = abs(rl - rr) * amplification;
const int g_diff = abs(gl - gr) * amplification;
const int b_diff = abs(bl - br) * amplification;
p_diff[out_x] = clamp_int_to_10_bpc(r_diff) << 6;
p_diff[out_x + 1] = clamp_int_to_10_bpc(g_diff) << 6;
p_diff[out_x + 2] = clamp_int_to_10_bpc(b_diff) << 6;
}
p_left += pitches_left[0] / sizeof(uint16_t);
p_right += pitches_right[0] / sizeof(uint16_t);
p_diff += diff_pitches_[0] / sizeof(uint16_t);
}
} else {
uint8_t* p_left = planes_left[0] + split_x * 3;
uint8_t* p_right = planes_right[0] + split_x * 3;
uint8_t* p_diff = diff_planes_[0] + split_x * 3;
for (int y = 0; y < video_height_; y++) {
for (int in_x = 0, out_x = 0; out_x < (video_width_ - split_x) * 3; in_x += 3, out_x += 3) {
const int rl = p_left[in_x];
const int gl = p_left[in_x + 1];
const int bl = p_left[in_x + 2];
const int rr = p_right[in_x];
const int gr = p_right[in_x + 1];
const int br = p_right[in_x + 2];
const int r_diff = abs(rl - rr) * amplification;
const int g_diff = abs(gl - gr) * amplification;
const int b_diff = abs(bl - br) * amplification;
p_diff[out_x] = clamp_int_to_byte(r_diff);
p_diff[out_x + 1] = clamp_int_to_byte(g_diff);
p_diff[out_x + 2] = clamp_int_to_byte(b_diff);
}
p_left += pitches_left[0];
p_right += pitches_right[0];
p_diff += diff_pitches_[0];
}
}
}
void Display::save_image_frames(const AVFrame* left_frame, const AVFrame* right_frame) {
std::atomic_bool error_occurred(false);
const auto create_onscreen_display_avframe = [&]() -> AVFramePtr {
const size_t pitch = use_10_bpc_ ? drawable_width_ * 3 * sizeof(uint16_t) : drawable_width_ * 3;
uint8_t* pixels = new uint8_t[pitch * drawable_height_];
if (use_10_bpc_) {
const size_t temp_pitch = drawable_width_ * sizeof(uint32_t);
std::vector<uint8_t> temp_pixels(temp_pitch * drawable_height_);
SDL_RenderReadPixels(renderer_, nullptr, SDL_PIXELFORMAT_ARGB2101010, temp_pixels.data(), temp_pitch);
const uint32_t* src = reinterpret_cast<const uint32_t*>(temp_pixels.data());
uint16_t* dest = reinterpret_cast<uint16_t*>(pixels);
for (int i = 0; i < drawable_width_ * drawable_height_; i++) {
const uint32_t argb = *(src++);
const uint32_t r10 = (argb >> 20) & 0x3FF;
const uint32_t g10 = (argb >> 10) & 0x3FF;
const uint32_t b10 = argb & 0x3FF;
*(dest++) = static_cast<uint16_t>(r10 << 6);
*(dest++) = static_cast<uint16_t>(g10 << 6);
*(dest++) = static_cast<uint16_t>(b10 << 6);
}
} else {
SDL_RenderReadPixels(renderer_, nullptr, SDL_PIXELFORMAT_RGB24, pixels, pitch);
}
AVFrame* renderer_frame = av_frame_alloc();
renderer_frame->format = use_10_bpc_ ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24;
renderer_frame->width = drawable_width_;
renderer_frame->height = drawable_height_;
renderer_frame->data[0] = pixels;
renderer_frame->linesize[0] = pitch;
return AVFramePtr(renderer_frame, frame_deleter);
};
const auto osd_frame = create_onscreen_display_avframe();
const auto write_png = [this, &error_occurred](const AVFrame* frame, const std::string& filename) {
try {
PngSaver::save(frame, filename);
} catch (const PngSaver::IOException& e) {
std::cerr << "Error saving video PNG image to file: " << filename << std::endl;
error_occurred = true;
} catch (const std::runtime_error& e) {
std::cerr << "Unexpected while error saving PNG: " << e.what() << std::endl;
error_occurred = true;
}
};
const std::string left_filename = string_sprintf("%s%s_%04d.png", left_file_stem_.c_str(), (left_file_stem_ == right_file_stem_) ? "_left" : "", saved_image_number_);
const std::string right_filename = string_sprintf("%s%s_%04d.png", right_file_stem_.c_str(), (left_file_stem_ == right_file_stem_) ? "_right" : "", saved_image_number_);
const std::string osd_filename = string_sprintf("%s_%s_osd_%04d.png", left_file_stem_.c_str(), right_file_stem_.c_str(), saved_image_number_);
std::thread save_left_frame_thread(write_png, left_frame, left_filename);
std::thread save_right_frame_thread(write_png, right_frame, right_filename);
std::thread save_osd_frame_thread(write_png, osd_frame.get(), osd_filename);
save_left_frame_thread.join();
save_right_frame_thread.join();
save_osd_frame_thread.join();
if (!error_occurred) {
std::cout << "Saved " << string_sprintf("%s, %s and %s", left_filename.c_str(), right_filename.c_str(), osd_filename.c_str()) << std::endl;
saved_image_number_++;
}
}
void Display::render_text(const int x, const int y, SDL_Texture* texture, const int texture_width, const int texture_height, const int border_extension, const bool left_adjust) {
// compute clip amount which ensures the filename does not extend more than half the display width
const int clip_amount = std::max((texture_width + double_border_extension_) - max_text_width_, 0);
const int gradient_amount = std::min(clip_amount, 24);
SDL_Rect fill_rect = {x - border_extension + gradient_amount, y - border_extension, texture_width + double_border_extension_ - clip_amount - gradient_amount, texture_height + double_border_extension_};
SDL_Rect src_rect = {clip_amount + gradient_amount, 0, texture_width - clip_amount - gradient_amount, texture_height};
SDL_Rect text_rect = {x + gradient_amount, y, texture_width - clip_amount - gradient_amount, texture_height};
if (!left_adjust && (mode_ != Mode::vstack)) {
fill_rect.x += clip_amount;
text_rect.x += clip_amount;
}
SDL_RenderFillRect(renderer_, &fill_rect);
SDL_RenderCopy(renderer_, texture, &src_rect, &text_rect);
// render gradient
if (gradient_amount > 0) {
Uint8 draw_color_r;
Uint8 draw_color_g;
Uint8 draw_color_b;
Uint8 draw_color_a;
Uint8 alpha_mod;
SDL_GetRenderDrawColor(renderer_, &draw_color_r, &draw_color_g, &draw_color_b, &draw_color_a);
SDL_GetTextureAlphaMod(texture, &alpha_mod);
fill_rect.x--;
fill_rect.w = 1;
src_rect.x--;
src_rect.w = 1;
text_rect.x--;
text_rect.w = 1;
for (int i = (gradient_amount - 1); i >= 0; i--, fill_rect.x--, src_rect.x--, text_rect.x--) {
SDL_SetRenderDrawColor(renderer_, draw_color_r, draw_color_g, draw_color_b, draw_color_a * i / gradient_amount);
SDL_RenderFillRect(renderer_, &fill_rect);
SDL_SetTextureAlphaMod(texture, alpha_mod * i / gradient_amount);
SDL_RenderCopy(renderer_, texture, &src_rect, &text_rect);
}
// reset
SDL_SetRenderDrawColor(renderer_, draw_color_r, draw_color_g, draw_color_b, draw_color_a);
SDL_SetTextureAlphaMod(texture, alpha_mod);
}
}
void Display::render_progress_dots(const float position, const float progress, const bool is_top) {
if (duration_ > 0) {
const float dot_size = 2.f;
const int dot_width = std::round(drawable_to_window_width_factor_ * dot_size);
const int dot_height = std::round(drawable_to_window_height_factor_ * dot_size);
const int y_offset = is_top ? 1 : drawable_height_ - 1 - dot_height;
const int x_position = std::round(position * drawable_width_ / duration_);
const int x_progress = std::round(progress * drawable_width_ / duration_);
for (int x = 0; x < x_position; x++) {
if (x % (2 * dot_width) < dot_width) {
SDL_SetRenderDrawColor(renderer_, POSITION_COLOR.r, POSITION_COLOR.g, POSITION_COLOR.b, BACKGROUND_ALPHA * 3 / 2);
} else {
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, BACKGROUND_ALPHA);
}
SDL_RenderDrawLine(renderer_, x, y_offset, x, y_offset + dot_height - 1);
}
// draw current frame
SDL_SetRenderDrawColor(renderer_, POSITION_COLOR.r, POSITION_COLOR.g, POSITION_COLOR.b, BACKGROUND_ALPHA * 2);
const SDL_Rect current_frame = {x_position, is_top ? y_offset : y_offset - dot_height, x_progress - x_position, dot_height * 2};
SDL_RenderDrawRect(renderer_, ¤t_frame);
}
}
SDL_Texture* Display::get_video_texture() const {
return use_bilinear_texture_filtering_ ? video_texture_linear_ : video_texture_nn_;
}
void Display::update_texture(const SDL_Rect* rect, const void* pixels, int pitch, const std::string& message) {
check_sdl(SDL_UpdateTexture(get_video_texture(), rect, pixels, pitch) == 0, "video texture - " + message);
}
int Display::round_and_clamp(const float value) {
const int result = static_cast<int>(std::roundf(value));
return use_10_bpc_ ? clamp_int_to_10_bpc_range(result) : clamp_int_to_byte_range(result);
}
const std::array<int, 3> Display::get_rgb_pixel(uint8_t* rgb_plane, const size_t pitch, const int x, const int y) {
int r, g, b;
if (use_10_bpc_) {
uint16_t* rgb_pixel = reinterpret_cast<uint16_t*>(rgb_plane + x * 6 + y * pitch);
r = *(rgb_pixel) >> 6;
g = *(rgb_pixel + 1) >> 6;
b = *(rgb_pixel + 2) >> 6;
} else {
uint8_t* rgb_pixel = rgb_plane + x * 3 + y * pitch;
r = *(rgb_pixel);
g = *(rgb_pixel + 1);
b = *(rgb_pixel + 2);
}
return {r, g, b};
}
const std::array<int, 3> Display::convert_rgb_to_yuv(const std::array<int, 3> rgb, const AVPixelFormat rgb_format, const AVColorSpace color_space, const AVColorRange color_range) {
auto allocate_frame = [&](const AVPixelFormat format) -> AVFramePtr {
AVFrame* raw_frame = av_frame_alloc();
if (raw_frame == nullptr) {
throw ffmpeg::Error("Couldn't allocate frame");
}
raw_frame->format = format;
raw_frame->width = 1;
raw_frame->height = 1;
raw_frame->colorspace = color_space;
raw_frame->color_range = color_range;
ffmpeg::check(av_image_alloc(raw_frame->data, raw_frame->linesize, raw_frame->width, raw_frame->height, format, 64));
return AVFramePtr(raw_frame, frame_deleter);
};
const AVPixelFormat yuv_format = use_10_bpc_ ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV444P;
auto rgb_pixel_frame = allocate_frame(rgb_format);
auto yuv_pixel_frame = allocate_frame(yuv_format);
if (use_10_bpc_) {
uint16_t* rgb_data = reinterpret_cast<uint16_t*>(rgb_pixel_frame->data[0]);
auto extend_10_to_16_bit = [](const int value) {
return (value * 1025) >> 4; // 1023->65535
};
rgb_data[0] = extend_10_to_16_bit(rgb[0]);
rgb_data[1] = extend_10_to_16_bit(rgb[1]);
rgb_data[2] = extend_10_to_16_bit(rgb[2]);
} else {
uint8_t* rgb_data = reinterpret_cast<uint8_t*>(rgb_pixel_frame->data[0]);
rgb_data[0] = rgb[0];
rgb_data[1] = rgb[1];
rgb_data[2] = rgb[2];
}
FormatConverter rgb_to_yuv_converter(1, 1, 1, 1, rgb_format, yuv_format, color_space, color_range);
rgb_to_yuv_converter(rgb_pixel_frame.get(), yuv_pixel_frame.get());
if (use_10_bpc_) {
auto y_data = reinterpret_cast<const uint16_t*>(yuv_pixel_frame->data[0]);
auto u_data = reinterpret_cast<const uint16_t*>(yuv_pixel_frame->data[1]);
auto v_data = reinterpret_cast<const uint16_t*>(yuv_pixel_frame->data[2]);
return {y_data[0], u_data[0], v_data[0]};
} else {
return {yuv_pixel_frame->data[0][0], yuv_pixel_frame->data[1][0], yuv_pixel_frame->data[2][0]};
}
}
std::string Display::format_pixel(const std::array<int, 3>& pixel) {
std::string hex_pixel = use_10_bpc_ ? to_hex((pixel[0] << 20) | (pixel[1] << 10) | pixel[2], 8) : to_hex((pixel[0] << 16) | (pixel[1] << 8) | pixel[2], 6);
return use_10_bpc_ ? string_sprintf("(%4d,%4d,%4d#%s)", pixel[0], pixel[1], pixel[2], hex_pixel.c_str()) : string_sprintf("(%3d,%3d,%3d#%s)", pixel[0], pixel[1], pixel[2], hex_pixel.c_str());
}
std::string Display::get_and_format_rgb_yuv_pixel(uint8_t* rgb_plane, const size_t pitch, const AVFrame* frame, const int x, const int y) {
auto rgb_format = static_cast<AVPixelFormat>(frame->format);
const std::array<int, 3> rgb = get_rgb_pixel(rgb_plane, pitch, x, y);
const std::array<int, 3> yuv = convert_rgb_to_yuv(rgb, rgb_format, frame->colorspace, frame->color_range);
return "RGB" + format_pixel(rgb) + ", YUV" + format_pixel(yuv);
}
float* Display::rgb_to_grayscale(const uint8_t* plane, const size_t pitch) {
float* grayscale_image = new float[video_width_ * video_height_];
float* p_out = grayscale_image;
auto to_grayscale = [](const float r, const float g, const float b, const float normalization_factor) -> float { return (r * 0.299f + g * 0.587f + b * 0.114f) * normalization_factor; };
if (use_10_bpc_) {
const uint16_t* p_in = reinterpret_cast<const uint16_t*>(plane);
for (int y = 0; y < video_height_; y++) {
for (int x = 0; x < (video_width_ * 3); x += 3) {
const float r = p_in[x] >> 6;
const float g = p_in[x + 1] >> 6;
const float b = p_in[x + 2] >> 6;
*(p_out++) = to_grayscale(r, g, b, 1.f / 1023.f);
}
p_in += pitch / sizeof(uint16_t);
}
} else {
for (int y = 0; y < video_height_; y++) {
for (int x = 0; x < (video_width_ * 3); x += 3) {
const float r = plane[x];
const float g = plane[x + 1];
const float b = plane[x + 2];
*(p_out++) = to_grayscale(r, g, b, 1.f / 255.f);
}
plane += pitch;
}
}
return grayscale_image;
}
float Display::compute_ssim_block(const float* left_plane, const float* right_plane, const int x_offset, const int y_offset, const int block_size) {
const int block_elements = block_size * block_size;
auto compute_mean = [&](const float* plane) {
float sum = 0;
for (int y = y_offset; y < (y_offset + block_size); y++) {
const float* row = plane + y * video_width_ + x_offset;
for (int x = 0; x < block_size; x++) {
sum += *(row++);
}
}
return sum / block_elements;
};
float mean1 = compute_mean(left_plane);
float mean2 = compute_mean(right_plane);
// compute variance and convariance
float sum_var1 = 0, sum_var2 = 0, sum_covar = 0;
for (int y = y_offset; y < (y_offset + block_size); y++) {
const float* row1 = left_plane + y * video_width_ + x_offset;
const float* row2 = right_plane + y * video_width_ + x_offset;
for (int x = 0; x < block_size; x++) {
float diff1 = *(row1++) - mean1;
float diff2 = *(row2++) - mean2;
sum_var1 += diff1 * diff1;
sum_var2 += diff2 * diff2;
sum_covar += diff1 * diff2;
}
}
float variance1 = sum_var1 / block_elements;
float variance2 = sum_var2 / block_elements;
float covariance = sum_covar / block_elements;
float geomtric_mean_variance12 = sqrtf(variance1 * variance2);
// compute SSIM metrics
static constexpr float k1 = 0.01f;
static constexpr float k2 = 0.03f;
static constexpr float c1 = k1 * k1;
static constexpr float c2 = k2 * k2;
static constexpr float c3 = c2 / 2.f;
float luminance = (2.f * mean1 * mean2 + c1) / (mean1 * mean1 + mean2 * mean2 + c1);
float contrast = (2.f * geomtric_mean_variance12 + c2) / (variance1 + variance2 + c2);
float structure = (covariance + c3) / (geomtric_mean_variance12 + c3);
return luminance * contrast * structure;
}
float Display::compute_ssim(const float* left_plane, const float* right_plane) {
static constexpr int overlap = 4;
static constexpr int block_size = 8;
float ssim_sum = 0.0;
int count = 0;
for (int y = 0; y < video_height_ - (block_size - 1); y += block_size - overlap) {
for (int x = 0; x < video_width_ - (block_size - 1); count++, x += block_size - overlap) {
ssim_sum += compute_ssim_block(left_plane, right_plane, x, y, block_size);
}
}
return ssim_sum / count;
}
float Display::compute_psnr(const float* left_plane, const float* right_plane) {
// compute MSE
float mse = 0.0;
for (int i = 0; i < (video_width_ * video_height_); i++) {
const float diff = *(left_plane++) - *(right_plane++);
mse += diff * diff;
}
mse /= (video_width_ * video_height_);
if (mse == 0) {
return std::numeric_limits<float>::infinity();
}
// compute PSNR
return -10.f * log10f(mse);
}
void Display::render_help() {
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, BACKGROUND_ALPHA * 3 / 2);
SDL_RenderFillRect(renderer_, nullptr);
int y = help_y_offset_;
for (size_t i = 0; i < help_textures_.size(); i++) {
int w, h;
SDL_QueryTexture(help_textures_[i], nullptr, nullptr, &w, &h);
SDL_Rect screen_area = {HELP_TEXT_HORIZONTAL_MARGIN, y, w, h};
SDL_RenderCopy(renderer_, help_textures_[i], nullptr, &screen_area);
y += h + HELP_TEXT_LINE_SPACING;
}
}
bool Display::possibly_refresh(const AVFrame* left_frame, const AVFrame* right_frame, const std::string& current_total_browsable, const std::string& message) {
const bool has_updated_left_pts = previous_left_frame_pts_ != left_frame->pts;
const bool has_updated_right_pts = previous_right_frame_pts_ != right_frame->pts;
if (!input_received_ && !has_updated_left_pts && !has_updated_right_pts && !timer_based_update_performed_ && message.empty()) {
return false;
}
std::array<uint8_t*, 3> planes_left{left_frame->data[0], left_frame->data[1], left_frame->data[2]};
std::array<uint8_t*, 3> planes_right{right_frame->data[0], right_frame->data[1], right_frame->data[2]};
std::array<size_t, 3> pitches_left{static_cast<size_t>(left_frame->linesize[0]), static_cast<size_t>(left_frame->linesize[1]), static_cast<size_t>(left_frame->linesize[2])};
std::array<size_t, 3> pitches_right{static_cast<size_t>(right_frame->linesize[0]), static_cast<size_t>(right_frame->linesize[1]), static_cast<size_t>(right_frame->linesize[2])};
// init 10 bpc temp buffers
if (use_10_bpc_) {
if (left_buffer_ == nullptr) {
left_buffer_ = new uint32_t[pitches_left[0] * video_height_ / 4];
left_planes_ = {left_buffer_, nullptr, nullptr};
}
if (right_buffer_ == nullptr) {
right_buffer_ = new uint32_t[pitches_right[0] * video_height_ / 4];
right_planes_ = {right_buffer_, nullptr, nullptr};
}
}
const bool compare_mode = show_left_ && show_right_;
const Vector2D video_extent(video_width_, video_height_);
const Vector2D zoom_rect_start((global_center_ - global_zoom_factor_ * 0.5F) * video_extent);
const Vector2D zoom_rect_end((global_center_ + global_zoom_factor_ * 0.5F) * video_extent);
const Vector2D zoom_rect_size(zoom_rect_end - zoom_rect_start);
const int mouse_video_x = std::floor((static_cast<float>(mouse_x_) * video_to_window_width_factor_ - zoom_rect_start.x()) * static_cast<float>(video_width_) / zoom_rect_size.x());
const int mouse_video_y = std::floor((static_cast<float>(mouse_y_) * video_to_window_height_factor_ - zoom_rect_start.y()) * static_cast<float>(video_height_) / zoom_rect_size.y());