Debian Codegraph @

src/core/videosource.cpp

raw symbols SCIP
1 // Copyright (c) 2007-2017 Fredrik Mellbin
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 #include "videosource.h"
22 #include "indexing.h"
23 #include "videoutils.h"
24 #include <algorithm>
25 #include <thread>
26
27
28 void DecoderDelay::Reset() {
29 ThreadDelayCounter = 0;
30 ReorderDelayCounter = 0;
31 }
32
33 void DecoderDelay::Increment(bool MarkedHidden, bool SecondField) {
34 if (ThreadDelayCounter < ThreadDelay && (!MarkedHidden || SecondField)) {
35 ThreadDelayCounter++;
36 } else if (!SecondField && !MarkedHidden) {
37 ReorderDelayCounter++;
38 }
39 }
40
41 void DecoderDelay::Decrement() {
42 if (ReorderDelayCounter) {
43 ReorderDelayCounter--;
44 } else {
45 ThreadDelayCounter--;
46 }
47 }
48
49 bool DecoderDelay::IsExceeded() {
50 return ThreadDelayCounter >= ThreadDelay && ReorderDelayCounter > ReorderDelay;
51 }
52
53
54 void FFMS_VideoSource::SanityCheckFrameForData(AVFrame *Frame) {
55 for (int i = 0; i < 4; i++) {
56 if (Frame->data[i] != nullptr && Frame->linesize[i] != 0)
57 return;
58 }
59
60 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, "Insanity detected: decoder returned an empty frame");
61 }
62
63 void FFMS_VideoSource::GetFrameCheck(int n) {
64 if (n < 0 || n >= VP.NumFrames)
65 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_INVALID_ARGUMENT,
66 "Out of bounds frame requested");
67 }
68
69 FFMS_Frame *FFMS_VideoSource::OutputFrame(AVFrame *Frame) {
70 SanityCheckFrameForData(Frame);
71
72 if (LastFrameWidth != Frame->width || LastFrameHeight != Frame->height || LastFramePixelFormat != Frame->format) {
73 if (TargetHeight > 0 && TargetWidth > 0 && !TargetPixelFormats.empty()) {
74 if (!InputFormatOverridden) {
75 InputFormat = AV_PIX_FMT_NONE;
76 InputColorSpace = AVCOL_SPC_UNSPECIFIED;
77 InputColorRange = AVCOL_RANGE_UNSPECIFIED;
78 }
79
80 ReAdjustOutputFormat(Frame);
81 } else {
82 OutputFormat = (AVPixelFormat) Frame->format;
83 }
84 }
85
86 if (SWS) {
87 sws_scale(SWS, Frame->data, Frame->linesize, 0, Frame->height, SWSFrameData, SWSFrameLinesize);
88 for (int i = 0; i < 4; i++) {
89 LocalFrame.Data[i] = SWSFrameData[i];
90 LocalFrame.Linesize[i] = SWSFrameLinesize[i];
91 }
92 } else {
93 // Special case to avoid ugly casts
94 for (int i = 0; i < 4; i++) {
95 LocalFrame.Data[i] = Frame->data[i];
96 LocalFrame.Linesize[i] = Frame->linesize[i];
97 }
98 }
99
100 LocalFrame.EncodedWidth = Frame->width;
101 LocalFrame.EncodedHeight = Frame->height;
102 LocalFrame.EncodedPixelFormat = Frame->format;
103 LocalFrame.ScaledWidth = TargetWidth;
104 LocalFrame.ScaledHeight = TargetHeight;
105 LocalFrame.ConvertedPixelFormat = OutputFormat;
106 LocalFrame.KeyFrame = !!(Frame->flags & AV_FRAME_FLAG_KEY);
107 LocalFrame.PictType = av_get_picture_type_char(Frame->pict_type);
108 LocalFrame.RepeatPict = Frame->repeat_pict;
109 LocalFrame.InterlacedFrame = !!(Frame->flags & AV_FRAME_FLAG_INTERLACED);
110 LocalFrame.TopFieldFirst = !!(Frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
111 LocalFrame.ColorSpace = OutputColorSpaceSet ? OutputColorSpace : Frame->colorspace;
112 LocalFrame.ColorRange = OutputColorRangeSet ? OutputColorRange : Frame->color_range;
113 LocalFrame.ColorPrimaries = (OutputColorPrimaries >= 0) ? OutputColorPrimaries : Frame->color_primaries;
114 LocalFrame.TransferCharateristics = (OutputTransferCharateristics >= 0) ? OutputTransferCharateristics : Frame->color_trc;
115 LocalFrame.ChromaLocation = (OutputChromaLocation >= 0) ? OutputChromaLocation : Frame->chroma_location;
116
117 const AVFrameSideData *MasteringDisplaySideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
118 if (MasteringDisplaySideData) {
119 const AVMasteringDisplayMetadata *MasteringDisplay = reinterpret_cast<const AVMasteringDisplayMetadata *>(MasteringDisplaySideData->data);
120 if (MasteringDisplay->has_primaries) {
121 LocalFrame.HasMasteringDisplayPrimaries = MasteringDisplay->has_primaries;
122 for (int i = 0; i < 3; i++) {
123 LocalFrame.MasteringDisplayPrimariesX[i] = av_q2d(MasteringDisplay->display_primaries[i][0]);
124 LocalFrame.MasteringDisplayPrimariesY[i] = av_q2d(MasteringDisplay->display_primaries[i][1]);
125 }
126 LocalFrame.MasteringDisplayWhitePointX = av_q2d(MasteringDisplay->white_point[0]);
127 LocalFrame.MasteringDisplayWhitePointY = av_q2d(MasteringDisplay->white_point[1]);
128 }
129 if (MasteringDisplay->has_luminance) {
130 LocalFrame.HasMasteringDisplayLuminance = MasteringDisplay->has_luminance;
131 LocalFrame.MasteringDisplayMinLuminance = av_q2d(MasteringDisplay->min_luminance);
132 LocalFrame.MasteringDisplayMaxLuminance = av_q2d(MasteringDisplay->max_luminance);
133 }
134 }
135 LocalFrame.HasMasteringDisplayPrimaries = !!LocalFrame.MasteringDisplayPrimariesX[0] && !!LocalFrame.MasteringDisplayPrimariesY[0] &&
136 !!LocalFrame.MasteringDisplayPrimariesX[1] && !!LocalFrame.MasteringDisplayPrimariesY[1] &&
137 !!LocalFrame.MasteringDisplayPrimariesX[2] && !!LocalFrame.MasteringDisplayPrimariesY[2] &&
138 !!LocalFrame.MasteringDisplayWhitePointX && !!LocalFrame.MasteringDisplayWhitePointY;
139 /* MasteringDisplayMinLuminance can be 0 */
140 LocalFrame.HasMasteringDisplayLuminance = !!LocalFrame.MasteringDisplayMaxLuminance;
141
142 const AVFrameSideData *DolbyVisionRPUSideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_DOVI_RPU_BUFFER);
143 if (DolbyVisionRPUSideData) {
144 if (DolbyVisionRPUSideData->size > RPUBufferSize) {
145 void *tmp = av_realloc(RPUBuffer, DolbyVisionRPUSideData->size);
146 if (!tmp)
147 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
148 "Could not allocate RPU buffer.");
149 RPUBuffer = reinterpret_cast<uint8_t *>(tmp);
150 RPUBufferSize = DolbyVisionRPUSideData->size;
151 }
152
153 memcpy(RPUBuffer, DolbyVisionRPUSideData->data, DolbyVisionRPUSideData->size);
154
155 LocalFrame.DolbyVisionRPU = RPUBuffer;
156 LocalFrame.DolbyVisionRPUSize = DolbyVisionRPUSideData->size;
157 }
158
159 AVFrameSideData *HDR10PlusSideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_DYNAMIC_HDR_PLUS);
160 if (HDR10PlusSideData) {
161 uint8_t *T35Buffer = nullptr;
162 size_t T35Size;
163 int ret = av_dynamic_hdr_plus_to_t35(reinterpret_cast<const AVDynamicHDRPlus *>(HDR10PlusSideData->data), &T35Buffer, &T35Size);
164 if (ret < 0)
165 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_INVALID_ARGUMENT,
166 "HDR10+ dynamic metadata could not be serialized.");
167 if (T35Size > HDR10PlusBufferSize) {
168 void *tmp = av_realloc(HDR10PlusBuffer, T35Size);
169 if (!tmp)
170 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
171 "Could not allocate HDR10+ buffer.");
172 HDR10PlusBuffer = reinterpret_cast<uint8_t *>(tmp);
173 HDR10PlusBufferSize = T35Size;
174 }
175
176 memcpy(HDR10PlusBuffer, T35Buffer, T35Size);
177 av_free(T35Buffer);
178
179 LocalFrame.HDR10Plus = HDR10PlusBuffer;
180 LocalFrame.HDR10PlusSize = T35Size;
181 }
182
183 const AVFrameSideData *ContentLightSideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
184 if (ContentLightSideData) {
185 const AVContentLightMetadata *ContentLightLevel = reinterpret_cast<const AVContentLightMetadata *>(ContentLightSideData->data);
186 LocalFrame.ContentLightLevelMax = ContentLightLevel->MaxCLL;
187 LocalFrame.ContentLightLevelAverage = ContentLightLevel->MaxFALL;
188 }
189 /* Only check for either of them */
190 LocalFrame.HasContentLightLevel = !!LocalFrame.ContentLightLevelMax || !!LocalFrame.ContentLightLevelAverage;
191
192 LastFrameHeight = Frame->height;
193 LastFrameWidth = Frame->width;
194 LastFramePixelFormat = (AVPixelFormat) Frame->format;
195
196 return &LocalFrame;
197 }
198
199 FFMS_VideoSource::FFMS_VideoSource(const char *SourceFile, FFMS_Index &Index, int Track, int Threads, int SeekMode)
200 : Index(Index), SeekMode(SeekMode) {
201
202 try {
203 if (Track < 0 || Track >= static_cast<int>(Index.size()))
204 throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
205 "Out of bounds track index selected");
206
207 if (Index[Track].TT != FFMS_TYPE_VIDEO)
208 throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
209 "Not a video track");
210
211 if (Index[Track].empty())
212 throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
213 "Video track contains no frames");
214
215 if (!Index.CompareFileSignature(SourceFile))
216 throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_FILE_MISMATCH,
217 "The index does not match the source file");
218
219 Frames = Index[Track];
220 VideoTrack = Track;
221
222 if (Threads < 1)
223 DecodingThreads = (std::min)(std::thread::hardware_concurrency(), 16u);
224 else
225 DecodingThreads = Threads;
226
227 DecodeFrame = av_frame_alloc();
228 LastDecodedFrame = av_frame_alloc();
229 StashedPacket = av_packet_alloc();
230
231 if (!DecodeFrame || !LastDecodedFrame || !StashedPacket)
232 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
233 "Could not allocate dummy frame / stashed packet.");
234
235 // Dummy allocations so the unallocated case doesn't have to be handled later
236 if (av_image_alloc(SWSFrameData, SWSFrameLinesize, 16, 16, AV_PIX_FMT_GRAY8, 4) < 0)
237 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
238 "Could not allocate dummy frame.");
239
240 LAVFOpenFile(SourceFile, FormatContext, VideoTrack, Index.LAVFOpts);
241
242 auto *Codec = avcodec_find_decoder(FormatContext->streams[VideoTrack]->codecpar->codec_id);
243 if (Codec == nullptr)
244 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
245 "Video codec not found");
246
247 CodecContext = avcodec_alloc_context3(Codec);
248 if (CodecContext == nullptr)
249 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
250 "Could not allocate video codec context.");
251 if (avcodec_parameters_to_context(CodecContext, FormatContext->streams[VideoTrack]->codecpar) < 0)
252 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
253 "Could not copy video decoder parameters.");
254 CodecContext->thread_count = DecodingThreads;
255 CodecContext->has_b_frames = Frames.MaxBFrames;
256
257 // Full explanation by more clever person availale here: https://github.com/Nevcairiel/LAVFilters/issues/113
258 if (CodecContext->codec_id == AV_CODEC_ID_H264 && CodecContext->has_b_frames)
259 CodecContext->has_b_frames = 15; // the maximum possible value for h264
260
261 if (avcodec_open2(CodecContext, Codec, nullptr) < 0)
262 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
263 "Could not open video codec");
264
265 // Similar yet different to h264 workaround above
266 // vc1 simply sets has_b_frames to 1 no matter how many there are so instead we set it to the max value
267 // in order to not confuse our own delay guesses later
268 // Doesn't affect actual vc1 reordering unlike h264
269 if (CodecContext->codec_id == AV_CODEC_ID_VC1 && CodecContext->has_b_frames) {
270 Delay.ReorderDelay = 7; // the maximum possible value for vc1
271 Delay.ThreadDelay = CodecContext->thread_count - 1;
272 } else if (CodecContext->codec_id == AV_CODEC_ID_AV1) {
273 // libdav1d.c exports delay like this.
274 Delay.ReorderDelay = CodecContext->delay;
275 } else {
276 // In theory we can move this to CodecContext->delay, sort of, one day, maybe. Not now.
277 Delay.ReorderDelay = CodecContext->has_b_frames; // Normal decoder delay
278 if (CodecContext->active_thread_type & FF_THREAD_FRAME) // Adjust for frame based threading
279 Delay.ThreadDelay = CodecContext->thread_count - 1;
280 }
281
282 SeekByPos = !strcmp(FormatContext->iformat->name, "mpeg") || !strcmp(FormatContext->iformat->name, "mpegts") || !strcmp(FormatContext->iformat->name, "mpegtsraw");
283
284 // Always try to decode a frame to make sure all required parameters are known
285 int64_t DummyPTS = 0, DummyPos = 0;
286 DecodeNextFrame(DummyPTS, DummyPos);
287
288 //VP.image_type = VideoInfo::IT_TFF;
289 VP.FPSDenominator = FormatContext->streams[VideoTrack]->time_base.num;
290 VP.FPSNumerator = FormatContext->streams[VideoTrack]->time_base.den;
291
292 // sanity check framerate
293 if (VP.FPSDenominator <= 0 || VP.FPSNumerator <= 0) {
294 VP.FPSDenominator = 1;
295 VP.FPSNumerator = 30;
296 }
297
298 // Calculate the average framerate
299 size_t TotalFrames = 0;
300 for (size_t i = 0; i < Frames.size(); i++)
301 if (!Frames[i].Skipped())
302 TotalFrames++;
303
304 if (TotalFrames >= 2) {
305 double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
306 double TD = (double)(Frames.TB.Den);
307 double TN = (double)(Frames.TB.Num);
308 VP.FPSDenominator = (unsigned int)(PTSDiff * TN / TD * 1000.0 / (TotalFrames - 1));
309 VP.FPSNumerator = 1000000;
310 } else if (TotalFrames == 1 && Frames.LastDuration > 0) {
311 VP.FPSDenominator *= Frames.LastDuration;
312 }
313
314 // Set the video properties from the codec context
315 SetVideoProperties();
316
317 // Set the SAR from the container if the codec SAR is invalid
318 if (VP.SARNum <= 0 || VP.SARDen <= 0) {
319 VP.SARNum = FormatContext->streams[VideoTrack]->sample_aspect_ratio.num;
320 VP.SARDen = FormatContext->streams[VideoTrack]->sample_aspect_ratio.den;
321 }
322
323 // Set stereoscopic 3d type
324 VP.Stereo3DType = FFMS_S3D_TYPE_2D;
325 VP.Stereo3DFlags = 0;
326
327 for (int i = 0; i < FormatContext->streams[VideoTrack]->codecpar->nb_coded_side_data; i++) {
328 if (FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].type == AV_PKT_DATA_STEREO3D) {
329 const AVStereo3D *StereoSideData = (const AVStereo3D *)FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].data;
330 VP.Stereo3DType = StereoSideData->type;
331 VP.Stereo3DFlags = StereoSideData->flags;
332 } else if (FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].type == AV_PKT_DATA_MASTERING_DISPLAY_METADATA) {
333 const AVMasteringDisplayMetadata *MasteringDisplay = (const AVMasteringDisplayMetadata *)FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].data;
334 if (MasteringDisplay->has_primaries) {
335 VP.HasMasteringDisplayPrimaries = MasteringDisplay->has_primaries;
336 for (int i = 0; i < 3; i++) {
337 VP.MasteringDisplayPrimariesX[i] = av_q2d(MasteringDisplay->display_primaries[i][0]);
338 VP.MasteringDisplayPrimariesY[i] = av_q2d(MasteringDisplay->display_primaries[i][1]);
339 }
340 VP.MasteringDisplayWhitePointX = av_q2d(MasteringDisplay->white_point[0]);
341 VP.MasteringDisplayWhitePointY = av_q2d(MasteringDisplay->white_point[1]);
342 }
343 if (MasteringDisplay->has_luminance) {
344 VP.HasMasteringDisplayLuminance = MasteringDisplay->has_luminance;
345 VP.MasteringDisplayMinLuminance = av_q2d(MasteringDisplay->min_luminance);
346 VP.MasteringDisplayMaxLuminance = av_q2d(MasteringDisplay->max_luminance);
347 }
348
349 VP.HasMasteringDisplayPrimaries = !!VP.MasteringDisplayPrimariesX[0] && !!VP.MasteringDisplayPrimariesY[0] &&
350 !!VP.MasteringDisplayPrimariesX[1] && !!VP.MasteringDisplayPrimariesY[1] &&
351 !!VP.MasteringDisplayPrimariesX[2] && !!VP.MasteringDisplayPrimariesY[2] &&
352 !!VP.MasteringDisplayWhitePointX && !!VP.MasteringDisplayWhitePointY;
353 /* MasteringDisplayMinLuminance can be 0 */
354 VP.HasMasteringDisplayLuminance = !!VP.MasteringDisplayMaxLuminance;
355 } else if (FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].type == AV_PKT_DATA_CONTENT_LIGHT_LEVEL) {
356 const AVContentLightMetadata *ContentLightLevel = (const AVContentLightMetadata *)FormatContext->streams[VideoTrack]->codecpar->coded_side_data[i].data;
357
358 VP.ContentLightLevelMax = ContentLightLevel->MaxCLL;
359 VP.ContentLightLevelAverage = ContentLightLevel->MaxFALL;
360
361 /* Only check for either of them */
362 VP.HasContentLightLevel = !!VP.ContentLightLevelMax || !!VP.ContentLightLevelAverage;
363 }
364 }
365
366 // Set rotation
367 VP.Rotation = 0;
368 VP.Flip = 0;
369 const AVPacketSideData *SideData = av_packet_side_data_get(FormatContext->streams[VideoTrack]->codecpar->coded_side_data, FormatContext->streams[VideoTrack]->codecpar->nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX);
370 const int32_t *RotationMatrixSrc = reinterpret_cast<const int32_t *>(SideData ? SideData->data : nullptr);
371 if (RotationMatrixSrc) {
372 int32_t RotationMatrix[9];
373 memcpy(RotationMatrix, RotationMatrixSrc, sizeof(RotationMatrix));
374 int64_t det = (int64_t)RotationMatrix[0] * RotationMatrix[4] - (int64_t)RotationMatrix[1] * RotationMatrix[3];
375 if (det < 0) {
376 /* Always assume an horizontal flip for simplicity, it can be changed later if rotation is 180. */
377 VP.Flip = 1;
378
379 /* Flip the matrix to decouple flip and rotation operations. */
380 av_display_matrix_flip(RotationMatrix, 1, 0);
381 }
382
383 int rot = lround(av_display_rotation_get(RotationMatrix));
384
385 if (rot == 180 && det < 0) {
386 /* This is a vertical flip with no rotation. */
387 VP.Flip = -1;
388 } else {
389 /* It is possible to have a 90/270 rotation and a horizontal flip:
390 * in this case, the rotation angle applies to the video frame
391 * (rather than the rendering frame), so add this step to nullify
392 * the conversion below. */
393 if (VP.Flip)
394 rot *= -1;
395
396 /* Return a positive value, noting that this converts angles
397 * from the rendering frame to the video frame. */
398 VP.Rotation = -rot;
399 if (VP.Rotation < 0)
400 VP.Rotation += 360;
401 }
402 }
403
404 if (SeekMode >= 0 && Frames.size() > 1) {
405 if (Seek(0) < 0) {
406 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
407 "Video track is unseekable");
408 }
409 }
410
411 // Cannot "output" without doing all other initialization
412 // This is the additional mess required for seekmode=-1 to work in a reasonable way
413 OutputFrame(DecodeFrame);
414
415 if (LocalFrame.HasMasteringDisplayPrimaries) {
416 VP.HasMasteringDisplayPrimaries = LocalFrame.HasMasteringDisplayPrimaries;
417 for (int i = 0; i < 3; i++) {
418 VP.MasteringDisplayPrimariesX[i] = LocalFrame.MasteringDisplayPrimariesX[i];
419 VP.MasteringDisplayPrimariesY[i] = LocalFrame.MasteringDisplayPrimariesY[i];
420 }
421
422 // Simply copy this from the first frame to make it easier to access
423 VP.MasteringDisplayWhitePointX = LocalFrame.MasteringDisplayWhitePointX;
424 VP.MasteringDisplayWhitePointY = LocalFrame.MasteringDisplayWhitePointY;
425 }
426 if (LocalFrame.HasMasteringDisplayLuminance) {
427 VP.HasMasteringDisplayLuminance = LocalFrame.HasMasteringDisplayLuminance;
428 VP.MasteringDisplayMinLuminance = LocalFrame.MasteringDisplayMinLuminance;
429 VP.MasteringDisplayMaxLuminance = LocalFrame.MasteringDisplayMaxLuminance;
430 }
431 if (LocalFrame.HasContentLightLevel) {
432 VP.HasContentLightLevel = LocalFrame.HasContentLightLevel;
433 VP.ContentLightLevelMax = LocalFrame.ContentLightLevelMax;
434 VP.ContentLightLevelAverage = LocalFrame.ContentLightLevelAverage;
435 }
436 } catch (FFMS_Exception &) {
437 Free();
438 throw;
439 }
440 }
441
442 FFMS_VideoSource::~FFMS_VideoSource() {
443 Free();
444 }
445
446 FFMS_Frame *FFMS_VideoSource::GetFrameByTime(double Time) {
447 // The final 1/1000th of a PTS is added to avoid frame duplication due to floating point math inexactness
448 // Basically only a problem when the fps is externally set to the same or a multiple of the input clip fps
449 int Frame = Frames.ClosestFrameFromPTS(static_cast<int64_t>(((Time * 1000 * Frames.TB.Den) / Frames.TB.Num) + .001));
450 return GetFrame(Frame);
451 }
452
453 static AVColorRange handle_jpeg(AVPixelFormat *format) {
454 switch (*format) {
455 case AV_PIX_FMT_YUVJ420P: *format = AV_PIX_FMT_YUV420P; return AVCOL_RANGE_JPEG;
456 case AV_PIX_FMT_YUVJ422P: *format = AV_PIX_FMT_YUV422P; return AVCOL_RANGE_JPEG;
457 case AV_PIX_FMT_YUVJ444P: *format = AV_PIX_FMT_YUV444P; return AVCOL_RANGE_JPEG;
458 case AV_PIX_FMT_YUVJ440P: *format = AV_PIX_FMT_YUV440P; return AVCOL_RANGE_JPEG;
459 default: return AVCOL_RANGE_UNSPECIFIED;
460 }
461 }
462
463 void FFMS_VideoSource::SetOutputFormat(const AVPixelFormat *TargetFormats, int Width, int Height, int Resizer) {
464 TargetWidth = Width;
465 TargetHeight = Height;
466 TargetResizer = Resizer;
467 TargetPixelFormats.clear();
468 while (*TargetFormats != AV_PIX_FMT_NONE)
469 TargetPixelFormats.push_back(*TargetFormats++);
470 OutputColorSpaceSet = true;
471 OutputColorRangeSet = true;
472 OutputFormat = AV_PIX_FMT_NONE;
473
474 ReAdjustOutputFormat(DecodeFrame);
475 OutputFrame(DecodeFrame);
476 }
477
478 void FFMS_VideoSource::SetInputFormat(int ColorSpace, int ColorRange, AVPixelFormat Format) {
479 InputFormatOverridden = true;
480
481 if (Format != AV_PIX_FMT_NONE)
482 InputFormat = Format;
483 if (ColorRange != AVCOL_RANGE_UNSPECIFIED)
484 InputColorRange = (AVColorRange)ColorRange;
485 if (ColorSpace != AVCOL_SPC_UNSPECIFIED)
486 InputColorSpace = (AVColorSpace)ColorSpace;
487
488 if (TargetPixelFormats.size()) {
489 ReAdjustOutputFormat(DecodeFrame);
490 OutputFrame(DecodeFrame);
491 }
492 }
493
494 void FFMS_VideoSource::DetectInputFormat() {
495 if (InputFormat == AV_PIX_FMT_NONE)
496 InputFormat = CodecContext->pix_fmt;
497
498 AVColorRange RangeFromFormat = handle_jpeg(&InputFormat);
499
500 if (InputColorRange == AVCOL_RANGE_UNSPECIFIED)
501 InputColorRange = RangeFromFormat;
502 if (InputColorRange == AVCOL_RANGE_UNSPECIFIED)
503 InputColorRange = CodecContext->color_range;
504
505 if (InputColorSpace == AVCOL_SPC_UNSPECIFIED)
506 InputColorSpace = CodecContext->colorspace;
507 }
508
509 void FFMS_VideoSource::ReAdjustOutputFormat(AVFrame *Frame) {
510 if (SWS) {
511 sws_freeContext(SWS);
512 SWS = nullptr;
513 }
514
515 DetectInputFormat();
516
517 OutputFormat = FindBestPixelFormat(TargetPixelFormats, InputFormat);
518 if (OutputFormat == AV_PIX_FMT_NONE) {
519 ResetOutputFormat();
520 throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_INVALID_ARGUMENT,
521 "No suitable output format found");
522 }
523
524 OutputColorRange = handle_jpeg(&OutputFormat);
525 if (OutputColorRange == AVCOL_RANGE_UNSPECIFIED)
526 OutputColorRange = CodecContext->color_range;
527 if (OutputColorRange == AVCOL_RANGE_UNSPECIFIED)
528 OutputColorRange = InputColorRange;
529
530 OutputColorSpace = CodecContext->colorspace;
531 if (OutputColorSpace == AVCOL_SPC_UNSPECIFIED)
532 OutputColorSpace = InputColorSpace;
533
534 BCSType InputType = GuessCSType(InputFormat);
535 BCSType OutputType = GuessCSType(OutputFormat);
536
537 if (InputType != OutputType) {
538 if (OutputType == cRGB) {
539 OutputColorSpace = AVCOL_SPC_RGB;
540 OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
541 OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
542 OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
543 OutputChromaLocation = AVCHROMA_LOC_UNSPECIFIED;
544 } else if (OutputType == cYUV) {
545 OutputColorSpace = AVCOL_SPC_BT470BG;
546 OutputColorRange = AVCOL_RANGE_MPEG;
547 OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
548 OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
549 OutputChromaLocation = AVCHROMA_LOC_LEFT;
550 } else if (OutputType == cGRAY) {
551 OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
552 OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
553 OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
554 OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
555 OutputChromaLocation = AVCHROMA_LOC_UNSPECIFIED;
556 }
557 } else {
558 OutputColorPrimaries = -1;
559 OutputTransferCharateristics = -1;
560 OutputChromaLocation = -1;
561 }
562
563 if (InputFormat != OutputFormat ||
564 TargetWidth != CodecContext->width ||
565 TargetHeight != CodecContext->height ||
566 InputColorSpace != OutputColorSpace ||
567 InputColorRange != OutputColorRange) {
568 SWS = GetSwsContext(
569 Frame->width, Frame->height, InputFormat, InputColorSpace, InputColorRange,
570 TargetWidth, TargetHeight, OutputFormat, OutputColorSpace, OutputColorRange,
571 TargetResizer);
572
573 if (!SWS) {
574 ResetOutputFormat();
575 throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_INVALID_ARGUMENT,
576 "Failed to allocate SWScale context");
577 }
578 }
579
580 av_freep(&SWSFrameData[0]);
581 if (av_image_alloc(SWSFrameData, SWSFrameLinesize, TargetWidth, TargetHeight, OutputFormat, 4) < 0)
582 throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_ALLOCATION_FAILED,
583 "Could not allocate frame with new resolution.");
584 }
585
586 void FFMS_VideoSource::ResetOutputFormat() {
587 if (SWS) {
588 sws_freeContext(SWS);
589 SWS = nullptr;
590 }
591
592 TargetWidth = -1;
593 TargetHeight = -1;
594 TargetPixelFormats.clear();
595
596 OutputFormat = AV_PIX_FMT_NONE;
597 OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
598 OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
599 OutputColorSpaceSet = false;
600 OutputColorRangeSet = false;
601
602 OutputFrame(DecodeFrame);
603 }
604
605 void FFMS_VideoSource::ResetInputFormat() {
606 InputFormatOverridden = false;
607 InputFormat = AV_PIX_FMT_NONE;
608 InputColorSpace = AVCOL_SPC_UNSPECIFIED;
609 InputColorRange = AVCOL_RANGE_UNSPECIFIED;
610
611 ReAdjustOutputFormat(DecodeFrame);
612 OutputFrame(DecodeFrame);
613 }
614
615 void FFMS_VideoSource::SetVideoProperties() {
616 VP.RFFDenominator = FormatContext->streams[VideoTrack]->time_base.num;
617 VP.RFFNumerator = FormatContext->streams[VideoTrack]->time_base.den;
618 if (CodecContext->codec_id == AV_CODEC_ID_H264) {
619 if (VP.RFFNumerator & 1)
620 VP.RFFDenominator *= 2;
621 else
622 VP.RFFNumerator /= 2;
623 }
624 VP.NumFrames = Frames.VisibleFrameCount();
625 VP.TopFieldFirst = !!(DecodeFrame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
626 VP.ColorSpace = CodecContext->colorspace;
627 VP.ColorRange = CodecContext->color_range;
628 // these pixfmt's are deprecated but still used
629 if (CodecContext->pix_fmt == AV_PIX_FMT_YUVJ420P ||
630 CodecContext->pix_fmt == AV_PIX_FMT_YUVJ422P ||
631 CodecContext->pix_fmt == AV_PIX_FMT_YUVJ444P
632 )
633 VP.ColorRange = AVCOL_RANGE_JPEG;
634
635
636 VP.FirstTime = ((Frames[Frames.RealFrameNumber(0)].PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
637 VP.LastTime = ((Frames[Frames.RealFrameNumber(Frames.VisibleFrameCount()-1)].PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
638 VP.LastEndTime = (((Frames[Frames.RealFrameNumber(Frames.VisibleFrameCount()-1)].PTS + Frames.LastDuration) * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
639
640 if (CodecContext->width <= 0 || CodecContext->height <= 0)
641 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
642 "Codec returned zero size video");
643
644 // attempt to correct framerate to the proper NTSC fraction, if applicable
645 CorrectRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
646 // correct the timebase, if necessary
647 CorrectTimebase(&VP, &Frames.TB);
648
649 // Set AR variables
650 VP.SARNum = CodecContext->sample_aspect_ratio.num;
651 VP.SARDen = CodecContext->sample_aspect_ratio.den;
652
653 // Set input and output formats now that we have a CodecContext
654 DetectInputFormat();
655
656 OutputFormat = InputFormat;
657 OutputColorSpace = InputColorSpace;
658 OutputColorRange = InputColorRange;
659 }
660
661 bool FFMS_VideoSource::HasPendingDelayedFrames() {
662 if (Stage == DecodeStage::APPLY_DELAY) {
663 if (Delay.IsExceeded()) {
664 Delay.Decrement();
665 return true;
666 }
667 Stage = DecodeStage::DECODE_LOOP;
668 }
669 return false;
670 }
671
672 bool FFMS_VideoSource::DecodePacket(AVPacket *Packet) {
673 std::swap(DecodeFrame, LastDecodedFrame);
674 ResendPacket = false;
675
676 int PacketNum = Frames.FrameFromPTS(Frames.UseDTS ? Packet->dts : Packet->pts, true);
677 bool PacketHidden = !!(Packet->flags & AV_PKT_FLAG_DISCARD) || (PacketNum != -1 && Frames[PacketNum].MarkedHidden);
678 bool SecondField = PacketNum != -1 && Frames[PacketNum].SecondField;
679
680 int Ret = avcodec_send_packet(CodecContext, Packet);
681 if (Ret == AVERROR(EAGAIN)) {
682 // Send queue is full, so stash packet to resend on the next call.
683 ResendPacket = true;
684 } else if (Ret == 0) {
685 Delay.Increment(PacketHidden, SecondField);
686 }
687
688 Ret = avcodec_receive_frame(CodecContext, DecodeFrame);
689 if (Ret == 0) {
690 Delay.Decrement();
691 } else {
692 std::swap(DecodeFrame, LastDecodedFrame);
693 }
694
695 if (Ret == 0 && Stage == DecodeStage::INITIALIZE)
696 Stage = DecodeStage::APPLY_DELAY;
697
698 return Ret == 0;
699 }
700
701 int FFMS_VideoSource::Seek(int n) {
702 int ret = -1;
703
704 Delay.Reset();
705 if (Stage != DecodeStage::INITIALIZE_SOURCE)
706 Stage = DecodeStage::INITIALIZE;
707
708 if (!SeekByPos || Frames[n].FilePos < 0) {
709 ret = av_seek_frame(FormatContext, VideoTrack, Frames[n].PTS, AVSEEK_FLAG_BACKWARD);
710 }
711
712 if (ret < 0 && Frames[n].FilePos >= 0) {
713 ret = av_seek_frame(FormatContext, VideoTrack, Frames[n].FilePos, AVSEEK_FLAG_BYTE);
714 if (ret >= 0)
715 SeekByPos = true;
716 }
717
718 // We always assume seeking is possible if the first seek succeeds
719 avcodec_flush_buffers(CodecContext);
720 ResendPacket = false;
721 av_packet_unref(StashedPacket);
722
723 // When it's 0 we always know what the next frame is (or more exactly should be)
724 if (n == 0)
725 CurrentFrame = 0;
726
727 return ret;
728 }
729
730 void FFMS_VideoSource::Free() {
731 av_freep(&RPUBuffer);
732 av_freep(&HDR10PlusBuffer);
733 avcodec_free_context(&CodecContext);
734 avformat_close_input(&FormatContext);
735 if (SWS)
736 sws_freeContext(SWS);
737 av_freep(&SWSFrameData[0]);
738 av_frame_free(&DecodeFrame);
739 av_frame_free(&LastDecodedFrame);
740 av_packet_free(&StashedPacket);
741 }
742
743 void FFMS_VideoSource::DecodeNextFrame(int64_t &AStartTime, int64_t &Pos) {
744 AStartTime = -1;
745
746 if (HasPendingDelayedFrames())
747 return;
748
749 AVPacket *Packet = av_packet_alloc();
750 if (!Packet)
751 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
752 "Could not allocate packet.");
753
754 int ret;
755 if (ResendPacket) {
756 // If we have a packet previously stashed due to a full input queue,
757 // send it again.
758 ret = 0;
759 av_packet_ref(Packet, StashedPacket);
760 av_packet_unref(StashedPacket);
761 } else {
762 ret = av_read_frame(FormatContext, Packet);
763 }
764 while (ret >= 0) {
765 if (Packet->stream_index != VideoTrack) {
766 av_packet_unref(Packet);
767 ret = av_read_frame(FormatContext, Packet);
768 continue;
769 }
770
771 if (AStartTime < 0)
772 AStartTime = Frames.UseDTS ? Packet->dts : Packet->pts;
773
774 if (Pos < 0)
775 Pos = Packet->pos;
776
777 bool FrameFinished = DecodePacket(Packet);
778 if (ResendPacket)
779 av_packet_ref(StashedPacket, Packet);
780 av_packet_unref(Packet);
781 if (FrameFinished) {
782 av_packet_free(&Packet);
783 return;
784 }
785
786 if (ResendPacket) {
787 ret = 0;
788 av_packet_ref(Packet, StashedPacket);
789 av_packet_unref(StashedPacket);
790 } else {
791 ret = av_read_frame(FormatContext, Packet);
792 }
793 }
794 if (IsIOError(ret))
795 throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_FILE_READ,
796 "Failed to read packet: " + AVErrorToString(ret));
797
798 // Flush final frames
799 DecodePacket(Packet);
800 av_packet_free(&Packet);
801 }
802
803 bool FFMS_VideoSource::SeekTo(int n, int SeekOffset) {
804 bool ForceSeek = false;
805 if (Stage == DecodeStage::INITIALIZE_SOURCE) {
806 ForceSeek = true;
807 Stage = DecodeStage::INITIALIZE;
808 }
809
810 // The semantics here are basically "return true if we don't know exactly where our seek ended up (destination isn't frame 0)"
811 if (SeekMode >= 0) {
812 int TargetFrame = n + SeekOffset;
813 if (TargetFrame < 0)
814 throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_UNKNOWN,
815 "Frame accurate seeking is not possible in this file");
816
817 // Seeking too close to the end of the stream can result in a different decoder delay since
818 // frames are returned as soon as draining starts, so avoid this to keep the delay predictable.
819 // Is the +1 necessary here? Not sure, but let's keep it to be safe.
820 int EndOfStreamDist = CodecContext->has_b_frames + 1;
821
822 if (CodecContext->codec_id == AV_CODEC_ID_H264)
823 // Work around a bug in ffmpeg's h264 decoder where frames are skipped when seeking too
824 // close to the end in open-gop files: https://trac.ffmpeg.org/ticket/10936
825 EndOfStreamDist *= 2;
826
827 TargetFrame = std::min(TargetFrame, Frames.RealFrameNumber(std::max(0, VP.NumFrames - 1 - EndOfStreamDist)));
828
829 if (SeekMode < 3)
830 TargetFrame = Frames.FindClosestVideoKeyFrame(TargetFrame);
831
832 if (SeekMode == 0) {
833 if (n < CurrentFrame) {
834 Seek(Frames[0].OriginalPos);
835 }
836 } else {
837 // 10 frames is used as a margin to prevent excessive seeking since the predicted best keyframe isn't always selected by avformat
838 if (ForceSeek || n < CurrentFrame || TargetFrame > CurrentFrame + 10 || (SeekMode == 3 && n > CurrentFrame + 10)) {
839 Seek(TargetFrame);
840 return true;
841 }
842 }
843 } else if (n < CurrentFrame) {
844 throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_INVALID_ARGUMENT,
845 "Non-linear access attempted");
846 }
847 return false;
848 }
849
850 FFMS_Frame *FFMS_VideoSource::GetFrame(int n) {
851 GetFrameCheck(n);
852 n = Frames.RealFrameNumber(n);
853
854 if (Stage != DecodeStage::INITIALIZE_SOURCE && LastFrameNum == n)
855 return &LocalFrame;
856
857 int SeekOffset = 0;
858 bool Seek = true;
859 bool WasSkipped = false;
860
861 do {
862 bool HasSeeked = false;
863 if (Seek) {
864 HasSeeked = SeekTo(n, SeekOffset);
865 Seek = false;
866 WasSkipped = false;
867 }
868
869 int64_t StartTime = AV_NOPTS_VALUE, FilePos = -1;
870 bool Skipped = (((unsigned) CurrentFrame < Frames.size()) && Frames[CurrentFrame].Skipped());
871 if (HasSeeked || !Skipped) {
872 if (WasSkipped)
873 WasSkipped = false;
874 else
875 DecodeNextFrame(StartTime, FilePos);
876 }
877
878 if (!HasSeeked)
879 continue;
880
881 if (StartTime == AV_NOPTS_VALUE && !Frames.HasTS) {
882 if (FilePos >= 0) {
883 CurrentFrame = Frames.FrameFromPos(FilePos);
884 if (CurrentFrame >= 0)
885 continue;
886 }
887 // If the track doesn't have timestamps or file positions then
888 // just trust that we got to the right place, since we have no
889 // way to tell where we are
890 else {
891 CurrentFrame = n;
892 continue;
893 }
894 }
895
896 CurrentFrame = Frames.FrameFromPTS(StartTime);
897
898 // Is the seek destination time known? Does it belong to a frame?
899 if (CurrentFrame < 0) {
900 if (SeekMode == 1 || StartTime < 0) {
901 // No idea where we are so go back a bit further
902 SeekOffset -= 10;
903 Seek = true;
904 continue;
905 }
906 CurrentFrame = Frames.ClosestFrameFromPTS(StartTime);
907 }
908
909 // We want to know the frame number that we just got out of the decoder,
910 // but what we currently know is the frame number of the first packet
911 // we fed into the decoder, and these can be different with open-gop or
912 // aggressive (non-keyframe) seeking.
913 int64_t Pos = Frames[CurrentFrame].FilePos;
914 if (CurrentFrame > 0 && Pos != -1) {
915 while (true) {
916 int Prev = CurrentFrame - 1;
917 if (Prev >= 0 && Frames[Prev].SecondField)
918 --Prev;
919
920 if (Prev >= 0 && (Frames[Prev].FilePos != -1 && Frames[Prev].FilePos > Pos))
921 CurrentFrame = Prev;
922 else
923 break;
924 }
925 }
926
927 if (Frames[CurrentFrame].Skipped()) {
928 // The frame number we seeked to was hidden.
929 // (This is not the same as the first packet we got being marked as hidden,
930 // it happens in cases like when the timestamps in decoding order are
931 // 0 -2 -1 1 2 ...
932 // and the frames with negative timestamps are hidden. Then, the first packet
933 // we get is the packet with timestamp 0, but Frames[CurrentFrame] corresponds
934 // to the frame with PTS -2. This can happen for open-gop files that have
935 // been cut at a non-IDR recovery point.)
936 // We should have skipped this frame at the start of this loop iteration, but
937 // we didn't know CurrentFrame at that point we and had to decode a frame to know
938 // the current frame. So now we need to remember to skip an extra frame.
939 WasSkipped = true;
940 }
941 } while (++CurrentFrame <= n);
942
943 LastFrameNum = n;
944 return OutputFrame(DecodeFrame);
945 }