OpenShot Library | libopenshot  0.6.0
FFmpegReader.cpp
Go to the documentation of this file.
1 
12 // Copyright (c) 2008-2024 OpenShot Studios, LLC, Fabrice Bellard
13 //
14 // SPDX-License-Identifier: LGPL-3.0-or-later
15 
16 #include <thread> // for std::this_thread::sleep_for
17 #include <chrono> // for std::chrono::milliseconds
18 #include <algorithm>
19 #include <cmath>
20 #include <sstream>
21 #include <unistd.h>
22 
23 #include "FFmpegUtilities.h"
24 #include "effects/CropHelpers.h"
25 
26 #include "FFmpegReader.h"
27 #include "Exceptions.h"
28 #include "MemoryTrim.h"
29 #include "Timeline.h"
30 #include "ZmqLogger.h"
31 
32 #define ENABLE_VAAPI 0
33 
34 #if USE_HW_ACCEL
35 #define MAX_SUPPORTED_WIDTH 1950
36 #define MAX_SUPPORTED_HEIGHT 1100
37 
38 #if ENABLE_VAAPI
39 #include "libavutil/hwcontext_vaapi.h"
40 
41 typedef struct VAAPIDecodeContext {
42  VAProfile va_profile;
43  VAEntrypoint va_entrypoint;
44  VAConfigID va_config;
45  VAContextID va_context;
46 
47 #if FF_API_STRUCT_VAAPI_CONTEXT
48  // FF_DISABLE_DEPRECATION_WARNINGS
49  int have_old_context;
50  struct vaapi_context *old_context;
51  AVBufferRef *device_ref;
52  // FF_ENABLE_DEPRECATION_WARNINGS
53 #endif
54 
55  AVHWDeviceContext *device;
56  AVVAAPIDeviceContext *hwctx;
57 
58  AVHWFramesContext *frames;
59  AVVAAPIFramesContext *hwfc;
60 
61  enum AVPixelFormat surface_format;
62  int surface_count;
63  } VAAPIDecodeContext;
64 #endif // ENABLE_VAAPI
65 #endif // USE_HW_ACCEL
66 
67 
68 using namespace openshot;
69 
70 int hw_de_on = 0;
71 #if USE_HW_ACCEL
72  AVPixelFormat hw_de_av_pix_fmt_global = AV_PIX_FMT_NONE;
73  AVHWDeviceType hw_de_av_device_type_global = AV_HWDEVICE_TYPE_NONE;
74 #endif
75 
76 // Normalize deprecated JPEG-range YUVJ formats before creating swscale contexts.
77 // swscale expects non-YUVJ formats plus explicit color-range metadata.
78 static AVPixelFormat NormalizeDeprecatedPixFmt(AVPixelFormat pix_fmt, bool& is_full_range) {
79  switch (pix_fmt) {
80  case AV_PIX_FMT_YUVJ420P:
81  is_full_range = true;
82  return AV_PIX_FMT_YUV420P;
83  case AV_PIX_FMT_YUVJ422P:
84  is_full_range = true;
85  return AV_PIX_FMT_YUV422P;
86  case AV_PIX_FMT_YUVJ444P:
87  is_full_range = true;
88  return AV_PIX_FMT_YUV444P;
89  case AV_PIX_FMT_YUVJ440P:
90  is_full_range = true;
91  return AV_PIX_FMT_YUV440P;
92 #ifdef AV_PIX_FMT_YUVJ411P
93  case AV_PIX_FMT_YUVJ411P:
94  is_full_range = true;
95  return AV_PIX_FMT_YUV411P;
96 #endif
97  default:
98  return pix_fmt;
99  }
100 }
101 
102 FFmpegReader::FFmpegReader(const std::string &path, bool inspect_reader)
103  : FFmpegReader(path, DurationStrategy::VideoPreferred, inspect_reader) {}
104 
105 FFmpegReader::FFmpegReader(const std::string &path, DurationStrategy duration_strategy, bool inspect_reader)
106  : path(path), pFormatCtx(NULL), videoStream(-1), audioStream(-1), pCodecCtx(NULL), aCodecCtx(NULL),
107  pStream(NULL), aStream(NULL), packet(NULL), pFrame(NULL), is_open(false), is_duration_known(false),
108  check_interlace(false), check_fps(false), duration_strategy(duration_strategy), previous_packet_location{-1, 0},
109  is_seeking(false), seeking_pts(0), seeking_frame(0), is_video_seek(true), seek_count(0),
110  seek_audio_frame_found(0), seek_video_frame_found(0), last_seek_max_frame(-1), seek_stagnant_count(0),
111  last_frame(0), largest_frame_processed(0), current_video_frame(0), audio_pts(0), video_pts(0),
112  hold_packet(false), pts_offset_seconds(0.0), audio_pts_seconds(0.0), video_pts_seconds(0.0),
113  NO_PTS_OFFSET(-99999), enable_seek(true) {
114 
115  // Initialize FFMpeg, and register all formats and codecs
118 
119  // Init timestamp offsets
120  pts_offset_seconds = NO_PTS_OFFSET;
121  video_pts_seconds = NO_PTS_OFFSET;
122  audio_pts_seconds = NO_PTS_OFFSET;
123 
124  // Init cache
125  const int init_working_cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, OPEN_MP_NUM_PROCESSORS * 4);
126  const int init_final_cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, OPEN_MP_NUM_PROCESSORS * 4);
127  working_cache.SetMaxBytesFromInfo(init_working_cache_frames, info.width, info.height, info.sample_rate, info.channels);
128  final_cache.SetMaxBytesFromInfo(init_final_cache_frames, info.width, info.height, info.sample_rate, info.channels);
129 
130  // Open and Close the reader, to populate its attributes (such as height, width, etc...)
131  if (inspect_reader) {
132  Open();
133  Close();
134  }
135 }
136 
138  if (is_open)
139  // Auto close reader if not already done
140  Close();
141 }
142 
143 // This struct holds the associated video frame and starting sample # for an audio packet.
144 bool AudioLocation::is_near(AudioLocation location, int samples_per_frame, int64_t amount) {
145  // Is frame even close to this one?
146  if (abs(location.frame - frame) >= 2)
147  // This is too far away to be considered
148  return false;
149 
150  // Note that samples_per_frame can vary slightly frame to frame when the
151  // audio sampling rate is not an integer multiple of the video fps.
152  int64_t diff = samples_per_frame * (location.frame - frame) + location.sample_start - sample_start;
153  if (abs(diff) <= amount)
154  // close
155  return true;
156 
157  // not close
158  return false;
159 }
160 
161 #if USE_HW_ACCEL
162 
163 // Get hardware pix format
164 static enum AVPixelFormat get_hw_dec_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
165 {
166  const enum AVPixelFormat *p;
167 
168  // Prefer only the format matching the selected hardware decoder
170 
171  for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
172  switch (*p) {
173 #if defined(__linux__)
174  // Linux pix formats
175  case AV_PIX_FMT_VAAPI:
176  if (selected == 1) {
177  hw_de_av_pix_fmt_global = AV_PIX_FMT_VAAPI;
178  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VAAPI;
179  return *p;
180  }
181  break;
182  case AV_PIX_FMT_VDPAU:
183  if (selected == 6) {
184  hw_de_av_pix_fmt_global = AV_PIX_FMT_VDPAU;
185  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VDPAU;
186  return *p;
187  }
188  break;
189 #endif
190 #if defined(_WIN32)
191  // Windows pix formats
192  case AV_PIX_FMT_DXVA2_VLD:
193  if (selected == 3) {
194  hw_de_av_pix_fmt_global = AV_PIX_FMT_DXVA2_VLD;
195  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_DXVA2;
196  return *p;
197  }
198  break;
199  case AV_PIX_FMT_D3D11:
200  if (selected == 4) {
201  hw_de_av_pix_fmt_global = AV_PIX_FMT_D3D11;
202  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_D3D11VA;
203  return *p;
204  }
205  break;
206 #endif
207 #if defined(__APPLE__)
208  // Apple pix formats
209  case AV_PIX_FMT_VIDEOTOOLBOX:
210  if (selected == 5) {
211  hw_de_av_pix_fmt_global = AV_PIX_FMT_VIDEOTOOLBOX;
212  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
213  return *p;
214  }
215  break;
216 #endif
217  // Cross-platform pix formats
218  case AV_PIX_FMT_CUDA:
219  if (selected == 2) {
220  hw_de_av_pix_fmt_global = AV_PIX_FMT_CUDA;
221  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_CUDA;
222  return *p;
223  }
224  break;
225  case AV_PIX_FMT_QSV:
226  if (selected == 7) {
227  hw_de_av_pix_fmt_global = AV_PIX_FMT_QSV;
228  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_QSV;
229  return *p;
230  }
231  break;
232  default:
233  // This is only here to silence unused-enum warnings
234  break;
235  }
236  }
237  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::get_hw_dec_format (Unable to decode this file using hardware decode)");
238  return AV_PIX_FMT_NONE;
239 }
240 
241 int FFmpegReader::IsHardwareDecodeSupported(int codecid)
242 {
243  int ret;
244  switch (codecid) {
245  case AV_CODEC_ID_H264:
246  case AV_CODEC_ID_MPEG2VIDEO:
247  case AV_CODEC_ID_VC1:
248  case AV_CODEC_ID_WMV1:
249  case AV_CODEC_ID_WMV2:
250  case AV_CODEC_ID_WMV3:
251  ret = 1;
252  break;
253  default :
254  ret = 0;
255  break;
256  }
257  return ret;
258 }
259 #endif // USE_HW_ACCEL
260 
262  // Open reader if not already open
263  if (!is_open) {
264  // Prevent async calls to the following code
265  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
266 
267  // Initialize format context
268  pFormatCtx = NULL;
269  {
270  hw_de_on = (!force_sw_decode && openshot::Settings::Instance()->HARDWARE_DECODER != 0 ? 1 : 0);
271  hw_decode_failed = false;
272  hw_decode_error_count = 0;
273  hw_decode_succeeded = false;
274  ZmqLogger::Instance()->AppendDebugMethod("Decode hardware acceleration settings", "hw_de_on", hw_de_on, "HARDWARE_DECODER", openshot::Settings::Instance()->HARDWARE_DECODER);
275  }
276 
277  // Open video file
278  if (avformat_open_input(&pFormatCtx, path.c_str(), NULL, NULL) != 0)
279  throw InvalidFile("FFmpegReader could not open media file.", path);
280 
281  // Retrieve stream information
282  if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
283  throw NoStreamsFound("No streams found in file.", path);
284 
285  videoStream = -1;
286  audioStream = -1;
287 
288  // Init end-of-file detection variables
289  packet_status.reset(true);
290 
291  // Loop through each stream, and identify the video and audio stream index
292  for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
293  // Is this a video stream?
294  if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_VIDEO && videoStream < 0) {
295  videoStream = i;
296  packet_status.video_eof = false;
297  packet_status.packets_eof = false;
298  packet_status.end_of_file = false;
299  }
300  // Is this an audio stream?
301  if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_AUDIO && audioStream < 0) {
302  audioStream = i;
303  packet_status.audio_eof = false;
304  packet_status.packets_eof = false;
305  packet_status.end_of_file = false;
306  }
307  }
308  if (videoStream == -1 && audioStream == -1)
309  throw NoStreamsFound("No video or audio streams found in this file.", path);
310 
311  // Is there a video stream?
312  if (videoStream != -1) {
313  // Set the stream index
314  info.video_stream_index = videoStream;
315 
316  // Set the codec and codec context pointers
317  pStream = pFormatCtx->streams[videoStream];
318 
319  // Find the codec ID from stream
320  const AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(pStream);
321 
322  // Get codec and codec context from stream
323  const AVCodec *pCodec = avcodec_find_decoder(codecId);
324  AVDictionary *opts = NULL;
325  int retry_decode_open = 2;
326  // If hw accel is selected but hardware cannot handle repeat with software decoding
327  do {
328  pCodecCtx = AV_GET_CODEC_CONTEXT(pStream, pCodec);
329 #if USE_HW_ACCEL
330  if (hw_de_on && (retry_decode_open==2)) {
331  // Up to here no decision is made if hardware or software decode
332  hw_de_supported = IsHardwareDecodeSupported(pCodecCtx->codec_id);
333  }
334 #endif
335  retry_decode_open = 0;
336 
337  // Set number of threads equal to number of processors (not to exceed 16)
338  pCodecCtx->thread_count = std::min(FF_VIDEO_NUM_PROCESSORS, 16);
339 
340  if (pCodec == NULL) {
341  throw InvalidCodec("A valid video codec could not be found for this file.", path);
342  }
343 
344  // Init options
345  av_dict_set(&opts, "strict", "experimental", 0);
346 #if USE_HW_ACCEL
347  if (hw_de_on && hw_de_supported) {
348  // Open Hardware Acceleration
349  int i_decoder_hw = 0;
350  char adapter[256];
351  char *adapter_ptr = NULL;
352  int adapter_num;
354  ZmqLogger::Instance()->AppendDebugMethod("Hardware decoding device number", "adapter_num", adapter_num);
355 
356  // Set hardware pix format (callback)
357  pCodecCtx->get_format = get_hw_dec_format;
358 
359  if (adapter_num < 3 && adapter_num >=0) {
360 #if defined(__linux__)
361  snprintf(adapter,sizeof(adapter),"/dev/dri/renderD%d", adapter_num+128);
362  adapter_ptr = adapter;
364  switch (i_decoder_hw) {
365  case 1:
366  hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
367  break;
368  case 2:
369  hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
370  break;
371  case 6:
372  hw_de_av_device_type = AV_HWDEVICE_TYPE_VDPAU;
373  break;
374  case 7:
375  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
376  break;
377  default:
378  hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
379  break;
380  }
381 
382 #elif defined(_WIN32)
383  adapter_ptr = NULL;
385  switch (i_decoder_hw) {
386  case 2:
387  hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
388  break;
389  case 3:
390  hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
391  break;
392  case 4:
393  hw_de_av_device_type = AV_HWDEVICE_TYPE_D3D11VA;
394  break;
395  case 7:
396  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
397  break;
398  default:
399  hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
400  break;
401  }
402 #elif defined(__APPLE__)
403  adapter_ptr = NULL;
405  switch (i_decoder_hw) {
406  case 5:
407  hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
408  break;
409  case 7:
410  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
411  break;
412  default:
413  hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
414  break;
415  }
416 #endif
417 
418  } else {
419  adapter_ptr = NULL; // Just to be sure
420  }
421 
422  // Check if it is there and writable
423 #if defined(__linux__)
424  if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
425 #elif defined(_WIN32)
426  if( adapter_ptr != NULL ) {
427 #elif defined(__APPLE__)
428  if( adapter_ptr != NULL ) {
429 #endif
430  ZmqLogger::Instance()->AppendDebugMethod("Decode Device present using device");
431  }
432  else {
433  adapter_ptr = NULL; // use default
434  ZmqLogger::Instance()->AppendDebugMethod("Decode Device not present using default");
435  }
436 
437  hw_device_ctx = NULL;
438  // Here the first hardware initialisations are made
439  if (av_hwdevice_ctx_create(&hw_device_ctx, hw_de_av_device_type, adapter_ptr, NULL, 0) >= 0) {
440  const char* hw_name = av_hwdevice_get_type_name(hw_de_av_device_type);
441  std::string hw_msg = "HW decode active: ";
442  hw_msg += (hw_name ? hw_name : "unknown");
443  ZmqLogger::Instance()->Log(hw_msg);
444  if (!(pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx))) {
445  throw InvalidCodec("Hardware device reference create failed.", path);
446  }
447 
448  /*
449  av_buffer_unref(&ist->hw_frames_ctx);
450  ist->hw_frames_ctx = av_hwframe_ctx_alloc(hw_device_ctx);
451  if (!ist->hw_frames_ctx) {
452  av_log(avctx, AV_LOG_ERROR, "Error creating a CUDA frames context\n");
453  return AVERROR(ENOMEM);
454  }
455 
456  frames_ctx = (AVHWFramesContext*)ist->hw_frames_ctx->data;
457 
458  frames_ctx->format = AV_PIX_FMT_CUDA;
459  frames_ctx->sw_format = avctx->sw_pix_fmt;
460  frames_ctx->width = avctx->width;
461  frames_ctx->height = avctx->height;
462 
463  av_log(avctx, AV_LOG_DEBUG, "Initializing CUDA frames context: sw_format = %s, width = %d, height = %d\n",
464  av_get_pix_fmt_name(frames_ctx->sw_format), frames_ctx->width, frames_ctx->height);
465 
466 
467  ret = av_hwframe_ctx_init(pCodecCtx->hw_device_ctx);
468  ret = av_hwframe_ctx_init(ist->hw_frames_ctx);
469  if (ret < 0) {
470  av_log(avctx, AV_LOG_ERROR, "Error initializing a CUDA frame pool\n");
471  return ret;
472  }
473  */
474  }
475  else {
476  ZmqLogger::Instance()->Log("HW decode active: no (falling back to software)");
477  throw InvalidCodec("Hardware device create failed.", path);
478  }
479  }
480 #endif // USE_HW_ACCEL
481 
482  // Disable per-frame threading for album arts
483  // Using FF_THREAD_FRAME adds one frame decoding delay per thread,
484  // but there's only one frame in this case.
485  if (HasAlbumArt())
486  {
487  pCodecCtx->thread_type &= ~FF_THREAD_FRAME;
488  }
489 
490  // Open video codec
491  int avcodec_return = avcodec_open2(pCodecCtx, pCodec, &opts);
492  if (avcodec_return < 0) {
493  std::stringstream avcodec_error_msg;
494  avcodec_error_msg << "A video codec was found, but could not be opened. Error: " << av_err2string(avcodec_return);
495  throw InvalidCodec(avcodec_error_msg.str(), path);
496  }
497 
498 #if USE_HW_ACCEL
499  if (hw_de_on && hw_de_supported) {
500  AVHWFramesConstraints *constraints = NULL;
501  void *hwconfig = NULL;
502  hwconfig = av_hwdevice_hwconfig_alloc(hw_device_ctx);
503 
504 // TODO: needs va_config!
505 #if ENABLE_VAAPI
506  ((AVVAAPIHWConfig *)hwconfig)->config_id = ((VAAPIDecodeContext *)(pCodecCtx->priv_data))->va_config;
507  constraints = av_hwdevice_get_hwframe_constraints(hw_device_ctx,hwconfig);
508 #endif // ENABLE_VAAPI
509  if (constraints) {
510  if (pCodecCtx->coded_width < constraints->min_width ||
511  pCodecCtx->coded_height < constraints->min_height ||
512  pCodecCtx->coded_width > constraints->max_width ||
513  pCodecCtx->coded_height > constraints->max_height) {
514  ZmqLogger::Instance()->AppendDebugMethod("DIMENSIONS ARE TOO LARGE for hardware acceleration\n");
515  hw_de_supported = 0;
516  retry_decode_open = 1;
517  AV_FREE_CONTEXT(pCodecCtx);
518  if (hw_device_ctx) {
519  av_buffer_unref(&hw_device_ctx);
520  hw_device_ctx = NULL;
521  }
522  }
523  else {
524  // All is just peachy
525  ZmqLogger::Instance()->AppendDebugMethod("\nDecode hardware acceleration is used\n", "Min width :", constraints->min_width, "Min Height :", constraints->min_height, "MaxWidth :", constraints->max_width, "MaxHeight :", constraints->max_height, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
526  retry_decode_open = 0;
527  }
528  av_hwframe_constraints_free(&constraints);
529  if (hwconfig) {
530  av_freep(&hwconfig);
531  }
532  }
533  else {
534  int max_h, max_w;
535  //max_h = ((getenv( "LIMIT_HEIGHT_MAX" )==NULL) ? MAX_SUPPORTED_HEIGHT : atoi(getenv( "LIMIT_HEIGHT_MAX" )));
537  //max_w = ((getenv( "LIMIT_WIDTH_MAX" )==NULL) ? MAX_SUPPORTED_WIDTH : atoi(getenv( "LIMIT_WIDTH_MAX" )));
539  ZmqLogger::Instance()->AppendDebugMethod("Constraints could not be found using default limit\n");
540  //cerr << "Constraints could not be found using default limit\n";
541  if (pCodecCtx->coded_width < 0 ||
542  pCodecCtx->coded_height < 0 ||
543  pCodecCtx->coded_width > max_w ||
544  pCodecCtx->coded_height > max_h ) {
545  ZmqLogger::Instance()->AppendDebugMethod("DIMENSIONS ARE TOO LARGE for hardware acceleration\n", "Max Width :", max_w, "Max Height :", max_h, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
546  hw_de_supported = 0;
547  retry_decode_open = 1;
548  AV_FREE_CONTEXT(pCodecCtx);
549  if (hw_device_ctx) {
550  av_buffer_unref(&hw_device_ctx);
551  hw_device_ctx = NULL;
552  }
553  }
554  else {
555  ZmqLogger::Instance()->AppendDebugMethod("\nDecode hardware acceleration is used\n", "Max Width :", max_w, "Max Height :", max_h, "Frame width :", pCodecCtx->coded_width, "Frame height :", pCodecCtx->coded_height);
556  retry_decode_open = 0;
557  }
558  }
559  } // if hw_de_on && hw_de_supported
560  else {
561  ZmqLogger::Instance()->AppendDebugMethod("\nDecode in software is used\n");
562  }
563 #else
564  retry_decode_open = 0;
565 #endif // USE_HW_ACCEL
566  } while (retry_decode_open); // retry_decode_open
567  // Free options
568  av_dict_free(&opts);
569 
570  // Update the File Info struct with video details (if a video stream is found)
571  UpdateVideoInfo();
572  }
573 
574  // Is there an audio stream?
575  if (audioStream != -1) {
576  // Set the stream index
577  info.audio_stream_index = audioStream;
578 
579  // Get a pointer to the codec context for the audio stream
580  aStream = pFormatCtx->streams[audioStream];
581 
582  // Find the codec ID from stream
583  AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(aStream);
584 
585  // Get codec and codec context from stream
586  const AVCodec *aCodec = avcodec_find_decoder(codecId);
587  aCodecCtx = AV_GET_CODEC_CONTEXT(aStream, aCodec);
588 
589  // Audio encoding does not typically use more than 2 threads (most codecs use 1 thread)
590  aCodecCtx->thread_count = std::min(FF_AUDIO_NUM_PROCESSORS, 2);
591 
592  bool audio_opened = false;
593  if (aCodec != NULL) {
594  // Init options
595  AVDictionary *opts = NULL;
596  av_dict_set(&opts, "strict", "experimental", 0);
597 
598  // Open audio codec
599  audio_opened = (avcodec_open2(aCodecCtx, aCodec, &opts) >= 0);
600 
601  // Free options
602  av_dict_free(&opts);
603  }
604 
605  if (audio_opened) {
606  // Update the File Info struct with audio details (if an audio stream is found)
607  UpdateAudioInfo();
608 
609  // Disable malformed audio stream metadata (prevents divide-by-zero / invalid resampling math)
610  const bool invalid_audio_info =
611  (info.channels <= 0) ||
612  (info.sample_rate <= 0) ||
613  (info.audio_timebase.num <= 0) ||
614  (info.audio_timebase.den <= 0) ||
615  (aCodecCtx->sample_fmt == AV_SAMPLE_FMT_NONE);
616  if (invalid_audio_info) {
618  "FFmpegReader::Open (Disable invalid audio stream)",
619  "channels", info.channels,
620  "sample_rate", info.sample_rate,
621  "audio_timebase.num", info.audio_timebase.num,
622  "audio_timebase.den", info.audio_timebase.den,
623  "sample_fmt", static_cast<int>(aCodecCtx ? aCodecCtx->sample_fmt : AV_SAMPLE_FMT_NONE));
624  info.has_audio = false;
626  audioStream = -1;
627  packet_status.audio_eof = true;
628  if (aCodecCtx) {
629  if (avcodec_is_open(aCodecCtx)) {
630  avcodec_flush_buffers(aCodecCtx);
631  }
632  AV_FREE_CONTEXT(aCodecCtx);
633  aCodecCtx = nullptr;
634  }
635  aStream = nullptr;
636  }
637  } else {
638  // Keep decoding video, but disable bad/unsupported audio stream.
640  "FFmpegReader::Open (Audio codec unavailable; disabling audio)",
641  "audioStream", audioStream);
642  info.has_audio = false;
644  audioStream = -1;
645  packet_status.audio_eof = true;
646  if (aCodecCtx) {
647  AV_FREE_CONTEXT(aCodecCtx);
648  aCodecCtx = nullptr;
649  }
650  aStream = nullptr;
651  }
652  }
653 
654  // Guard invalid frame-rate / timebase values from malformed streams.
655  if (info.fps.num <= 0 || info.fps.den <= 0) {
657  "FFmpegReader::Open (Invalid FPS detected; applying fallback)",
658  "fps.num", info.fps.num,
659  "fps.den", info.fps.den);
660  info.fps.num = 30;
661  info.fps.den = 1;
662  }
663  if (info.video_timebase.num <= 0 || info.video_timebase.den <= 0) {
665  "FFmpegReader::Open (Invalid video_timebase detected; applying fallback)",
666  "video_timebase.num", info.video_timebase.num,
667  "video_timebase.den", info.video_timebase.den);
669  }
670 
671  // Add format metadata (if any)
672  AVDictionaryEntry *tag = NULL;
673  while ((tag = av_dict_get(pFormatCtx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
674  QString str_key = tag->key;
675  QString str_value = tag->value;
676  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
677  }
678 
679  // Process video stream side data (rotation, spherical metadata, etc)
680  for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
681  AVStream* st = pFormatCtx->streams[i];
682  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
683  size_t side_data_size = 0;
684  const uint8_t *displaymatrix = ffmpeg_stream_get_side_data(
685  st, AV_PKT_DATA_DISPLAYMATRIX, &side_data_size);
686  if (displaymatrix &&
687  side_data_size >= 9 * sizeof(int32_t) &&
688  !info.metadata.count("rotate")) {
689  double rotation = -av_display_rotation_get(
690  reinterpret_cast<const int32_t *>(displaymatrix));
691  if (std::isnan(rotation))
692  rotation = 0;
693  info.metadata["rotate"] = std::to_string(rotation);
694  }
695 
696  const uint8_t *spherical = ffmpeg_stream_get_side_data(
697  st, AV_PKT_DATA_SPHERICAL, &side_data_size);
698  if (spherical && side_data_size >= sizeof(AVSphericalMapping)) {
699  info.metadata["spherical"] = "1";
700 
701  const AVSphericalMapping *map =
702  reinterpret_cast<const AVSphericalMapping *>(spherical);
703  const char *proj_name = av_spherical_projection_name(map->projection);
704  info.metadata["spherical_projection"] = proj_name ? proj_name : "unknown";
705 
706  auto to_deg = [](int32_t v) {
707  return static_cast<double>(v) / 65536.0;
708  };
709  info.metadata["spherical_yaw"] = std::to_string(to_deg(map->yaw));
710  info.metadata["spherical_pitch"] = std::to_string(to_deg(map->pitch));
711  info.metadata["spherical_roll"] = std::to_string(to_deg(map->roll));
712  }
713  break;
714  }
715  }
716 
717  // Init previous audio location to zero
718  previous_packet_location.frame = -1;
719  previous_packet_location.sample_start = 0;
720 
721  // Adjust cache size based on size of frame and audio
722  const int working_cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, int(OPEN_MP_NUM_PROCESSORS * info.fps.ToDouble() * 2));
723  const int final_cache_frames = std::max(Settings::Instance()->CACHE_MIN_FRAMES, OPEN_MP_NUM_PROCESSORS * 2);
724  working_cache.SetMaxBytesFromInfo(working_cache_frames, info.width, info.height, info.sample_rate, info.channels);
726 
727  // Scan PTS for any offsets (i.e. non-zero starting streams). At least 1 stream must start at zero timestamp.
728  // This method allows us to shift timestamps to ensure at least 1 stream is starting at zero.
729  UpdatePTSOffset();
730 
731  // Override an invalid framerate
732  if (info.fps.ToFloat() > 240.0f || (info.fps.num <= 0 || info.fps.den <= 0) || info.video_length <= 0) {
733  // Calculate FPS, duration, video bit rate, and video length manually
734  // by scanning through all the video stream packets
735  CheckFPS();
736  }
737 
738  // Mark as "open"
739  is_open = true;
740 
741  // Seek back to beginning of file (if not already seeking)
742  if (!is_seeking) {
743  Seek(1);
744  }
745  }
746 }
747 
749  // Close all objects, if reader is 'open'
750  if (is_open) {
751  // Prevent async calls to the following code
752  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
753 
754  // Mark as "closed"
755  is_open = false;
756 
757  // Keep track of most recent packet
758  AVPacket *recent_packet = packet;
759 
760  // Drain any packets from the decoder
761  packet = NULL;
762  int attempts = 0;
763  int max_attempts = 128;
764  while (packet_status.packets_decoded() < packet_status.packets_read() && attempts < max_attempts) {
765  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::Close (Drain decoder loop)",
766  "packets_read", packet_status.packets_read(),
767  "packets_decoded", packet_status.packets_decoded(),
768  "attempts", attempts);
769  if (packet_status.video_decoded < packet_status.video_read) {
770  ProcessVideoPacket(info.video_length);
771  }
772  if (packet_status.audio_decoded < packet_status.audio_read) {
773  ProcessAudioPacket(info.video_length);
774  }
775  attempts++;
776  }
777 
778  // Remove packet
779  if (recent_packet) {
780  RemoveAVPacket(recent_packet);
781  }
782 
783  // Close the video codec
784  if (info.has_video) {
785  if(avcodec_is_open(pCodecCtx)) {
786  avcodec_flush_buffers(pCodecCtx);
787  }
788  AV_FREE_CONTEXT(pCodecCtx);
789 #if USE_HW_ACCEL
790  if (hw_de_on) {
791  if (hw_device_ctx) {
792  av_buffer_unref(&hw_device_ctx);
793  hw_device_ctx = NULL;
794  }
795  }
796 #endif // USE_HW_ACCEL
797  if (img_convert_ctx) {
798  sws_freeContext(img_convert_ctx);
799  img_convert_ctx = nullptr;
800  }
801  if (pFrameRGB_cached) {
802  AV_FREE_FRAME(&pFrameRGB_cached);
803  }
804  }
805 
806  // Close the audio codec
807  if (info.has_audio) {
808  if(avcodec_is_open(aCodecCtx)) {
809  avcodec_flush_buffers(aCodecCtx);
810  }
811  AV_FREE_CONTEXT(aCodecCtx);
812  if (avr_ctx) {
813  SWR_CLOSE(avr_ctx);
814  SWR_FREE(&avr_ctx);
815  avr_ctx = nullptr;
816  }
817  }
818 
819  // Clear final cache
820  final_cache.Clear();
821  working_cache.Clear();
822 
823  // Close the video file
824  avformat_close_input(&pFormatCtx);
825  av_freep(&pFormatCtx);
826 
827  // Do not trim here; trimming is handled on explicit cache clears
828 
829  // Reset some variables
830  last_frame = 0;
831  hold_packet = false;
832  largest_frame_processed = 0;
833  seek_audio_frame_found = 0;
834  seek_video_frame_found = 0;
835  current_video_frame = 0;
836  last_video_frame.reset();
837  last_final_video_frame.reset();
838  }
839 }
840 
841 bool FFmpegReader::HasAlbumArt() {
842  // Check if the video stream we use is an attached picture
843  // This won't return true if the file has a cover image as a secondary stream
844  // like an MKV file with an attached image file
845  return pFormatCtx && videoStream >= 0 && pFormatCtx->streams[videoStream]
846  && (pFormatCtx->streams[videoStream]->disposition & AV_DISPOSITION_ATTACHED_PIC);
847 }
848 
849 double FFmpegReader::PickDurationSeconds() const {
850  auto has_value = [](double value) { return value > 0.0; };
851 
852  switch (duration_strategy) {
854  if (has_value(video_stream_duration_seconds))
855  return video_stream_duration_seconds;
856  if (has_value(audio_stream_duration_seconds))
857  return audio_stream_duration_seconds;
858  if (has_value(format_duration_seconds))
859  return format_duration_seconds;
860  break;
862  if (has_value(audio_stream_duration_seconds))
863  return audio_stream_duration_seconds;
864  if (has_value(video_stream_duration_seconds))
865  return video_stream_duration_seconds;
866  if (has_value(format_duration_seconds))
867  return format_duration_seconds;
868  break;
870  default:
871  {
872  double longest = 0.0;
873  if (has_value(video_stream_duration_seconds))
874  longest = std::max(longest, video_stream_duration_seconds);
875  if (has_value(audio_stream_duration_seconds))
876  longest = std::max(longest, audio_stream_duration_seconds);
877  if (has_value(format_duration_seconds))
878  longest = std::max(longest, format_duration_seconds);
879  if (has_value(longest))
880  return longest;
881  }
882  break;
883  }
884 
885  if (has_value(format_duration_seconds))
886  return format_duration_seconds;
887  if (has_value(inferred_duration_seconds))
888  return inferred_duration_seconds;
889 
890  return 0.0;
891 }
892 
893 void FFmpegReader::ApplyDurationStrategy() {
894  const double fps_value = info.fps.ToDouble();
895  const double chosen_seconds = PickDurationSeconds();
896 
897  if (chosen_seconds <= 0.0 || fps_value <= 0.0) {
898  info.duration = 0.0f;
899  info.video_length = 0;
900  is_duration_known = false;
901  return;
902  }
903 
904  const int64_t frames = static_cast<int64_t>(std::llround(chosen_seconds * fps_value));
905  if (frames <= 0) {
906  info.duration = 0.0f;
907  info.video_length = 0;
908  is_duration_known = false;
909  return;
910  }
911 
912  info.video_length = frames;
913  info.duration = static_cast<float>(static_cast<double>(frames) / fps_value);
914  is_duration_known = true;
915 }
916 
917 void FFmpegReader::UpdateAudioInfo() {
918  int codec_channels =
919 #if HAVE_CH_LAYOUT
920  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout.nb_channels;
921 #else
922  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
923 #endif
924 
925  // Set default audio channel layout (if needed)
926 #if HAVE_CH_LAYOUT
927  AVChannelLayout audio_ch_layout = ffmpeg_get_valid_channel_layout(
928  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout, codec_channels);
929  if (audio_ch_layout.nb_channels > 0) {
930  av_channel_layout_uninit(&(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout));
931  av_channel_layout_copy(&(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout), &audio_ch_layout);
932  codec_channels = audio_ch_layout.nb_channels;
933  }
934 #else
935  if (codec_channels > 0 && AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout == 0)
936  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout = av_get_default_channel_layout(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels);
937 #endif
938 
939  if (info.sample_rate > 0) {
940  // Skip init - if info struct already populated
941  return;
942  }
943 
944  auto record_duration = [](double &target, double seconds) {
945  if (seconds > 0.0)
946  target = std::max(target, seconds);
947  };
948 
949  // Set values of FileInfo struct
950  info.has_audio = true;
951  info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
952  info.acodec = aCodecCtx->codec->name;
953 #if HAVE_CH_LAYOUT
954  info.channels = audio_ch_layout.nb_channels;
955  info.channel_layout = static_cast<ChannelLayout>(ffmpeg_channel_layout_mask(audio_ch_layout));
956 #else
957  info.channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
958  info.channel_layout = (ChannelLayout) AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout;
959 #endif
960 
961  // If channel layout is not set, guess based on the number of channels
962  if (info.channel_layout == 0) {
963  if (info.channels == 1) {
965  } else if (info.channels == 2) {
967  }
968  }
969 
970  info.sample_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->sample_rate;
971  info.audio_bit_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->bit_rate;
972  if (info.audio_bit_rate <= 0) {
973  // Get bitrate from format
974  info.audio_bit_rate = pFormatCtx->bit_rate;
975  }
976 
977  // Set audio timebase
978  info.audio_timebase.num = aStream->time_base.num;
979  info.audio_timebase.den = aStream->time_base.den;
980 
981  // Get timebase of audio stream (if valid) and greater than the current duration
982  if (aStream->duration > 0) {
983  record_duration(audio_stream_duration_seconds, aStream->duration * info.audio_timebase.ToDouble());
984  }
985  if (pFormatCtx->duration > 0) {
986  // Use the format's duration when stream duration is missing or shorter
987  record_duration(format_duration_seconds, static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
988  }
989 
990  // Calculate duration from filesize and bitrate (if any)
991  if (info.duration <= 0.0f && info.video_bit_rate > 0 && info.file_size > 0) {
992  // Estimate from bitrate, total bytes, and framerate
993  record_duration(inferred_duration_seconds, static_cast<double>(info.file_size) / info.video_bit_rate);
994  }
995 
996  // Set video timebase (if no video stream was found)
997  if (!info.has_video) {
998  // Set a few important default video settings (so audio can be divided into frames)
999  info.fps.num = 30;
1000  info.fps.den = 1;
1001  info.video_timebase.num = 1;
1002  info.video_timebase.den = 30;
1003  info.width = 720;
1004  info.height = 480;
1005 
1006  // Use timeline to set correct width & height (if any)
1007  Clip *parent = static_cast<Clip *>(ParentClip());
1008  if (parent) {
1009  if (parent->ParentTimeline()) {
1010  // Set max width/height based on parent clip's timeline (if attached to a timeline)
1011  info.width = parent->ParentTimeline()->preview_width;
1012  info.height = parent->ParentTimeline()->preview_height;
1013  }
1014  }
1015  }
1016 
1017  ApplyDurationStrategy();
1018 
1019  // Add audio metadata (if any found)
1020  AVDictionaryEntry *tag = NULL;
1021  while ((tag = av_dict_get(aStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1022  QString str_key = tag->key;
1023  QString str_value = tag->value;
1024  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
1025  }
1026 #if HAVE_CH_LAYOUT
1027  av_channel_layout_uninit(&audio_ch_layout);
1028 #endif
1029 }
1030 
1031 void FFmpegReader::UpdateVideoInfo() {
1032  if (info.vcodec.length() > 0) {
1033  // Skip init - if info struct already populated
1034  return;
1035  }
1036 
1037  auto record_duration = [](double &target, double seconds) {
1038  if (seconds > 0.0)
1039  target = std::max(target, seconds);
1040  };
1041 
1042  // Set values of FileInfo struct
1043  info.has_video = true;
1044  info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
1045  info.height = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->height;
1046  info.width = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->width;
1047  info.vcodec = pCodecCtx->codec->name;
1048  info.video_bit_rate = (pFormatCtx->bit_rate / 8);
1049 
1050  // Frame rate from the container and codec
1051  AVRational framerate = av_guess_frame_rate(pFormatCtx, pStream, NULL);
1052  if (!check_fps) {
1053  info.fps.num = framerate.num;
1054  info.fps.den = framerate.den;
1055  }
1056 
1057  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo", "info.fps.num", info.fps.num, "info.fps.den", info.fps.den);
1058 
1059  // TODO: remove excessive debug info in the next releases
1060  // The debug info below is just for comparison and troubleshooting on users side during the transition period
1061  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo (pStream->avg_frame_rate)", "num", pStream->avg_frame_rate.num, "den", pStream->avg_frame_rate.den);
1062 
1063  if (pStream->sample_aspect_ratio.num != 0) {
1064  info.pixel_ratio.num = pStream->sample_aspect_ratio.num;
1065  info.pixel_ratio.den = pStream->sample_aspect_ratio.den;
1066  } else if (AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num != 0) {
1067  info.pixel_ratio.num = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num;
1068  info.pixel_ratio.den = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.den;
1069  } else {
1070  info.pixel_ratio.num = 1;
1071  info.pixel_ratio.den = 1;
1072  }
1073  info.pixel_format = AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx);
1074 
1075  // Calculate the DAR (display aspect ratio)
1077 
1078  // Reduce size fraction
1079  size.Reduce();
1080 
1081  // Set the ratio based on the reduced fraction
1082  info.display_ratio.num = size.num;
1083  info.display_ratio.den = size.den;
1084 
1085  // Get scan type and order from codec context/params
1086  if (!check_interlace) {
1087  check_interlace = true;
1088  AVFieldOrder field_order = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->field_order;
1089  switch(field_order) {
1090  case AV_FIELD_PROGRESSIVE:
1091  info.interlaced_frame = false;
1092  break;
1093  case AV_FIELD_TT:
1094  case AV_FIELD_TB:
1095  info.interlaced_frame = true;
1096  info.top_field_first = true;
1097  break;
1098  case AV_FIELD_BT:
1099  case AV_FIELD_BB:
1100  info.interlaced_frame = true;
1101  info.top_field_first = false;
1102  break;
1103  case AV_FIELD_UNKNOWN:
1104  // Check again later?
1105  check_interlace = false;
1106  break;
1107  }
1108  // check_interlace will prevent these checks being repeated,
1109  // unless it was cleared because we got an AV_FIELD_UNKNOWN response.
1110  }
1111 
1112  // Set the video timebase
1113  info.video_timebase.num = pStream->time_base.num;
1114  info.video_timebase.den = pStream->time_base.den;
1115 
1116  // Set the duration in seconds, and video length (# of frames)
1117  record_duration(video_stream_duration_seconds, pStream->duration * info.video_timebase.ToDouble());
1118 
1119  // Check for valid duration (if found)
1120  if (pFormatCtx->duration >= 0) {
1121  // Use the format's duration as another candidate
1122  record_duration(format_duration_seconds, static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
1123  }
1124 
1125  // Calculate duration from filesize and bitrate (if any)
1126  if (info.video_bit_rate > 0 && info.file_size > 0) {
1127  // Estimate from bitrate, total bytes, and framerate
1128  record_duration(inferred_duration_seconds, static_cast<double>(info.file_size) / info.video_bit_rate);
1129  }
1130 
1131  // Certain "image" formats do not have a valid duration
1132  if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1133  pStream->duration == AV_NOPTS_VALUE && pFormatCtx->duration == AV_NOPTS_VALUE) {
1134  // Force an "image" duration
1135  record_duration(video_stream_duration_seconds, 60 * 60 * 1); // 1 hour duration
1136  info.has_single_image = true;
1137  }
1138  // Static GIFs can have no usable duration; fall back to a small default
1139  if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1140  pFormatCtx && pFormatCtx->iformat && strcmp(pFormatCtx->iformat->name, "gif") == 0) {
1141  record_duration(video_stream_duration_seconds, 60 * 60 * 1); // 1 hour duration
1142  info.has_single_image = true;
1143  }
1144 
1145  ApplyDurationStrategy();
1146 
1147  // Normalize FFmpeg-decoded still images (e.g. JPG/JPEG) to match image-reader behavior.
1148  // This keeps timing/flags consistent regardless of which reader path was used.
1149  if (!info.has_single_image) {
1150  const AVCodecID codec_id = AV_FIND_DECODER_CODEC_ID(pStream);
1151  const bool likely_still_codec =
1152  codec_id == AV_CODEC_ID_MJPEG ||
1153  codec_id == AV_CODEC_ID_PNG ||
1154  codec_id == AV_CODEC_ID_BMP ||
1155  codec_id == AV_CODEC_ID_TIFF ||
1156  codec_id == AV_CODEC_ID_WEBP ||
1157  codec_id == AV_CODEC_ID_JPEG2000;
1158  const bool likely_image_demuxer =
1159  pFormatCtx && pFormatCtx->iformat && pFormatCtx->iformat->name &&
1160  strstr(pFormatCtx->iformat->name, "image2");
1161  const bool has_attached_pic = HasAlbumArt();
1162  const bool single_frame_stream =
1163  (pStream && pStream->nb_frames > 0 && pStream->nb_frames <= 1);
1164  const bool single_frame_clip = info.video_length <= 1;
1165 
1166  const bool is_still_image_video =
1167  has_attached_pic ||
1168  ((single_frame_stream || single_frame_clip) &&
1169  (likely_still_codec || likely_image_demuxer));
1170 
1171  if (is_still_image_video) {
1172  info.has_single_image = true;
1173 
1174  // Only force long duration for standalone images. For audio + attached-art
1175  // files, keep stream-derived duration so the cover image spans the audio.
1176  if (audioStream < 0) {
1177  record_duration(video_stream_duration_seconds, 60 * 60 * 1); // 1 hour duration
1178  }
1179 
1180  ApplyDurationStrategy();
1181  }
1182  }
1183 
1184  // Add video metadata (if any)
1185  AVDictionaryEntry *tag = NULL;
1186  while ((tag = av_dict_get(pStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1187  QString str_key = tag->key;
1188  QString str_value = tag->value;
1189  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
1190  }
1191 }
1192 
1194  return this->is_duration_known;
1195 }
1196 
1197 std::shared_ptr<Frame> FFmpegReader::GetFrame(int64_t requested_frame) {
1198  last_seek_max_frame = -1;
1199  seek_stagnant_count = 0;
1200  // Check for open reader (or throw exception)
1201  if (!is_open)
1202  throw ReaderClosed("The FFmpegReader is closed. Call Open() before calling this method.", path);
1203 
1204  // Adjust for a requested frame that is too small or too large
1205  if (requested_frame < 1)
1206  requested_frame = 1;
1207  if (requested_frame > info.video_length && is_duration_known)
1208  requested_frame = info.video_length;
1209  if (info.has_video && info.video_length == 0)
1210  // Invalid duration of video file
1211  throw InvalidFile("Could not detect the duration of the video or audio stream.", path);
1212 
1213  // Debug output
1214  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "requested_frame", requested_frame, "last_frame", last_frame);
1215 
1216  // Check the cache for this frame
1217  std::shared_ptr<Frame> frame = final_cache.GetFrame(requested_frame);
1218  if (frame) {
1219  // Debug output
1220  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame", requested_frame);
1221  // Return the cached frame
1222  return frame;
1223  } else {
1224 
1225  // Prevent async calls to the remainder of this code
1226  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1227 
1228  // Check the cache a 2nd time (due to the potential previous lock)
1229  frame = final_cache.GetFrame(requested_frame);
1230  if (frame) {
1231  // Debug output
1232  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame on 2nd look", requested_frame);
1233  } else {
1234  // Frame is not in cache
1235  // Reset seek count
1236  seek_count = 0;
1237 
1238  // Are we within X frames of the requested frame?
1239  int64_t diff = requested_frame - last_frame;
1240  if (diff >= 1 && diff <= 20) {
1241  // Continue walking the stream
1242  frame = ReadStream(requested_frame);
1243  } else {
1244  // Greater than 30 frames away, or backwards, we need to seek to the nearest key frame
1245  if (enable_seek) {
1246  // Only seek if enabled
1247  Seek(requested_frame);
1248 
1249  } else if (!enable_seek && diff < 0) {
1250  // Start over, since we can't seek, and the requested frame is smaller than our position
1251  // Since we are seeking to frame 1, this actually just closes/re-opens the reader
1252  Seek(1);
1253  }
1254 
1255  // Then continue walking the stream
1256  frame = ReadStream(requested_frame);
1257  }
1258  }
1259  return frame;
1260  }
1261 }
1262 
1263 // Read the stream until we find the requested Frame
1264 std::shared_ptr<Frame> FFmpegReader::ReadStream(int64_t requested_frame) {
1265  // Allocate video frame
1266  bool check_seek = false;
1267  int packet_error = -1;
1268  int64_t no_progress_count = 0;
1269  int64_t prev_packets_read = packet_status.packets_read();
1270  int64_t prev_packets_decoded = packet_status.packets_decoded();
1271  int64_t prev_video_decoded = packet_status.video_decoded;
1272  double prev_video_pts_seconds = video_pts_seconds;
1273 
1274  // Debug output
1275  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream", "requested_frame", requested_frame);
1276 
1277  // Loop through the stream until the correct frame is found
1278  while (true) {
1279  // Check if working frames are 'finished'
1280  if (!is_seeking) {
1281  // Check for final frames
1282  CheckWorkingFrames(requested_frame);
1283  }
1284 
1285  // Check if requested 'final' frame is available (and break out of loop if found)
1286  bool is_cache_found = (final_cache.GetFrame(requested_frame) != NULL);
1287  if (is_cache_found) {
1288  break;
1289  }
1290 
1291  if (!hold_packet || !packet) {
1292  // Get the next packet
1293  packet_error = GetNextPacket();
1294  if (packet_error < 0 && !packet) {
1295  // No more packets to be found
1296  packet_status.packets_eof = true;
1297  }
1298  }
1299 
1300  // Debug output
1301  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (GetNextPacket)", "requested_frame", requested_frame,"packets_read", packet_status.packets_read(), "packets_decoded", packet_status.packets_decoded(), "is_seeking", is_seeking);
1302 
1303  // Check the status of a seek (if any)
1304  if (is_seeking) {
1305  check_seek = CheckSeek();
1306  } else {
1307  check_seek = false;
1308  }
1309 
1310  if (check_seek) {
1311  // Packet may become NULL on Close inside Seek if CheckSeek returns false
1312  // Jump to the next iteration of this loop
1313  continue;
1314  }
1315 
1316  // Video packet
1317  if ((info.has_video && packet && packet->stream_index == videoStream) ||
1318  (info.has_video && packet_status.video_decoded < packet_status.video_read) ||
1319  (info.has_video && !packet && !packet_status.video_eof)) {
1320  // Process Video Packet
1321  ProcessVideoPacket(requested_frame);
1322  if (ReopenWithoutHardwareDecode(requested_frame)) {
1323  continue;
1324  }
1325  }
1326  // Audio packet
1327  if ((info.has_audio && packet && packet->stream_index == audioStream) ||
1328  (info.has_audio && !packet && packet_status.audio_decoded < packet_status.audio_read) ||
1329  (info.has_audio && !packet && !packet_status.audio_eof)) {
1330  // Process Audio Packet
1331  ProcessAudioPacket(requested_frame);
1332  }
1333 
1334  // Remove unused packets (sometimes we purposely ignore video or audio packets,
1335  // if the has_video or has_audio properties are manually overridden)
1336  if ((!info.has_video && packet && packet->stream_index == videoStream) ||
1337  (!info.has_audio && packet && packet->stream_index == audioStream)) {
1338  // Keep track of deleted packet counts
1339  if (packet->stream_index == videoStream) {
1340  packet_status.video_decoded++;
1341  } else if (packet->stream_index == audioStream) {
1342  packet_status.audio_decoded++;
1343  }
1344 
1345  // Remove unused packets (sometimes we purposely ignore video or audio packets,
1346  // if the has_video or has_audio properties are manually overridden)
1347  RemoveAVPacket(packet);
1348  packet = NULL;
1349  }
1350 
1351  // Determine end-of-stream (waiting until final decoder threads finish)
1352  // Force end-of-stream in some situations
1353  packet_status.end_of_file = packet_status.packets_eof && packet_status.video_eof && packet_status.audio_eof;
1354  if ((packet_status.packets_eof && packet_status.packets_read() == packet_status.packets_decoded()) || packet_status.end_of_file) {
1355  // Force EOF (end of file) variables to true, if decoder does not support EOF detection.
1356  // If we have no more packets, and all known packets have been decoded
1357  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (force EOF)", "packets_read", packet_status.packets_read(), "packets_decoded", packet_status.packets_decoded(), "packets_eof", packet_status.packets_eof, "video_eof", packet_status.video_eof, "audio_eof", packet_status.audio_eof, "end_of_file", packet_status.end_of_file);
1358  if (!packet_status.video_eof) {
1359  packet_status.video_eof = true;
1360  }
1361  if (!packet_status.audio_eof) {
1362  packet_status.audio_eof = true;
1363  }
1364  packet_status.end_of_file = true;
1365  break;
1366  }
1367 
1368  // Detect decoder stalls with no progress at EOF and force completion so
1369  // missing frames can be finalized from prior image data.
1370  const bool has_progress =
1371  (packet_status.packets_read() != prev_packets_read) ||
1372  (packet_status.packets_decoded() != prev_packets_decoded) ||
1373  (packet_status.video_decoded != prev_video_decoded) ||
1374  (video_pts_seconds != prev_video_pts_seconds);
1375 
1376  if (has_progress) {
1377  no_progress_count = 0;
1378  } else {
1379  no_progress_count++;
1380  if (no_progress_count >= 2000
1381  && packet_status.packets_eof
1382  && !packet
1383  && !hold_packet) {
1384  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (force EOF after stall)",
1385  "requested_frame", requested_frame,
1386  "no_progress_count", no_progress_count,
1387  "packets_read", packet_status.packets_read(),
1388  "packets_decoded", packet_status.packets_decoded(),
1389  "video_decoded", packet_status.video_decoded,
1390  "audio_decoded", packet_status.audio_decoded);
1391  packet_status.video_eof = true;
1392  packet_status.audio_eof = true;
1393  packet_status.end_of_file = true;
1394  break;
1395  }
1396  }
1397  prev_packets_read = packet_status.packets_read();
1398  prev_packets_decoded = packet_status.packets_decoded();
1399  prev_video_decoded = packet_status.video_decoded;
1400  prev_video_pts_seconds = video_pts_seconds;
1401  } // end while
1402 
1403  // Debug output
1404  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (Completed)",
1405  "packets_read", packet_status.packets_read(),
1406  "packets_decoded", packet_status.packets_decoded(),
1407  "end_of_file", packet_status.end_of_file,
1408  "largest_frame_processed", largest_frame_processed,
1409  "Working Cache Count", working_cache.Count());
1410 
1411  // Have we reached end-of-stream (or the final frame)?
1412  if (!packet_status.end_of_file && requested_frame >= info.video_length) {
1413  // Force end-of-stream
1414  packet_status.end_of_file = true;
1415  }
1416  if (packet_status.end_of_file) {
1417  // Mark any other working frames as 'finished'
1418  CheckWorkingFrames(requested_frame);
1419  }
1420 
1421  // Return requested frame (if found)
1422  std::shared_ptr<Frame> frame = final_cache.GetFrame(requested_frame);
1423  if (frame)
1424  // Return prepared frame
1425  return frame;
1426  else {
1427 
1428  // Check if largest frame is still cached
1429  frame = final_cache.GetFrame(largest_frame_processed);
1430  int samples_in_frame = Frame::GetSamplesPerFrame(requested_frame, info.fps,
1432  if (frame) {
1433  // Copy and return the largest processed frame (assuming it was the last in the video file)
1434  std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1435 
1436  // Use solid color (if no image data found)
1437  if (!frame->has_image_data) {
1438  // Use solid black frame if no image data available
1439  f->AddColor(info.width, info.height, "#000");
1440  }
1441  // Silence audio data (if any), since we are repeating the last frame
1442  frame->AddAudioSilence(samples_in_frame);
1443 
1444  return frame;
1445  } else {
1446  // The largest processed frame is no longer in cache. Prefer the most recent
1447  // finalized image first, then decoded image, to avoid black flashes.
1448  std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1449  if (last_final_video_frame && last_final_video_frame->has_image_data
1450  && last_final_video_frame->number <= requested_frame) {
1451  f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
1452  } else if (last_video_frame && last_video_frame->has_image_data
1453  && last_video_frame->number <= requested_frame) {
1454  f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
1455  } else {
1456  f->AddColor(info.width, info.height, "#000");
1457  }
1458  f->AddAudioSilence(samples_in_frame);
1459  return f;
1460  }
1461  }
1462 
1463 }
1464 
1465 // Get the next packet (if any)
1466 int FFmpegReader::GetNextPacket() {
1467  int found_packet = 0;
1468  AVPacket *next_packet;
1469  next_packet = new AVPacket();
1470  found_packet = av_read_frame(pFormatCtx, next_packet);
1471 
1472  if (packet) {
1473  // Remove previous packet before getting next one
1474  RemoveAVPacket(packet);
1475  packet = NULL;
1476  }
1477  if (found_packet >= 0) {
1478  // Update current packet pointer
1479  packet = next_packet;
1480 
1481  // Keep track of packet stats
1482  if (packet->stream_index == videoStream) {
1483  packet_status.video_read++;
1484  } else if (packet->stream_index == audioStream) {
1485  packet_status.audio_read++;
1486  }
1487  } else {
1488  // No more packets found
1489  delete next_packet;
1490  packet = NULL;
1491  }
1492  // Return if packet was found (or error number)
1493  return found_packet;
1494 }
1495 
1496 // Get an AVFrame (if any)
1497 bool FFmpegReader::GetAVFrame() {
1498  int frameFinished = 0;
1499  auto note_hw_decode_failure = [&](int err, const char* stage) {
1500 #if USE_HW_ACCEL
1501  if (!hw_de_on || !hw_de_supported || force_sw_decode) {
1502  return;
1503  }
1504  if (err == AVERROR_INVALIDDATA && packet_status.video_decoded == 0) {
1505  hw_decode_error_count++;
1507  std::string("FFmpegReader::GetAVFrame (hardware decode failure candidate during ") + stage + ")",
1508  "error_count", hw_decode_error_count,
1509  "error", err);
1510  if (hw_decode_error_count >= 3) {
1511  hw_decode_failed = true;
1512  }
1513  }
1514 #else
1515  (void) err;
1516  (void) stage;
1517 #endif
1518  };
1519 
1520  // Decode video frame
1521  AVFrame *next_frame = AV_ALLOCATE_FRAME();
1522 
1523 #if IS_FFMPEG_3_2
1524  int send_packet_err = 0;
1525  int64_t send_packet_pts = 0;
1526  if ((packet && packet->stream_index == videoStream) || !packet) {
1527  send_packet_err = avcodec_send_packet(pCodecCtx, packet);
1528 
1529  if (packet && send_packet_err >= 0) {
1530  send_packet_pts = GetPacketPTS();
1531  hold_packet = false;
1532  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet succeeded)", "send_packet_err", send_packet_err, "send_packet_pts", send_packet_pts);
1533  }
1534  }
1535 
1536  #if USE_HW_ACCEL
1537  // Get the format from the variables set in get_hw_dec_format
1538  hw_de_av_pix_fmt = hw_de_av_pix_fmt_global;
1539  hw_de_av_device_type = hw_de_av_device_type_global;
1540  #endif // USE_HW_ACCEL
1541  if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1542  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet: Not sent [" + av_err2string(send_packet_err) + "])", "send_packet_err", send_packet_err, "send_packet_pts", send_packet_pts);
1543  note_hw_decode_failure(send_packet_err, "send_packet");
1544  if (send_packet_err == AVERROR(EAGAIN)) {
1545  hold_packet = true;
1546  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet: AVERROR(EAGAIN): user must read output with avcodec_receive_frame()", "send_packet_pts", send_packet_pts);
1547  }
1548  if (send_packet_err == AVERROR(EINVAL)) {
1549  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet: AVERROR(EINVAL): codec not opened, it is an encoder, or requires flush", "send_packet_pts", send_packet_pts);
1550  }
1551  if (send_packet_err == AVERROR(ENOMEM)) {
1552  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet: AVERROR(ENOMEM): failed to add packet to internal queue, or legitimate decoding errors", "send_packet_pts", send_packet_pts);
1553  }
1554  }
1555 
1556  // Always try and receive a packet, if not EOF.
1557  // Even if the above avcodec_send_packet failed to send,
1558  // we might still need to receive a packet.
1559  int receive_frame_err = 0;
1560  AVFrame *decoded_frame = next_frame;
1561  AVFrame *next_frame2;
1562 #if USE_HW_ACCEL
1563  if (hw_de_on && hw_de_supported) {
1564  next_frame2 = AV_ALLOCATE_FRAME();
1565  }
1566  else
1567 #endif // USE_HW_ACCEL
1568  {
1569  next_frame2 = next_frame;
1570  }
1571  pFrame = AV_ALLOCATE_FRAME();
1572  while (receive_frame_err >= 0) {
1573  receive_frame_err = avcodec_receive_frame(pCodecCtx, next_frame2);
1574 
1575  if (receive_frame_err != 0) {
1576  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (receive frame: frame not ready yet from decoder [\" + av_err2string(receive_frame_err) + \"])", "receive_frame_err", receive_frame_err, "send_packet_pts", send_packet_pts);
1577  note_hw_decode_failure(receive_frame_err, "receive_frame");
1578 
1579  if (receive_frame_err == AVERROR_EOF) {
1581  "FFmpegReader::GetAVFrame (receive frame: AVERROR_EOF: EOF detected from decoder, flushing buffers)", "send_packet_pts", send_packet_pts);
1582  avcodec_flush_buffers(pCodecCtx);
1583  packet_status.video_eof = true;
1584  }
1585  if (receive_frame_err == AVERROR(EINVAL)) {
1587  "FFmpegReader::GetAVFrame (receive frame: AVERROR(EINVAL): invalid frame received, flushing buffers)", "send_packet_pts", send_packet_pts);
1588  avcodec_flush_buffers(pCodecCtx);
1589  }
1590  if (receive_frame_err == AVERROR(EAGAIN)) {
1592  "FFmpegReader::GetAVFrame (receive frame: AVERROR(EAGAIN): output is not available in this state - user must try to send new input)", "send_packet_pts", send_packet_pts);
1593  }
1594  if (receive_frame_err == AVERROR_INPUT_CHANGED) {
1596  "FFmpegReader::GetAVFrame (receive frame: AVERROR_INPUT_CHANGED: current decoded frame has changed parameters with respect to first decoded frame)", "send_packet_pts", send_packet_pts);
1597  }
1598 
1599  // Break out of decoding loop
1600  // Nothing ready for decoding yet
1601  break;
1602  }
1603 
1604 #if USE_HW_ACCEL
1605  if (hw_de_on && hw_de_supported) {
1606  int err;
1607  if (next_frame2->format == hw_de_av_pix_fmt) {
1608  if ((err = av_hwframe_transfer_data(next_frame, next_frame2, 0)) < 0) {
1610  "FFmpegReader::GetAVFrame (Failed to transfer data to output frame)",
1611  "hw_de_on", hw_de_on,
1612  "error", err);
1613  note_hw_decode_failure(AVERROR_INVALIDDATA, "hwframe_transfer");
1614  break;
1615  }
1616  if ((err = av_frame_copy_props(next_frame, next_frame2)) < 0) {
1618  "FFmpegReader::GetAVFrame (Failed to copy props to output frame)",
1619  "hw_de_on", hw_de_on,
1620  "error", err);
1621  note_hw_decode_failure(AVERROR_INVALIDDATA, "hwframe_copy_props");
1622  break;
1623  }
1624  if (next_frame->format == AV_PIX_FMT_NONE) {
1625  next_frame->format = pCodecCtx->sw_pix_fmt;
1626  }
1627  if (next_frame->width <= 0) {
1628  next_frame->width = next_frame2->width;
1629  }
1630  if (next_frame->height <= 0) {
1631  next_frame->height = next_frame2->height;
1632  }
1633  decoded_frame = next_frame;
1634  } else {
1635  // Some hardware decoders can still return software-readable frames.
1636  decoded_frame = next_frame2;
1637  }
1638  }
1639  else
1640 #endif // USE_HW_ACCEL
1641  { // No hardware acceleration used -> no copy from GPU memory needed
1642  decoded_frame = next_frame2;
1643  }
1644 
1645  if (!decoded_frame->data[0]) {
1647  "FFmpegReader::GetAVFrame (Decoded frame missing image data)",
1648  "format", decoded_frame->format,
1649  "width", decoded_frame->width,
1650  "height", decoded_frame->height);
1651  note_hw_decode_failure(AVERROR_INVALIDDATA, "decoded_frame_empty");
1652  break;
1653  }
1654 
1655  // TODO also handle possible further frames
1656  // Use only the first frame like avcodec_decode_video2
1657  frameFinished = 1;
1658  hw_decode_error_count = 0;
1659 #if USE_HW_ACCEL
1660  if (hw_de_on && hw_de_supported && !force_sw_decode) {
1661  hw_decode_succeeded = true;
1662  }
1663 #endif
1664  packet_status.video_decoded++;
1665 
1666  // Allocate image (align 32 for simd)
1667  AVPixelFormat decoded_pix_fmt = (AVPixelFormat)(decoded_frame->format);
1668  if (decoded_pix_fmt == AV_PIX_FMT_NONE)
1669  decoded_pix_fmt = (AVPixelFormat)(pStream->codecpar->format);
1670  if (AV_ALLOCATE_IMAGE(pFrame, decoded_pix_fmt, info.width, info.height) <= 0) {
1671  throw OutOfMemory("Failed to allocate image buffer", path);
1672  }
1673  av_image_copy(pFrame->data, pFrame->linesize, (const uint8_t**)decoded_frame->data, decoded_frame->linesize,
1674  decoded_pix_fmt, info.width, info.height);
1675  pFrame->format = decoded_pix_fmt;
1676  pFrame->width = info.width;
1677  pFrame->height = info.height;
1678  pFrame->color_range = decoded_frame->color_range;
1679  pFrame->colorspace = decoded_frame->colorspace;
1680  pFrame->color_primaries = decoded_frame->color_primaries;
1681  pFrame->color_trc = decoded_frame->color_trc;
1682  pFrame->chroma_location = decoded_frame->chroma_location;
1683 
1684  // Get display PTS from video frame, often different than packet->pts.
1685  // Sending packets to the decoder (i.e. packet->pts) is async,
1686  // and retrieving packets from the decoder (frame->pts) is async. In most decoders
1687  // sending and retrieving are separated by multiple calls to this method.
1688  if (decoded_frame->pts != AV_NOPTS_VALUE) {
1689  // This is the current decoded frame (and should be the pts used) for
1690  // processing this data
1691  video_pts = decoded_frame->pts;
1692  } else if (decoded_frame->pkt_dts != AV_NOPTS_VALUE) {
1693  // Some videos only set this timestamp (fallback)
1694  video_pts = decoded_frame->pkt_dts;
1695  }
1696 
1698  "FFmpegReader::GetAVFrame (Successful frame received)", "video_pts", video_pts, "send_packet_pts", send_packet_pts);
1699 
1700  // break out of loop after each successful image returned
1701  break;
1702  }
1703 #if USE_HW_ACCEL
1704  if (hw_de_on && hw_de_supported && next_frame2 != next_frame) {
1705  AV_FREE_FRAME(&next_frame2);
1706  }
1707  #endif // USE_HW_ACCEL
1708 #else
1709  avcodec_decode_video2(pCodecCtx, next_frame, &frameFinished, packet);
1710 
1711  // always allocate pFrame (because we do that in the ffmpeg >= 3.2 as well); it will always be freed later
1712  pFrame = AV_ALLOCATE_FRAME();
1713 
1714  // is frame finished
1715  if (frameFinished) {
1716  // AVFrames are clobbered on the each call to avcodec_decode_video, so we
1717  // must make a copy of the image data before this method is called again.
1718  avpicture_alloc((AVPicture *) pFrame, pCodecCtx->pix_fmt, info.width, info.height);
1719  av_picture_copy((AVPicture *) pFrame, (AVPicture *) next_frame, pCodecCtx->pix_fmt, info.width,
1720  info.height);
1721  }
1722 #endif // IS_FFMPEG_3_2
1723 
1724  // deallocate the frame
1725  AV_FREE_FRAME(&next_frame);
1726 
1727  // Did we get a video frame?
1728  return frameFinished;
1729 }
1730 
1731 bool FFmpegReader::ReopenWithoutHardwareDecode(int64_t requested_frame) {
1732 #if USE_HW_ACCEL
1733  if (!hw_decode_failed || force_sw_decode) {
1734  return false;
1735  }
1736 
1738  "FFmpegReader::ReopenWithoutHardwareDecode (falling back to software decode)",
1739  "requested_frame", requested_frame,
1740  "video_packets_read", packet_status.video_read,
1741  "video_packets_decoded", packet_status.video_decoded,
1742  "hw_decode_error_count", hw_decode_error_count);
1743 
1744  force_sw_decode = true;
1745  hw_decode_failed = false;
1746  hw_decode_error_count = 0;
1747 
1748  Close();
1749  Open();
1750  Seek(requested_frame);
1751  return true;
1752 #else
1753  (void) requested_frame;
1754  return false;
1755 #endif
1756 }
1757 
1759 #if USE_HW_ACCEL
1760  return hw_decode_succeeded;
1761 #else
1762  return false;
1763 #endif
1764 }
1765 
1766 // Check the current seek position and determine if we need to seek again
1767 bool FFmpegReader::CheckSeek() {
1768  // Are we seeking for a specific frame?
1769  if (is_seeking) {
1770  const int64_t kSeekRetryMax = 5;
1771  const int kSeekStagnantMax = 2;
1772 
1773  // Determine if both an audio and video packet have been decoded since the seek happened.
1774  // If not, allow the ReadStream method to keep looping
1775  if ((is_video_seek && !seek_video_frame_found) || (!is_video_seek && !seek_audio_frame_found))
1776  return false;
1777 
1778  // Check for both streams
1779  if ((info.has_video && !seek_video_frame_found) || (info.has_audio && !seek_audio_frame_found))
1780  return false;
1781 
1782  // Determine max seeked frame
1783  int64_t max_seeked_frame = std::max(seek_audio_frame_found, seek_video_frame_found);
1784  // Track stagnant seek results (no progress between retries)
1785  if (max_seeked_frame == last_seek_max_frame) {
1786  seek_stagnant_count++;
1787  } else {
1788  last_seek_max_frame = max_seeked_frame;
1789  seek_stagnant_count = 0;
1790  }
1791 
1792  // determine if we are "before" the requested frame
1793  if (max_seeked_frame >= seeking_frame) {
1794  // SEEKED TOO FAR
1795  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckSeek (Too far, seek again)",
1796  "is_video_seek", is_video_seek,
1797  "max_seeked_frame", max_seeked_frame,
1798  "seeking_frame", seeking_frame,
1799  "seeking_pts", seeking_pts,
1800  "seek_video_frame_found", seek_video_frame_found,
1801  "seek_audio_frame_found", seek_audio_frame_found);
1802 
1803  // Seek again... to the nearest Keyframe
1804  if (seek_count < kSeekRetryMax) {
1805  Seek(seeking_frame - (10 * seek_count * seek_count));
1806  } else if (seek_stagnant_count >= kSeekStagnantMax) {
1807  // Stagnant seek: force a much earlier target and keep seeking.
1808  Seek(seeking_frame - (10 * kSeekRetryMax * kSeekRetryMax));
1809  } else {
1810  // Retry budget exhausted: keep seeking from a conservative offset.
1811  Seek(seeking_frame - (10 * seek_count * seek_count));
1812  }
1813  } else {
1814  // SEEK WORKED
1815  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckSeek (Successful)",
1816  "is_video_seek", is_video_seek,
1817  "packet->pts", GetPacketPTS(),
1818  "seeking_pts", seeking_pts,
1819  "seeking_frame", seeking_frame,
1820  "seek_video_frame_found", seek_video_frame_found,
1821  "seek_audio_frame_found", seek_audio_frame_found);
1822 
1823  // Seek worked, and we are "before" the requested frame
1824  is_seeking = false;
1825  seeking_frame = 0;
1826  seeking_pts = -1;
1827  }
1828  }
1829 
1830  // return the pts to seek to (if any)
1831  return is_seeking;
1832 }
1833 
1834 // Process a video packet
1835 void FFmpegReader::ProcessVideoPacket(int64_t requested_frame) {
1836  // Get the AVFrame from the current packet
1837  // This sets the video_pts to the correct timestamp
1838  int frame_finished = GetAVFrame();
1839 
1840  // Check if the AVFrame is finished and set it
1841  if (!frame_finished) {
1842  // No AVFrame decoded yet, bail out
1843  if (pFrame) {
1844  RemoveAVFrame(pFrame);
1845  }
1846  return;
1847  }
1848 
1849  // Calculate current frame #
1850  int64_t current_frame = ConvertVideoPTStoFrame(video_pts);
1851 
1852  // Track 1st video packet after a successful seek
1853  if (!seek_video_frame_found && is_seeking)
1854  seek_video_frame_found = current_frame;
1855 
1856  // Create or get the existing frame object. Requested frame needs to be created
1857  // in working_cache at least once. Seek can clear the working_cache, so we must
1858  // add the requested frame back to the working_cache here. If it already exists,
1859  // it will be moved to the top of the working_cache.
1860  working_cache.Add(CreateFrame(requested_frame));
1861 
1862  // Debug output
1863  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessVideoPacket (Before)", "requested_frame", requested_frame, "current_frame", current_frame);
1864 
1865  // Init some things local (for OpenMP)
1866  AVPixelFormat decoded_pix_fmt = (pFrame && pFrame->format != AV_PIX_FMT_NONE)
1867  ? static_cast<AVPixelFormat>(pFrame->format)
1868  : AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx);
1869  bool src_full_range = (pFrame && pFrame->color_range == AVCOL_RANGE_JPEG);
1870  AVPixelFormat src_pix_fmt = NormalizeDeprecatedPixFmt(decoded_pix_fmt, src_full_range);
1871  int src_width = (pFrame && pFrame->width > 0) ? pFrame->width : info.width;
1872  int src_height = (pFrame && pFrame->height > 0) ? pFrame->height : info.height;
1873  int height = src_height;
1874  int width = src_width;
1875  // Create or reuse a RGB Frame (since most videos are not in RGB, we must convert it)
1876  AVFrame *pFrameRGB = pFrameRGB_cached;
1877  if (!pFrameRGB) {
1878  pFrameRGB = AV_ALLOCATE_FRAME();
1879  if (pFrameRGB == nullptr)
1880  throw OutOfMemory("Failed to allocate frame buffer", path);
1881  pFrameRGB_cached = pFrameRGB;
1882  }
1883  AV_RESET_FRAME(pFrameRGB);
1884  uint8_t *buffer = nullptr;
1885 
1886  // Determine the max size of this source image (based on the timeline's size, the scaling mode,
1887  // and the scaling keyframes). This is a performance improvement, to keep the images as small as possible,
1888  // without losing quality. NOTE: We cannot go smaller than the timeline itself, or the add_layer timeline
1889  // method will scale it back to timeline size before scaling it smaller again. This needs to be fixed in
1890  // the future.
1891  int max_width = info.width;
1892  int max_height = info.height;
1893 
1894  Clip *parent = static_cast<Clip *>(ParentClip());
1895  if (parent) {
1896  if (parent->ParentTimeline()) {
1897  // Set max width/height based on parent clip's timeline (if attached to a timeline)
1898  max_width = parent->ParentTimeline()->preview_width;
1899  max_height = parent->ParentTimeline()->preview_height;
1900  }
1901  if (parent->scale == SCALE_FIT || parent->scale == SCALE_STRETCH) {
1902  // Best fit or Stretch scaling (based on max timeline size * scaling keyframes)
1903  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1904  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1905  max_width = std::max(float(max_width), max_width * max_scale_x);
1906  max_height = std::max(float(max_height), max_height * max_scale_y);
1907 
1908  } else if (parent->scale == SCALE_CROP) {
1909  // Cropping scale mode (based on max timeline size * cropped size * scaling keyframes)
1910  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1911  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1912  QSize width_size(max_width * max_scale_x,
1913  round(max_width / (float(info.width) / float(info.height))));
1914  QSize height_size(round(max_height / (float(info.height) / float(info.width))),
1915  max_height * max_scale_y);
1916  // respect aspect ratio
1917  if (width_size.width() >= max_width && width_size.height() >= max_height) {
1918  max_width = std::max(max_width, width_size.width());
1919  max_height = std::max(max_height, width_size.height());
1920  } else {
1921  max_width = std::max(max_width, height_size.width());
1922  max_height = std::max(max_height, height_size.height());
1923  }
1924 
1925  } else {
1926  // Scale video to equivalent unscaled size
1927  // Since the preview window can change sizes, we want to always
1928  // scale against the ratio of original video size to timeline size
1929  float preview_ratio = 1.0;
1930  if (parent->ParentTimeline()) {
1931  Timeline *t = (Timeline *) parent->ParentTimeline();
1932  preview_ratio = t->preview_width / float(t->info.width);
1933  }
1934  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1935  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1936  max_width = info.width * max_scale_x * preview_ratio;
1937  max_height = info.height * max_scale_y * preview_ratio;
1938  }
1939 
1940  // If a crop effect is resizing the image, request enough pixels to preserve detail
1941  ApplyCropResizeScale(parent, info.width, info.height, max_width, max_height);
1942  }
1943 
1944  // Determine if image needs to be scaled (for performance reasons)
1945  int original_height = src_height;
1946  if (max_width != 0 && max_height != 0 && max_width < width && max_height < height) {
1947  // Override width and height (but maintain aspect ratio)
1948  float ratio = float(width) / float(height);
1949  int possible_width = round(max_height * ratio);
1950  int possible_height = round(max_width / ratio);
1951 
1952  if (possible_width <= max_width) {
1953  // use calculated width, and max_height
1954  width = possible_width;
1955  height = max_height;
1956  } else {
1957  // use max_width, and calculated height
1958  width = max_width;
1959  height = possible_height;
1960  }
1961  }
1962 
1963  // Determine required buffer size and allocate buffer
1964  const int bytes_per_pixel = 4;
1965  int raw_buffer_size = (width * height * bytes_per_pixel) + 128;
1966 
1967  // Aligned memory allocation (for speed)
1968  constexpr size_t ALIGNMENT = 32; // AVX2
1969  int buffer_size = ((raw_buffer_size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT;
1970  buffer = (unsigned char*) aligned_malloc(buffer_size, ALIGNMENT);
1971 
1972  // Copy picture data from one AVFrame (or AVPicture) to another one.
1973  AV_COPY_PICTURE_DATA(pFrameRGB, buffer, PIX_FMT_RGBA, width, height);
1974 
1975  int scale_mode = SWS_FAST_BILINEAR;
1976  if (openshot::Settings::Instance()->HIGH_QUALITY_SCALING) {
1977  scale_mode = SWS_BICUBIC;
1978  }
1979  img_convert_ctx = sws_getCachedContext(img_convert_ctx, src_width, src_height, src_pix_fmt, width, height, PIX_FMT_RGBA, scale_mode, NULL, NULL, NULL);
1980  if (!img_convert_ctx)
1981  throw OutOfMemory("Failed to initialize sws context", path);
1982  const int *src_coeff = sws_getCoefficients(SWS_CS_DEFAULT);
1983  const int *dst_coeff = sws_getCoefficients(SWS_CS_DEFAULT);
1984  const int dst_full_range = 1; // RGB outputs are full-range
1985  sws_setColorspaceDetails(img_convert_ctx, src_coeff, src_full_range ? 1 : 0,
1986  dst_coeff, dst_full_range, 0, 1 << 16, 1 << 16);
1987 
1988  if (!pFrame || !pFrame->data[0] || pFrame->linesize[0] <= 0) {
1989 #if USE_HW_ACCEL
1990  if (hw_de_on && hw_de_supported && !force_sw_decode) {
1991  hw_decode_failed = true;
1993  "FFmpegReader::ProcessVideoPacket (Invalid source frame; forcing software fallback)",
1994  "requested_frame", requested_frame,
1995  "current_frame", current_frame,
1996  "src_pix_fmt", src_pix_fmt,
1997  "src_width", src_width,
1998  "src_height", src_height);
1999  }
2000 #endif
2001  if (pFrame) {
2002  RemoveAVFrame(pFrame);
2003  pFrame = NULL;
2004  }
2005  return;
2006  }
2007 
2008  // Resize / Convert to RGB
2009  const int scaled_lines = sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0,
2010  original_height, pFrameRGB->data, pFrameRGB->linesize);
2011  if (scaled_lines <= 0) {
2012 #if USE_HW_ACCEL
2013  if (hw_de_on && hw_de_supported && !force_sw_decode) {
2014  hw_decode_failed = true;
2016  "FFmpegReader::ProcessVideoPacket (sws_scale failed; forcing software fallback)",
2017  "requested_frame", requested_frame,
2018  "current_frame", current_frame,
2019  "scaled_lines", scaled_lines,
2020  "src_pix_fmt", src_pix_fmt,
2021  "src_width", src_width,
2022  "src_height", src_height);
2023  }
2024 #endif
2025  free(buffer);
2026  AV_RESET_FRAME(pFrameRGB);
2027  RemoveAVFrame(pFrame);
2028  pFrame = NULL;
2029  return;
2030  }
2031 
2032  // Create or get the existing frame object
2033  std::shared_ptr<Frame> f = CreateFrame(current_frame);
2034 
2035  // Add Image data to frame
2036  if (!ffmpeg_has_alpha(src_pix_fmt)) {
2037  // Add image with no alpha channel, Speed optimization
2038  f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888_Premultiplied, buffer);
2039  } else {
2040  // Add image with alpha channel (this will be converted to premultipled when needed, but is slower)
2041  f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888, buffer);
2042  }
2043 
2044  // Update working cache
2045  working_cache.Add(f);
2046 
2047  // Keep track of last last_video_frame
2048  last_video_frame = f;
2049 
2050  // Free the RGB image
2051  AV_RESET_FRAME(pFrameRGB);
2052 
2053  // Remove frame and packet
2054  RemoveAVFrame(pFrame);
2055 
2056  // Get video PTS in seconds
2057  video_pts_seconds = (double(video_pts) * info.video_timebase.ToDouble()) + pts_offset_seconds;
2058 
2059  // Debug output
2060  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessVideoPacket (After)", "requested_frame", requested_frame, "current_frame", current_frame, "f->number", f->number, "video_pts_seconds", video_pts_seconds);
2061 }
2062 
2063 // Process an audio packet
2064 void FFmpegReader::ProcessAudioPacket(int64_t requested_frame) {
2065  AudioLocation location;
2066  // Calculate location of current audio packet
2067  if (packet && packet->pts != AV_NOPTS_VALUE) {
2068  // Determine related video frame and starting sample # from audio PTS
2069  location = GetAudioPTSLocation(packet->pts);
2070 
2071  // Track 1st audio packet after a successful seek
2072  if (!seek_audio_frame_found && is_seeking)
2073  seek_audio_frame_found = location.frame;
2074  }
2075 
2076  // Create or get the existing frame object. Requested frame needs to be created
2077  // in working_cache at least once. Seek can clear the working_cache, so we must
2078  // add the requested frame back to the working_cache here. If it already exists,
2079  // it will be moved to the top of the working_cache.
2080  working_cache.Add(CreateFrame(requested_frame));
2081 
2082  // Debug output
2083  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (Before)",
2084  "requested_frame", requested_frame,
2085  "target_frame", location.frame,
2086  "starting_sample", location.sample_start);
2087 
2088  // Init an AVFrame to hold the decoded audio samples
2089  int frame_finished = 0;
2090  AVFrame *audio_frame = AV_ALLOCATE_FRAME();
2091  AV_RESET_FRAME(audio_frame);
2092 
2093  int packet_samples = 0;
2094  int data_size = 0;
2095 
2096 #if IS_FFMPEG_3_2
2097  int send_packet_err = avcodec_send_packet(aCodecCtx, packet);
2098  if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
2099  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (Packet not sent)");
2100  }
2101  else {
2102  int receive_frame_err = avcodec_receive_frame(aCodecCtx, audio_frame);
2103  if (receive_frame_err >= 0) {
2104  frame_finished = 1;
2105  }
2106  if (receive_frame_err == AVERROR_EOF) {
2107  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (EOF detected from decoder)");
2108  packet_status.audio_eof = true;
2109  }
2110  if (receive_frame_err == AVERROR(EINVAL) || receive_frame_err == AVERROR_EOF) {
2111  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (invalid frame received or EOF from decoder)");
2112  avcodec_flush_buffers(aCodecCtx);
2113  }
2114  if (receive_frame_err != 0) {
2115  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (frame not ready yet from decoder)");
2116  }
2117  }
2118 #else
2119  int used = avcodec_decode_audio4(aCodecCtx, audio_frame, &frame_finished, packet);
2120 #endif
2121 
2122  if (frame_finished) {
2123  packet_status.audio_decoded++;
2124 
2125  // This can be different than the current packet, so we need to look
2126  // at the current AVFrame from the audio decoder. This timestamp should
2127  // be used for the remainder of this function
2128  audio_pts = audio_frame->pts;
2129 
2130  // Determine related video frame and starting sample # from audio PTS
2131  location = GetAudioPTSLocation(audio_pts);
2132 
2133  // determine how many samples were decoded
2134  int plane_size = -1;
2135 #if HAVE_CH_LAYOUT
2136  int nb_channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout.nb_channels;
2137 #else
2138  int nb_channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
2139 #endif
2140  data_size = av_samples_get_buffer_size(&plane_size, nb_channels,
2141  audio_frame->nb_samples, (AVSampleFormat) (AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx)), 1);
2142 
2143  // Calculate total number of samples
2144  packet_samples = audio_frame->nb_samples * nb_channels;
2145  } else {
2146  if (audio_frame) {
2147  // Free audio frame
2148  AV_FREE_FRAME(&audio_frame);
2149  }
2150  }
2151 
2152  // Estimate the # of samples and the end of this packet's location (to prevent GAPS for the next timestamp)
2153  int pts_remaining_samples = packet_samples / info.channels; // Adjust for zero based array
2154 
2155  // Bail if no samples found
2156  if (pts_remaining_samples == 0) {
2157  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (No samples, bailing)",
2158  "packet_samples", packet_samples,
2159  "info.channels", info.channels,
2160  "pts_remaining_samples", pts_remaining_samples);
2161  return;
2162  }
2163 
2164  while (pts_remaining_samples) {
2165  // Get Samples per frame (for this frame number)
2166  int samples_per_frame = Frame::GetSamplesPerFrame(previous_packet_location.frame, info.fps, info.sample_rate, info.channels);
2167 
2168  // Calculate # of samples to add to this frame
2169  int samples = samples_per_frame - previous_packet_location.sample_start;
2170  if (samples > pts_remaining_samples)
2171  samples = pts_remaining_samples;
2172 
2173  // Decrement remaining samples
2174  pts_remaining_samples -= samples;
2175 
2176  if (pts_remaining_samples > 0) {
2177  // next frame
2178  previous_packet_location.frame++;
2179  previous_packet_location.sample_start = 0;
2180  } else {
2181  // Increment sample start
2182  previous_packet_location.sample_start += samples;
2183  }
2184  }
2185 
2186  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (ReSample)",
2187  "packet_samples", packet_samples,
2188  "info.channels", info.channels,
2189  "info.sample_rate", info.sample_rate,
2190  "aCodecCtx->sample_fmt", AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx));
2191 
2192  // Create output frame
2193  AVFrame *audio_converted = AV_ALLOCATE_FRAME();
2194  AV_RESET_FRAME(audio_converted);
2195  audio_converted->nb_samples = audio_frame->nb_samples;
2196  av_samples_alloc(audio_converted->data, audio_converted->linesize, info.channels, audio_frame->nb_samples, AV_SAMPLE_FMT_FLTP, 0);
2197 
2198  SWRCONTEXT *avr = avr_ctx;
2199  // setup resample context if needed
2200  if (!avr) {
2201  avr = SWR_ALLOC();
2202 #if HAVE_CH_LAYOUT
2203  AVChannelLayout input_layout = ffmpeg_get_valid_channel_layout(
2204  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout, info.channels);
2205  AVChannelLayout output_layout = ffmpeg_get_valid_channel_layout(
2206  input_layout, info.channels);
2207  int in_layout_err = av_opt_set_chlayout(avr, "in_chlayout", &input_layout, 0);
2208  int out_layout_err = av_opt_set_chlayout(avr, "out_chlayout", &output_layout, 0);
2209 #else
2210  av_opt_set_int(avr, "in_channel_layout", AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout, 0);
2211  av_opt_set_int(avr, "out_channel_layout", AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout, 0);
2212  av_opt_set_int(avr, "in_channels", info.channels, 0);
2213  av_opt_set_int(avr, "out_channels", info.channels, 0);
2214 #endif
2215  av_opt_set_int(avr, "in_sample_fmt", AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx), 0);
2216  av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
2217  av_opt_set_int(avr, "in_sample_rate", info.sample_rate, 0);
2218  av_opt_set_int(avr, "out_sample_rate", info.sample_rate, 0);
2219  int swr_init_err = SWR_INIT(avr);
2220 #if HAVE_CH_LAYOUT
2221  av_channel_layout_uninit(&input_layout);
2222  av_channel_layout_uninit(&output_layout);
2223  if (in_layout_err < 0 || out_layout_err < 0 || swr_init_err < 0) {
2224  SWR_FREE(&avr);
2225  throw InvalidChannels("Could not initialize FFmpeg audio channel layout or resampler.", path);
2226  }
2227 #else
2228  if (swr_init_err < 0) {
2229  SWR_FREE(&avr);
2230  throw InvalidChannels("Could not initialize FFmpeg audio resampler.", path);
2231  }
2232 #endif
2233  avr_ctx = avr;
2234  }
2235 
2236  // Convert audio samples
2237  int nb_samples = SWR_CONVERT(avr, // audio resample context
2238  audio_converted->data, // output data pointers
2239  audio_converted->linesize[0], // output plane size, in bytes. (0 if unknown)
2240  audio_converted->nb_samples, // maximum number of samples that the output buffer can hold
2241  audio_frame->data, // input data pointers
2242  audio_frame->linesize[0], // input plane size, in bytes (0 if unknown)
2243  audio_frame->nb_samples); // number of input samples to convert
2244 
2245 
2246  int64_t starting_frame_number = -1;
2247  for (int channel_filter = 0; channel_filter < info.channels; channel_filter++) {
2248  // Array of floats (to hold samples for each channel)
2249  starting_frame_number = location.frame;
2250  int channel_buffer_size = nb_samples;
2251  auto *channel_buffer = (float *) (audio_converted->data[channel_filter]);
2252 
2253  // Loop through samples, and add them to the correct frames
2254  int start = location.sample_start;
2255  int remaining_samples = channel_buffer_size;
2256  while (remaining_samples > 0) {
2257  // Get Samples per frame (for this frame number)
2258  int samples_per_frame = Frame::GetSamplesPerFrame(starting_frame_number, info.fps, info.sample_rate, info.channels);
2259 
2260  // Calculate # of samples to add to this frame
2261  int samples = std::fmin(samples_per_frame - start, remaining_samples);
2262 
2263  // Create or get the existing frame object
2264  std::shared_ptr<Frame> f = CreateFrame(starting_frame_number);
2265 
2266  // Add samples for current channel to the frame.
2267  f->AddAudio(true, channel_filter, start, channel_buffer, samples, 1.0f);
2268 
2269  // Debug output
2270  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (f->AddAudio)",
2271  "frame", starting_frame_number,
2272  "start", start,
2273  "samples", samples,
2274  "channel", channel_filter,
2275  "samples_per_frame", samples_per_frame);
2276 
2277  // Add or update cache
2278  working_cache.Add(f);
2279 
2280  // Decrement remaining samples
2281  remaining_samples -= samples;
2282 
2283  // Increment buffer (to next set of samples)
2284  if (remaining_samples > 0)
2285  channel_buffer += samples;
2286 
2287  // Increment frame number
2288  starting_frame_number++;
2289 
2290  // Reset starting sample #
2291  start = 0;
2292  }
2293  }
2294 
2295  // Free AVFrames
2296  av_free(audio_converted->data[0]);
2297  AV_FREE_FRAME(&audio_converted);
2298  AV_FREE_FRAME(&audio_frame);
2299 
2300  // Get audio PTS in seconds
2301  audio_pts_seconds = (double(audio_pts) * info.audio_timebase.ToDouble()) + pts_offset_seconds;
2302 
2303  // Debug output
2304  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (After)",
2305  "requested_frame", requested_frame,
2306  "starting_frame", location.frame,
2307  "end_frame", starting_frame_number - 1,
2308  "audio_pts_seconds", audio_pts_seconds);
2309 
2310 }
2311 
2312 
2313 // Seek to a specific frame. This is not always frame accurate, it's more of an estimation on many codecs.
2314 void FFmpegReader::Seek(int64_t requested_frame) {
2315  // Adjust for a requested frame that is too small or too large
2316  if (requested_frame < 1)
2317  requested_frame = 1;
2318  if (requested_frame > info.video_length)
2319  requested_frame = info.video_length;
2320  if (requested_frame > largest_frame_processed && packet_status.end_of_file) {
2321  // Not possible to search past largest_frame once EOF is reached (no more packets)
2322  return;
2323  }
2324 
2325  // Debug output
2326  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::Seek",
2327  "requested_frame", requested_frame,
2328  "seek_count", seek_count,
2329  "last_frame", last_frame);
2330 
2331  // Clear working cache (since we are seeking to another location in the file)
2332  working_cache.Clear();
2333 
2334  // Reset the last frame variable
2335  video_pts = 0.0;
2336  video_pts_seconds = NO_PTS_OFFSET;
2337  audio_pts = 0.0;
2338  audio_pts_seconds = NO_PTS_OFFSET;
2339  hold_packet = false;
2340  last_frame = 0;
2341  current_video_frame = 0;
2342  largest_frame_processed = 0;
2343  last_final_video_frame.reset();
2344  bool has_audio_override = info.has_audio;
2345  bool has_video_override = info.has_video;
2346 
2347  // Init end-of-file detection variables
2348  packet_status.reset(false);
2349 
2350  // Increment seek count
2351  seek_count++;
2352 
2353  // If seeking near frame 1, we need to close and re-open the file (this is more reliable than seeking)
2354  int buffer_amount = 12;
2355  if (requested_frame - buffer_amount < 20) {
2356  // prevent Open() from seeking again
2357  is_seeking = true;
2358 
2359  // Close and re-open file (basically seeking to frame 1)
2360  Close();
2361  Open();
2362 
2363  // Update overrides (since closing and re-opening might update these)
2364  info.has_audio = has_audio_override;
2365  info.has_video = has_video_override;
2366 
2367  // Not actually seeking, so clear these flags
2368  is_seeking = false;
2369  if (seek_count == 1) {
2370  // Don't redefine this on multiple seek attempts for a specific frame
2371  seeking_frame = 1;
2372  seeking_pts = ConvertFrameToVideoPTS(1);
2373  }
2374  seek_audio_frame_found = 0; // used to detect which frames to throw away after a seek
2375  seek_video_frame_found = 0; // used to detect which frames to throw away after a seek
2376 
2377  } else {
2378  // Seek to nearest key-frame (aka, i-frame)
2379  bool seek_worked = false;
2380  int64_t seek_target = 0;
2381 
2382  // Seek video stream (if any), except album arts
2383  if (!seek_worked && info.has_video && !HasAlbumArt()) {
2384  seek_target = ConvertFrameToVideoPTS(requested_frame - buffer_amount);
2385  if (av_seek_frame(pFormatCtx, info.video_stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
2386  ZmqLogger::Instance()->Log(std::string(pFormatCtx->AV_FILENAME) + ": error while seeking video stream");
2387  } else {
2388  // VIDEO SEEK
2389  is_video_seek = true;
2390  seek_worked = true;
2391  }
2392  }
2393 
2394  // Seek audio stream (if not already seeked... and if an audio stream is found)
2395  if (!seek_worked && info.has_audio) {
2396  seek_target = ConvertFrameToAudioPTS(requested_frame - buffer_amount);
2397  if (av_seek_frame(pFormatCtx, info.audio_stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
2398  ZmqLogger::Instance()->Log(std::string(pFormatCtx->AV_FILENAME) + ": error while seeking audio stream");
2399  } else {
2400  // AUDIO SEEK
2401  is_video_seek = false;
2402  seek_worked = true;
2403  }
2404  }
2405 
2406  // Was the seek successful?
2407  if (seek_worked) {
2408  // Flush audio buffer
2409  if (info.has_audio)
2410  avcodec_flush_buffers(aCodecCtx);
2411 
2412  // Flush video buffer
2413  if (info.has_video)
2414  avcodec_flush_buffers(pCodecCtx);
2415 
2416  // Reset previous audio location to zero
2417  previous_packet_location.frame = -1;
2418  previous_packet_location.sample_start = 0;
2419 
2420  // init seek flags
2421  is_seeking = true;
2422  if (seek_count == 1) {
2423  // Don't redefine this on multiple seek attempts for a specific frame
2424  seeking_pts = seek_target;
2425  seeking_frame = requested_frame;
2426  }
2427  seek_audio_frame_found = 0; // used to detect which frames to throw away after a seek
2428  seek_video_frame_found = 0; // used to detect which frames to throw away after a seek
2429 
2430  } else {
2431  // seek failed
2432  seeking_pts = 0;
2433  seeking_frame = 0;
2434 
2435  // prevent Open() from seeking again
2436  is_seeking = true;
2437 
2438  // Close and re-open file (basically seeking to frame 1)
2439  Close();
2440  Open();
2441 
2442  // Not actually seeking, so clear these flags
2443  is_seeking = false;
2444 
2445  // disable seeking for this reader (since it failed)
2446  enable_seek = false;
2447 
2448  // Update overrides (since closing and re-opening might update these)
2449  info.has_audio = has_audio_override;
2450  info.has_video = has_video_override;
2451  }
2452  }
2453 }
2454 
2455 // Get the PTS for the current video packet
2456 int64_t FFmpegReader::GetPacketPTS() {
2457  if (packet) {
2458  int64_t current_pts = packet->pts;
2459  if (current_pts == AV_NOPTS_VALUE && packet->dts != AV_NOPTS_VALUE)
2460  current_pts = packet->dts;
2461 
2462  // Return adjusted PTS
2463  return current_pts;
2464  } else {
2465  // No packet, return NO PTS
2466  return AV_NOPTS_VALUE;
2467  }
2468 }
2469 
2470 // Update PTS Offset (if any)
2471 void FFmpegReader::UpdatePTSOffset() {
2472  if (pts_offset_seconds != NO_PTS_OFFSET) {
2473  // Skip this method if we have already set PTS offset
2474  return;
2475  }
2476  pts_offset_seconds = 0.0;
2477  double video_pts_offset_seconds = 0.0;
2478  double audio_pts_offset_seconds = 0.0;
2479 
2480  bool has_video_pts = false;
2481  if (!info.has_video) {
2482  // Mark as checked
2483  has_video_pts = true;
2484  }
2485  bool has_audio_pts = false;
2486  if (!info.has_audio) {
2487  // Mark as checked
2488  has_audio_pts = true;
2489  }
2490 
2491  // Loop through the stream (until a packet from all streams is found)
2492  while (!has_video_pts || !has_audio_pts) {
2493  // Get the next packet (if any)
2494  if (GetNextPacket() < 0)
2495  // Break loop when no more packets found
2496  break;
2497 
2498  // Get PTS of this packet
2499  int64_t pts = GetPacketPTS();
2500 
2501  // Video packet
2502  if (!has_video_pts && packet->stream_index == videoStream) {
2503  // Get the video packet start time (in seconds)
2504  video_pts_offset_seconds = 0.0 - (pts * info.video_timebase.ToDouble());
2505 
2506  // Is timestamp close to zero (within X seconds)
2507  // Ignore wildly invalid timestamps (i.e. -234923423423)
2508  if (std::abs(video_pts_offset_seconds) <= 10.0) {
2509  has_video_pts = true;
2510  }
2511  }
2512  else if (!has_audio_pts && packet->stream_index == audioStream) {
2513  // Get the audio packet start time (in seconds)
2514  audio_pts_offset_seconds = 0.0 - (pts * info.audio_timebase.ToDouble());
2515 
2516  // Is timestamp close to zero (within X seconds)
2517  // Ignore wildly invalid timestamps (i.e. -234923423423)
2518  if (std::abs(audio_pts_offset_seconds) <= 10.0) {
2519  has_audio_pts = true;
2520  }
2521  }
2522  }
2523 
2524  // Choose timestamp origin:
2525  // - If video exists, anchor timeline frame mapping to video start.
2526  // This avoids AAC priming / audio preroll shifting video frame 1 to frame 2.
2527  // - If no video exists (audio-only readers), use audio start.
2528  if (info.has_video && has_video_pts) {
2529  pts_offset_seconds = video_pts_offset_seconds;
2530  } else if (!info.has_video && has_audio_pts) {
2531  pts_offset_seconds = audio_pts_offset_seconds;
2532  } else if (has_video_pts && has_audio_pts) {
2533  // Fallback when stream flags are unusual but both timestamps exist.
2534  pts_offset_seconds = video_pts_offset_seconds;
2535  }
2536 }
2537 
2538 // Convert PTS into Frame Number
2539 int64_t FFmpegReader::ConvertVideoPTStoFrame(int64_t pts) {
2540  // Apply PTS offset
2541  int64_t previous_video_frame = current_video_frame;
2542  const double fps_value = (info.fps.num > 0 && info.fps.den > 0) ? info.fps.ToDouble() : 30.0;
2543  const double video_timebase_value =
2546  : (1.0 / 30.0);
2547 
2548  // Get the video packet start time (in seconds)
2549  double video_seconds = (double(pts) * video_timebase_value) + pts_offset_seconds;
2550 
2551  // Divide by the video timebase, to get the video frame number (frame # is decimal at this point)
2552  int64_t frame = round(video_seconds * fps_value) + 1;
2553 
2554  // Keep track of the expected video frame #
2555  if (current_video_frame == 0)
2556  current_video_frame = frame;
2557  else {
2558 
2559  // Sometimes frames are duplicated due to identical (or similar) timestamps
2560  if (frame == previous_video_frame) {
2561  // return -1 frame number
2562  frame = -1;
2563  } else {
2564  // Increment expected frame
2565  current_video_frame++;
2566  }
2567  }
2568 
2569  // Return frame #
2570  return frame;
2571 }
2572 
2573 // Convert Frame Number into Video PTS
2574 int64_t FFmpegReader::ConvertFrameToVideoPTS(int64_t frame_number) {
2575  const double fps_value = (info.fps.num > 0 && info.fps.den > 0) ? info.fps.ToDouble() : 30.0;
2576  const double video_timebase_value =
2579  : (1.0 / 30.0);
2580 
2581  // Get timestamp of this frame (in seconds)
2582  double seconds = (double(frame_number - 1) / fps_value) + pts_offset_seconds;
2583 
2584  // Calculate the # of video packets in this timestamp
2585  int64_t video_pts = round(seconds / video_timebase_value);
2586 
2587  // Apply PTS offset (opposite)
2588  return video_pts;
2589 }
2590 
2591 // Convert Frame Number into Video PTS
2592 int64_t FFmpegReader::ConvertFrameToAudioPTS(int64_t frame_number) {
2593  const double fps_value = (info.fps.num > 0 && info.fps.den > 0) ? info.fps.ToDouble() : 30.0;
2594  const double audio_timebase_value =
2597  : (1.0 / 48000.0);
2598 
2599  // Get timestamp of this frame (in seconds)
2600  double seconds = (double(frame_number - 1) / fps_value) + pts_offset_seconds;
2601 
2602  // Calculate the # of audio packets in this timestamp
2603  int64_t audio_pts = round(seconds / audio_timebase_value);
2604 
2605  // Apply PTS offset (opposite)
2606  return audio_pts;
2607 }
2608 
2609 // Calculate Starting video frame and sample # for an audio PTS
2610 AudioLocation FFmpegReader::GetAudioPTSLocation(int64_t pts) {
2611  const double audio_timebase_value =
2614  : (1.0 / 48000.0);
2615  const double fps_value = (info.fps.num > 0 && info.fps.den > 0) ? info.fps.ToDouble() : 30.0;
2616 
2617  // Get the audio packet start time (in seconds)
2618  double audio_seconds = (double(pts) * audio_timebase_value) + pts_offset_seconds;
2619 
2620  // Divide by the video timebase, to get the video frame number (frame # is decimal at this point)
2621  double frame = (audio_seconds * fps_value) + 1;
2622 
2623  // Frame # as a whole number (no more decimals)
2624  int64_t whole_frame = int64_t(frame);
2625 
2626  // Remove the whole number, and only get the decimal of the frame
2627  double sample_start_percentage = frame - double(whole_frame);
2628 
2629  // Get Samples per frame
2630  int samples_per_frame = Frame::GetSamplesPerFrame(whole_frame, info.fps, info.sample_rate, info.channels);
2631 
2632  // Calculate the sample # to start on
2633  int sample_start = round(double(samples_per_frame) * sample_start_percentage);
2634 
2635  // Protect against broken (i.e. negative) timestamps
2636  if (whole_frame < 1)
2637  whole_frame = 1;
2638  if (sample_start < 0)
2639  sample_start = 0;
2640 
2641  // Prepare final audio packet location
2642  AudioLocation location = {whole_frame, sample_start};
2643 
2644  // Compare to previous audio packet (and fix small gaps due to varying PTS timestamps)
2645  if (previous_packet_location.frame != -1) {
2646  if (location.is_near(previous_packet_location, samples_per_frame, samples_per_frame)) {
2647  int64_t orig_frame = location.frame;
2648  int orig_start = location.sample_start;
2649 
2650  // Update sample start, to prevent gaps in audio
2651  location.sample_start = previous_packet_location.sample_start;
2652  location.frame = previous_packet_location.frame;
2653 
2654  // Debug output
2655  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAudioPTSLocation (Audio Gap Detected)", "Source Frame", orig_frame, "Source Audio Sample", orig_start, "Target Frame", location.frame, "Target Audio Sample", location.sample_start, "pts", pts);
2656 
2657  } else {
2658  // Debug output
2659  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAudioPTSLocation (Audio Gap Ignored - too big)", "Previous location frame", previous_packet_location.frame, "Target Frame", location.frame, "Target Audio Sample", location.sample_start, "pts", pts);
2660  }
2661  }
2662 
2663  // Set previous location
2664  previous_packet_location = location;
2665 
2666  // Return the associated video frame and starting sample #
2667  return location;
2668 }
2669 
2670 // Create a new Frame (or return an existing one) and add it to the working queue.
2671 std::shared_ptr<Frame> FFmpegReader::CreateFrame(int64_t requested_frame) {
2672  // Check working cache
2673  std::shared_ptr<Frame> output = working_cache.GetFrame(requested_frame);
2674 
2675  if (!output) {
2676  // (re-)Check working cache
2677  output = working_cache.GetFrame(requested_frame);
2678  if(output) return output;
2679 
2680  // Create a new frame on the working cache
2681  output = std::make_shared<Frame>(requested_frame, info.width, info.height, "#000000", Frame::GetSamplesPerFrame(requested_frame, info.fps, info.sample_rate, info.channels), info.channels);
2682  output->SetPixelRatio(info.pixel_ratio.num, info.pixel_ratio.den); // update pixel ratio
2683  output->ChannelsLayout(info.channel_layout); // update audio channel layout from the parent reader
2684  output->SampleRate(info.sample_rate); // update the frame's sample rate of the parent reader
2685 
2686  working_cache.Add(output);
2687 
2688  // Set the largest processed frame (if this is larger)
2689  if (requested_frame > largest_frame_processed)
2690  largest_frame_processed = requested_frame;
2691  }
2692  // Return frame
2693  return output;
2694 }
2695 
2696 // Determine if frame is partial due to seek
2697 bool FFmpegReader::IsPartialFrame(int64_t requested_frame) {
2698 
2699  // Sometimes a seek gets partial frames, and we need to remove them
2700  bool seek_trash = false;
2701  int64_t max_seeked_frame = seek_audio_frame_found; // determine max seeked frame
2702  if (seek_video_frame_found > max_seeked_frame) {
2703  max_seeked_frame = seek_video_frame_found;
2704  }
2705  if ((info.has_audio && seek_audio_frame_found && max_seeked_frame >= requested_frame) ||
2706  (info.has_video && seek_video_frame_found && max_seeked_frame >= requested_frame)) {
2707  seek_trash = true;
2708  }
2709 
2710  return seek_trash;
2711 }
2712 
2713 // Check the working queue, and move finished frames to the finished queue
2714 void FFmpegReader::CheckWorkingFrames(int64_t requested_frame) {
2715 
2716  // Prevent async calls to the following code
2717  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
2718 
2719  // Get a list of current working queue frames in the cache (in-progress frames)
2720  std::vector<std::shared_ptr<openshot::Frame>> working_frames = working_cache.GetFrames();
2721  std::vector<std::shared_ptr<openshot::Frame>>::iterator working_itr;
2722 
2723  // Loop through all working queue frames (sorted by frame #)
2724  for(working_itr = working_frames.begin(); working_itr != working_frames.end(); ++working_itr)
2725  {
2726  // Get working frame
2727  std::shared_ptr<Frame> f = *working_itr;
2728 
2729  // Was a frame found? Is frame requested yet?
2730  if (!f || f->number > requested_frame) {
2731  // If not, skip to next one
2732  continue;
2733  }
2734 
2735  // Calculate PTS in seconds (of working frame), and the most recent processed pts value
2736  double frame_pts_seconds = (double(f->number - 1) / info.fps.ToDouble()) + pts_offset_seconds;
2737  double recent_pts_seconds = std::max(video_pts_seconds, audio_pts_seconds);
2738 
2739  // Determine if video and audio are ready (based on timestamps)
2740  bool is_video_ready = false;
2741  bool is_audio_ready = false;
2742  double recent_pts_diff = recent_pts_seconds - frame_pts_seconds;
2743  if ((frame_pts_seconds <= video_pts_seconds)
2744  || (recent_pts_diff > 1.5)
2745  || packet_status.video_eof || packet_status.end_of_file) {
2746  // Video stream is past this frame (so it must be done)
2747  // OR video stream is too far behind, missing, or end-of-file
2748  is_video_ready = true;
2749  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (video ready)",
2750  "frame_number", f->number,
2751  "frame_pts_seconds", frame_pts_seconds,
2752  "video_pts_seconds", video_pts_seconds,
2753  "recent_pts_diff", recent_pts_diff);
2754  if (info.has_video && !f->has_image_data &&
2755  (packet_status.video_eof || packet_status.end_of_file)) {
2756  // Frame has no image data. Prefer timeline-previous frames to preserve
2757  // visual order, especially when decode/prefetch is out-of-order.
2758  std::shared_ptr<Frame> previous_frame_instance = final_cache.GetFrame(f->number - 1);
2759  if (previous_frame_instance && previous_frame_instance->has_image_data) {
2760  f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2761  }
2762 
2763  // Fall back to last finalized timeline image (survives cache churn).
2764  if (!f->has_image_data
2765  && last_final_video_frame
2766  && last_final_video_frame->has_image_data
2767  && last_final_video_frame->number <= f->number) {
2768  f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2769  }
2770 
2771  // Fall back to the last decoded image only when it is not from the future.
2772  if (!f->has_image_data
2773  && last_video_frame
2774  && last_video_frame->has_image_data
2775  && last_video_frame->number <= f->number) {
2776  f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2777  }
2778 
2779  // Last-resort fallback if no prior image is available.
2780  if (!f->has_image_data) {
2782  "FFmpegReader::CheckWorkingFrames (no previous image found; using black frame)",
2783  "frame_number", f->number);
2784  f->AddColor("#000000");
2785  }
2786  }
2787  }
2788 
2789  double audio_pts_diff = audio_pts_seconds - frame_pts_seconds;
2790  if ((frame_pts_seconds < audio_pts_seconds && audio_pts_diff > 1.0)
2791  || (recent_pts_diff > 1.5)
2792  || packet_status.audio_eof || packet_status.end_of_file) {
2793  // Audio stream is past this frame (so it must be done)
2794  // OR audio stream is too far behind, missing, or end-of-file
2795  // Adding a bit of margin here, to allow for partial audio packets
2796  is_audio_ready = true;
2797  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (audio ready)",
2798  "frame_number", f->number,
2799  "frame_pts_seconds", frame_pts_seconds,
2800  "audio_pts_seconds", audio_pts_seconds,
2801  "audio_pts_diff", audio_pts_diff,
2802  "recent_pts_diff", recent_pts_diff);
2803  }
2804  bool is_seek_trash = IsPartialFrame(f->number);
2805 
2806  // Adjust for available streams
2807  if (!info.has_video) is_video_ready = true;
2808  if (!info.has_audio) is_audio_ready = true;
2809 
2810  // Debug output
2811  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames",
2812  "frame_number", f->number,
2813  "is_video_ready", is_video_ready,
2814  "is_audio_ready", is_audio_ready,
2815  "video_eof", packet_status.video_eof,
2816  "audio_eof", packet_status.audio_eof,
2817  "end_of_file", packet_status.end_of_file);
2818 
2819  // Check if working frame is final
2820  if (info.has_video && !f->has_image_data
2821  && !packet_status.end_of_file && !is_seek_trash) {
2822  if (info.has_single_image) {
2823  // For still-image video (including attached cover art), reuse the most
2824  // recent image so playback does not stall waiting for video EOF.
2825  std::shared_ptr<Frame> previous_frame_instance = final_cache.GetFrame(f->number - 1);
2826  if (previous_frame_instance && previous_frame_instance->has_image_data) {
2827  f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2828  }
2829  if (!f->has_image_data
2830  && last_final_video_frame
2831  && last_final_video_frame->has_image_data
2832  && last_final_video_frame->number <= f->number) {
2833  f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2834  }
2835  if (!f->has_image_data
2836  && last_video_frame
2837  && last_video_frame->has_image_data
2838  && last_video_frame->number <= f->number) {
2839  f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2840  }
2841  }
2842 
2843  // If both streams have advanced past this frame but the decoder never
2844  // produced image data for it, reuse the most recent non-future image.
2845  // This avoids stalling indefinitely on sparse/missing decoded frames.
2846  if (!f->has_image_data && is_video_ready && is_audio_ready) {
2847  std::shared_ptr<Frame> previous_frame_instance = final_cache.GetFrame(f->number - 1);
2848  if (previous_frame_instance && previous_frame_instance->has_image_data) {
2849  f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2850  }
2851  if (!f->has_image_data
2852  && last_final_video_frame
2853  && last_final_video_frame->has_image_data
2854  && last_final_video_frame->number <= f->number) {
2855  f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2856  }
2857  if (!f->has_image_data
2858  && last_video_frame
2859  && last_video_frame->has_image_data
2860  && last_video_frame->number <= f->number) {
2861  f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2862  }
2863  }
2864 
2865  // Do not finalize non-EOF video frames without decoded image data.
2866  // This prevents repeated previous-frame fallbacks being cached as real frames.
2867  if (!f->has_image_data) {
2868  continue;
2869  }
2870  }
2871  if ((!packet_status.end_of_file && is_video_ready && is_audio_ready) || packet_status.end_of_file || is_seek_trash) {
2872  // Debug output
2873  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (mark frame as final)",
2874  "requested_frame", requested_frame,
2875  "f->number", f->number,
2876  "is_seek_trash", is_seek_trash,
2877  "Working Cache Count", working_cache.Count(),
2878  "Final Cache Count", final_cache.Count(),
2879  "end_of_file", packet_status.end_of_file);
2880 
2881  if (!is_seek_trash) {
2882  // Move frame to final cache
2883  final_cache.Add(f);
2884  if (f->has_image_data) {
2885  last_final_video_frame = f;
2886  }
2887 
2888  // Remove frame from working cache
2889  working_cache.Remove(f->number);
2890 
2891  // Update last frame processed
2892  last_frame = f->number;
2893  } else {
2894  // Seek trash, so delete the frame from the working cache, and never add it to the final cache.
2895  working_cache.Remove(f->number);
2896  }
2897 
2898  }
2899  }
2900 
2901  // Clear vector of frames
2902  working_frames.clear();
2903  working_frames.shrink_to_fit();
2904 }
2905 
2906 // Check for the correct frames per second (FPS) value by scanning the 1st few seconds of video packets.
2907 void FFmpegReader::CheckFPS() {
2908  if (check_fps) {
2909  // Do not check FPS more than 1 time
2910  return;
2911  } else {
2912  check_fps = true;
2913  }
2914 
2915  int frames_per_second[3] = {0,0,0};
2916  int max_fps_index = sizeof(frames_per_second) / sizeof(frames_per_second[0]);
2917  int fps_index = 0;
2918 
2919  int all_frames_detected = 0;
2920  int starting_frames_detected = 0;
2921 
2922  // Loop through the stream
2923  while (true) {
2924  // Get the next packet (if any)
2925  if (GetNextPacket() < 0)
2926  // Break loop when no more packets found
2927  break;
2928 
2929  // Video packet
2930  if (packet->stream_index == videoStream) {
2931  // Get the video packet start time (in seconds)
2932  double video_seconds = (double(GetPacketPTS()) * info.video_timebase.ToDouble()) + pts_offset_seconds;
2933  fps_index = int(video_seconds); // truncate float timestamp to int (second 1, second 2, second 3)
2934 
2935  // Is this video packet from the first few seconds?
2936  if (fps_index >= 0 && fps_index < max_fps_index) {
2937  // Yes, keep track of how many frames per second (over the first few seconds)
2938  starting_frames_detected++;
2939  frames_per_second[fps_index]++;
2940  }
2941 
2942  // Track all video packets detected
2943  all_frames_detected++;
2944  }
2945  }
2946 
2947  // Calculate FPS (based on the first few seconds of video packets)
2948  float avg_fps = 30.0;
2949  if (starting_frames_detected > 0 && fps_index > 0) {
2950  avg_fps = float(starting_frames_detected) / std::min(fps_index, max_fps_index);
2951  }
2952 
2953  // Verify average FPS is a reasonable value
2954  if (avg_fps < 8.0) {
2955  // Invalid FPS assumed, so switching to a sane default FPS instead
2956  avg_fps = 30.0;
2957  }
2958 
2959  // Update FPS (truncate average FPS to Integer)
2960  info.fps = Fraction(int(avg_fps), 1);
2961 
2962  // Update Duration and Length
2963  if (all_frames_detected > 0) {
2964  // Use all video frames detected to calculate # of frames
2965  info.video_length = all_frames_detected;
2966  info.duration = all_frames_detected / avg_fps;
2967  } else {
2968  // Use previous duration to calculate # of frames
2969  info.video_length = info.duration * avg_fps;
2970  }
2971 
2972  // Update video bit rate
2974 }
2975 
2976 // Remove AVFrame from cache (and deallocate its memory)
2977 void FFmpegReader::RemoveAVFrame(AVFrame *remove_frame) {
2978  // Remove pFrame (if exists)
2979  if (remove_frame) {
2980  // Free memory
2981  av_freep(&remove_frame->data[0]);
2982 #ifndef WIN32
2983  AV_FREE_FRAME(&remove_frame);
2984 #endif
2985  }
2986 }
2987 
2988 // Remove AVPacket from cache (and deallocate its memory)
2989 void FFmpegReader::RemoveAVPacket(AVPacket *remove_packet) {
2990  // deallocate memory for packet
2991  AV_FREE_PACKET(remove_packet);
2992 
2993  // Delete the object
2994  delete remove_packet;
2995 }
2996 
2997 // Generate JSON string of this object
2998 std::string FFmpegReader::Json() const {
2999 
3000  // Return formatted string
3001  return JsonValue().toStyledString();
3002 }
3003 
3004 // Generate Json::Value for this object
3005 Json::Value FFmpegReader::JsonValue() const {
3006 
3007  // Create root json object
3008  Json::Value root = ReaderBase::JsonValue(); // get parent properties
3009  root["type"] = "FFmpegReader";
3010  root["path"] = path;
3011  switch (duration_strategy) {
3013  root["duration_strategy"] = "VideoPreferred";
3014  break;
3016  root["duration_strategy"] = "AudioPreferred";
3017  break;
3019  default:
3020  root["duration_strategy"] = "LongestStream";
3021  break;
3022  }
3023 
3024  // return JsonValue
3025  return root;
3026 }
3027 
3028 // Load JSON string into this object
3029 void FFmpegReader::SetJson(const std::string value) {
3030 
3031  // Parse JSON string into JSON objects
3032  try {
3033  const Json::Value root = openshot::stringToJson(value);
3034  // Set all values that match
3035  SetJsonValue(root);
3036  }
3037  catch (const std::exception& e) {
3038  // Error parsing JSON (or missing keys)
3039  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
3040  }
3041 }
3042 
3043 // Load Json::Value into this object
3044 void FFmpegReader::SetJsonValue(const Json::Value root) {
3045 
3046  // Set parent data
3048 
3049  // Set data from Json (if key is found)
3050  if (!root["path"].isNull())
3051  path = root["path"].asString();
3052  if (!root["duration_strategy"].isNull()) {
3053  const std::string strategy = root["duration_strategy"].asString();
3054  if (strategy == "VideoPreferred") {
3055  duration_strategy = DurationStrategy::VideoPreferred;
3056  } else if (strategy == "AudioPreferred") {
3057  duration_strategy = DurationStrategy::AudioPreferred;
3058  } else {
3059  duration_strategy = DurationStrategy::LongestStream;
3060  }
3061  }
3062 }
openshot::stringToJson
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:16
openshot::CacheMemory::Clear
void Clear()
Clear the cache of all frames.
Definition: CacheMemory.cpp:224
AV_FIND_DECODER_CODEC_ID
#define AV_FIND_DECODER_CODEC_ID(av_stream)
Definition: FFmpegUtilities.h:318
openshot::ReaderInfo::sample_rate
int sample_rate
The number of audio samples per second (44100 is a common sample rate)
Definition: ReaderBase.h:60
openshot::FFmpegReader::FFmpegReader
FFmpegReader(const std::string &path, bool inspect_reader=true)
Constructor for FFmpegReader.
Definition: FFmpegReader.cpp:102
openshot::Fraction::ToFloat
float ToFloat()
Return this fraction as a float (i.e. 1/2 = 0.5)
Definition: Fraction.cpp:35
openshot::Settings::HARDWARE_DECODER
int HARDWARE_DECODER
Use video codec for faster video decoding (if supported)
Definition: Settings.h:62
openshot::Coordinate::Y
double Y
The Y value of the coordinate (usually representing the value of the property being animated)
Definition: Coordinate.h:41
openshot::CacheMemory::Count
int64_t Count()
Count the frames in the queue.
Definition: CacheMemory.cpp:240
FFmpegUtilities.h
Header file for FFmpegUtilities.
openshot::ReaderBase::JsonValue
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
Definition: ReaderBase.cpp:106
openshot::InvalidCodec
Exception when no valid codec is found for a file.
Definition: Exceptions.h:178
openshot::TimelineBase::preview_width
int preview_width
Optional preview width of timeline image. If your preview window is smaller than the timeline,...
Definition: TimelineBase.h:45
openshot::PacketStatus::reset
void reset(bool eof)
Definition: FFmpegReader.h:70
openshot::CacheMemory::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)
Get a frame from the cache.
Definition: CacheMemory.cpp:84
openshot::FFmpegReader::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t requested_frame) override
Definition: FFmpegReader.cpp:1197
AV_COPY_PICTURE_DATA
#define AV_COPY_PICTURE_DATA(av_frame, buffer, pix_fmt, width, height)
Definition: FFmpegUtilities.h:327
openshot::CacheMemory::Add
void Add(std::shared_ptr< openshot::Frame > frame)
Add a Frame to the cache.
Definition: CacheMemory.cpp:47
AV_ALLOCATE_FRAME
#define AV_ALLOCATE_FRAME()
Definition: FFmpegUtilities.h:310
openshot::ReaderBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ReaderBase.cpp:157
SWR_CONVERT
#define SWR_CONVERT(ctx, out, linesize, out_count, in, linesize2, in_count)
Definition: FFmpegUtilities.h:259
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:28
openshot::Point::co
Coordinate co
This is the primary coordinate.
Definition: Point.h:66
openshot::Clip::scale_y
openshot::Keyframe scale_y
Curve representing the vertical scaling in percent (0 to 1)
Definition: Clip.h:319
openshot::AudioLocation
This struct holds the associated video frame and starting sample # for an audio packet.
Definition: AudioLocation.h:25
openshot::AudioLocation::frame
int64_t frame
Definition: AudioLocation.h:26
openshot::ZmqLogger::Log
void Log(std::string message)
Log message to all subscribers of this logger (if any)
Definition: ZmqLogger.cpp:103
openshot::Clip
This class represents a clip (used to arrange readers on the timeline)
Definition: Clip.h:89
openshot::DurationStrategy::AudioPreferred
@ AudioPreferred
Prefer the audio stream's duration, fallback to video then container.
openshot::Fraction
This class represents a fraction.
Definition: Fraction.h:30
openshot::AudioLocation::sample_start
int sample_start
Definition: AudioLocation.h:27
AV_FREE_FRAME
#define AV_FREE_FRAME(av_frame)
Definition: FFmpegUtilities.h:314
MemoryTrim.h
Cross-platform helper to encourage returning freed memory to the OS.
openshot::Keyframe::GetMaxPoint
Point GetMaxPoint() const
Get max point (by Y coordinate)
Definition: KeyFrame.cpp:245
openshot::ReaderBase::info
openshot::ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:88
openshot::ReaderInfo::interlaced_frame
bool interlaced_frame
Definition: ReaderBase.h:56
Timeline.h
Header file for Timeline class.
openshot::Clip::ParentTimeline
void ParentTimeline(openshot::TimelineBase *new_timeline) override
Set associated Timeline pointer.
Definition: Clip.cpp:447
openshot::FFmpegReader::~FFmpegReader
virtual ~FFmpegReader()
Destructor.
Definition: FFmpegReader.cpp:137
openshot::ReaderInfo::audio_bit_rate
int audio_bit_rate
The bit rate of the audio stream (in bytes)
Definition: ReaderBase.h:59
openshot::CacheMemory::Remove
void Remove(int64_t frame_number)
Remove a specific frame.
Definition: CacheMemory.cpp:158
AV_FREE_PACKET
#define AV_FREE_PACKET(av_packet)
Definition: FFmpegUtilities.h:315
openshot::ReaderInfo::duration
float duration
Length of time (in seconds)
Definition: ReaderBase.h:43
openshot::ReaderInfo::has_video
bool has_video
Determines if this file has a video stream.
Definition: ReaderBase.h:40
openshot::FFmpegReader::JsonValue
Json::Value JsonValue() const override
Generate Json::Value for this object.
Definition: FFmpegReader.cpp:3005
openshot::PacketStatus::audio_read
int64_t audio_read
Definition: FFmpegReader.h:51
openshot::ReaderInfo::width
int width
The width of the video (in pixesl)
Definition: ReaderBase.h:46
openshot::LAYOUT_STEREO
@ LAYOUT_STEREO
Definition: ChannelLayouts.h:31
openshot::FFmpegReader::SetJson
void SetJson(const std::string value) override
Load JSON string into this object.
Definition: FFmpegReader.cpp:3029
openshot::PacketStatus::packets_eof
bool packets_eof
Definition: FFmpegReader.h:57
hw_de_av_pix_fmt_global
AVPixelFormat hw_de_av_pix_fmt_global
Definition: FFmpegReader.cpp:72
openshot::PacketStatus::audio_decoded
int64_t audio_decoded
Definition: FFmpegReader.h:52
openshot::Fraction::ToDouble
double ToDouble() const
Return this fraction as a double (i.e. 1/2 = 0.5)
Definition: Fraction.cpp:40
openshot::PacketStatus::video_read
int64_t video_read
Definition: FFmpegReader.h:49
hw_de_on
int hw_de_on
Definition: FFmpegReader.cpp:70
openshot::CacheBase::SetMaxBytesFromInfo
void SetMaxBytesFromInfo(int64_t number_of_frames, int width, int height, int sample_rate, int channels)
Set maximum bytes to a different amount based on a ReaderInfo struct.
Definition: CacheBase.cpp:28
AV_ALLOCATE_IMAGE
#define AV_ALLOCATE_IMAGE(av_frame, pix_fmt, width, height)
Definition: FFmpegUtilities.h:311
openshot::LAYOUT_MONO
@ LAYOUT_MONO
Definition: ChannelLayouts.h:30
openshot::Clip::scale_x
openshot::Keyframe scale_x
Curve representing the horizontal scaling in percent (0 to 1)
Definition: Clip.h:318
AV_GET_CODEC_ATTRIBUTES
#define AV_GET_CODEC_ATTRIBUTES(av_stream, av_context)
Definition: FFmpegUtilities.h:322
openshot::ReaderInfo::video_length
int64_t video_length
The number of frames in the video stream.
Definition: ReaderBase.h:53
hw_de_av_device_type_global
AVHWDeviceType hw_de_av_device_type_global
Definition: FFmpegReader.cpp:73
openshot::ReaderInfo::height
int height
The height of the video (in pixels)
Definition: ReaderBase.h:45
openshot::PacketStatus::video_eof
bool video_eof
Definition: FFmpegReader.h:55
openshot::Fraction::num
int num
Numerator for the fraction.
Definition: Fraction.h:32
if
if(!codec) codec
ZmqLogger.h
Header file for ZeroMQ-based Logger class.
openshot::Fraction::den
int den
Denominator for the fraction.
Definition: Fraction.h:33
OPEN_MP_NUM_PROCESSORS
#define OPEN_MP_NUM_PROCESSORS
Definition: OpenMPUtilities.h:23
AV_RESET_FRAME
#define AV_RESET_FRAME(av_frame)
Definition: FFmpegUtilities.h:313
openshot::AudioLocation::is_near
bool is_near(AudioLocation location, int samples_per_frame, int64_t amount)
Definition: FFmpegReader.cpp:144
SWR_CLOSE
#define SWR_CLOSE(ctx)
Definition: FFmpegUtilities.h:262
openshot::Fraction::Reciprocal
Fraction Reciprocal() const
Return the reciprocal as a Fraction.
Definition: Fraction.cpp:78
openshot::ReaderInfo::has_audio
bool has_audio
Determines if this file has an audio stream.
Definition: ReaderBase.h:41
openshot::Settings::DE_LIMIT_HEIGHT_MAX
int DE_LIMIT_HEIGHT_MAX
Maximum rows that hardware decode can handle.
Definition: Settings.h:77
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:223
openshot::FFmpegReader::enable_seek
bool enable_seek
Definition: FFmpegReader.h:261
openshot::ReaderInfo::file_size
int64_t file_size
Size of file (in bytes)
Definition: ReaderBase.h:44
openshot::Timeline
This class represents a timeline.
Definition: Timeline.h:153
openshot::FFmpegReader::Open
void Open() override
Open File - which is called by the constructor automatically.
Definition: FFmpegReader.cpp:261
openshot::OutOfMemory
Exception when memory could not be allocated.
Definition: Exceptions.h:354
openshot::SCALE_CROP
@ SCALE_CROP
Scale the clip until both height and width fill the canvas (cropping the overlap)
Definition: Enums.h:37
SWR_INIT
#define SWR_INIT(ctx)
Definition: FFmpegUtilities.h:264
SWRCONTEXT
#define SWRCONTEXT
Definition: FFmpegUtilities.h:265
openshot::PacketStatus::audio_eof
bool audio_eof
Definition: FFmpegReader.h:56
openshot::ReaderInfo::has_single_image
bool has_single_image
Determines if this file only contains a single image.
Definition: ReaderBase.h:42
openshot::FFmpegReader::final_cache
CacheMemory final_cache
Final cache object used to hold final frames.
Definition: FFmpegReader.h:257
openshot::ReaderInfo::video_timebase
openshot::Fraction video_timebase
The video timebase determines how long each frame stays on the screen.
Definition: ReaderBase.h:55
openshot::Settings::Instance
static Settings * Instance()
Create or get an instance of this logger singleton (invoke the class with this method)
Definition: Settings.cpp:23
CropHelpers.h
Shared helpers for Crop effect scaling logic.
openshot::ReaderInfo::metadata
std::map< std::string, std::string > metadata
An optional map/dictionary of metadata for this reader.
Definition: ReaderBase.h:65
openshot::DurationStrategy::LongestStream
@ LongestStream
Use the longest value from video, audio, or container.
openshot::FFmpegReader
This class uses the FFmpeg libraries, to open video files and audio files, and return openshot::Frame...
Definition: FFmpegReader.h:103
path
path
Definition: FFmpegWriter.cpp:1474
openshot::Frame::GetSamplesPerFrame
int GetSamplesPerFrame(openshot::Fraction fps, int sample_rate, int channels)
Calculate the # of samples per video frame (for the current frame number)
Definition: Frame.cpp:484
openshot::InvalidFile
Exception for files that can not be found or opened.
Definition: Exceptions.h:193
openshot::ReaderInfo::audio_stream_index
int audio_stream_index
The index of the audio stream.
Definition: ReaderBase.h:63
openshot::ZmqLogger::Instance
static ZmqLogger * Instance()
Create or get an instance of this logger singleton (invoke the class with this method)
Definition: ZmqLogger.cpp:35
openshot::DurationStrategy
DurationStrategy
This enumeration determines which duration source to favor.
Definition: Enums.h:60
openshot::ReaderInfo::audio_timebase
openshot::Fraction audio_timebase
The audio timebase determines how long each audio packet should be played.
Definition: ReaderBase.h:64
openshot::FFmpegReader::Close
void Close() override
Close File.
Definition: FFmpegReader.cpp:748
openshot::SCALE_FIT
@ SCALE_FIT
Scale the clip until either height or width fills the canvas (with no cropping)
Definition: Enums.h:38
openshot::PacketStatus::packets_read
int64_t packets_read()
Definition: FFmpegReader.h:60
openshot::ReaderInfo::pixel_format
int pixel_format
The pixel format (i.e. YUV420P, RGB24, etc...)
Definition: ReaderBase.h:47
openshot::ZmqLogger::AppendDebugMethod
void AppendDebugMethod(std::string method_name, std::string arg1_name="", float arg1_value=-1.0, std::string arg2_name="", float arg2_value=-1.0, std::string arg3_name="", float arg3_value=-1.0, std::string arg4_name="", float arg4_value=-1.0, std::string arg5_name="", float arg5_value=-1.0, std::string arg6_name="", float arg6_value=-1.0)
Append debug information.
Definition: ZmqLogger.cpp:178
openshot::ReaderInfo::vcodec
std::string vcodec
The name of the video codec used to encode / decode the video stream.
Definition: ReaderBase.h:52
openshot::PacketStatus::packets_decoded
int64_t packets_decoded()
Definition: FFmpegReader.h:65
AV_GET_CODEC_TYPE
#define AV_GET_CODEC_TYPE(av_stream)
Definition: FFmpegUtilities.h:317
openshot::ReaderClosed
Exception when a reader is closed, and a frame is requested.
Definition: Exceptions.h:369
openshot::ReaderInfo::channel_layout
openshot::ChannelLayout channel_layout
The channel layout (mono, stereo, 5 point surround, etc...)
Definition: ReaderBase.h:62
AV_FREE_CONTEXT
#define AV_FREE_CONTEXT(av_context)
Definition: FFmpegUtilities.h:316
PIX_FMT_RGBA
#define PIX_FMT_RGBA
Definition: FFmpegUtilities.h:110
AV_GET_CODEC_PIXEL_FORMAT
#define AV_GET_CODEC_PIXEL_FORMAT(av_stream, av_context)
Definition: FFmpegUtilities.h:323
AVCODEC_REGISTER_ALL
#define AVCODEC_REGISTER_ALL
Definition: FFmpegUtilities.h:306
SWR_FREE
#define SWR_FREE(ctx)
Definition: FFmpegUtilities.h:263
openshot::Settings::DE_LIMIT_WIDTH_MAX
int DE_LIMIT_WIDTH_MAX
Maximum columns that hardware decode can handle.
Definition: Settings.h:80
openshot::ReaderInfo::fps
openshot::Fraction fps
Frames per second, as a fraction (i.e. 24/1 = 24 fps)
Definition: ReaderBase.h:48
AV_GET_SAMPLE_FORMAT
#define AV_GET_SAMPLE_FORMAT(av_stream, av_context)
Definition: FFmpegUtilities.h:325
FF_AUDIO_NUM_PROCESSORS
#define FF_AUDIO_NUM_PROCESSORS
Definition: OpenMPUtilities.h:25
openshot::ReaderInfo::video_bit_rate
int video_bit_rate
The bit rate of the video stream (in bytes)
Definition: ReaderBase.h:49
openshot::PacketStatus::end_of_file
bool end_of_file
Definition: FFmpegReader.h:58
FF_VIDEO_NUM_PROCESSORS
#define FF_VIDEO_NUM_PROCESSORS
Definition: OpenMPUtilities.h:24
openshot::Clip::scale
openshot::ScaleType scale
The scale determines how a clip should be resized to fit its parent.
Definition: Clip.h:179
openshot::ReaderInfo::top_field_first
bool top_field_first
Definition: ReaderBase.h:57
openshot::InvalidChannels
Exception when an invalid # of audio channels are detected.
Definition: Exceptions.h:163
openshot::ChannelLayout
ChannelLayout
This enumeration determines the audio channel layout (such as stereo, mono, 5 point surround,...
Definition: ChannelLayouts.h:28
SWR_ALLOC
#define SWR_ALLOC()
Definition: FFmpegUtilities.h:261
openshot::ReaderInfo::pixel_ratio
openshot::Fraction pixel_ratio
The pixel ratio of the video stream as a fraction (i.e. some pixels are not square)
Definition: ReaderBase.h:50
AV_REGISTER_ALL
#define AV_REGISTER_ALL
Definition: FFmpegUtilities.h:305
openshot::DurationStrategy::VideoPreferred
@ VideoPreferred
Prefer the video stream's duration, fallback to audio then container.
openshot::CacheMemory::GetFrames
std::vector< std::shared_ptr< openshot::Frame > > GetFrames()
Get an array of all Frames.
Definition: CacheMemory.cpp:100
AV_GET_CODEC_CONTEXT
#define AV_GET_CODEC_CONTEXT(av_stream, av_codec)
Definition: FFmpegUtilities.h:319
openshot::ReaderInfo::video_stream_index
int video_stream_index
The index of the video stream.
Definition: ReaderBase.h:54
openshot::FFmpegReader::SetJsonValue
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
Definition: FFmpegReader.cpp:3044
openshot::SCALE_STRETCH
@ SCALE_STRETCH
Scale the clip until both height and width fill the canvas (distort to fit)
Definition: Enums.h:39
openshot::ReaderInfo::acodec
std::string acodec
The name of the audio codec used to encode / decode the video stream.
Definition: ReaderBase.h:58
openshot::NoStreamsFound
Exception when no streams are found in the file.
Definition: Exceptions.h:291
openshot::ReaderInfo::display_ratio
openshot::Fraction display_ratio
The ratio of width to height of the video stream (i.e. 640x480 has a ratio of 4/3)
Definition: ReaderBase.h:51
openshot::ReaderInfo::channels
int channels
The number of audio channels used in the audio stream.
Definition: ReaderBase.h:61
openshot::FFmpegReader::Json
std::string Json() const override
Generate JSON string of this object.
Definition: FFmpegReader.cpp:2998
openshot::FFmpegReader::HardwareDecodeSuccessful
bool HardwareDecodeSuccessful() const override
Return true if hardware decode was requested and successfully produced at least one frame.
Definition: FFmpegReader.cpp:1758
openshot::FFmpegReader::GetIsDurationKnown
bool GetIsDurationKnown()
Return true if frame can be read with GetFrame()
Definition: FFmpegReader.cpp:1193
openshot::ApplyCropResizeScale
void ApplyCropResizeScale(Clip *clip, int source_width, int source_height, int &max_width, int &max_height)
Scale the requested max_width / max_height based on the Crop resize amount, capped by source size.
Definition: CropHelpers.cpp:40
openshot::PacketStatus::video_decoded
int64_t video_decoded
Definition: FFmpegReader.h:50
opts
AVDictionary * opts
Definition: FFmpegWriter.cpp:1485
Exceptions.h
Header file for all Exception classes.
openshot::Settings::HW_DE_DEVICE_SET
int HW_DE_DEVICE_SET
Which GPU to use to decode (0 is the first)
Definition: Settings.h:83
FFmpegReader.h
Header file for FFmpegReader class.
openshot::ReaderBase::getFrameMutex
std::recursive_mutex getFrameMutex
Mutex for multiple threads.
Definition: ReaderBase.h:79
openshot::ReaderBase::ParentClip
openshot::ClipBase * ParentClip()
Parent clip object of this reader (which can be unparented and NULL)
Definition: ReaderBase.cpp:240