Repository navigation
Expand file tree
/
Copy pathav_format.cpp
More file actions
5260 lines (4371 loc) · 173 KB
/
Copy pathav_format.cpp
File metadata and controls
5260 lines (4371 loc) · 173 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: FFmpeg media decoder implementation. Provides video/audio decoding, frame scaling,
// audio resampling, metadata extraction for the files libfiles cannot describe, hardware acceleration
// support, decode-thread preparation of pictures for upload, and the HDR-to-SDR tone mapping cube.
// A played file's streams and tags are described by libfiles' reading of its container. Subtitles are
// decoded here, a stream's as the read thread meets its packets and a sidecar's whole, into av_subtitle's
// events.
#include "pch.h"
#include "av_format.h"
#include "av_player.h"
#include "av_sid.h"
#include "metadata.h"
#include "files.h"
#include "libfiles/media.h"
// Both of these are MSVC dialect repairs. excpt.h has no equivalent elsewhere, and __restrict__ is
// a real keyword on GCC and Clang: defining it away there would strip the qualifier FFmpeg's
// headers rely on rather than supply one MSVC lacks.
#ifdef _MSC_VER
#include <excpt.h>
#define __restrict__
#endif
#define __STDC_CONSTANT_MACROS
#define FF_API_PIX_FMT 0
extern "C" {
#include "libavformat/avformat.h"
#include "libavutil/display.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/mastering_display_metadata.h"
#include "libavutil/pixdesc.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include "libavcodec/avcodec.h"
#include "libavutil/frame.h"
#include "libavutil/hwcontext.h"
}
df_assert_movable(av_stream_info);
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
static void av_log(void*, const int level, const char* format, va_list argList)
{
#ifdef _DEBUG
if (level <= AV_LOG_WARNING)
{
if (strstr(format, "%td") == nullptr && strstr(format, "%ti") == nullptr) // Don't handle '%td'
{
const auto length = _vscprintf(format, argList);
std::string result(length + 1u, 0);
vsprintf_s(result.data(), length + 1u, format, argList);
core::debug_output(result);
}
}
#endif
}
void av_initialise()
{
av_log_set_level(AV_LOG_WARNING);
av_log_set_callback(av_log);
}
std::vector<av_codec_doc> av_supported_codecs()
{
std::vector<av_codec_doc> result;
const AVCodec* codec = nullptr;
void* iter = nullptr;
while ((codec = av_codec_iterate(&iter)) != nullptr)
{
if (!av_codec_is_decoder(codec))
{
continue;
}
auto media_type = av_codec_media_type::other;
switch (codec->type)
{
case AVMEDIA_TYPE_VIDEO:
media_type = av_codec_media_type::video;
break;
case AVMEDIA_TYPE_AUDIO:
media_type = av_codec_media_type::audio;
break;
default:
continue; // only document video and audio codecs
}
result.emplace_back(av_codec_doc{
codec->name ? codec->name : "",
codec->long_name ? codec->long_name : "",
media_type
});
}
return result;
}
static double calc_duration(int64_t t, const AVRational& base, const int64_t start)
{
if (t == AV_NOPTS_VALUE) t = 0;
if (start != AV_NOPTS_VALUE) t -= start;
// Scale in double: a 64-bit timestamp times a large time-base numerator overflows.
return static_cast<double>(t) * base.num / base.den;
}
static double calc_duration(int64_t t, const int64_t& start)
{
if (t == AV_NOPTS_VALUE) t = 0;
if (start != AV_NOPTS_VALUE) t -= start;
return t / static_cast<double>(AV_TIME_BASE);
}
static int hex_char_to_int(const char byte)
{
if (byte >= '0' && byte <= '9') return byte - '0';
if (byte >= 'a' && byte <= 'f') return byte - 'a' + 10;
if (byte >= 'A' && byte <= 'F') return byte - 'A' + 10;
return 0;
}
static std::vector<uint8_t> unescape_xmp(const char* sz)
{
std::string result;
const auto len = strlen(sz);
result.reserve(len);
for (auto i = 0u; i < len; i++)
{
auto c = sz[i];
if (c == '\\')
{
if (i + 3 < len && sz[i + 1] == 'x')
{
c = hex_char_to_int(sz[i + 2]) << 4 |
hex_char_to_int(sz[i + 3]);
i += 3;
}
}
result += c;
}
return {result.data(), result.data() + result.size()};
}
static int64_t codec_working_bytes_per_pixel(const AVCodecID codec_id)
{
switch (codec_id)
{
case AV_CODEC_ID_MJPEG:
case AV_CODEC_ID_MJPEGB:
case AV_CODEC_ID_LJPEG:
// Progressive 4:4:4 JPEG/MJPEG can hold full sample planes plus coefficient and
// non-zero-count arrays before the BGRA destination exists. Ten bytes per pixel is a
// conservative admission bound for that finite working set.
return 10;
default:
return 4;
}
}
static int64_t codec_pixel_ceiling(const AVCodecID codec_id)
{
if (render::max_decode_bytes <= 0) return 0;
return std::max<int64_t>(1, render::max_decode_bytes / codec_working_bytes_per_pixel(codec_id));
}
static void set_probe_decode_ceiling(AVDictionary** const opts, const AVCodecID codec_id)
{
const auto max_pixels = codec_pixel_ceiling(codec_id);
if (max_pixels > 0) av_dict_set_int(opts, "max_pixels", max_pixels, 0);
}
static AVDictionary** alloc_stream_probe_options(const AVFormatContext* const fc)
{
if (!fc || fc->nb_streams == 0 || render::max_decode_bytes <= 0) return nullptr;
auto** result = static_cast<AVDictionary**>(av_calloc(fc->nb_streams, sizeof(AVDictionary*)));
if (!result) return nullptr;
for (unsigned i = 0; i < fc->nb_streams; ++i)
{
const auto* const stream = fc->streams[i];
if (stream && stream->codecpar) set_probe_decode_ceiling(&result[i], stream->codecpar->codec_id);
}
return result;
}
static void free_stream_probe_options(AVDictionary*** const opts, const unsigned count)
{
if (!opts || !*opts) return;
for (unsigned i = 0; i < count; ++i) av_dict_free(&(*opts)[i]);
av_freep(opts);
}
static bool reject_over_budget_codec_working(load_diagnostic* const diagnostic, const AVCodecID codec_id,
const sizei source_dimensions, const std::string_view format)
{
if (diagnostic) diagnostic->source_dimensions = source_dimensions;
const auto bytes = static_cast<int64_t>(source_dimensions.cx) * source_dimensions.cy *
codec_working_bytes_per_pixel(codec_id);
if (bytes <= render::max_decode_bytes) return false;
if (diagnostic) diagnostic->over_budget = true;
core::log(__FUNCTION__,
std::format("{} {} x {} needs {} of codec working storage, over the {} budget", format, source_dimensions.cx,
source_dimensions.cy, platform::format_size(core::file_size(bytes)),
platform::format_size(core::file_size(render::max_decode_bytes))));
return true;
}
static bool frame_palette_uses_alpha(const AVFrame& frame)
{
if (!frame.data[0] || !frame.data[1] || frame.width <= 0 || frame.height <= 0) return false;
std::array<bool, 256> used{};
for (auto y = 0; y < frame.height; ++y)
{
const auto* const line = frame.data[0] + static_cast<ptrdiff_t>(y) * frame.linesize[0];
for (auto x = 0; x < frame.width; ++x)
{
used[line[x]] = true;
}
}
const auto* const palette = std::bit_cast<const uint32_t*>(frame.data[1]);
for (auto index = 0u; index < used.size(); ++index)
{
if (used[index] && ((palette[index] >> 24) & 0xff) != 0xff) return true;
}
return false;
}
static bool frame_packed_alpha_is_used(const AVFrame& frame, const AVPixFmtDescriptor& desc)
{
if (desc.nb_components < 4 || frame.width <= 0 || frame.height <= 0) return false;
const auto alpha = desc.comp[desc.nb_components - 1];
if (alpha.depth != 8 || alpha.plane < 0 || alpha.plane >= 4 || !frame.data[alpha.plane]) return true;
auto all_zero = true;
auto all_opaque = true;
for (auto y = 0; y < frame.height; ++y)
{
const auto* const line = frame.data[alpha.plane] + static_cast<ptrdiff_t>(y) * frame.linesize[alpha.plane];
for (auto x = 0; x < frame.width; ++x)
{
const auto a = line[x * alpha.step + alpha.offset];
all_zero &= a == 0;
all_opaque &= a == 0xff;
if (!all_zero && !all_opaque) return true;
}
}
return false;
}
static bool av_frame_uses_alpha(const AVFrame& frame)
{
const auto fmt = static_cast<AVPixelFormat>(frame.format);
const auto* const desc = av_pix_fmt_desc_get(fmt);
if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_ALPHA)) return false;
if (fmt == AV_PIX_FMT_PAL8) return frame_palette_uses_alpha(frame);
return frame_packed_alpha_is_used(frame, *desc);
}
static std::string normalize_still_extension_hint(const std::string_view extension_hint)
{
if (extension_hint.empty() || extension_hint.front() == '.') return std::string(extension_hint);
return std::format(".{}", extension_hint);
}
static bool tga_declares_alpha(const core::cspan data, const std::string_view extension_hint)
{
if (core::icmp(extension_hint, ".tga") != 0 || data.size < 18) return true;
if (data.data[16] != 32) return true;
return (data.data[17] & 0x0f) != 0;
}
static sizei hinted_tga_dimensions(const core::cspan data, const std::string_view extension_hint)
{
if (core::icmp(extension_hint, ".tga") != 0 || data.size < 18) return {};
return {
static_cast<int>(data.data[12] | (data.data[13] << 8)),
static_cast<int>(data.data[14] | (data.data[15] << 8))
};
}
static sizei hinted_bmp_dimensions(const core::cspan data, const std::string_view extension_hint)
{
if (core::icmp(extension_hint, ".bmp") != 0 || data.size < 26 || data.data[0] != 'B' || data.data[1] != 'M')
{
return {};
}
const auto width = static_cast<int32_t>(data.data[18] | (data.data[19] << 8) | (data.data[20] << 16) |
(data.data[21] << 24));
const auto height = static_cast<int32_t>(data.data[22] | (data.data[23] << 8) | (data.data[24] << 16) |
(data.data[25] << 24));
return {std::abs(width), std::abs(height)};
}
static bool reject_hinted_over_budget_still(load_diagnostic* const diagnostic, const core::cspan data,
const std::string_view extension_hint)
{
if (const auto tga_dimensions = hinted_tga_dimensions(data, extension_hint); !tga_dimensions.is_empty())
{
return reject_over_budget_source(diagnostic, tga_dimensions, "ffmpeg");
}
if (const auto bmp_dimensions = hinted_bmp_dimensions(data, extension_hint); !bmp_dimensions.is_empty())
{
return reject_over_budget_source(diagnostic, bmp_dimensions, "ffmpeg");
}
return false;
}
// A display matrix's clockwise turn, normalised onto [0,360), and whether it mirrors the picture before
// turning it. Shared by the container-level (stream) and frame-level side data so both map onto the same
// set of orientations, and read as libfiles reads a container's transform, so the player shows a file as
// its scan does: a transform that mirrors has a negative determinant, and undoing the mirror leaves the turn.
struct display_turn
{
double rotation = 0.0;
bool mirrored = false;
};
static display_turn turn_from_display_matrix(const uint8_t* const data, const size_t size)
{
if (!data || size < 9 * sizeof(int32_t))
{
return {};
}
int32_t matrix[9];
std::memcpy(matrix, data, sizeof(matrix));
display_turn result;
result.mirrored = static_cast<double>(matrix[0]) * matrix[4] - static_cast<double>(matrix[1]) * matrix[3] < 0.0;
if (result.mirrored)
{
const auto negated = [](const int32_t v) { return v == INT32_MIN ? INT32_MAX : -v; };
matrix[0] = negated(matrix[0]);
matrix[1] = negated(matrix[1]);
}
const auto theta = -av_display_rotation_get(matrix);
result.rotation = theta - 360.0 * floor(theta / 360.0 + 0.9 / 360.0);
return result;
}
static display_turn get_display_turn(const AVStream* const st)
{
const AVPacketSideData* side_data = av_packet_side_data_get(st->codecpar->coded_side_data,
st->codecpar->nb_coded_side_data,
AV_PKT_DATA_DISPLAYMATRIX);
return side_data ? turn_from_display_matrix(side_data->data, side_data->size) : display_turn{};
}
// Locates a DV VAUX recording-date (0x62) or recording-time (0x63) pack within a
// raw DV frame. These packs live in the three VAUX DIF blocks (block index 3, 4
// and 5) of each DIF sequence and are duplicated at two pack slots within each
// block. The offsets mirror those written by the DV muxer (libavformat/dvenc.c
// dv_inject_metadata). Returns a pointer to the 5-byte pack, or null.
static const uint8_t* dv_find_vaux_pack(const uint8_t* frame, const size_t frame_size,
const uint8_t pack_id, const int off_a, const int off_b)
{
constexpr int dif_sequence_size = 12000; // 150 DIF blocks * 80 bytes
constexpr int vaux_blocks[] = {80 * 3, 80 * 4, 80 * 5};
for (int seq = 0; seq < 12; ++seq)
{
const int seq_base = seq * dif_sequence_size;
if (static_cast<size_t>(seq_base) >= frame_size) break;
for (const int block : vaux_blocks)
{
for (const int pack : {off_a, off_b})
{
const int offs = seq_base + block + pack;
if (offs >= 0 && static_cast<size_t>(offs) + 5 <= frame_size &&
frame[offs] == pack_id)
{
return &frame[offs];
}
}
}
}
return nullptr;
}
core::date_t dv_extract_rec_datetime(const uint8_t* frame, const size_t frame_size)
{
if (!frame) return {};
const auto* const date_pack = dv_find_vaux_pack(frame, frame_size, 0x62, 13, 58);
if (!date_pack) return {};
// Date pack: PC2 = day, PC3 = month, PC4 = two-digit year (all BCD).
const int day = ((date_pack[2] >> 4) & 0x03) * 10 + (date_pack[2] & 0x0f);
const int month = ((date_pack[3] >> 4) & 0x01) * 10 + (date_pack[3] & 0x0f);
const int year2 = ((date_pack[4] >> 4) & 0x0f) * 10 + (date_pack[4] & 0x0f);
if (day < 1 || day > 31 || month < 1 || month > 12 || year2 > 99) return {};
const int year = year2 < 75 ? 2000 + year2 : 1900 + year2;
// Time pack: PC2 = seconds, PC3 = minutes, PC4 = hours (all BCD). Optional.
int hour = 0, minute = 0, second = 0;
const auto* const time_pack = dv_find_vaux_pack(frame, frame_size, 0x63, 18, 63);
if (time_pack)
{
second = ((time_pack[2] >> 4) & 0x07) * 10 + (time_pack[2] & 0x0f);
minute = ((time_pack[3] >> 4) & 0x07) * 10 + (time_pack[3] & 0x0f);
hour = ((time_pack[4] >> 4) & 0x03) * 10 + (time_pack[4] & 0x0f);
if (hour > 23 || minute > 59 || second > 59)
{
hour = minute = second = 0;
}
}
return {year, month, day, hour, minute, second};
}
// Reads the first full DV video frame from the demuxer and extracts its embedded
// recording date/time. Used for DVCAM / DV-in-AVI files, whose creation date is
// stored inside the DV frames rather than the container.
static core::date_t read_dv_rec_datetime(AVFormatContext* fc, const int video_stream_index)
{
if (!fc || video_stream_index < 0 || video_stream_index >= static_cast<int>(fc->nb_streams)) return {};
// The date is read whether or not the picture is being decoded, and a stream nothing decodes is
// discarded, so the demuxer would otherwise never hand a DV frame back.
auto* const stream = fc->streams[video_stream_index];
const auto previous_discard = stream->discard;
stream->discard = AVDISCARD_DEFAULT;
// Rewind so we read the first recorded frame (a thumbnail extraction may have
// left the demuxer positioned mid-stream).
av_seek_frame(fc, -1, 0, AVSEEK_FLAG_BACKWARD);
core::date_t result;
auto* pkt = av_packet_alloc();
for (int tries = 0; tries < 64 && av_read_frame(fc, pkt) >= 0; ++tries)
{
// A full SD DV frame is 120000 (NTSC) / 144000 (PAL) bytes; require at
// least one DIF sequence so the VAUX pack offsets are in range.
if (pkt->stream_index == video_stream_index && pkt->data && pkt->size >= 12000)
{
result = dv_extract_rec_datetime(pkt->data, static_cast<size_t>(pkt->size));
av_packet_unref(pkt);
if (result.is_valid()) break;
continue;
}
av_packet_unref(pkt);
}
av_packet_free(&pkt);
stream->discard = previous_discard;
return result;
}
static void populate_properties(const AVFormatContext* ctx, file_scan_result& result, const bool with_tags)
{
if (ctx)
{
result.nb_streams = ctx->nb_streams;
result.duration = calc_duration(ctx->duration, AV_NOPTS_VALUE);
// FFmpeg's mov demuxer reads the iTunes 'rtng' atom - the content advisory flag, 0 none,
// 1 explicit, 2 clean - under the shared "rating" key, where an explicit-content marker would
// read as a one-star rating.
const auto is_mov = ctx->iformat && std::string_view(ctx->iformat->name).starts_with("mov");
const AVDictionaryEntry* tag = nullptr;
while (with_tags && (tag = av_dict_get(ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
{
if (core::icmp(tag->key, "xmp") == 0 || core::icmp(tag->key, "id3v2_priv.XMP") == 0)
{
result.metadata.xmp = unescape_xmp(tag->value);
}
else if (is_mov && core::icmp(tag->key, "rating") == 0)
{
result.ffmpeg_metadata.emplace_back(std::string_view{"itunes_advisory"}, core::utf8_cast(tag->value));
}
else
{
result.ffmpeg_metadata.emplace_back(tag->key, core::utf8_cast(tag->value));
}
}
}
}
static AVSampleFormat to_AVSampleFormat(const prop::audio_sample_t sample_fmt)
{
switch (sample_fmt)
{
case prop::audio_sample_t::none: return AV_SAMPLE_FMT_NONE;
case prop::audio_sample_t::unsigned_8bit: return AV_SAMPLE_FMT_U8;
case prop::audio_sample_t::signed_16bit: return AV_SAMPLE_FMT_S16;
case prop::audio_sample_t::signed_32bit: return AV_SAMPLE_FMT_S32;
case prop::audio_sample_t::signed_64bit: return AV_SAMPLE_FMT_S64;
case prop::audio_sample_t::signed_float: return AV_SAMPLE_FMT_FLT;
case prop::audio_sample_t::signed_double: return AV_SAMPLE_FMT_DBL;
case prop::audio_sample_t::unsigned_planar_8bit: return AV_SAMPLE_FMT_U8P;
case prop::audio_sample_t::signed_planar_16bit: return AV_SAMPLE_FMT_S16P;
case prop::audio_sample_t::signed_planar_32bit: return AV_SAMPLE_FMT_S32P;
case prop::audio_sample_t::signed_planar_64bit: return AV_SAMPLE_FMT_S64P;
case prop::audio_sample_t::planar_float: return AV_SAMPLE_FMT_FLTP;
case prop::audio_sample_t::planar_double: return AV_SAMPLE_FMT_DBLP;
default: ;
}
return AV_SAMPLE_FMT_NONE;
}
static prop::audio_sample_t to_sample_type(const AVSampleFormat format)
{
switch (format)
{
case AV_SAMPLE_FMT_U8: return prop::audio_sample_t::unsigned_8bit;
case AV_SAMPLE_FMT_S16: return prop::audio_sample_t::signed_16bit;
case AV_SAMPLE_FMT_S32: return prop::audio_sample_t::signed_32bit;
case AV_SAMPLE_FMT_FLT: return prop::audio_sample_t::signed_float;
case AV_SAMPLE_FMT_DBL: return prop::audio_sample_t::signed_double;
case AV_SAMPLE_FMT_U8P: return prop::audio_sample_t::unsigned_planar_8bit;
case AV_SAMPLE_FMT_S16P: return prop::audio_sample_t::signed_planar_16bit;
case AV_SAMPLE_FMT_S32P: return prop::audio_sample_t::signed_planar_32bit;
case AV_SAMPLE_FMT_FLTP: return prop::audio_sample_t::planar_float;
case AV_SAMPLE_FMT_DBLP: return prop::audio_sample_t::planar_double;
case AV_SAMPLE_FMT_S64: return prop::audio_sample_t::signed_64bit;
case AV_SAMPLE_FMT_S64P: return prop::audio_sample_t::signed_planar_64bit;
default:
case AV_SAMPLE_FMT_NONE:
break;
}
return prop::audio_sample_t::none;
}
// The orientation a turn shows the picture with, numbered as EXIF numbers it: a quarter turn exactly, as a
// container states one, after the mirror when there is one; any other angle is shown unturned.
static core::orientation calc_orientation_impl(const display_turn& turn)
{
const auto rr = core::round(turn.rotation);
const auto quarter = rr == 90 || rr == 180 || rr == 270 ? rr : 0;
return static_cast<core::orientation>(libfiles::orientation_from_turn(quarter, turn.mirrored));
}
// The codec in Diffractor's terms: FFmpeg's codec name, but "mpeg2" for "mpeg2video", "dv" for
// "dvvideo" and "pcm" for every linear PCM layout, whose depth is the sample type - the names libfiles
// gives the codecs it reads, so a file reads alike whichever described it.
static core::cached short_codec_name(const AVCodecParameters* const codec)
{
if (!codec || codec->codec_id == AV_CODEC_ID_NONE) return {};
switch (codec->codec_id)
{
case AV_CODEC_ID_MPEG1VIDEO: return "mpeg1"_c;
case AV_CODEC_ID_MPEG2VIDEO: return "mpeg2"_c;
case AV_CODEC_ID_DVVIDEO: return "dv"_c;
case AV_CODEC_ID_PCM_ALAW: return "alaw"_c;
case AV_CODEC_ID_PCM_MULAW: return "mulaw"_c;
default: break;
}
const std::string_view name = avcodec_get_name(codec->codec_id);
if (name.starts_with("pcm_")) return "pcm"_c;
return core::cache(name);
}
// A pixel format as chroma and depth, as libfiles names a stream's: "yuv420", "yuv422 10bit", "gray",
// "rgb". Empty when unset or unknown.
static core::cached own_pixel_format(const int format)
{
const auto* const desc = format == AV_PIX_FMT_NONE
? nullptr
: av_pix_fmt_desc_get(static_cast<AVPixelFormat>(format));
if (!desc) return {};
const auto alpha = (desc->flags & AV_PIX_FMT_FLAG_ALPHA) != 0;
std::string name;
if (desc->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_BAYER))
{
name = alpha ? "rgba" : "rgb";
}
else if (desc->nb_components <= 2)
{
name = alpha ? "graya" : "gray";
}
else
{
const auto w = desc->log2_chroma_w;
const auto h = desc->log2_chroma_h;
const auto* const chroma = w == 1 && h == 1
? "420"
: w == 1 && h == 0
? "422"
: w == 0 && h == 0
? "444"
: w == 2 && h == 0
? "411"
: w == 2 && h == 2
? "410"
: w == 0 && h == 1
? "440"
: nullptr;
if (!chroma) return {};
name = std::format("{}{}", alpha ? "yuva" : "yuv", chroma);
}
if (desc->comp[0].depth > 8) name += std::format(" {}bit", desc->comp[0].depth);
return core::cache(name);
}
// The audio sample type as the stream codes it: a depth for linear PCM and lossless codecs, none for a
// lossy one, whose samples have no depth until a decoder gives them one.
static prop::audio_sample_t coded_sample_type(const AVCodecParameters* const codec)
{
const auto* const desc = codec ? avcodec_descriptor_get(codec->codec_id) : nullptr;
if (!desc || (desc->props & AV_CODEC_PROP_LOSSLESS) == 0 || (desc->props & AV_CODEC_PROP_LOSSY) != 0)
{
return prop::audio_sample_t::none;
}
auto bits = codec->bits_per_raw_sample;
if (bits <= 0) bits = av_get_bits_per_sample(codec->codec_id);
if (bits <= 0) bits = codec->bits_per_coded_sample;
const auto id = codec->codec_id;
const auto is_float = id == AV_CODEC_ID_PCM_F16LE || id == AV_CODEC_ID_PCM_F24LE || id == AV_CODEC_ID_PCM_F32BE ||
id == AV_CODEC_ID_PCM_F32LE || id == AV_CODEC_ID_PCM_F64BE || id == AV_CODEC_ID_PCM_F64LE;
return coded_sample_type(static_cast<unsigned>(std::max(bits, 0)), is_float);
}
static void populate_audio_properties(const AVStream* const s, file_scan_result& result)
{
auto* codec = s->codecpar;
if (codec && codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
if (const auto name = short_codec_name(codec); !core::is_empty(name)) result.audio_codec = name;
result.audio_sample_rate = codec->sample_rate;
result.audio_channels = codec->ch_layout.nb_channels;
result.audio_sample_type = coded_sample_type(codec);
}
}
static void populate_video_properties(const AVStream* const s, file_scan_result& result)
{
const auto* codec = s->codecpar;
if (codec && codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
if (const auto name = short_codec_name(codec); !core::is_empty(name)) result.video_codec = name;
result.width = codec->width;
result.height = codec->height;
// Apply the pixel (sample) aspect ratio so anamorphic / non-square-pixel
// video reports its display dimensions rather than the stored frame size,
// matching the aspect used during playback (#78).
auto sar = codec->sample_aspect_ratio;
if (sar.num == 0 || sar.den == 0 || sar.num == sar.den)
{
sar = s->sample_aspect_ratio;
}
if (sar.num > 0 && sar.den > 0 && sar.num != sar.den && codec->width > 0 && codec->height > 0)
{
const auto w = static_cast<int64_t>(codec->width);
result.height = static_cast<uint32_t>(core::mul_div(
w, static_cast<int64_t>(sar.den) * codec->height, static_cast<int64_t>(sar.num) * w));
}
if (const auto name = own_pixel_format(codec->format); !core::is_empty(name))
{
result.pixel_format = name;
}
result.orientation = calc_orientation_impl(get_display_turn(s));
}
}
int try_avcodec_send_packet(AVCodecContext* avctx, const AVPacket* avpkt)
{
// A fault here (typically in a hardware decoder / GPU driver) is deliberately NOT caught:
// it propagates to the global unhandled-exception handler so the app writes a minidump,
// reports the crash, and is relaunched by Application Restart. The persisted hardware-decode
// crash guard (see init_streams / apply_gpu_crash_guard) then disables HW video decoding on
// the next launch. Swallowing the fault here would instead leave playback silently broken.
return avcodec_send_packet(avctx, avpkt);
}
// Number of live decoders currently using hardware video decode. The crash guard flag is
// written on the 0->1 transition and cleared on the 1->0 transition so concurrent decoders
// (playback plus any preview) keep it set for as long as any hardware decode is in progress.
static std::atomic<int> g_hw_decode_sessions{0};
// The layout of a hardware frame's surfaces; AV_PIX_FMT_NONE for a frame in system memory.
static int hw_surface_format(const AVFrame& frame)
{
const auto* const frames = frame.hw_frames_ctx
? std::bit_cast<const AVHWFramesContext*>(frame.hw_frames_ctx->data)
: nullptr;
return frames ? frames->sw_format : AV_PIX_FMT_NONE;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
class av_frame final : public render::video_frame
{
public:
double time = 0.0;
int gen = 0;
core::orientation orientation = core::orientation::top_left;
bool eof = false;
// Allocated by FFmpeg rather than held by value: the struct's size is the library's to change,
// and only av_frame_alloc is sized to the library actually linked.
AVFrame* frm = nullptr;
// The picture converted for upload on the decode thread, so presenting it is an upload and nothing
// more. Once this exists frm is released, so the queue holds the picture only once.
core::const_surface_ptr surface;
// For an HDR picture the renderer shares straight from the decoder: the mapping to SDR its shader
// applies, made here on the decode thread because making it is far too slow for a paint.
core::tone_map_lut_ptr tone_map;
bool operator<(const av_frame& other) const
{
return gen == other.gen ? time < other.time : gen < other.gen;
}
av_frame() : frm(av_frame_alloc())
{
if (!frm) throw std::bad_alloc();
}
av_frame(av_frame&& other) : av_frame()
{
av_frame_move_ref(frm, other.frm);
copy_properties(other);
}
av_frame(const av_frame& other) : av_frame()
{
av_frame_ref(frm, other.frm);
copy_properties(other);
}
av_frame& operator=(const av_frame& other)
{
if (this != &other)
{
av_frame_unref(frm);
av_frame_ref(frm, other.frm);
copy_properties(other);
}
return *this;
}
av_frame& operator=(av_frame&& other) noexcept
{
if (this != &other)
{
av_frame_unref(frm);
av_frame_move_ref(frm, other.frm);
copy_properties(other);
}
return *this;
}
~av_frame()
{
av_frame_free(&frm);
}
bool is_empty() const
{
if (surface) return surface->empty();
return frm->width == 0 || frm->height == 0 || frm->data[0] == nullptr;
}
core::const_surface_ptr prepared_surface() const override
{
return surface;
}
render::video_picture picture() const override;
void request_cpu_frames() const override
{
av_request_cpu_video_frames(hw_surface_format(*frm));
}
private:
void copy_properties(const av_frame& other)
{
gen = other.gen;
time = other.time;
orientation = other.orientation;
eof = other.eof;
surface = other.surface;
tone_map = other.tone_map;
}
};
class av_packet
{
public:
AVPacket* pkt = nullptr;
int seek_ver = 0;
bool eof = false;
av_packet() : pkt(av_packet_alloc())
{
if (!pkt) throw std::bad_alloc();
}
av_packet(av_packet&& other) : av_packet()
{
av_packet_move_ref(pkt, other.pkt);
seek_ver = other.seek_ver;
eof = other.eof;
}
av_packet(const av_packet& other) : av_packet()
{
copy(other.pkt);
seek_ver = other.seek_ver;
eof = other.eof;
}
av_packet& operator=(const av_packet& other)
{
if (this != &other)
{
av_packet copied(other);
*this = std::move(copied);
}
return *this;
}
av_packet& operator=(av_packet&& other) noexcept
{
if (this != &other)
{
av_packet_unref(pkt);
av_packet_move_ref(pkt, other.pkt);
seek_ver = other.seek_ver;
eof = other.eof;
}
return *this;
}
~av_packet() noexcept
{
av_packet_free(&pkt);
}
void copy(const AVPacket* src_avpkt) const
{
if (src_avpkt == pkt) return;
av_packet_unref(pkt);
const auto result = av_packet_ref(pkt, src_avpkt);
if (result < 0) throw app_exception(std::format("Cannot reference audio/video packet: {}", result));
}
void move(AVPacket* src_avpkt) const
{
av_packet_move_ref(pkt, src_avpkt);
}
bool is_empty() const
{
return pkt->data == nullptr;
};
};
size_t av_queued_payload_bytes(const av_packet_ptr& p)
{
return p && p->pkt && p->pkt->size > 0 ? static_cast<size_t>(p->pkt->size) : 0;
}
size_t av_queued_payload_bytes(const av_frame_ptr& f)
{
if (!f) return 0;
if (f->surface) return f->surface->size();
const auto& frm = *f->frm;
// A hardware frame's own buffer is a handle, not pixels. What it costs is the pool surface it
// keeps checked out, and that pool is allocated in full when the stream opens, so charging the
// surface is what makes one read-ahead budget size both the queue and the pool.
if (frm.hw_frames_ctx)
{
const auto* const ctx = std::bit_cast<const AVHWFramesContext*>(frm.hw_frames_ctx->data);
const auto bytes = av_image_get_buffer_size(ctx->sw_format, ctx->width, ctx->height, 1);
return bytes > 0 ? static_cast<size_t>(bytes) : 0;
}
size_t result = 0;
for (const auto* const buf : frm.buf)
{
if (buf) result += buf->size;
}
for (auto i = 0; i < frm.nb_extended_buf; ++i)
{
if (frm.extended_buf[i]) result += frm.extended_buf[i]->size;
}
return result;
}
av_pts_correction::av_pts_correction()
{
clear();
}
void av_pts_correction::clear()
{
last_output = AV_NOPTS_VALUE;
frame_interval = 0;
}
int64_t av_pts_correction::guess(const int64_t best_effort, const int64_t pts, const int64_t dts,
const int64_t duration)
{
// Step 1 - take FFmpeg's own answer. avcodec_receive_frame runs guess_correct_pts over
// (pts, pkt_dts) and publishes the result as best_effort_timestamp, using fault counters
// that avcodec_flush_buffers resets with the decoder. Running a second, separately reset
// copy of that heuristic here could only diverge from the decoder's view.
int64_t result = best_effort;
if (result == AV_NOPTS_VALUE) result = pts;
if (result == AV_NOPTS_VALUE) result = dts;
// Step 2 - guarantee a usable, strictly increasing result. Some codecs and
// containers (raw video, MJPEG sequences, damaged MPEG-TS) supply no usable
// timestamp or one that fails to advance. Emitting a stale/duplicate value
// makes the presenter treat the frame as "not newer" and stall, so instead we
// extend the timeline by one frame interval - preferring the decoder-reported
// duration and otherwise the cadence learned from earlier frames.
if (result != AV_NOPTS_VALUE && last_output != AV_NOPTS_VALUE && result > last_output)
{
// Smallest positive step seen, not the most recent one: a gap in a damaged stream
// would otherwise become the synthetic step and run the timeline away from the media.
const auto observed = result - last_output;
frame_interval = frame_interval > 0 ? std::min(frame_interval, observed) : observed;
}
const auto step = duration > 0 ? duration : (frame_interval > 0 ? frame_interval : 1);