-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathMovieFFMpeg.cpp
More file actions
6236 lines (5483 loc) · 240 KB
/
Copy pathMovieFFMpeg.cpp
File metadata and controls
6236 lines (5483 loc) · 240 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
//******************************************************************************
//
// Copyright (C) 2025 Autodesk, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
//******************************************************************************
#include <MovieFFMpeg/MovieFFMpeg.h>
#include <TwkFB/Operations.h>
#include <TwkExc/Exception.h>
#include <TwkMovie/Exception.h>
#include <TwkMovie/Movie.h>
#include <TwkMovie/ReformattingMovie.h>
#include <TwkAudio/Audio.h>
#include <TwkAudio/Interlace.h>
#include <TwkFB/FastMemcpy.h>
#include <TwkFB/FastConversion.h>
#include <TwkUtil/EnvVar.h>
#include <TwkUtil/Timer.h>
#include <TwkUtil/PathConform.h>
#include <TwkUtil/File.h>
#include <TwkUtil/sgcHop.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <array>
#include <string_view>
#include <stl_ext/stl_ext_algo.h>
#include <stl_ext/string_algo.h>
#include <string>
#include <set>
#include <limits>
#include <cmath>
#include <mutex>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/algorithm/string.hpp>
#include <mp4v2Utils/mp4v2Utils.h>
#include <cstring>
#include <IOhtj2k/IOhtj2k.h>
#if defined(RV_FFMPEG_USE_VIDEOTOOLBOX)
#include <VideoToolbox/VideoToolbox.h>
#endif
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/timecode.h>
#include <libavutil/display.h>
#include <libswscale/swscale.h>
}
#if defined(RV_USE_APPLE_PRORES_SDK)
#include <AppleProRes.h>
#endif
static ENVVAR_BOOL(evUseUploadedMovieForStreaming, "RV_SHOTGRID_USE_UPLOADED_MOVIE_FOR_STREAMING", false);
namespace TwkMovie
{
using namespace std;
using namespace TwkUtil;
using namespace TwkFB;
using namespace TwkMovie;
using namespace TwkAudio;
#define TWK_AVFORMAT_PROBESIZE UINT_MAX
#define RV_OUTPUT_FFMPEG_FMT AV_PIX_FMT_RGBA64
#define FPS_PRECISION_LIMIT 1000 // 5 sig figs
#define RV_OUTPUT_VIDEO_CODEC "mjpeg"
#define RV_OUTPUT_AUDIO_CODEC "pcm_s16be"
static bool isHEVCElementaryStream(const AVFormatContext* formatContext, const AVStream* stream, const string& filename)
{
if (!stream || !stream->codecpar || stream->codecpar->codec_id != AV_CODEC_ID_H265)
return false;
if (formatContext && formatContext->iformat && formatContext->iformat->name && !std::strcmp(formatContext->iformat->name, "hevc"))
{
return true;
}
string ext = boost::filesystem::path(filename).extension().string();
boost::algorithm::to_lower(ext);
return ext == ".265" || ext == ".h265" || ext == ".hevc";
}
#if 0
#define DB_LOG_LEVEL AV_LOG_ERROR
#define DB_GENERAL 0x001
#define DB_VIDEO 0x002
#define DB_AUDIO 0x004
#define DB_METADATA 0x008
#define DB_AUDIO_SAMPLES 0x010
#define DB_TIMING 0x020
#define DB_WRITE 0x040
#define DB_DURATION 0x080
#define DB_SUBTITLES 0x100
#define DB_TIMESTAMPS 0x200
#define DB_MOST 0x3ef
#define DB_ALL 0xfff
#define DB_LEVEL (DB_GENERAL | DB_MOST)
#define DB(x) \
if (DB_GENERAL & DB_LEVEL) \
{ \
stringstream msg; \
msg << "INFO [" << this << "," << setw(7) << setfill('0') << this->m_dbline++ << setw(0) << "]: MovieFFMpeg: " << x << endl; \
cerr << msg.str(); \
}
#define DBL(level, x) \
if (level & DB_LEVEL) \
{ \
stringstream msg; \
msg << "INFO [" << this << "," << setw(7) << setfill('0') << this->m_dbline++ << setw(0) << "," << level \
<< "]: MovieFFMpeg: " << x << endl; \
cerr << msg.str(); \
}
#else
#define DB_LOG_LEVEL AV_LOG_WARNING
#define DB_LEVEL 0x0
#define DB(x)
#define DBL(level, x)
#endif
//----------------------------------------------------------------------
//
// Helper Structs & Classes
//
//----------------------------------------------------------------------
//
// The MovieTimer and TimingDetails debugging helper classes that are used
// to keep track of time spent in various parts of the seeking and decoding
// loops.
//
struct MovieTimer
{
MovieTimer()
: duration(0)
, runs(0)
{
timer = new TwkUtil::Timer();
};
~MovieTimer() { delete timer; };
void start() { timer->start(); };
double stop()
{
duration += timer->elapsed();
runs++;
return timer->elapsed();
}
TwkUtil::Timer* timer;
double duration;
int runs;
};
struct TimingDetails
{
TimingDetails() {};
~TimingDetails()
{
map<string, MovieTimer*>::iterator timerItr;
for (timerItr = m_timers.begin(); timerItr != m_timers.end(); timerItr++)
{
delete m_timers[timerItr->first];
}
};
void startTimer(string name)
{
if (m_timers.find(name) == m_timers.end())
{
m_timers[name] = new MovieTimer();
}
m_timers[name]->start();
};
double pauseTimer(string name) { return m_timers[name]->stop(); };
string summary()
{
ostringstream summary;
summary << "timing summary (time/runs = avg) ";
map<string, MovieTimer*>::iterator timerItr;
for (timerItr = m_timers.begin(); timerItr != m_timers.end(); timerItr++)
{
string name = timerItr->first;
summary << name << ": " << m_timers[name]->duration << " / " << m_timers[name]->runs << " = "
<< m_timers[name]->duration / float(m_timers[name]->runs) << " ";
}
return summary.str();
};
map<string, MovieTimer*> m_timers;
};
struct AudioState
{
AudioState() { layout = UnknownLayout; };
~AudioState() {};
ChannelsMap chmap;
ChannelsVector channels;
int channelsPerTrack;
Layout layout;
};
//
// AudioTrack and VideoTrack are used by both MovieFFMpegReader and
// MovieFFMpegWriter to store additional information about the AVStreams in
// each file. These objects contain special AVClasses that are used to both
// decode and encode as appropriate for reading and writing.
//
struct AudioTrack
{
AudioTrack()
: audioPacket(0)
, audioFrame(0)
, lastDecodedAudio(AV_NOPTS_VALUE)
, lastEncodedAudio(0)
, bufferStart(AV_NOPTS_VALUE)
, bufferEnd(AV_NOPTS_VALUE)
, bufferLength(0)
, isOpen(false)
, numChannels(0)
, start(0)
, desired(0)
, bufferPointer(0)
, avCodecContext(0)
{
audioFrame = av_frame_alloc();
audioPacket = av_packet_alloc();
};
~AudioTrack()
{
if (audioPacket)
av_packet_free(&audioPacket);
if (audioFrame)
av_frame_free(&audioFrame);
};
AudioTrack& initFrom(const AudioTrack* t)
{
number = t->number;
numChannels = t->numChannels;
return *this;
}
int number;
int numChannels;
bool isOpen;
int64_t lastDecodedAudio;
int64_t lastEncodedAudio;
int64_t bufferStart;
int64_t bufferEnd;
int64_t bufferLength;
AVPacket* audioPacket;
AVFrame* audioFrame;
SampleTime start;
SampleTime desired;
float* bufferPointer;
AVCodecContext* avCodecContext;
};
struct HardwareContext
{
AVPixelFormat pixelFormat;
AVBufferRef* deviceContext;
};
struct VideoTrack
{
VideoTrack()
: videoPacket(0)
, videoFrame(0)
, lastDecodedVideo(-1)
, lastEncodedVideo(0)
, nextSyntheticTS(0)
, imgConvertContext(0)
, isOpen(false)
, useOpenJPH(false)
, useAppleProRes(false)
, rotate(false)
, colrType("")
, avCodecContext(0)
, hardwareContext({AV_PIX_FMT_NONE, nullptr})
{
videoFrame = av_frame_alloc();
videoPacket = av_packet_alloc();
inPicture = av_frame_alloc();
outPicture = av_frame_alloc();
};
~VideoTrack()
{
//
// Be paranoid: get rid of these pointers that were borrowed
// from AVFrame. ffmpeg doesn't touch them on deletion, but
// it also doesn't say it won't
//
for (size_t i = 0; i < AV_NUM_DATA_POINTERS; i++)
{
videoFrame->data[i] = 0;
videoFrame->linesize[i] = 0;
}
if (imgConvertContext)
sws_freeContext(imgConvertContext);
if (videoPacket)
av_packet_free(&videoPacket);
if (videoFrame)
av_frame_free(&videoFrame);
av_frame_free(&inPicture);
av_frame_free(&outPicture);
};
VideoTrack& initFrom(const VideoTrack* t)
{
fb.copyFrom(&t->fb);
name = t->name;
useOpenJPH = t->useOpenJPH;
useAppleProRes = t->useAppleProRes;
number = t->number;
rotate = t->rotate;
nextSyntheticTS = t->nextSyntheticTS;
#if defined(RV_USE_APPLE_PRORES_SDK)
appleProResCtx = t->appleProResCtx;
#endif
return *this;
}
string name;
int number;
bool isOpen;
bool rotate;
int lastDecodedVideo;
int lastEncodedVideo;
bool useOpenJPH;
bool useAppleProRes;
set<int64_t> tsSet;
int64_t nextSyntheticTS;
FrameBuffer fb;
struct SwsContext* imgConvertContext;
AVPacket* videoPacket;
AVFrame* videoFrame;
AVFrame* inPicture;
AVFrame* outPicture;
string colrType;
AVCodecContext* avCodecContext;
struct HardwareContext hardwareContext;
#if defined(RV_USE_APPLE_PRORES_SDK)
AppleProResContext appleProResCtx;
#endif
};
//
// Manage limited pool of open contexts.
//
// ContextPool does not open codecs, but does close them if a Reservation
// object is requested, the requested context is closed, and the
// ContextPool size is at it's max.
//
class ContextPool
{
public:
ContextPool(int poolSize)
: m_maxOpenThreads(poolSize)
, m_currentOpenThreads(0)
{
}
private:
//
// Wrapper for AV codec context
//
struct Context
{
Context()
: reader(0)
, streamIndex(-1)
, avContext(0)
, vTrack(0)
, aTrack(0)
, reserved(false)
, inOpenList(false) {};
MovieFFMpegReader* reader;
int streamIndex;
AVCodecContext* avContext;
VideoTrack* vTrack;
AudioTrack* aTrack;
std::list<Context*>::iterator listIterator;
bool reserved;
bool inOpenList;
};
public:
//
// State/lock object for reserved contexts. Contexts are reserved by
// MovieFFMpeg during use, cannot be closed while reserved.
//
class Reservation
{
public:
Reservation(MovieFFMpegReader* reader, int streamIndex);
~Reservation();
private:
Context* m_context;
int m_dbline;
int m_dblline;
};
//
// MovieFFMpeg calls flushContext() when it is going to close the
// context itself.
//
static void flushContext(MovieFFMpegReader* reader, int streamIndex);
private:
typedef std::pair<MovieFFMpegReader*, int> ContextKey;
typedef std::map<ContextKey, Context> ContextMap;
typedef std::list<Context*> ContextList;
typedef boost::mutex Mutex;
typedef boost::lock_guard<Mutex> LockGuard;
ContextMap m_contextMap;
ContextList m_openContexts;
Mutex m_mutex;
int m_maxOpenThreads;
int m_currentOpenThreads;
};
//
// Global pool object:
//
ContextPool* globalContextPool = 0;
void ContextPool::flushContext(MovieFFMpegReader* reader, int streamIndex)
{
if (!globalContextPool)
return;
ContextPool& gcp = *globalContextPool;
LockGuard lock(gcp.m_mutex);
ContextMap::iterator i = gcp.m_contextMap.find(ContextKey(reader, streamIndex));
if (i == gcp.m_contextMap.end())
return;
Context& context = i->second;
if (context.inOpenList)
{
gcp.m_openContexts.erase(context.listIterator);
gcp.m_currentOpenThreads -= context.avContext->thread_count;
}
gcp.m_contextMap.erase(i);
}
ContextPool::Reservation::Reservation(MovieFFMpegReader* reader, int streamIndex)
: m_context(0)
, m_dbline(0)
, m_dblline(0)
{
if (!globalContextPool)
return;
ContextPool& gcp = *globalContextPool;
LockGuard lock(gcp.m_mutex);
//
// Look up Context object, possibly creating an empty one at this
// point.
//
Context& context = gcp.m_contextMap[ContextKey(reader, streamIndex)];
m_context = &context;
context.reserved = true;
context.reader = reader;
context.streamIndex = streamIndex;
//
// If it's already in the list move it to the front now.
//
if (context.inOpenList)
{
gcp.m_openContexts.erase(context.listIterator);
gcp.m_openContexts.push_front(&context);
context.listIterator = gcp.m_openContexts.begin();
}
//
// Make sure there is room in the list, in case we are about to open
// this context.
//
while (gcp.m_currentOpenThreads >= gcp.m_maxOpenThreads)
{
Context& closeContext = *gcp.m_openContexts.back();
gcp.m_openContexts.pop_back();
closeContext.inOpenList = false;
if (closeContext.reserved)
{
//
// XXX Should never happen since reserved Contexts get pushed
// to front of list, but how do we ensure it never happens ?
//
cout << "ERROR: Attempted to reuse reserved context! (" << closeContext.reader->filename() << ")" << endl;
}
else if (closeContext.avContext)
{
DB("closing " << closeContext.reader << " " << closeContext.reader->filename() << ", stream " << closeContext.streamIndex
<< ", threads " << closeContext.avContext->thread_count << endl);
gcp.m_currentOpenThreads -= closeContext.avContext->thread_count;
avcodec_free_context(&closeContext.avContext);
if (closeContext.vTrack)
closeContext.vTrack->isOpen = false;
if (closeContext.aTrack)
closeContext.aTrack->isOpen = false;
}
}
}
ContextPool::Reservation::~Reservation()
{
if (!globalContextPool)
return;
ContextPool& gcp = *globalContextPool;
LockGuard lock(gcp.m_mutex);
Context& context = *m_context;
context.reserved = false;
//
// Make sure the context still exists and we aren't closing.
//
ContextKey key(context.reader, context.streamIndex);
if (gcp.m_contextMap.find(key) == gcp.m_contextMap.end())
return;
//
// If this is the first time we've encountered this Context, it's only
// now that it corresponds to an actual AVCodecContext, so look that up
// and add to Context struct. Also find and remember corresponding
// Track.
//
if (!context.avContext)
{
AVStream* avStream = context.reader->m_avFormatContext->streams[context.streamIndex];
context.reader->trackFromStreamIndex(context.streamIndex, context.vTrack, context.aTrack);
if (context.vTrack)
{
context.avContext = context.vTrack->avCodecContext;
}
else if (context.aTrack)
{
context.avContext = context.aTrack->avCodecContext;
}
}
//
// If the context is not open at this point, something went wrong.
// Otherwise we want to push it to the front of the open list, adding
// it first if necessary.
//
if (!context.avContext)
{
if (context.inOpenList)
{
gcp.m_openContexts.erase(context.listIterator);
context.inOpenList = false;
}
}
else if (gcp.m_openContexts.empty() || gcp.m_openContexts.front() != &context)
{
if (context.inOpenList)
//
// We're going to add it to the front of the list, so remove it
// from it's current location.
//
{
gcp.m_openContexts.erase(context.listIterator);
}
else
//
// It's not in the list, so it's threads are not accounted for yet
// in global thread count, so do that.
//
{
gcp.m_currentOpenThreads += context.avContext->thread_count;
}
gcp.m_openContexts.push_front(&context);
context.inOpenList = true;
context.listIterator = gcp.m_openContexts.begin();
}
}
namespace
{
constexpr int rv_seek_frame_offset = 1;
//----------------------------------------------------------------------
//
// Static Lookups
//
//----------------------------------------------------------------------
//
// Put anything we know about in here: some of these we don't
// actually support. But just in case ....
//
constexpr std::array slowRandomAccessCodecs = {"3iv2"sv,
"3ivd"sv,
"ap41"sv,
"avc1"sv,
"div1"sv,
"div2"sv,
"div3"sv,
"div4"sv,
"div5"sv,
"div6"sv,
"divx"sv,
"dnxhd"sv,
"dx50"sv,
"h263"sv,
"h264"sv,
"i263"sv,
"iv31"sv,
"iv32"sv,
"m4s2"sv,
"mp42"sv,
"mp43"sv,
"mp4s"sv,
"mp4v"sv,
"apv"sv,
"mpeg4"sv,
"mpg1"sv,
"mpg3"sv,
"mpg4"sv,
"pim1"sv,
"png"sv,
"s263"sv,
"svq1"sv,
"svq3"sv,
"u263"sv,
"vc1"sv,
"vc1_vdpau"sv,
"vc1image"sv,
"viv1"sv,
"wmv3"sv,
"wmv3_vdpau"sv,
"wmv3image"sv,
"xith"sv,
"xvid"sv,
"libdav1d"sv
#if defined(RV_FFMPEG_USE_VIDEOTOOLBOX) || defined(RV_USE_APPLE_PRORES_SDK)
,
"prores"sv
#endif
};
const char* supportedEncodingCodecsArray[] = {"dvvideo", "libx264", "mjpeg", "pcm_s16be", "rawvideo", 0};
const char* metadataFieldsArray[] = {"album", "album_artist", "artist", "author", "comment", "composer", "copyright",
"description", "encoder", "episode_id", "genre", "grouping", "lyrics", "network",
"rotate", "show", "synopsis", "title", "track", "year", 0};
const char* ignoreMetadataFieldsArray[] = {"major_brand", "minor_version", "compatible_brands", "handler_name", "vendor_id",
"language",
"duration", // We ignore it here, since its explicitly added
// elsewhere.
0};
//----------------------------------------------------------------------
//
// Static Helpers
//
//----------------------------------------------------------------------
string avErr2Str(int errNum)
{
char errBuf[AV_ERROR_MAX_STRING_SIZE];
av_make_error_string(&errBuf[0], AV_ERROR_MAX_STRING_SIZE, errNum);
return string(errBuf);
}
void avLogCallback(void* ptr, int level, const char* fmt, va_list vargs)
{
if ((string(fmt).substr(0, 51) == "Encoder did not produce proper pts, making some up.")
|| (string(fmt).substr(0, 47) == "No accelerated colorspace conversion found from")
|| (string(fmt).substr(0, 28) == "Increasing reorder buffer to")
|| (string(fmt).substr(0, 34) == "sample aspect ratio already set to")
|| (string(fmt).substr(0, 67)
== "deprecated pixel format used, make sure you did set "
"range correctly")
|| (string(fmt).substr(0, 20) == "overread end of atom") || (string(fmt).substr(0, 19) == "Timecode frame rate")
|| (string(fmt).substr(0, 32) == "unsupported color_parameter_type"))
{
return;
}
ostringstream message;
if (level > av_log_get_level())
{
return;
}
else if (level > AV_LOG_WARNING)
{
message << "INFO";
}
else if (level == AV_LOG_WARNING)
{
message << "WARNING";
}
else
{
message << "ERROR";
}
#if DB_GENERAL & DB_LEVEL
message << " [" << level << "]: ";
message << "MovieFFMpeg";
#endif
message << ": " << string(fmt);
vprintf(message.str().c_str(), vargs);
}
bool codecHasSlowAccess(string name)
{
boost::algorithm::to_lower(name);
return std::any_of(slowRandomAccessCodecs.begin(), slowRandomAccessCodecs.end(),
[&name](const auto& codec) { return codec == name; });
}
bool isMP4format(AVFormatContext* avFormatContext)
{
return avFormatContext != nullptr && avFormatContext->iformat != nullptr && avFormatContext->iformat->name != nullptr
&& strstr(avFormatContext->iformat->name, "mp4") != nullptr;
}
bool isMOVformat(AVFormatContext* avFormatContext)
{
return avFormatContext != nullptr && avFormatContext->iformat != nullptr && avFormatContext->iformat->name != nullptr
&& strstr(avFormatContext->iformat->name, "mov") != nullptr;
}
int64_t findBestTS(int64_t goalTS, double frameDur, VideoTrack* track, bool finalPacket)
{
//
// The timestamps we have collected from unordered packets give us
// a view into the future timestamps for the frames we _will_
// decode. This helps us "predict the future" for interframe codecs
// and do a better job of finding the best timestamp match for RV's
// frame request.
//
// Below we look through the timestamps we know are coming to find
// the one that is closest to the goalTS that represents the RV
// requested frame
//
int64_t smallest = -1;
map<int64_t, int64_t> diffs;
for (set<int64_t>::iterator ts = track->tsSet.begin(); ts != track->tsSet.end(); ts++)
{
int64_t diff = abs(goalTS - *ts);
if (diff < smallest || smallest == -1)
smallest = diff;
diffs[diff] = *ts;
}
return (smallest != -1 && (smallest < (frameDur * 0.5) || finalPacket)) ? diffs[smallest] : goalTS;
}
bool fpsEquals(double& fps, double f)
{
//
// We get fps from all kinds of places, may have varying sig figs,
// so compare to "standard" values loosely.
//
if (fabs(fps - f) < 0.01)
{
fps = f;
return true;
}
return false;
}
AVPixelFormat getBestAVFormat(AVPixelFormat native)
{
const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(native);
int bitSize = desc->comp[0].depth - desc->comp[0].shift;
bool hasAlpha = true; //(desc->flags & AV_PIX_FMT_FLAG_ALPHA);
return (hasAlpha) ? ((bitSize > 8) ? AV_PIX_FMT_RGBA64 : AV_PIX_FMT_RGBA)
: ((bitSize > 8) ? AV_PIX_FMT_RGB48 : AV_PIX_FMT_RGB24);
}
AVPixelFormat getBestRVFormat(AVPixelFormat native)
{
//
// This method is primarily designed to be run on pixel formats for
// which RV cannot natively make use of. Right now that primarily
// means 10-bit YUV & YUVA data, but could also include anything we
// haven't found samples of or we simply don't have any anologous
// FrameBuffer format.
//
// NOTE: The one type of formats we do natively support that can
// pass through this unchanged are the 8-bit YUV & YUVA formats.
//
const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(native);
int bitSize = desc->comp[0].depth - desc->comp[0].shift;
bool hasAlpha = (desc->flags & AV_PIX_FMT_FLAG_ALPHA);
bool isPlanar = (desc->flags & AV_PIX_FMT_FLAG_PLANAR);
bool isRGB = (desc->flags & AV_PIX_FMT_FLAG_RGB);
AVPixelFormat best = AV_PIX_FMT_NONE;
// Planar YUV+
if (isPlanar && !isRGB)
{
if (bitSize == 8)
{
best = native;
}
else if (bitSize < 8)
{
best = (hasAlpha) ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUV444P;
}
else if (bitSize > 8)
{
int log2w, log2h;
av_pix_fmt_get_chroma_sub_sample(native, &log2w, &log2h);
int usampling = int(pow(2.0f, log2w));
int vsampling = int(pow(2.0f, log2h));
int hfourcc = 4 / (usampling * vsampling);
switch (hfourcc)
{
case 0:
best = (hasAlpha) ? AV_PIX_FMT_YUVA420P16 : AV_PIX_FMT_YUV420P16;
break;
case 1:
case 2:
best = (hasAlpha) ? AV_PIX_FMT_YUVA422P16 : AV_PIX_FMT_YUV422P16;
break;
case 4:
default:
best = (hasAlpha) ? AV_PIX_FMT_YUVA444P16 : AV_PIX_FMT_YUV444P16;
break;
}
}
}
else // Everything else
{
best = (hasAlpha) ? ((bitSize > 8) ? AV_PIX_FMT_RGBA64 : AV_PIX_FMT_RGBA)
: ((bitSize > 8) ? AV_PIX_FMT_RGB48 : AV_PIX_FMT_RGB24);
}
return best;
}
bool isMetadataField(string check)
{
for (const char** p = metadataFieldsArray; *p; p++)
{
if (*p == check)
return true;
}
return false;
}
bool ignoreMetadataField(const string& check)
{
for (const char** p = ignoreMetadataFieldsArray; *p; p++)
{
if (*p == check)
return true;
}
return false;
}
void report(string message, bool warn = false)
{
string warning = (warn) ? "WARNING: " : "INFO: ";
cout << warning << "MovieFFMpeg: " << message << endl;
}
void rowColumnSwap(unsigned char* in, int w, int h, unsigned char* out)
{
for (int i = 0; i < h; ++i)
{
unsigned char* rp = in + (i * w);
unsigned char* rpLim = rp + w;
unsigned char* cp = out + h - 1 - i;
do
{
*cp = *rp;
//
// h is _width_ of out buffer
//
cp += h;
} while (++rp < rpLim);
}
}
void validateTimestamps(AVPacket* pkt, AVStream* stm, AVCodecContext* context, int64_t frameCount, bool isAudio = false)
{
if (pkt->pts == AV_NOPTS_VALUE && !isAudio && !(context->codec->capabilities & AV_CODEC_CAP_DELAY))
pkt->pts = frameCount;
if (pkt->pts != AV_NOPTS_VALUE)
pkt->pts = av_rescale_q(pkt->pts, context->time_base, stm->time_base);
if (pkt->dts != AV_NOPTS_VALUE)
pkt->dts = av_rescale_q(pkt->dts, context->time_base, stm->time_base);
if (pkt->duration > 0 && isAudio)
pkt->duration = av_rescale_q(pkt->duration, context->time_base, stm->time_base);
// Video AVPacket's duration needs to be initialized starting with
// FFmpeg 4.4.3 as the automatic computing of the frame duration
// code was removed from FFmpeg. Otherwise the exported media will
// have an incorrect duration (-1 frame) which will result in a
// slightly higher (incorrect) frame rate.
if (pkt->duration == 0 && !isAudio)
{
pkt->duration = av_rescale_q(1, context->time_base, stm->time_base);
}
}
void copyImage(AVFrame* dst, const AVFrame* src, const AVPixelFormat pix_fmt, int width, int height)
{
HOP_PROF_FUNC();
// Following code is a multithreaded version of the code found in
// image_copy() from imgutils.
const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(pix_fmt);
if (desc && !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
{
if (desc->flags & AV_PIX_FMT_FLAG_PAL)
{
// copy the palette
FastMemcpy(dst->data[1], src->data[1], 4 * 256);
}
else
{
int planes_nb = 0;
for (int i = 0; i < desc->nb_components; i++)
{
planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1);
}