Repository navigation
Expand file tree
/
Copy pathtest_av.cpp
More file actions
4354 lines (3665 loc) · 195 KB
/
Copy pathtest_av.cpp
File metadata and controls
4354 lines (3665 loc) · 195 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
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This program is free software; you can redistribute it and / or modify it
// under the terms of the LGPL License either version 2.1 or later.
// License details are available at https://www.gnu.org/licenses/lgpl-2.1.html
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY
// Purpose: Tests for the audio and video layer (av*) -- stream naming, audio buffering, resampling and
// visualization, container probing, seeking, playback timing, the hover preview decoder, and subtitles:
// their styling, placement, timing and choice, and decoding them from sidecars and streams.
#include "pch.h"
#include "test.h"
#include "av_format.h"
#include "av_player.h"
#include "av_sid.h"
#include "av_sound.h"
#include "av_visualizer.h"
#include "files.h"
#include "model.h"
#include "model_display.h"
#include "test_fixtures.h"
#include "test_runner.h"
#include "app_text.h"
#include <condition_variable>
#include <future>
#include <mutex>
extern "C"
{
#include <libavutil/frame.h>
#include <libavcodec/avcodec.h>
}
extern thread_local std::function<void(AVFrame&)> test_audio_pcm_frame;
extern thread_local std::function<int(int)> test_audio_receive_status;
static void should_format_audio_stream_names()
{
av_stream_info stream;
stream.type = av_stream_type::audio;
stream.language = "eng";
stream.audio_channels = 2;
assert_equal("English - stereo", format_audio_stream_name(stream, 1), "language and channels");
stream.language.clear();
stream.title = "Director";
stream.is_commentary = true;
stream.audio_channels = 6;
assert_equal("Director - commentary - 5.1 surround", format_audio_stream_name(stream, 1),
"title, role and channels");
stream = {};
stream.type = av_stream_type::audio;
stream.audio_channels = 2;
assert_equal("Audio track 2 - stereo", format_audio_stream_name(stream, 2), "numbered fallback");
stream.audio_channels = 0;
stream.codec = "aac";
assert_equal("Audio track 3 - aac", format_audio_stream_name(stream, 3), "codec fallback");
}
// Not static: av_visualizer.h declares this a friend, which names the external-linkage function.
void should_compact_consumed_audio_only_when_needed()
{
audio_info_t format;
format.channel_layout = av_get_def_channel_layout(2);
format.sample_fmt = prop::audio_sample_t::signed_16bit;
format.sample_rate = 10;
audio_buffer buffer;
buffer.init(format);
const std::array<uint8_t, 60> first{};
const std::array<uint8_t, 40> second{};
buffer.append(first.data(), static_cast<uint32_t>(first.size()), 1.0, 1);
buffer.remove(40);
buffer.append(second.data(), static_cast<uint32_t>(second.size()), 2.0, 1);
assert_equal(60u, buffer.used_bytes(), "audio bytes retained after cursor compaction");
assert_equal(1.5, buffer.seconds(), "audio duration retained after cursor compaction");
assert_equal(1.5, buffer.start_time(), "audio start time follows appended frame timing");
assert_equal(3.0, buffer.end_time(), "audio end time follows appended frame timing");
audio_info_t visualizer_format;
visualizer_format.channel_layout = av_get_def_channel_layout(2);
visualizer_format.sample_fmt = prop::audio_sample_t::signed_16bit;
visualizer_format.sample_rate = 48000;
audio_buffer visualizer_buffer;
visualizer_buffer.init(visualizer_format);
std::array<int16_t, FFT_BUFFER_SIZE * 4> samples{};
std::fill_n(samples.begin(), FFT_BUFFER_SIZE * 2, 100);
for (size_t frame = 0; frame < FFT_BUFFER_SIZE; ++frame)
{
const auto sample = static_cast<int16_t>(12000.0 * sin(2.0 * M_PI * 16.0 * frame / FFT_BUFFER_SIZE));
const auto i = FFT_BUFFER_SIZE * 2 + frame * 2;
samples[i] = sample;
samples[i + 1] = sample;
}
visualizer_buffer.append(std::bit_cast<const uint8_t*>(samples.data()),
static_cast<uint32_t>(samples.size() * sizeof(int16_t)), 0.0, 1);
visualizer_buffer.remove(FFT_BUFFER_SIZE * 4);
av_visualizer visualizer;
visualizer.update(visualizer_buffer);
assert_equal(true, visualizer.step(1.0),
"visualizer consumes the live audio window");
assert_equal(true, std::any_of(std::begin(visualizer._frame._data[0]),
std::end(visualizer._frame._data[0]), [](const int bar) { return bar > 0; }),
"visualizer ignores consumed samples before the cursor");
}
// An endpoint's frames hold its own count of channels, and its speaker mask only places them. A mask
// that disagrees once made a mono endpoint with a stereo mask take stereo frames - twice the bytes of
// the buffer it hands out for them.
static void should_lay_out_an_endpoint_by_its_channel_count()
{
const auto layout = [](const uint64_t mask, const int channels)
{
audio_info_t format;
format.channel_layout = av_get_channel_layout(mask, channels);
return format;
};
const auto mask_of = [](const audio_info_t& format)
{
return format.channel_layout->order == AV_CHANNEL_ORDER_NATIVE ? format.channel_layout->u.mask : 0;
};
const auto quad = layout(AV_CH_LAYOUT_QUAD, 4);
assert_equal(4u, quad.channel_count(), "a mask naming every channel");
assert_equal(true, mask_of(quad) == AV_CH_LAYOUT_QUAD, "places them on its speakers");
const auto fewer = layout(AV_CH_LAYOUT_5POINT1_BACK, 4);
assert_equal(4u, fewer.channel_count(), "speakers named past the endpoint's channels are ignored");
assert_equal(true, mask_of(fewer) == AV_CH_LAYOUT_3POINT1, "and its first four kept");
assert_equal(1u, layout(AV_CH_LAYOUT_STEREO, 1).channel_count(), "a mono endpoint with a stereo mask");
assert_equal(6u, layout(AV_CH_LAYOUT_STEREO, 6).channel_count(), "channels beyond the speakers named count");
assert_equal(6u, layout(0, 6).channel_count(), "missing speaker mask uses endpoint channel count");
}
// An endpoint with room for a set number of frames, keeping what it is handed.
class fake_audio_output final : public platform::audio_output
{
public:
platform::audio_output_format mix;
size_t frame_bytes = 1;
size_t room_frames = 0;
std::vector<uint8_t> written;
std::string id() override { return "fake"; }
platform::audio_output_format format() override { return mix; }
double time() const override { return 0.0; }
bool is_stopped() const override { return true; }
bool is_device_lost() const override { return false; }
void reset() override {}
void start() override {}
void stop() override {}
void wait_for_buffer(const core::thread_event&, uint32_t) override {}
size_t write(const core::cspan samples) override
{
const auto frames = std::min(samples.size / frame_bytes, room_frames);
const auto bytes = frames * frame_bytes;
written.insert(written.end(), samples.data, samples.data + bytes);
room_frames -= frames;
return bytes;
}
void write_silence() override {}
void volume(double) override {}
};
// The playback and preview buffers are laid out by the format their endpoint describes, hand it what
// it has room for, and keep the rest queued, in order and on time, for the next write.
static void should_hand_an_endpoint_the_samples_it_has_room_for()
{
fake_audio_output endpoint;
endpoint.mix = {10, platform::audio_sample_format::int16, 2, AV_CH_LAYOUT_STEREO};
endpoint.frame_bytes = 4;
const auto format = av_audio_info(endpoint.format());
assert_equal(10u, format.sample_rate, "the endpoint's rate");
assert_equal(true, format.sample_fmt == prop::audio_sample_t::signed_16bit, "its samples");
assert_equal(2u, format.channel_count(), "and its channels lay out the buffer");
audio_buffer buffer;
buffer.init(format);
std::array<uint8_t, 40> second = {};
for (size_t i = 0; i < second.size(); ++i) second[i] = static_cast<uint8_t>(i + 1);
buffer.append(second.data(), static_cast<uint32_t>(second.size()), 5.0, 1);
endpoint.room_frames = 3;
buffer.write_to(endpoint);
assert_equal(12u, static_cast<uint32_t>(endpoint.written.size()), "the endpoint takes the frames it has room for");
assert_equal(28u, buffer.used_bytes(), "and the rest stays queued");
assert_equal(true, core::equiv(buffer.start_time(), 5.3), "from the time the endpoint reached");
buffer.write_to(endpoint);
assert_equal(28u, buffer.used_bytes(), "a full endpoint takes nothing");
endpoint.room_frames = 100;
buffer.write_to(endpoint);
assert_equal(true, buffer.is_empty(), "and one with room takes the rest");
assert_equal(true, std::ranges::equal(endpoint.written, second), "in order");
const auto surround = av_audio_info({48000, platform::audio_sample_format::float32, 6, AV_CH_LAYOUT_5POINT1});
assert_equal(true, surround.sample_fmt == prop::audio_sample_t::signed_float, "float samples");
assert_equal(6u, surround.channel_count(), "on six channels");
assert_equal(true, av_audio_info({48000, platform::audio_sample_format::int32, 2, 0}).sample_fmt ==
prop::audio_sample_t::signed_32bit, "32-bit samples");
assert_equal(true, av_audio_info({48000, platform::audio_sample_format::none, 2, 0}).sample_fmt ==
prop::audio_sample_t::none, "and none the mixer does not speak");
}
// audio_buffer keeps its samples private; this declared friend lets the test read them.
struct audio_ramp_probe
{
static int16_t sample(const audio_buffer& buffer, const size_t i)
{
return std::bit_cast<const int16_t*>(buffer.data + buffer.start_pos)[i];
}
};
static void should_ramp_audio_at_buffer_edges()
{
audio_info_t format;
format.channel_layout = av_get_def_channel_layout(2);
format.sample_fmt = prop::audio_sample_t::signed_16bit;
format.sample_rate = 1000;
audio_buffer buffer;
buffer.init(format);
std::array<int16_t, 2000> samples{};
samples.fill(1000);
buffer.append(std::bit_cast<const uint8_t*>(samples.data()),
static_cast<uint32_t>(samples.size() * sizeof(int16_t)), 0.0, 1);
buffer.apply_fade_in(0.010);
buffer.apply_fade_out(0.010);
// 1000 frames of stereo audio at 1kHz, so a 10ms ramp covers 10 frames = 20 samples.
const auto sample = [&buffer](const size_t i) { return audio_ramp_probe::sample(buffer, i); };
assert_equal(true, sample(0) < 200, "playback starts near silence");
assert_equal(1000, static_cast<int>(sample(19)), "the fade in reaches full level after 10ms");
assert_equal(1000, static_cast<int>(sample(1000)), "audio between the ramps is untouched");
assert_equal(0, static_cast<int>(sample(1999)), "playback ends at silence");
assert_equal(true, sample(1979) == 1000, "the fade out only covers the last 10ms");
assert_equal(4000u, buffer.used_bytes(), "ramping does not consume buffered audio");
}
// Not static: av_visualizer.h declares this a friend, which names the external-linkage function.
void should_time_visualizer_independently_of_refresh_rate()
{
auto animate = [](const double frame_seconds)
{
av_visualizer visualizer;
av_visualizer::frame peak(0.0);
peak._data[0][8] = 1000;
visualizer._frames.push(peak);
for (auto time = 0.0; time <= 0.1; time += frame_seconds)
{
visualizer.step(time);
}
return visualizer._frame._data[0][8];
};
const auto level_30hz = animate(1.0 / 30.0);
const auto level_120hz = animate(1.0 / 120.0);
assert_equal(true, std::abs(level_30hz - level_120hz) < 30,
"visualizer attack is independent of display refresh rate");
av_visualizer visualizer;
av_visualizer::frame loud(0.010);
loud._data[0][8] = 1000;
av_visualizer::frame quiet(0.020);
visualizer._frames.push(loud);
visualizer._frames.push(quiet);
visualizer.step(0.0);
assert_equal(true, visualizer._frame._data[0][8] > 0,
"visualizer preserves a transient between presentation frames");
}
// MEDIA-007 - the frequency table is one immutable object. The old constructor rewrote the shared
// bins for every visualizer instance; this catches that deterministically without a race detector.
void should_share_one_immutable_visualizer_frequency_table()
{
const auto& first = av_visualizer::frequency_scale();
const auto* const first_address = first.data();
const auto first_contents = first;
const auto init_count = av_visualizer::frequency_scale_init_count().load();
for (auto i = 0; i < 64; ++i)
{
av_visualizer visualizer;
}
const auto& second = av_visualizer::frequency_scale();
assert_equal(true, first_address == second.data(), "visualizer instances share one frequency table object");
assert_equal(true, std::ranges::equal(first_contents, second), "constructing visualizers does not rewrite bins");
assert_equal(init_count, av_visualizer::frequency_scale_init_count().load(),
"constructing visualizers does not reinitialize bins");
}
// MEDIA-007 - constructing one visualizer must not rewrite the frequency bins another session's
// audio path is reading. This exercises the session-switch interleaving with independent inputs.
void should_keep_visualizer_frequency_bins_stable_across_sessions()
{
audio_info_t format;
format.channel_layout = av_get_def_channel_layout(2);
format.sample_fmt = prop::audio_sample_t::signed_16bit;
format.sample_rate = 48000;
const auto fill_buffer = [&format](audio_buffer& buffer, const double frequency)
{
buffer.clear();
std::array<int16_t, FFT_BUFFER_SIZE * 2> samples{};
for (size_t frame = 0; frame < FFT_BUFFER_SIZE; ++frame)
{
const auto sample = static_cast<int16_t>(14000.0 * sin(2.0 * M_PI * frequency * frame / FFT_BUFFER_SIZE));
samples[frame * 2] = sample;
samples[frame * 2 + 1] = sample;
}
buffer.append(std::bit_cast<const uint8_t*>(samples.data()),
static_cast<uint32_t>(samples.size() * sizeof(int16_t)), 0.0, 1);
};
std::atomic_bool stop = false;
std::mutex update_mutex;
std::condition_variable update_changed;
auto updates_requested = 0;
auto updates_completed = 0;
av_visualizer first;
const auto worker = std::async(std::launch::async, [&]
{
audio_buffer buffer;
buffer.init(format);
for (;;)
{
{
std::unique_lock lock(update_mutex);
update_changed.wait(lock, [&]
{
return stop.load() || updates_completed < updates_requested;
});
if (stop.load()) return;
}
fill_buffer(buffer, 12.0);
first.update(buffer);
{
std::lock_guard lock(update_mutex);
++updates_completed;
}
update_changed.notify_all();
}
});
const core::scope_exit stop_worker([&]
{
stop = true;
update_changed.notify_all();
});
(void)av_visualizer::frequency_scale();
const auto init_count = av_visualizer::frequency_scale_init_count().load();
for (auto i = 0; i < 64; ++i)
{
audio_buffer buffer;
buffer.init(format);
fill_buffer(buffer, 48.0);
av_visualizer second;
second.update(buffer);
assert_equal(true, second.step(1.0), "new session visualizer has bins");
{
std::lock_guard lock(update_mutex);
++updates_requested;
}
update_changed.notify_all();
{
std::unique_lock lock(update_mutex);
assert_equal(true, update_changed.wait_for(lock, std::chrono::seconds(5), [&]
{
return updates_completed >= updates_requested;
}),
"old session updated while new visualizers were constructed");
}
}
stop = true;
update_changed.notify_all();
worker.wait();
audio_buffer first_buffer;
first_buffer.init(format);
fill_buffer(first_buffer, 12.0);
first.update(first_buffer);
audio_buffer second_buffer;
second_buffer.init(format);
fill_buffer(second_buffer, 48.0);
av_visualizer second;
second.update(second_buffer);
assert_equal(64, updates_completed, "old session updated once for each constructed visualizer");
assert_equal(init_count, av_visualizer::frequency_scale_init_count().load(),
"constructing visualizers while another updates does not reinitialize bins");
assert_equal(true, first.step(1.0), "old session visualizer still has bins");
assert_equal(true, second.step(1.0), "new session visualizer still has bins");
}
static void should_extract_dv_datetime()
{
// Build a minimal raw DV frame (one DIF sequence) carrying the VAUX
// recording-date (0x62) and recording-time (0x63) packs at the offsets the
// DV format places them (VAUX DIF block 3 of the sequence).
std::vector<uint8_t> frame(12000, 0);
auto* const date_pack = &frame[80 * 3 + 13];
date_pack[0] = 0x62; // VAUX recording date pack id
date_pack[1] = 0xff; // timezone unknown
date_pack[2] = 0xc0 | (1 << 4) | 5; // day 15 (reserved bits set)
date_pack[3] = (0 << 4) | 7; // month 07
date_pack[4] = (0 << 4) | 3; // year 03 -> 2003
auto* const time_pack = &frame[80 * 3 + 18];
time_pack[0] = 0x63; // VAUX recording time pack id
time_pack[1] = 0xff; // frames unknown
time_pack[2] = (4 << 4) | 5; // 45 seconds
time_pack[3] = (3 << 4) | 0; // 30 minutes
time_pack[4] = (1 << 4) | 4; // 14 hours
const auto actual = dv_extract_rec_datetime(frame.data(), frame.size());
assert_equal(core::date_t(2003, 7, 15, 14, 30, 45), actual, "dv rec datetime");
// A frame without recording packs must yield an invalid (absent) date.
const std::vector<uint8_t> empty_frame(12000, 0);
assert_equal(false, dv_extract_rec_datetime(empty_frame.data(), empty_frame.size()).is_valid(),
"dv no packs");
}
static void should_correct_pts()
{
// av_pts_correction takes FFmpeg's AVFrame::best_effort_timestamp (falling back to pts
// then pkt_dts) and guarantees a strictly increasing result so the presenter can always
// order frames. AV_NOPTS_VALUE is INT64_MIN; mirror it here so the test does not need to
// pull in the libav* headers.
constexpr int64_t nopts = std::numeric_limits<int64_t>::min();
// Clean, monotonic timestamps pass straight through.
{
av_pts_correction pc;
assert_equal(0, static_cast<int>(pc.guess(0, 0, 0, 100)), "monotonic 0");
assert_equal(100, static_cast<int>(pc.guess(100, 100, 100, 100)), "monotonic 100");
assert_equal(200, static_cast<int>(pc.guess(200, 200, 200, 100)), "monotonic 200");
}
// best_effort_timestamp wins over pts and pkt_dts; those are only consulted when the
// decoder had nothing to publish.
{
av_pts_correction pc;
assert_equal(500, static_cast<int>(pc.guess(500, 700, 900, 100)), "best effort preferred");
assert_equal(700, static_cast<int>(pc.guess(nopts, 700, 900, 100)), "falls back to pts");
assert_equal(900, static_cast<int>(pc.guess(nopts, nopts, 900, 100)), "falls back to dts");
}
// A duplicated timestamp must not be returned verbatim - that would make the
// presenter treat the frame as "not newer" and stall - so it is advanced by
// one frame duration instead.
{
av_pts_correction pc;
assert_equal(0, static_cast<int>(pc.guess(0, nopts, nopts, 100)), "dup first");
assert_equal(100, static_cast<int>(pc.guess(100, nopts, nopts, 100)), "dup second");
assert_equal(200, static_cast<int>(pc.guess(100, nopts, nopts, 100)), "dup advanced by duration");
}
// With no timestamps at all (raw / MJPEG streams) and no reported duration,
// the timeline still advances using the cadence learned from earlier frames.
{
av_pts_correction pc;
assert_equal(0, static_cast<int>(pc.guess(0, nopts, nopts, 0)), "nopts first");
assert_equal(40, static_cast<int>(pc.guess(40, nopts, nopts, 0)), "nopts learn cadence");
assert_equal(80, static_cast<int>(pc.guess(nopts, nopts, nopts, 0)), "nopts synth 1");
assert_equal(120, static_cast<int>(pc.guess(nopts, nopts, nopts, 0)), "nopts synth 2");
}
// The learned cadence is the smallest step seen, not the most recent one: a gap in a
// damaged stream must not become the synthetic step and run the timeline away.
{
av_pts_correction pc;
assert_equal(0, static_cast<int>(pc.guess(0, nopts, nopts, 0)), "gap first");
assert_equal(40, static_cast<int>(pc.guess(40, nopts, nopts, 0)), "gap learn cadence");
assert_equal(9000, static_cast<int>(pc.guess(9000, nopts, nopts, 0)), "gap jump");
assert_equal(9040, static_cast<int>(pc.guess(nopts, nopts, nopts, 0)), "synth uses smallest step");
}
// Invariant: however messy the timestamps (duplicates, backward jumps), the output is
// always strictly increasing.
{
av_pts_correction pc;
const int64_t messy[] = {0, 200, 100, 100, 400, 300, 500};
auto prev = nopts;
for (const auto p : messy)
{
const auto t = pc.guess(p, nopts, nopts, 50);
if (prev != nopts) assert_equal(true, t > prev, "strictly increasing");
prev = t;
}
}
}
// MEDIA-006 - EOF is not the end of frame output for codecs with delayed/reordered pictures. The
// delayed frames must pass through the same nearest-choice logic before extraction concludes.
static void should_drain_delayed_video_frames_for_nearest_eof_choice()
{
constexpr auto wanted = 1.19;
av_nearest_frame_choice choice;
assert_equal(true, choice.consider(1.0, wanted, 0.0), "pre-EOF frame is the initial candidate");
assert_equal(true, should_drain_delayed_video_frames_at_eof(choice), "EOF drains delayed decoder output");
assert_equal(true, choice.consider(1.16, wanted, 0.0), "first delayed frame improves the choice");
assert_equal(true, choice.consider(1.20, wanted, 0.0), "final delayed frame is nearest");
assert_equal(true, core::equiv(1.20, choice.best_time),
std::format("delayed final frame wins nearest choice (got {:.2f})", choice.best_time));
}
// The index scan bounds FFmpeg's stream probe; the inspect scan does not. Every property the index
// records has to survive that bound, so the two intents are compared across the AV containers.
static void should_scan_av_metadata_with_a_bounded_probe()
{
auto fixtures_carrying_xmp = 0;
for (const auto* const name : {
"gizmo.mp4", "indy.mp4", "anamorphic.mp4", "ipod.mov", "StPauls.MOV", "tagged.mkv",
"Byzantium.avi", "Colorblind.mp3"
})
{
const auto path = test_files_folder().combine_file(name);
const auto* const ft = files::file_type_from_name(path);
files ff;
const auto inspected = ff.scan_file(path, false, ft, {}, {}, libfiles::scan_intent::inspect);
const auto indexed = ff.scan_file(path, false, ft, {}, {}, libfiles::scan_intent::index);
// The player's summary comes from a playback open, which lays libfiles' reading of the container
// over FFmpeg's streams.
av_format_decoder decoder;
assert_equal(true, decoder.open(path, media_intent::playback), name, "open media for its displayed summary");
const auto displayed = decoder.info();
assert_equal(inspected.video_codec.sv(), displayed.video_codec.sv(), name,
"attached artwork cannot replace the main video codec");
assert_equal(inspected.pixel_format.sv(), displayed.pixel_format.sv(), name,
"displayed pixel format belongs to the same video stream as the index");
assert_equal(true, indexed.success, name, "index scan succeeded");
assert_equal(inspected.width, indexed.width, name, "width");
assert_equal(inspected.height, indexed.height, name, "height");
assert_equal(inspected.duration, indexed.duration, name, "duration");
assert_equal(inspected.video_codec.sv(), indexed.video_codec.sv(), name, "video codec");
assert_equal(inspected.pixel_format.sv(), indexed.pixel_format.sv(), name, "pixel format");
assert_equal(inspected.audio_codec.sv(), indexed.audio_codec.sv(), name, "audio codec");
assert_equal(inspected.audio_sample_rate, indexed.audio_sample_rate, name, "audio sample rate");
assert_equal(inspected.audio_channels, indexed.audio_channels, name, "audio channels");
assert_equal(static_cast<int>(inspected.audio_sample_type), static_cast<int>(indexed.audio_sample_type),
name, "audio sample type");
assert_equal(inspected.bitrate.sv(), indexed.bitrate.sv(), name, "bit rate");
assert_equal(inspected.orientation, indexed.orientation, name, "orientation");
assert_equal(inspected.created_utc, indexed.created_utc, name, "created");
// gizmo.mp4, ipod.mov and Byzantium.avi carry their XMP packet in the last 1% of the file,
// megabytes past the probe budget. It survives because container metadata is read by the
// demuxer's read_header, inside avformat_open_input, which the bound is applied after.
assert_equal(inspected.metadata.xmp.size(), indexed.metadata.xmp.size(), name, "xmp size");
assert_equal(true, std::ranges::equal(inspected.metadata.xmp, indexed.metadata.xmp), name, "xmp bytes");
if (!inspected.metadata.xmp.empty()) ++fixtures_carrying_xmp;
}
// Without this the XMP assertions above would pass on an empty packet and prove nothing.
assert_equal(3, fixtures_carrying_xmp, "fixtures carrying a trailing xmp packet");
}
static core::blob make_tga(const uint16_t width, const uint16_t height, const uint8_t bits_per_pixel,
const std::vector<uint8_t>& pixels, const uint8_t alpha_bits = 8)
{
core::blob result(18, 0);
result[2] = 2; // uncompressed true-colour image
result[12] = static_cast<uint8_t>(width & 0xff);
result[13] = static_cast<uint8_t>(width >> 8);
result[14] = static_cast<uint8_t>(height & 0xff);
result[15] = static_cast<uint8_t>(height >> 8);
result[16] = bits_per_pixel;
result[17] = static_cast<uint8_t>(0x20 | (bits_per_pixel == 32 ? alpha_bits : 0)); // top-left origin
result.insert(result.end(), pixels.begin(), pixels.end());
return result;
}
static core::blob make_gif(const bool transparent)
{
core::blob result{
'G', 'I', 'F', '8', '9', 'a',
1, 0, 1, 0,
0x80, 0x00, 0x00,
0xff, 0x00, 0x00,
0x00, 0x00, 0xff
};
if (transparent)
{
constexpr std::array<uint8_t, 8> transparency{
0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00
};
result.insert(result.end(), transparency.begin(), transparency.end());
}
constexpr std::array<uint8_t, 16> image{
0x2c, 0, 0, 0, 0, 1, 0, 1, 0, 0,
0x02, 0x02, 0x44, 0x01, 0x00,
0x3b
};
result.insert(result.end(), image.begin(), image.end());
return result;
}
static core::blob make_bmp(const uint32_t width, const uint32_t height)
{
const auto stride = (width * 3 + 3) & ~3u;
const auto pixel_bytes = stride * height;
const auto file_bytes = 14u + 40u + pixel_bytes;
core::blob result(file_bytes);
result[0] = 'B';
result[1] = 'M';
result[2] = static_cast<uint8_t>(file_bytes & 0xff);
result[3] = static_cast<uint8_t>((file_bytes >> 8) & 0xff);
result[4] = static_cast<uint8_t>((file_bytes >> 16) & 0xff);
result[5] = static_cast<uint8_t>((file_bytes >> 24) & 0xff);
result[10] = 14 + 40;
result[14] = 40;
result[18] = static_cast<uint8_t>(width & 0xff);
result[19] = static_cast<uint8_t>((width >> 8) & 0xff);
result[20] = static_cast<uint8_t>((width >> 16) & 0xff);
result[21] = static_cast<uint8_t>((width >> 24) & 0xff);
result[22] = static_cast<uint8_t>(height & 0xff);
result[23] = static_cast<uint8_t>((height >> 8) & 0xff);
result[24] = static_cast<uint8_t>((height >> 16) & 0xff);
result[25] = static_cast<uint8_t>((height >> 24) & 0xff);
result[26] = 1;
result[28] = 24;
result[34] = static_cast<uint8_t>(pixel_bytes & 0xff);
result[35] = static_cast<uint8_t>((pixel_bytes >> 8) & 0xff);
result[36] = static_cast<uint8_t>((pixel_bytes >> 16) & 0xff);
result[37] = static_cast<uint8_t>((pixel_bytes >> 24) & 0xff);
std::fill(result.begin() + 54, result.end(), 0x80);
return result;
}
static uint8_t composite_over_green(const core::const_surface_ptr& surface, const int x)
{
const auto* const p = surface->pixels_line(0) + x * 4;
const auto alpha = surface->format() == core::texture_format::ARGB ? p[3] / 255.0f : 1.0f;
return static_cast<uint8_t>(std::clamp(static_cast<int>(p[1] * alpha + 255.0f * (1.0f - alpha) + 0.5f),
0, 255));
}
// MEDIA-008 - still fallback conversion must retain alpha-capable source semantics.
static void should_preserve_alpha_when_decoding_ffmpeg_stills()
{
std::array<uint8_t, 8> bgra{0, 0, 255, 255, 255, 0, 0, 0};
AVFrame frame{};
frame.format = AV_PIX_FMT_BGRA;
frame.width = 2;
frame.height = 1;
frame.data[0] = bgra.data();
frame.linesize[0] = 8;
av_scaler scaler;
core::surface_ptr with_alpha;
assert_equal(true, scaler.scale_frame(frame, with_alpha, {}, 0.0, core::orientation::top_left, {}, true),
"alpha frame converted");
assert_equal(static_cast<int>(core::texture_format::ARGB), static_cast<int>(with_alpha->format()),
"alpha frame keeps alpha-capable surface format");
assert_equal(0, static_cast<int>(composite_over_green(with_alpha, 0)), "opaque red covers green background");
assert_equal(255, static_cast<int>(composite_over_green(with_alpha, 1)),
"transparent pixel reveals green background");
core::surface_ptr opaque;
assert_equal(true, scaler.scale_frame(frame, opaque, {}, 0.0, core::orientation::top_left),
"opaque video frame converted");
assert_equal(static_cast<int>(core::texture_format::RGB), static_cast<int>(opaque->format()),
"opaque video frames keep the opaque fast path");
std::array<uint8_t, 2> palette_indices{0, 1};
std::array<uint32_t, 256> palette{};
palette[0] = 0xffff0000u;
palette[1] = 0xff0000ffu;
AVFrame palette_frame{};
palette_frame.format = AV_PIX_FMT_PAL8;
palette_frame.width = 2;
palette_frame.height = 1;
palette_frame.data[0] = palette_indices.data();
palette_frame.linesize[0] = static_cast<int>(palette_indices.size());
palette_frame.data[1] = std::bit_cast<uint8_t*>(palette.data());
core::surface_ptr opaque_palette;
assert_equal(true, scaler.scale_frame(palette_frame, opaque_palette, {}, 0.0, core::orientation::top_left, {}, true),
"opaque palette frame converted");
assert_equal(static_cast<int>(core::texture_format::RGB), static_cast<int>(opaque_palette->format()),
"opaque palette frames keep the opaque fast path");
palette[1] = 0x000000ffu;
core::surface_ptr transparent_palette;
assert_equal(true, scaler.scale_frame(palette_frame, transparent_palette, {}, 0.0, core::orientation::top_left, {},
true),
"transparent palette frame converted");
assert_equal(static_cast<int>(core::texture_format::ARGB), static_cast<int>(transparent_palette->format()),
"transparent palette frames keep alpha");
}
// MEDIA-008 - a 32-bit TGA with zero alpha-bit count stores padding, not transparency.
static void should_decode_zero_alpha_tga_as_opaque()
{
const auto tga = make_tga(1, 1, 32, {0, 0, 255, 0}, 0);
const auto decoded = av_decode_still(tga, {}, "tga");
assert_equal(true, is_valid(decoded), "zero-alpha tga decoded");
assert_equal(static_cast<int>(core::texture_format::RGB), static_cast<int>(decoded->format()),
"zero-alpha tga remains opaque");
assert_equal(0, static_cast<int>(composite_over_green(decoded, 0)), "opaque red covers green background");
}
// MEDIA-008 - GIF frames are alpha-capable, but opaque palettes do not need ARGB.
static void should_decode_opaque_gif_palette_as_rgb()
{
const auto opaque = av_decode_still(make_gif(false), {}, ".gif");
assert_equal(true, is_valid(opaque), "opaque gif decoded");
assert_equal(static_cast<int>(core::texture_format::RGB), static_cast<int>(opaque->format()),
"opaque palette gif remains RGB");
}
// MEDIA-009 - the application pixel ceiling is supplied before FFmpeg's still-image probe decoder.
static void should_refuse_over_budget_stills_during_probe()
{
constexpr uint16_t width = 16;
constexpr uint16_t height = 16;
const auto bmp = make_bmp(width, height);
const auto restore_budget = render::max_decode_bytes;
const core::scope_exit restore([restore_budget] { render::max_decode_bytes = restore_budget; });
render::max_decode_bytes = static_cast<int64_t>(width) * height * 4 - 1;
load_diagnostic diagnostic;
const auto refused = av_decode_still(bmp, {}, ".bmp", &diagnostic);
assert_equal(false, is_valid(refused), "over-budget still is refused");
assert_equal(true, diagnostic.over_budget, "probe refusal reports the budget reason");
assert_equal(static_cast<int>(width), diagnostic.source_dimensions.cx, "budget report width");
assert_equal(static_cast<int>(height), diagnostic.source_dimensions.cy, "budget report height");
}
// MEDIA-012 - MJPEG admission accounts for codec working storage, not only BGRA source pixels.
static void should_refuse_mjpeg_when_codec_working_storage_exceeds_budget()
{
const auto data = platform::blob_from_file(test_files_folder().combine_file("Test.jpg"));
const auto control = av_decode_still(data, {}, ".jpg");
assert_equal(true, is_valid(control), "jpeg decodes through ffmpeg control path");
const auto source_bytes = static_cast<int64_t>(control->dimensions().cx) * control->dimensions().cy * 4;
const auto restore_budget = render::max_decode_bytes;
const core::scope_exit restore([restore_budget] { render::max_decode_bytes = restore_budget; });
render::max_decode_bytes = source_bytes * 2;
const auto refused = av_decode_still(data, {}, ".jpg");
assert_equal(false, is_valid(refused), "codec working storage is budgeted separately from source pixels");
}
// FFmpeg falls back to matching a demuxer on the file extension alone, so a TypeScript source file
// named index.ts is handed to the MPEG-TS demuxer, opens without any error and then describes no
// stream whatsoever. The scan must report that as a failure rather than publish an empty video.
static void should_reject_a_non_media_file()
{
const auto path = test_files_folder().combine("excluded1").combine_file("not-media.ts");
const auto* const ft = files::file_type_from_name(path);
// The extension alone still says video; only the header settles it.
assert_equal(true, platform::exists(path), "fixture is present");
assert_equal(true, ft->has_trait(file_traits::av), "ts is an av extension");
assert_equal(false, files::media_header_matches(path.extension(), platform::blob_head_from_file(path, 1024)),
"the header rule refuses it before the demuxer sees it");
av_format_decoder decoder;
assert_equal(false, decoder.open(path, media_intent::metadata), "decoder rejects the file");
files ff;
assert_equal(false, ff.scan_file(path, false, ft, {}, {}, libfiles::scan_intent::inspect).success, "inspect scan fails");
assert_equal(false, ff.scan_file(path, false, ft, {}, {}, libfiles::scan_intent::index).success, "index scan fails");
}
// Issue #78 - Some videos ignore aspect ratio.
// anamorphic.mp4 is stored at 640x480 with a 4:3 pixel (sample) aspect ratio,
// i.e. a 16:9 display. The scanner must report the display dimensions (640x360)
// rather than the stored frame size (640x480).
static void should_apply_video_aspect_ratio()
{
const auto load_path = test_files_folder().combine_file("anamorphic.mp4");
files ff;
const auto actual = ff_scan_file(ff, load_path);
const auto md = actual.to_props();
assert_equal(640, md->width, "anamorphic display width");
assert_equal(360, md->height, "anamorphic display height");
}
// Issue #78 - thumbnails and the scrubber preview ignored the aspect ratio long after playback
// respected it. An MP4 'pasp' box reaches AVStream::sample_aspect_ratio only: FFmpeg copies it
// neither onto the codec parameters nor onto a decoded AVFrame. A file whose H.264 VUI declares
// no aspect (or square pixels) therefore hands the frame scaler a 1:1 frame the container
// contradicts, and every decoded picture came out at the stored 4:3 shape instead of 16:9.
// anamorphic-pasp.mp4 is anamorphic.mp4 with its VUI aspect_ratio_idc rewritten to 1 (square),
// leaving the 4:3 pasp box as the only surviving declaration.
static void should_apply_container_aspect_ratio_to_decoded_frames()
{
const auto load_path = test_files_folder().combine_file("anamorphic-pasp.mp4");
files ff;
const auto md = ff_scan_file(ff, load_path).to_props();
assert_equal(640, md->width, "scanned display width");
assert_equal(360, md->height, "scanned display height");
av_format_decoder decoder;
assert_equal(true, decoder.open(load_path, media_intent::thumbnail), "open anamorphic-pasp.mp4");
decoder.init_streams(-1, -1, false, false, false);
assert_equal(true, decoder.has_video(), "anamorphic-pasp.mp4 has video");
constexpr sizei max_dim(256, 256);
// 640x480 stored, 16:9 displayed: bounded by 256 the thumbnail is 256x144, not 256x192.
core::surface_ptr thumbnail;
assert_equal(true, decoder.extract_thumbnail(thumbnail, max_dim, 1, 100), "thumbnail decoded");
assert_equal(true, is_valid(thumbnail), "thumbnail valid");
assert_equal(256, thumbnail->dimensions().cx, "thumbnail width");
assert_equal(144, thumbnail->dimensions().cy, "thumbnail height");
// The hover preview over the timeline decodes through a different entry point.
core::surface_ptr preview;
assert_equal(true, decoder.extract_seek_frame(preview, max_dim, 50, 100), "seek frame decoded");
assert_equal(true, is_valid(preview), "seek frame valid");
assert_equal(256, preview->dimensions().cx, "seek frame width");
assert_equal(144, preview->dimensions().cy, "seek frame height");
}
// Issue #78 - the file the reporter supplied after retesting 1.27.1 still showed square-pixel
// thumbnails. tvp.mp4 is broadcast-derived: 528x560 stored with a 249:176 pixel aspect, i.e. a
// 4:3 display. The scan reported 528x396 correctly from 1.27.0 onwards, which is why playback
// looked right while the thumbnail and the timeline hover preview stayed at the stored shape.
static void should_apply_aspect_ratio_to_broadcast_video_thumbnails()
{
const auto load_path = test_files_folder().combine_file("tvp.mp4");
files ff;
const auto md = ff_scan_file(ff, load_path).to_props();
assert_equal(528, md->width, "scanned display width");
assert_equal(396, md->height, "scanned display height");
av_format_decoder decoder;
assert_equal(true, decoder.open(load_path, media_intent::thumbnail), "open tvp.mp4");
decoder.init_streams(-1, -1, false, false, false);
assert_equal(true, decoder.has_video(), "tvp.mp4 has video");
constexpr sizei max_dim(256, 256);
// 4:3 displayed, so bounded by 256 the thumbnail is 256x192, not the stored 241x256.
core::surface_ptr thumbnail;
assert_equal(true, decoder.extract_thumbnail(thumbnail, max_dim, 1, 100), "thumbnail decoded");
assert_equal(true, is_valid(thumbnail), "thumbnail valid");
assert_equal(256, thumbnail->dimensions().cx, "thumbnail width");
assert_equal(192, thumbnail->dimensions().cy, "thumbnail height");
core::surface_ptr preview;
assert_equal(true, decoder.extract_seek_frame(preview, max_dim, 5, 10), "seek frame decoded");
assert_equal(true, is_valid(preview), "seek frame valid");
assert_equal(256, preview->dimensions().cx, "seek frame width");
assert_equal(192, preview->dimensions().cy, "seek frame height");
}
// A container-level seek does not flush the codec, so extract_thumbnail must flush
// the decoder after seeking - otherwise, when the decoder is reused across calls, a
// later-position thumbnail can be served from a frame that was buffered before the
// seek. This reuses one decoder for an early and a late thumbnail (the exact reuse
// scenario) and asserts the two frames differ.
static void should_flush_decoder_on_thumbnail_seek()
{
const auto load_path = test_files_folder().combine_file("gizmo.mp4");
av_format_decoder decoder;
assert_equal(true, decoder.open(load_path, media_intent::thumbnail), "open gizmo.mp4");
decoder.init_streams(-1, -1, false, false, false);
assert_equal(true, decoder.has_video(), "gizmo.mp4 has video");
constexpr sizei max_dim(256, 256);
core::surface_ptr early;
assert_equal(true, decoder.extract_thumbnail(early, max_dim, 1, 100), "early thumbnail decoded");
assert_equal(true, is_valid(early), "early thumbnail valid");
// Reuse the same decoder; the seek to 95% must flush the frames buffered by the
// early extraction above rather than replaying one of them.
core::surface_ptr late;
assert_equal(true, decoder.extract_thumbnail(late, max_dim, 95, 100), "late thumbnail decoded");
assert_equal(true, is_valid(late), "late thumbnail valid");
const auto same_size = is_valid(early) && is_valid(late) && early->size() == late->size();
assert_equal(true, same_size, "thumbnails allocated to the same size");
const auto identical = same_size && memcmp(early->pixels(), late->pixels(), early->size()) == 0;
assert_equal(false, identical, "late thumbnail differs from early (decoder flushed after seek)");
}
// Issue #78 - the aspect ratio a video plays at. should_apply_container_aspect_ratio_to_decoded_frames
// covers the thumbnail and scrubber-preview half of that report; this holds the player to the same
// answer, because the session's display dimensions are what the media view sizes its box from. The
// two have to agree or the same file is correct as a tile and wrong as a video.
static void should_report_container_aspect_ratio_to_the_player()
{
const auto load_path = test_files_folder().combine_file("anamorphic-pasp.mp4");
files ff;
const auto scanned = ff_scan_file(ff, load_path).to_props();
const auto ses = make_test_session();
assert_equal(true, ses->open(load_path, files::file_type_from_name(load_path), 0.0, true, -1, -1, false,
false, false), "session opened");
const auto info = ses->info();
// 640x480 stored, 4:3 pasp, so 16:9 displayed.
assert_equal(640, info.display_dimensions.cx, "player display width");
assert_equal(360, info.display_dimensions.cy, "player display height");
assert_equal(static_cast<int>(scanned->width), info.display_dimensions.cx, "player agrees with the scan on width");
assert_equal(static_cast<int>(scanned->height), info.display_dimensions.cy,
"player agrees with the scan on height");
ses->close(false);
}
// Issue #252 - a rotated video. The scan reads the rotation from the container display matrix and
// the player reads it again once it decodes, so the two have to agree: a disagreement is what made
// a portrait video draw a portrait tile and then play back landscape, or the reverse.
static void should_report_container_rotation_to_the_player()
{
const auto load_path = test_files_folder().combine("excluded1").combine_file("rotated90.mp4");
files ff;
const auto scanned = ff_scan_file(ff, load_path).to_props();
assert_equal(core::orientation::right_top, scanned->orientation, "scan reads the display matrix");
const auto ses = make_test_session();
assert_equal(true, ses->open(load_path, files::file_type_from_name(load_path), 0.0, true, -1, -1, false,
false, false), "session opened");
assert_equal(core::orientation::right_top, ses->info().display_orientation, "player agrees with the scan");
ses->close(false);
}
// A mirrored video. A container's transform can mirror the picture as well as turn it, and the scan and
// the player both read the mirror from it, as they read the turn, so a mirrored file's tile and its
// playback agree. rotated90.mp4 is made mirrored here by its track's matrix alone. Before, the scan
// dropped the mirror and the player read a horizontal mirror as a half turn: these failed with the scan
// upright and the player turned 180 degrees, and with the scan turned a quarter (6) and the player
// three quarters (8).
static void should_report_a_mirrored_container_to_the_player()
{
const auto original = read_test_file(test_files_folder().combine("excluded1").combine_file("rotated90.mp4"));
// The matrix's first four entries, 16.16 fixed point, of the track rotated90.mp4 turns a quarter.
constexpr uint32_t one = 0x00010000u;
constexpr uint32_t minus_one = 0xFFFF0000u;
const auto load_be32 = [](const std::string& s, const size_t at)