OpenShot Library | libopenshot  0.4.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 <unistd.h>
19 
20 #include "FFmpegUtilities.h"
21 
22 #include "FFmpegReader.h"
23 #include "Exceptions.h"
24 #include "Timeline.h"
25 #include "ZmqLogger.h"
26 
27 #define ENABLE_VAAPI 0
28 
29 #if USE_HW_ACCEL
30 #define MAX_SUPPORTED_WIDTH 1950
31 #define MAX_SUPPORTED_HEIGHT 1100
32 
33 #if ENABLE_VAAPI
34 #include "libavutil/hwcontext_vaapi.h"
35 
36 typedef struct VAAPIDecodeContext {
37  VAProfile va_profile;
38  VAEntrypoint va_entrypoint;
39  VAConfigID va_config;
40  VAContextID va_context;
41 
42 #if FF_API_STRUCT_VAAPI_CONTEXT
43  // FF_DISABLE_DEPRECATION_WARNINGS
44  int have_old_context;
45  struct vaapi_context *old_context;
46  AVBufferRef *device_ref;
47  // FF_ENABLE_DEPRECATION_WARNINGS
48 #endif
49 
50  AVHWDeviceContext *device;
51  AVVAAPIDeviceContext *hwctx;
52 
53  AVHWFramesContext *frames;
54  AVVAAPIFramesContext *hwfc;
55 
56  enum AVPixelFormat surface_format;
57  int surface_count;
58  } VAAPIDecodeContext;
59 #endif // ENABLE_VAAPI
60 #endif // USE_HW_ACCEL
61 
62 
63 using namespace openshot;
64 
65 int hw_de_on = 0;
66 #if USE_HW_ACCEL
67  AVPixelFormat hw_de_av_pix_fmt_global = AV_PIX_FMT_NONE;
68  AVHWDeviceType hw_de_av_device_type_global = AV_HWDEVICE_TYPE_NONE;
69 #endif
70 
71 FFmpegReader::FFmpegReader(const std::string &path, bool inspect_reader)
72  : last_frame(0), is_seeking(0), seeking_pts(0), seeking_frame(0), seek_count(0), NO_PTS_OFFSET(-99999),
73  path(path), is_video_seek(true), check_interlace(false), check_fps(false), enable_seek(true), is_open(false),
74  seek_audio_frame_found(0), seek_video_frame_found(0),is_duration_known(false), largest_frame_processed(0),
75  current_video_frame(0), packet(NULL), max_concurrent_frames(OPEN_MP_NUM_PROCESSORS), audio_pts(0),
76  video_pts(0), pFormatCtx(NULL), videoStream(-1), audioStream(-1), pCodecCtx(NULL), aCodecCtx(NULL),
77  pStream(NULL), aStream(NULL), pFrame(NULL), previous_packet_location{-1,0},
78  hold_packet(false) {
79 
80  // Initialize FFMpeg, and register all formats and codecs
83 
84  // Init timestamp offsets
85  pts_offset_seconds = NO_PTS_OFFSET;
86  video_pts_seconds = NO_PTS_OFFSET;
87  audio_pts_seconds = NO_PTS_OFFSET;
88 
89  // Init cache
90  working_cache.SetMaxBytesFromInfo(max_concurrent_frames * info.fps.ToDouble() * 2, info.width, info.height, info.sample_rate, info.channels);
91  final_cache.SetMaxBytesFromInfo(max_concurrent_frames * 2, info.width, info.height, info.sample_rate, info.channels);
92 
93  // Open and Close the reader, to populate its attributes (such as height, width, etc...)
94  if (inspect_reader) {
95  Open();
96  Close();
97  }
98 }
99 
101  if (is_open)
102  // Auto close reader if not already done
103  Close();
104 }
105 
106 // This struct holds the associated video frame and starting sample # for an audio packet.
107 bool AudioLocation::is_near(AudioLocation location, int samples_per_frame, int64_t amount) {
108  // Is frame even close to this one?
109  if (abs(location.frame - frame) >= 2)
110  // This is too far away to be considered
111  return false;
112 
113  // Note that samples_per_frame can vary slightly frame to frame when the
114  // audio sampling rate is not an integer multiple of the video fps.
115  int64_t diff = samples_per_frame * (location.frame - frame) + location.sample_start - sample_start;
116  if (abs(diff) <= amount)
117  // close
118  return true;
119 
120  // not close
121  return false;
122 }
123 
124 #if USE_HW_ACCEL
125 
126 // Get hardware pix format
127 static enum AVPixelFormat get_hw_dec_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
128 {
129  const enum AVPixelFormat *p;
130 
131  for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
132  switch (*p) {
133 #if defined(__linux__)
134  // Linux pix formats
135  case AV_PIX_FMT_VAAPI:
136  hw_de_av_pix_fmt_global = AV_PIX_FMT_VAAPI;
137  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VAAPI;
138  return *p;
139  break;
140  case AV_PIX_FMT_VDPAU:
141  hw_de_av_pix_fmt_global = AV_PIX_FMT_VDPAU;
142  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VDPAU;
143  return *p;
144  break;
145 #endif
146 #if defined(_WIN32)
147  // Windows pix formats
148  case AV_PIX_FMT_DXVA2_VLD:
149  hw_de_av_pix_fmt_global = AV_PIX_FMT_DXVA2_VLD;
150  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_DXVA2;
151  return *p;
152  break;
153  case AV_PIX_FMT_D3D11:
154  hw_de_av_pix_fmt_global = AV_PIX_FMT_D3D11;
155  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_D3D11VA;
156  return *p;
157  break;
158 #endif
159 #if defined(__APPLE__)
160  // Apple pix formats
161  case AV_PIX_FMT_VIDEOTOOLBOX:
162  hw_de_av_pix_fmt_global = AV_PIX_FMT_VIDEOTOOLBOX;
163  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
164  return *p;
165  break;
166 #endif
167  // Cross-platform pix formats
168  case AV_PIX_FMT_CUDA:
169  hw_de_av_pix_fmt_global = AV_PIX_FMT_CUDA;
170  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_CUDA;
171  return *p;
172  break;
173  case AV_PIX_FMT_QSV:
174  hw_de_av_pix_fmt_global = AV_PIX_FMT_QSV;
175  hw_de_av_device_type_global = AV_HWDEVICE_TYPE_QSV;
176  return *p;
177  break;
178  default:
179  // This is only here to silence unused-enum warnings
180  break;
181  }
182  }
183  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::get_hw_dec_format (Unable to decode this file using hardware decode)");
184  return AV_PIX_FMT_NONE;
185 }
186 
187 int FFmpegReader::IsHardwareDecodeSupported(int codecid)
188 {
189  int ret;
190  switch (codecid) {
191  case AV_CODEC_ID_H264:
192  case AV_CODEC_ID_MPEG2VIDEO:
193  case AV_CODEC_ID_VC1:
194  case AV_CODEC_ID_WMV1:
195  case AV_CODEC_ID_WMV2:
196  case AV_CODEC_ID_WMV3:
197  ret = 1;
198  break;
199  default :
200  ret = 0;
201  break;
202  }
203  return ret;
204 }
205 #endif // USE_HW_ACCEL
206 
208  // Open reader if not already open
209  if (!is_open) {
210  // Prevent async calls to the following code
211  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
212 
213  // Initialize format context
214  pFormatCtx = NULL;
215  {
217  ZmqLogger::Instance()->AppendDebugMethod("Decode hardware acceleration settings", "hw_de_on", hw_de_on, "HARDWARE_DECODER", openshot::Settings::Instance()->HARDWARE_DECODER);
218  }
219 
220  // Open video file
221  if (avformat_open_input(&pFormatCtx, path.c_str(), NULL, NULL) != 0)
222  throw InvalidFile("File could not be opened.", path);
223 
224  // Retrieve stream information
225  if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
226  throw NoStreamsFound("No streams found in file.", path);
227 
228  videoStream = -1;
229  audioStream = -1;
230 
231  // Init end-of-file detection variables
232  packet_status.reset(true);
233 
234  // Loop through each stream, and identify the video and audio stream index
235  for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
236  // Is this a video stream?
237  if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_VIDEO && videoStream < 0) {
238  videoStream = i;
239  packet_status.video_eof = false;
240  packet_status.packets_eof = false;
241  packet_status.end_of_file = false;
242  }
243  // Is this an audio stream?
244  if (AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_AUDIO && audioStream < 0) {
245  audioStream = i;
246  packet_status.audio_eof = false;
247  packet_status.packets_eof = false;
248  packet_status.end_of_file = false;
249  }
250  }
251  if (videoStream == -1 && audioStream == -1)
252  throw NoStreamsFound("No video or audio streams found in this file.", path);
253 
254  // Is there a video stream?
255  if (videoStream != -1) {
256  // Set the stream index
257  info.video_stream_index = videoStream;
258 
259  // Set the codec and codec context pointers
260  pStream = pFormatCtx->streams[videoStream];
261 
262  // Find the codec ID from stream
263  const AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(pStream);
264 
265  // Get codec and codec context from stream
266  const AVCodec *pCodec = avcodec_find_decoder(codecId);
267  AVDictionary *opts = NULL;
268  int retry_decode_open = 2;
269  // If hw accel is selected but hardware cannot handle repeat with software decoding
270  do {
271  pCodecCtx = AV_GET_CODEC_CONTEXT(pStream, pCodec);
272 #if USE_HW_ACCEL
273  if (hw_de_on && (retry_decode_open==2)) {
274  // Up to here no decision is made if hardware or software decode
275  hw_de_supported = IsHardwareDecodeSupported(pCodecCtx->codec_id);
276  }
277 #endif
278  retry_decode_open = 0;
279 
280  // Set number of threads equal to number of processors (not to exceed 16)
281  pCodecCtx->thread_count = std::min(FF_NUM_PROCESSORS, 16);
282 
283  if (pCodec == NULL) {
284  throw InvalidCodec("A valid video codec could not be found for this file.", path);
285  }
286 
287  // Init options
288  av_dict_set(&opts, "strict", "experimental", 0);
289 #if USE_HW_ACCEL
290  if (hw_de_on && hw_de_supported) {
291  // Open Hardware Acceleration
292  int i_decoder_hw = 0;
293  char adapter[256];
294  char *adapter_ptr = NULL;
295  int adapter_num;
297  fprintf(stderr, "Hardware decoding device number: %d\n", adapter_num);
298 
299  // Set hardware pix format (callback)
300  pCodecCtx->get_format = get_hw_dec_format;
301 
302  if (adapter_num < 3 && adapter_num >=0) {
303 #if defined(__linux__)
304  snprintf(adapter,sizeof(adapter),"/dev/dri/renderD%d", adapter_num+128);
305  adapter_ptr = adapter;
307  switch (i_decoder_hw) {
308  case 1:
309  hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
310  break;
311  case 2:
312  hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
313  break;
314  case 6:
315  hw_de_av_device_type = AV_HWDEVICE_TYPE_VDPAU;
316  break;
317  case 7:
318  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
319  break;
320  default:
321  hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
322  break;
323  }
324 
325 #elif defined(_WIN32)
326  adapter_ptr = NULL;
328  switch (i_decoder_hw) {
329  case 2:
330  hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
331  break;
332  case 3:
333  hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
334  break;
335  case 4:
336  hw_de_av_device_type = AV_HWDEVICE_TYPE_D3D11VA;
337  break;
338  case 7:
339  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
340  break;
341  default:
342  hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
343  break;
344  }
345 #elif defined(__APPLE__)
346  adapter_ptr = NULL;
348  switch (i_decoder_hw) {
349  case 5:
350  hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
351  break;
352  case 7:
353  hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
354  break;
355  default:
356  hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
357  break;
358  }
359 #endif
360 
361  } else {
362  adapter_ptr = NULL; // Just to be sure
363  }
364 
365  // Check if it is there and writable
366 #if defined(__linux__)
367  if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
368 #elif defined(_WIN32)
369  if( adapter_ptr != NULL ) {
370 #elif defined(__APPLE__)
371  if( adapter_ptr != NULL ) {
372 #endif
373  ZmqLogger::Instance()->AppendDebugMethod("Decode Device present using device");
374  }
375  else {
376  adapter_ptr = NULL; // use default
377  ZmqLogger::Instance()->AppendDebugMethod("Decode Device not present using default");
378  }
379 
380  hw_device_ctx = NULL;
381  // Here the first hardware initialisations are made
382  if (av_hwdevice_ctx_create(&hw_device_ctx, hw_de_av_device_type, adapter_ptr, NULL, 0) >= 0) {
383  if (!(pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx))) {
384  throw InvalidCodec("Hardware device reference create failed.", path);
385  }
386 
387  /*
388  av_buffer_unref(&ist->hw_frames_ctx);
389  ist->hw_frames_ctx = av_hwframe_ctx_alloc(hw_device_ctx);
390  if (!ist->hw_frames_ctx) {
391  av_log(avctx, AV_LOG_ERROR, "Error creating a CUDA frames context\n");
392  return AVERROR(ENOMEM);
393  }
394 
395  frames_ctx = (AVHWFramesContext*)ist->hw_frames_ctx->data;
396 
397  frames_ctx->format = AV_PIX_FMT_CUDA;
398  frames_ctx->sw_format = avctx->sw_pix_fmt;
399  frames_ctx->width = avctx->width;
400  frames_ctx->height = avctx->height;
401 
402  av_log(avctx, AV_LOG_DEBUG, "Initializing CUDA frames context: sw_format = %s, width = %d, height = %d\n",
403  av_get_pix_fmt_name(frames_ctx->sw_format), frames_ctx->width, frames_ctx->height);
404 
405 
406  ret = av_hwframe_ctx_init(pCodecCtx->hw_device_ctx);
407  ret = av_hwframe_ctx_init(ist->hw_frames_ctx);
408  if (ret < 0) {
409  av_log(avctx, AV_LOG_ERROR, "Error initializing a CUDA frame pool\n");
410  return ret;
411  }
412  */
413  }
414  else {
415  throw InvalidCodec("Hardware device create failed.", path);
416  }
417  }
418 #endif // USE_HW_ACCEL
419 
420  // Disable per-frame threading for album arts
421  // Using FF_THREAD_FRAME adds one frame decoding delay per thread,
422  // but there's only one frame in this case.
423  if (HasAlbumArt())
424  {
425  pCodecCtx->thread_type &= ~FF_THREAD_FRAME;
426  }
427 
428  // Open video codec
429  int avcodec_return = avcodec_open2(pCodecCtx, pCodec, &opts);
430  if (avcodec_return < 0) {
431  std::stringstream avcodec_error_msg;
432  avcodec_error_msg << "A video codec was found, but could not be opened. Error: " << av_err2string(avcodec_return);
433  throw InvalidCodec(avcodec_error_msg.str(), path);
434  }
435 
436 #if USE_HW_ACCEL
437  if (hw_de_on && hw_de_supported) {
438  AVHWFramesConstraints *constraints = NULL;
439  void *hwconfig = NULL;
440  hwconfig = av_hwdevice_hwconfig_alloc(hw_device_ctx);
441 
442 // TODO: needs va_config!
443 #if ENABLE_VAAPI
444  ((AVVAAPIHWConfig *)hwconfig)->config_id = ((VAAPIDecodeContext *)(pCodecCtx->priv_data))->va_config;
445  constraints = av_hwdevice_get_hwframe_constraints(hw_device_ctx,hwconfig);
446 #endif // ENABLE_VAAPI
447  if (constraints) {
448  if (pCodecCtx->coded_width < constraints->min_width ||
449  pCodecCtx->coded_height < constraints->min_height ||
450  pCodecCtx->coded_width > constraints->max_width ||
451  pCodecCtx->coded_height > constraints->max_height) {
452  ZmqLogger::Instance()->AppendDebugMethod("DIMENSIONS ARE TOO LARGE for hardware acceleration\n");
453  hw_de_supported = 0;
454  retry_decode_open = 1;
455  AV_FREE_CONTEXT(pCodecCtx);
456  if (hw_device_ctx) {
457  av_buffer_unref(&hw_device_ctx);
458  hw_device_ctx = NULL;
459  }
460  }
461  else {
462  // All is just peachy
463  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);
464  retry_decode_open = 0;
465  }
466  av_hwframe_constraints_free(&constraints);
467  if (hwconfig) {
468  av_freep(&hwconfig);
469  }
470  }
471  else {
472  int max_h, max_w;
473  //max_h = ((getenv( "LIMIT_HEIGHT_MAX" )==NULL) ? MAX_SUPPORTED_HEIGHT : atoi(getenv( "LIMIT_HEIGHT_MAX" )));
475  //max_w = ((getenv( "LIMIT_WIDTH_MAX" )==NULL) ? MAX_SUPPORTED_WIDTH : atoi(getenv( "LIMIT_WIDTH_MAX" )));
477  ZmqLogger::Instance()->AppendDebugMethod("Constraints could not be found using default limit\n");
478  //cerr << "Constraints could not be found using default limit\n";
479  if (pCodecCtx->coded_width < 0 ||
480  pCodecCtx->coded_height < 0 ||
481  pCodecCtx->coded_width > max_w ||
482  pCodecCtx->coded_height > max_h ) {
483  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);
484  hw_de_supported = 0;
485  retry_decode_open = 1;
486  AV_FREE_CONTEXT(pCodecCtx);
487  if (hw_device_ctx) {
488  av_buffer_unref(&hw_device_ctx);
489  hw_device_ctx = NULL;
490  }
491  }
492  else {
493  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);
494  retry_decode_open = 0;
495  }
496  }
497  } // if hw_de_on && hw_de_supported
498  else {
499  ZmqLogger::Instance()->AppendDebugMethod("\nDecode in software is used\n");
500  }
501 #else
502  retry_decode_open = 0;
503 #endif // USE_HW_ACCEL
504  } while (retry_decode_open); // retry_decode_open
505  // Free options
506  av_dict_free(&opts);
507 
508  // Update the File Info struct with video details (if a video stream is found)
509  UpdateVideoInfo();
510  }
511 
512  // Is there an audio stream?
513  if (audioStream != -1) {
514  // Set the stream index
515  info.audio_stream_index = audioStream;
516 
517  // Get a pointer to the codec context for the audio stream
518  aStream = pFormatCtx->streams[audioStream];
519 
520  // Find the codec ID from stream
521  AVCodecID codecId = AV_FIND_DECODER_CODEC_ID(aStream);
522 
523  // Get codec and codec context from stream
524  const AVCodec *aCodec = avcodec_find_decoder(codecId);
525  aCodecCtx = AV_GET_CODEC_CONTEXT(aStream, aCodec);
526 
527  // Set number of threads equal to number of processors (not to exceed 16)
528  aCodecCtx->thread_count = std::min(FF_NUM_PROCESSORS, 16);
529 
530  if (aCodec == NULL) {
531  throw InvalidCodec("A valid audio codec could not be found for this file.", path);
532  }
533 
534  // Init options
535  AVDictionary *opts = NULL;
536  av_dict_set(&opts, "strict", "experimental", 0);
537 
538  // Open audio codec
539  if (avcodec_open2(aCodecCtx, aCodec, &opts) < 0)
540  throw InvalidCodec("An audio codec was found, but could not be opened.", path);
541 
542  // Free options
543  av_dict_free(&opts);
544 
545  // Update the File Info struct with audio details (if an audio stream is found)
546  UpdateAudioInfo();
547  }
548 
549  // Add format metadata (if any)
550  AVDictionaryEntry *tag = NULL;
551  while ((tag = av_dict_get(pFormatCtx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
552  QString str_key = tag->key;
553  QString str_value = tag->value;
554  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
555  }
556 
557  // Process video stream side data (rotation, spherical metadata, etc)
558  for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
559  AVStream* st = pFormatCtx->streams[i];
560  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
561  // Only inspect the first video stream
562  for (int j = 0; j < st->nb_side_data; j++) {
563  AVPacketSideData *sd = &st->side_data[j];
564 
565  // Handle rotation metadata (unchanged)
566  if (sd->type == AV_PKT_DATA_DISPLAYMATRIX &&
567  sd->size >= 9 * sizeof(int32_t) &&
568  !info.metadata.count("rotate"))
569  {
570  double rotation = -av_display_rotation_get(
571  reinterpret_cast<int32_t *>(sd->data));
572  if (std::isnan(rotation)) rotation = 0;
573  info.metadata["rotate"] = std::to_string(rotation);
574  }
575  // Handle spherical video metadata
576  else if (sd->type == AV_PKT_DATA_SPHERICAL) {
577  // Always mark as spherical
578  info.metadata["spherical"] = "1";
579 
580  // Cast the raw bytes to an AVSphericalMapping
581  const AVSphericalMapping* map =
582  reinterpret_cast<const AVSphericalMapping*>(sd->data);
583 
584  // Projection enum → string
585  const char* proj_name = av_spherical_projection_name(map->projection);
586  info.metadata["spherical_projection"] = proj_name
587  ? proj_name
588  : "unknown";
589 
590  // Convert 16.16 fixed-point to float degrees
591  auto to_deg = [](int32_t v){
592  return (double)v / 65536.0;
593  };
594  info.metadata["spherical_yaw"] = std::to_string(to_deg(map->yaw));
595  info.metadata["spherical_pitch"] = std::to_string(to_deg(map->pitch));
596  info.metadata["spherical_roll"] = std::to_string(to_deg(map->roll));
597  }
598  }
599  break;
600  }
601  }
602 
603  // Init previous audio location to zero
604  previous_packet_location.frame = -1;
605  previous_packet_location.sample_start = 0;
606 
607  // Adjust cache size based on size of frame and audio
608  working_cache.SetMaxBytesFromInfo(max_concurrent_frames * info.fps.ToDouble() * 2, info.width, info.height, info.sample_rate, info.channels);
610 
611  // Scan PTS for any offsets (i.e. non-zero starting streams). At least 1 stream must start at zero timestamp.
612  // This method allows us to shift timestamps to ensure at least 1 stream is starting at zero.
613  UpdatePTSOffset();
614 
615  // Override an invalid framerate
616  if (info.fps.ToFloat() > 240.0f || (info.fps.num <= 0 || info.fps.den <= 0) || info.video_length <= 0) {
617  // Calculate FPS, duration, video bit rate, and video length manually
618  // by scanning through all the video stream packets
619  CheckFPS();
620  }
621 
622  // Mark as "open"
623  is_open = true;
624 
625  // Seek back to beginning of file (if not already seeking)
626  if (!is_seeking) {
627  Seek(1);
628  }
629  }
630 }
631 
633  // Close all objects, if reader is 'open'
634  if (is_open) {
635  // Prevent async calls to the following code
636  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
637 
638  // Mark as "closed"
639  is_open = false;
640 
641  // Keep track of most recent packet
642  AVPacket *recent_packet = packet;
643 
644  // Drain any packets from the decoder
645  packet = NULL;
646  int attempts = 0;
647  int max_attempts = 128;
648  while (packet_status.packets_decoded() < packet_status.packets_read() && attempts < max_attempts) {
649  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::Close (Drain decoder loop)",
650  "packets_read", packet_status.packets_read(),
651  "packets_decoded", packet_status.packets_decoded(),
652  "attempts", attempts);
653  if (packet_status.video_decoded < packet_status.video_read) {
654  ProcessVideoPacket(info.video_length);
655  }
656  if (packet_status.audio_decoded < packet_status.audio_read) {
657  ProcessAudioPacket(info.video_length);
658  }
659  attempts++;
660  }
661 
662  // Remove packet
663  if (recent_packet) {
664  RemoveAVPacket(recent_packet);
665  }
666 
667  // Close the video codec
668  if (info.has_video) {
669  if(avcodec_is_open(pCodecCtx)) {
670  avcodec_flush_buffers(pCodecCtx);
671  }
672  AV_FREE_CONTEXT(pCodecCtx);
673 #if USE_HW_ACCEL
674  if (hw_de_on) {
675  if (hw_device_ctx) {
676  av_buffer_unref(&hw_device_ctx);
677  hw_device_ctx = NULL;
678  }
679  }
680 #endif // USE_HW_ACCEL
681  }
682 
683  // Close the audio codec
684  if (info.has_audio) {
685  if(avcodec_is_open(aCodecCtx)) {
686  avcodec_flush_buffers(aCodecCtx);
687  }
688  AV_FREE_CONTEXT(aCodecCtx);
689  }
690 
691  // Clear final cache
692  final_cache.Clear();
693  working_cache.Clear();
694 
695  // Close the video file
696  avformat_close_input(&pFormatCtx);
697  av_freep(&pFormatCtx);
698 
699  // Reset some variables
700  last_frame = 0;
701  hold_packet = false;
702  largest_frame_processed = 0;
703  seek_audio_frame_found = 0;
704  seek_video_frame_found = 0;
705  current_video_frame = 0;
706  last_video_frame.reset();
707  }
708 }
709 
710 bool FFmpegReader::HasAlbumArt() {
711  // Check if the video stream we use is an attached picture
712  // This won't return true if the file has a cover image as a secondary stream
713  // like an MKV file with an attached image file
714  return pFormatCtx && videoStream >= 0 && pFormatCtx->streams[videoStream]
715  && (pFormatCtx->streams[videoStream]->disposition & AV_DISPOSITION_ATTACHED_PIC);
716 }
717 
718 void FFmpegReader::UpdateAudioInfo() {
719  // Set default audio channel layout (if needed)
720 #if HAVE_CH_LAYOUT
721  if (!av_channel_layout_check(&(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout)))
722  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout = (AVChannelLayout) AV_CHANNEL_LAYOUT_STEREO;
723 #else
724  if (AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout == 0)
725  AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout = av_get_default_channel_layout(AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels);
726 #endif
727 
728  if (info.sample_rate > 0) {
729  // Skip init - if info struct already populated
730  return;
731  }
732 
733  // Set values of FileInfo struct
734  info.has_audio = true;
735  info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
736  info.acodec = aCodecCtx->codec->name;
737 #if HAVE_CH_LAYOUT
738  info.channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout.nb_channels;
739  info.channel_layout = (ChannelLayout) AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout.u.mask;
740 #else
741  info.channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
742  info.channel_layout = (ChannelLayout) AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout;
743 #endif
744 
745  // If channel layout is not set, guess based on the number of channels
746  if (info.channel_layout == 0) {
747  if (info.channels == 1) {
749  } else if (info.channels == 2) {
751  }
752  }
753 
754  info.sample_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->sample_rate;
755  info.audio_bit_rate = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->bit_rate;
756  if (info.audio_bit_rate <= 0) {
757  // Get bitrate from format
758  info.audio_bit_rate = pFormatCtx->bit_rate;
759  }
760 
761  // Set audio timebase
762  info.audio_timebase.num = aStream->time_base.num;
763  info.audio_timebase.den = aStream->time_base.den;
764 
765  // Get timebase of audio stream (if valid) and greater than the current duration
766  if (aStream->duration > 0 && aStream->duration > info.duration) {
767  // Get duration from audio stream
768  info.duration = aStream->duration * info.audio_timebase.ToDouble();
769  } else if (pFormatCtx->duration > 0 && info.duration <= 0.0f) {
770  // Use the format's duration
771  info.duration = float(pFormatCtx->duration) / AV_TIME_BASE;
772  }
773 
774  // Calculate duration from filesize and bitrate (if any)
775  if (info.duration <= 0.0f && info.video_bit_rate > 0 && info.file_size > 0) {
776  // Estimate from bitrate, total bytes, and framerate
778  }
779 
780  // Check for an invalid video length
781  if (info.has_video && info.video_length <= 0) {
782  // Calculate the video length from the audio duration
784  }
785 
786  // Set video timebase (if no video stream was found)
787  if (!info.has_video) {
788  // Set a few important default video settings (so audio can be divided into frames)
789  info.fps.num = 24;
790  info.fps.den = 1;
791  info.video_timebase.num = 1;
792  info.video_timebase.den = 24;
794  info.width = 720;
795  info.height = 480;
796 
797  // Use timeline to set correct width & height (if any)
798  Clip *parent = static_cast<Clip *>(ParentClip());
799  if (parent) {
800  if (parent->ParentTimeline()) {
801  // Set max width/height based on parent clip's timeline (if attached to a timeline)
802  info.width = parent->ParentTimeline()->preview_width;
803  info.height = parent->ParentTimeline()->preview_height;
804  }
805  }
806  }
807 
808  // Fix invalid video lengths for certain types of files (MP3 for example)
809  if (info.has_video && ((info.duration * info.fps.ToDouble()) - info.video_length > 60)) {
811  }
812 
813  // Add audio metadata (if any found)
814  AVDictionaryEntry *tag = NULL;
815  while ((tag = av_dict_get(aStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
816  QString str_key = tag->key;
817  QString str_value = tag->value;
818  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
819  }
820 }
821 
822 void FFmpegReader::UpdateVideoInfo() {
823  if (info.vcodec.length() > 0) {
824  // Skip init - if info struct already populated
825  return;
826  }
827 
828  // Set values of FileInfo struct
829  info.has_video = true;
830  info.file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
831  info.height = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->height;
832  info.width = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->width;
833  info.vcodec = pCodecCtx->codec->name;
834  info.video_bit_rate = (pFormatCtx->bit_rate / 8);
835 
836  // Frame rate from the container and codec
837  AVRational framerate = av_guess_frame_rate(pFormatCtx, pStream, NULL);
838  if (!check_fps) {
839  info.fps.num = framerate.num;
840  info.fps.den = framerate.den;
841  }
842 
843  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo", "info.fps.num", info.fps.num, "info.fps.den", info.fps.den);
844 
845  // TODO: remove excessive debug info in the next releases
846  // The debug info below is just for comparison and troubleshooting on users side during the transition period
847  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::UpdateVideoInfo (pStream->avg_frame_rate)", "num", pStream->avg_frame_rate.num, "den", pStream->avg_frame_rate.den);
848 
849  if (pStream->sample_aspect_ratio.num != 0) {
850  info.pixel_ratio.num = pStream->sample_aspect_ratio.num;
851  info.pixel_ratio.den = pStream->sample_aspect_ratio.den;
852  } else if (AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num != 0) {
853  info.pixel_ratio.num = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.num;
854  info.pixel_ratio.den = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->sample_aspect_ratio.den;
855  } else {
856  info.pixel_ratio.num = 1;
857  info.pixel_ratio.den = 1;
858  }
859  info.pixel_format = AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx);
860 
861  // Calculate the DAR (display aspect ratio)
863 
864  // Reduce size fraction
865  size.Reduce();
866 
867  // Set the ratio based on the reduced fraction
868  info.display_ratio.num = size.num;
869  info.display_ratio.den = size.den;
870 
871  // Get scan type and order from codec context/params
872  if (!check_interlace) {
873  check_interlace = true;
874  AVFieldOrder field_order = AV_GET_CODEC_ATTRIBUTES(pStream, pCodecCtx)->field_order;
875  switch(field_order) {
876  case AV_FIELD_PROGRESSIVE:
877  info.interlaced_frame = false;
878  break;
879  case AV_FIELD_TT:
880  case AV_FIELD_TB:
881  info.interlaced_frame = true;
882  info.top_field_first = true;
883  break;
884  case AV_FIELD_BT:
885  case AV_FIELD_BB:
886  info.interlaced_frame = true;
887  info.top_field_first = false;
888  break;
889  case AV_FIELD_UNKNOWN:
890  // Check again later?
891  check_interlace = false;
892  break;
893  }
894  // check_interlace will prevent these checks being repeated,
895  // unless it was cleared because we got an AV_FIELD_UNKNOWN response.
896  }
897 
898  // Set the video timebase
899  info.video_timebase.num = pStream->time_base.num;
900  info.video_timebase.den = pStream->time_base.den;
901 
902  // Set the duration in seconds, and video length (# of frames)
903  info.duration = pStream->duration * info.video_timebase.ToDouble();
904 
905  // Check for valid duration (if found)
906  if (info.duration <= 0.0f && pFormatCtx->duration >= 0) {
907  // Use the format's duration
908  info.duration = float(pFormatCtx->duration) / AV_TIME_BASE;
909  }
910 
911  // Calculate duration from filesize and bitrate (if any)
912  if (info.duration <= 0.0f && info.video_bit_rate > 0 && info.file_size > 0) {
913  // Estimate from bitrate, total bytes, and framerate
915  }
916 
917  // Certain "image" formats do not have a valid duration
918  if (info.duration <= 0.0f && pStream->duration == AV_NOPTS_VALUE && pFormatCtx->duration == AV_NOPTS_VALUE) {
919  // Force an "image" duration
920  info.duration = 60 * 60 * 1; // 1 hour duration
921  info.video_length = 1;
922  info.has_single_image = true;
923  }
924 
925  // Get the # of video frames (if found in stream)
926  // Only set this 1 time (this method can be called multiple times)
927  if (pStream->nb_frames > 0 && info.video_length <= 0)
928  {
929  info.video_length = pStream->nb_frames;
930 
931  // If the file format is animated GIF, override the video_length to be (duration * fps) rounded.
932  if (pFormatCtx && pFormatCtx->iformat && strcmp(pFormatCtx->iformat->name, "gif") == 0)
933  {
934  if (pStream->nb_frames > 1) {
935  // Animated gif (nb_frames does not take into delays and gaps)
937  } else {
938  // Static non-animated gif (set a default duration)
939  info.duration = 10.0;
940  }
941  }
942  }
943 
944  // No duration found in stream of file
945  if (info.duration <= 0.0f) {
946  // No duration is found in the video stream
947  info.duration = -1;
948  info.video_length = -1;
949  is_duration_known = false;
950  } else {
951  // Yes, a duration was found
952  is_duration_known = true;
953 
954  // Calculate number of frames (if not already found in metadata)
955  // Only set this 1 time (this method can be called multiple times)
956  if (info.video_length <= 0) {
958  }
959  }
960 
961  // Add video metadata (if any)
962  AVDictionaryEntry *tag = NULL;
963  while ((tag = av_dict_get(pStream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
964  QString str_key = tag->key;
965  QString str_value = tag->value;
966  info.metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
967  }
968 }
969 
971  return this->is_duration_known;
972 }
973 
974 std::shared_ptr<Frame> FFmpegReader::GetFrame(int64_t requested_frame) {
975  // Check for open reader (or throw exception)
976  if (!is_open)
977  throw ReaderClosed("The FFmpegReader is closed. Call Open() before calling this method.", path);
978 
979  // Adjust for a requested frame that is too small or too large
980  if (requested_frame < 1)
981  requested_frame = 1;
982  if (requested_frame > info.video_length && is_duration_known)
983  requested_frame = info.video_length;
984  if (info.has_video && info.video_length == 0)
985  // Invalid duration of video file
986  throw InvalidFile("Could not detect the duration of the video or audio stream.", path);
987 
988  // Debug output
989  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "requested_frame", requested_frame, "last_frame", last_frame);
990 
991  // Check the cache for this frame
992  std::shared_ptr<Frame> frame = final_cache.GetFrame(requested_frame);
993  if (frame) {
994  // Debug output
995  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame", requested_frame);
996 
997  // Return the cached frame
998  return frame;
999  } else {
1000 
1001  // Prevent async calls to the remainder of this code
1002  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1003 
1004  // Check the cache a 2nd time (due to the potential previous lock)
1005  frame = final_cache.GetFrame(requested_frame);
1006  if (frame) {
1007  // Debug output
1008  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetFrame", "returned cached frame on 2nd look", requested_frame);
1009 
1010  } else {
1011  // Frame is not in cache
1012  // Reset seek count
1013  seek_count = 0;
1014 
1015  // Are we within X frames of the requested frame?
1016  int64_t diff = requested_frame - last_frame;
1017  if (diff >= 1 && diff <= 20) {
1018  // Continue walking the stream
1019  frame = ReadStream(requested_frame);
1020  } else {
1021  // Greater than 30 frames away, or backwards, we need to seek to the nearest key frame
1022  if (enable_seek) {
1023  // Only seek if enabled
1024  Seek(requested_frame);
1025 
1026  } else if (!enable_seek && diff < 0) {
1027  // Start over, since we can't seek, and the requested frame is smaller than our position
1028  // Since we are seeking to frame 1, this actually just closes/re-opens the reader
1029  Seek(1);
1030  }
1031 
1032  // Then continue walking the stream
1033  frame = ReadStream(requested_frame);
1034  }
1035  }
1036  return frame;
1037  }
1038 }
1039 
1040 // Read the stream until we find the requested Frame
1041 std::shared_ptr<Frame> FFmpegReader::ReadStream(int64_t requested_frame) {
1042  // Allocate video frame
1043  bool check_seek = false;
1044  int packet_error = -1;
1045 
1046  // Debug output
1047  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream", "requested_frame", requested_frame, "max_concurrent_frames", max_concurrent_frames);
1048 
1049  // Loop through the stream until the correct frame is found
1050  while (true) {
1051  // Check if working frames are 'finished'
1052  if (!is_seeking) {
1053  // Check for final frames
1054  CheckWorkingFrames(requested_frame);
1055  }
1056 
1057  // Check if requested 'final' frame is available (and break out of loop if found)
1058  bool is_cache_found = (final_cache.GetFrame(requested_frame) != NULL);
1059  if (is_cache_found) {
1060  break;
1061  }
1062 
1063  if (!hold_packet || !packet) {
1064  // Get the next packet
1065  packet_error = GetNextPacket();
1066  if (packet_error < 0 && !packet) {
1067  // No more packets to be found
1068  packet_status.packets_eof = true;
1069  }
1070  }
1071 
1072  // Debug output
1073  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);
1074 
1075  // Check the status of a seek (if any)
1076  if (is_seeking) {
1077  check_seek = CheckSeek(false);
1078  } else {
1079  check_seek = false;
1080  }
1081 
1082  if (check_seek) {
1083  // Packet may become NULL on Close inside Seek if CheckSeek returns false
1084  // Jump to the next iteration of this loop
1085  continue;
1086  }
1087 
1088  // Video packet
1089  if ((info.has_video && packet && packet->stream_index == videoStream) ||
1090  (info.has_video && packet_status.video_decoded < packet_status.video_read) ||
1091  (info.has_video && !packet && !packet_status.video_eof)) {
1092  // Process Video Packet
1093  ProcessVideoPacket(requested_frame);
1094  }
1095  // Audio packet
1096  if ((info.has_audio && packet && packet->stream_index == audioStream) ||
1097  (info.has_audio && !packet && packet_status.audio_decoded < packet_status.audio_read) ||
1098  (info.has_audio && !packet && !packet_status.audio_eof)) {
1099  // Process Audio Packet
1100  ProcessAudioPacket(requested_frame);
1101  }
1102 
1103  // Remove unused packets (sometimes we purposely ignore video or audio packets,
1104  // if the has_video or has_audio properties are manually overridden)
1105  if ((!info.has_video && packet && packet->stream_index == videoStream) ||
1106  (!info.has_audio && packet && packet->stream_index == audioStream)) {
1107  // Keep track of deleted packet counts
1108  if (packet->stream_index == videoStream) {
1109  packet_status.video_decoded++;
1110  } else if (packet->stream_index == audioStream) {
1111  packet_status.audio_decoded++;
1112  }
1113 
1114  // Remove unused packets (sometimes we purposely ignore video or audio packets,
1115  // if the has_video or has_audio properties are manually overridden)
1116  RemoveAVPacket(packet);
1117  packet = NULL;
1118  }
1119 
1120  // Determine end-of-stream (waiting until final decoder threads finish)
1121  // Force end-of-stream in some situations
1122  packet_status.end_of_file = packet_status.packets_eof && packet_status.video_eof && packet_status.audio_eof;
1123  if ((packet_status.packets_eof && packet_status.packets_read() == packet_status.packets_decoded()) || packet_status.end_of_file) {
1124  // Force EOF (end of file) variables to true, if decoder does not support EOF detection.
1125  // If we have no more packets, and all known packets have been decoded
1126  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);
1127  if (!packet_status.video_eof) {
1128  packet_status.video_eof = true;
1129  }
1130  if (!packet_status.audio_eof) {
1131  packet_status.audio_eof = true;
1132  }
1133  packet_status.end_of_file = true;
1134  break;
1135  }
1136  } // end while
1137 
1138  // Debug output
1139  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ReadStream (Completed)",
1140  "packets_read", packet_status.packets_read(),
1141  "packets_decoded", packet_status.packets_decoded(),
1142  "end_of_file", packet_status.end_of_file,
1143  "largest_frame_processed", largest_frame_processed,
1144  "Working Cache Count", working_cache.Count());
1145 
1146  // Have we reached end-of-stream (or the final frame)?
1147  if (!packet_status.end_of_file && requested_frame >= info.video_length) {
1148  // Force end-of-stream
1149  packet_status.end_of_file = true;
1150  }
1151  if (packet_status.end_of_file) {
1152  // Mark any other working frames as 'finished'
1153  CheckWorkingFrames(requested_frame);
1154  }
1155 
1156  // Return requested frame (if found)
1157  std::shared_ptr<Frame> frame = final_cache.GetFrame(requested_frame);
1158  if (frame)
1159  // Return prepared frame
1160  return frame;
1161  else {
1162 
1163  // Check if largest frame is still cached
1164  frame = final_cache.GetFrame(largest_frame_processed);
1165  int samples_in_frame = Frame::GetSamplesPerFrame(requested_frame, info.fps,
1167  if (frame) {
1168  // Copy and return the largest processed frame (assuming it was the last in the video file)
1169  std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1170 
1171  // Use solid color (if no image data found)
1172  if (!frame->has_image_data) {
1173  // Use solid black frame if no image data available
1174  f->AddColor(info.width, info.height, "#000");
1175  }
1176  // Silence audio data (if any), since we are repeating the last frame
1177  frame->AddAudioSilence(samples_in_frame);
1178 
1179  return frame;
1180  } else {
1181  // The largest processed frame is no longer in cache, return a blank frame
1182  std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1183  f->AddColor(info.width, info.height, "#000");
1184  f->AddAudioSilence(samples_in_frame);
1185  return f;
1186  }
1187  }
1188 
1189 }
1190 
1191 // Get the next packet (if any)
1192 int FFmpegReader::GetNextPacket() {
1193  int found_packet = 0;
1194  AVPacket *next_packet;
1195  next_packet = new AVPacket();
1196  found_packet = av_read_frame(pFormatCtx, next_packet);
1197 
1198  if (packet) {
1199  // Remove previous packet before getting next one
1200  RemoveAVPacket(packet);
1201  packet = NULL;
1202  }
1203  if (found_packet >= 0) {
1204  // Update current packet pointer
1205  packet = next_packet;
1206 
1207  // Keep track of packet stats
1208  if (packet->stream_index == videoStream) {
1209  packet_status.video_read++;
1210  } else if (packet->stream_index == audioStream) {
1211  packet_status.audio_read++;
1212  }
1213  } else {
1214  // No more packets found
1215  delete next_packet;
1216  packet = NULL;
1217  }
1218  // Return if packet was found (or error number)
1219  return found_packet;
1220 }
1221 
1222 // Get an AVFrame (if any)
1223 bool FFmpegReader::GetAVFrame() {
1224  int frameFinished = 0;
1225 
1226  // Decode video frame
1227  AVFrame *next_frame = AV_ALLOCATE_FRAME();
1228 
1229 #if IS_FFMPEG_3_2
1230  int send_packet_err = 0;
1231  int64_t send_packet_pts = 0;
1232  if ((packet && packet->stream_index == videoStream) || !packet) {
1233  send_packet_err = avcodec_send_packet(pCodecCtx, packet);
1234 
1235  if (packet && send_packet_err >= 0) {
1236  send_packet_pts = GetPacketPTS();
1237  hold_packet = false;
1238  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet succeeded)", "send_packet_err", send_packet_err, "send_packet_pts", send_packet_pts);
1239  }
1240  }
1241 
1242  #if USE_HW_ACCEL
1243  // Get the format from the variables set in get_hw_dec_format
1244  hw_de_av_pix_fmt = hw_de_av_pix_fmt_global;
1245  hw_de_av_device_type = hw_de_av_device_type_global;
1246  #endif // USE_HW_ACCEL
1247  if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1248  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);
1249  if (send_packet_err == AVERROR(EAGAIN)) {
1250  hold_packet = true;
1251  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (send packet: AVERROR(EAGAIN): user must read output with avcodec_receive_frame()", "send_packet_pts", send_packet_pts);
1252  }
1253  if (send_packet_err == AVERROR(EINVAL)) {
1254  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);
1255  }
1256  if (send_packet_err == AVERROR(ENOMEM)) {
1257  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);
1258  }
1259  }
1260 
1261  // Always try and receive a packet, if not EOF.
1262  // Even if the above avcodec_send_packet failed to send,
1263  // we might still need to receive a packet.
1264  int receive_frame_err = 0;
1265  AVFrame *next_frame2;
1266 #if USE_HW_ACCEL
1267  if (hw_de_on && hw_de_supported) {
1268  next_frame2 = AV_ALLOCATE_FRAME();
1269  }
1270  else
1271 #endif // USE_HW_ACCEL
1272  {
1273  next_frame2 = next_frame;
1274  }
1275  pFrame = AV_ALLOCATE_FRAME();
1276  while (receive_frame_err >= 0) {
1277  receive_frame_err = avcodec_receive_frame(pCodecCtx, next_frame2);
1278 
1279  if (receive_frame_err != 0) {
1280  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);
1281 
1282  if (receive_frame_err == AVERROR_EOF) {
1284  "FFmpegReader::GetAVFrame (receive frame: AVERROR_EOF: EOF detected from decoder, flushing buffers)", "send_packet_pts", send_packet_pts);
1285  avcodec_flush_buffers(pCodecCtx);
1286  packet_status.video_eof = true;
1287  }
1288  if (receive_frame_err == AVERROR(EINVAL)) {
1290  "FFmpegReader::GetAVFrame (receive frame: AVERROR(EINVAL): invalid frame received, flushing buffers)", "send_packet_pts", send_packet_pts);
1291  avcodec_flush_buffers(pCodecCtx);
1292  }
1293  if (receive_frame_err == AVERROR(EAGAIN)) {
1295  "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);
1296  }
1297  if (receive_frame_err == AVERROR_INPUT_CHANGED) {
1299  "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);
1300  }
1301 
1302  // Break out of decoding loop
1303  // Nothing ready for decoding yet
1304  break;
1305  }
1306 
1307 #if USE_HW_ACCEL
1308  if (hw_de_on && hw_de_supported) {
1309  int err;
1310  if (next_frame2->format == hw_de_av_pix_fmt) {
1311  next_frame->format = AV_PIX_FMT_YUV420P;
1312  if ((err = av_hwframe_transfer_data(next_frame,next_frame2,0)) < 0) {
1313  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (Failed to transfer data to output frame)", "hw_de_on", hw_de_on);
1314  }
1315  if ((err = av_frame_copy_props(next_frame,next_frame2)) < 0) {
1316  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::GetAVFrame (Failed to copy props to output frame)", "hw_de_on", hw_de_on);
1317  }
1318  }
1319  }
1320  else
1321 #endif // USE_HW_ACCEL
1322  { // No hardware acceleration used -> no copy from GPU memory needed
1323  next_frame = next_frame2;
1324  }
1325 
1326  // TODO also handle possible further frames
1327  // Use only the first frame like avcodec_decode_video2
1328  frameFinished = 1;
1329  packet_status.video_decoded++;
1330 
1331  // Allocate image (align 32 for simd)
1332  if (AV_ALLOCATE_IMAGE(pFrame, (AVPixelFormat)(pStream->codecpar->format), info.width, info.height) <= 0) {
1333  throw OutOfMemory("Failed to allocate image buffer", path);
1334  }
1335  av_image_copy(pFrame->data, pFrame->linesize, (const uint8_t**)next_frame->data, next_frame->linesize,
1336  (AVPixelFormat)(pStream->codecpar->format), info.width, info.height);
1337 
1338  // Get display PTS from video frame, often different than packet->pts.
1339  // Sending packets to the decoder (i.e. packet->pts) is async,
1340  // and retrieving packets from the decoder (frame->pts) is async. In most decoders
1341  // sending and retrieving are separated by multiple calls to this method.
1342  if (next_frame->pts != AV_NOPTS_VALUE) {
1343  // This is the current decoded frame (and should be the pts used) for
1344  // processing this data
1345  video_pts = next_frame->pts;
1346  } else if (next_frame->pkt_dts != AV_NOPTS_VALUE) {
1347  // Some videos only set this timestamp (fallback)
1348  video_pts = next_frame->pkt_dts;
1349  }
1350 
1352  "FFmpegReader::GetAVFrame (Successful frame received)", "video_pts", video_pts, "send_packet_pts", send_packet_pts);
1353 
1354  // break out of loop after each successful image returned
1355  break;
1356  }
1357 #if USE_HW_ACCEL
1358  if (hw_de_on && hw_de_supported) {
1359  AV_FREE_FRAME(&next_frame2);
1360  }
1361  #endif // USE_HW_ACCEL
1362 #else
1363  avcodec_decode_video2(pCodecCtx, next_frame, &frameFinished, packet);
1364 
1365  // always allocate pFrame (because we do that in the ffmpeg >= 3.2 as well); it will always be freed later
1366  pFrame = AV_ALLOCATE_FRAME();
1367 
1368  // is frame finished
1369  if (frameFinished) {
1370  // AVFrames are clobbered on the each call to avcodec_decode_video, so we
1371  // must make a copy of the image data before this method is called again.
1372  avpicture_alloc((AVPicture *) pFrame, pCodecCtx->pix_fmt, info.width, info.height);
1373  av_picture_copy((AVPicture *) pFrame, (AVPicture *) next_frame, pCodecCtx->pix_fmt, info.width,
1374  info.height);
1375  }
1376 #endif // IS_FFMPEG_3_2
1377 
1378  // deallocate the frame
1379  AV_FREE_FRAME(&next_frame);
1380 
1381  // Did we get a video frame?
1382  return frameFinished;
1383 }
1384 
1385 // Check the current seek position and determine if we need to seek again
1386 bool FFmpegReader::CheckSeek(bool is_video) {
1387  // Are we seeking for a specific frame?
1388  if (is_seeking) {
1389  // Determine if both an audio and video packet have been decoded since the seek happened.
1390  // If not, allow the ReadStream method to keep looping
1391  if ((is_video_seek && !seek_video_frame_found) || (!is_video_seek && !seek_audio_frame_found))
1392  return false;
1393 
1394  // Check for both streams
1395  if ((info.has_video && !seek_video_frame_found) || (info.has_audio && !seek_audio_frame_found))
1396  return false;
1397 
1398  // Determine max seeked frame
1399  int64_t max_seeked_frame = std::max(seek_audio_frame_found, seek_video_frame_found);
1400 
1401  // determine if we are "before" the requested frame
1402  if (max_seeked_frame >= seeking_frame) {
1403  // SEEKED TOO FAR
1404  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckSeek (Too far, seek again)",
1405  "is_video_seek", is_video_seek,
1406  "max_seeked_frame", max_seeked_frame,
1407  "seeking_frame", seeking_frame,
1408  "seeking_pts", seeking_pts,
1409  "seek_video_frame_found", seek_video_frame_found,
1410  "seek_audio_frame_found", seek_audio_frame_found);
1411 
1412  // Seek again... to the nearest Keyframe
1413  Seek(seeking_frame - (10 * seek_count * seek_count));
1414  } else {
1415  // SEEK WORKED
1416  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckSeek (Successful)",
1417  "is_video_seek", is_video_seek,
1418  "packet->pts", GetPacketPTS(),
1419  "seeking_pts", seeking_pts,
1420  "seeking_frame", seeking_frame,
1421  "seek_video_frame_found", seek_video_frame_found,
1422  "seek_audio_frame_found", seek_audio_frame_found);
1423 
1424  // Seek worked, and we are "before" the requested frame
1425  is_seeking = false;
1426  seeking_frame = 0;
1427  seeking_pts = -1;
1428  }
1429  }
1430 
1431  // return the pts to seek to (if any)
1432  return is_seeking;
1433 }
1434 
1435 // Process a video packet
1436 void FFmpegReader::ProcessVideoPacket(int64_t requested_frame) {
1437  // Get the AVFrame from the current packet
1438  // This sets the video_pts to the correct timestamp
1439  int frame_finished = GetAVFrame();
1440 
1441  // Check if the AVFrame is finished and set it
1442  if (!frame_finished) {
1443  // No AVFrame decoded yet, bail out
1444  if (pFrame) {
1445  RemoveAVFrame(pFrame);
1446  }
1447  return;
1448  }
1449 
1450  // Calculate current frame #
1451  int64_t current_frame = ConvertVideoPTStoFrame(video_pts);
1452 
1453  // Track 1st video packet after a successful seek
1454  if (!seek_video_frame_found && is_seeking)
1455  seek_video_frame_found = current_frame;
1456 
1457  // Create or get the existing frame object. Requested frame needs to be created
1458  // in working_cache at least once. Seek can clear the working_cache, so we must
1459  // add the requested frame back to the working_cache here. If it already exists,
1460  // it will be moved to the top of the working_cache.
1461  working_cache.Add(CreateFrame(requested_frame));
1462 
1463  // Debug output
1464  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessVideoPacket (Before)", "requested_frame", requested_frame, "current_frame", current_frame);
1465 
1466  // Init some things local (for OpenMP)
1467  PixelFormat pix_fmt = AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx);
1468  int height = info.height;
1469  int width = info.width;
1470  int64_t video_length = info.video_length;
1471 
1472  // Create variables for a RGB Frame (since most videos are not in RGB, we must convert it)
1473  AVFrame *pFrameRGB = nullptr;
1474  uint8_t *buffer = nullptr;
1475 
1476  // Allocate an AVFrame structure
1477  pFrameRGB = AV_ALLOCATE_FRAME();
1478  if (pFrameRGB == nullptr)
1479  throw OutOfMemory("Failed to allocate frame buffer", path);
1480 
1481  // Determine the max size of this source image (based on the timeline's size, the scaling mode,
1482  // and the scaling keyframes). This is a performance improvement, to keep the images as small as possible,
1483  // without losing quality. NOTE: We cannot go smaller than the timeline itself, or the add_layer timeline
1484  // method will scale it back to timeline size before scaling it smaller again. This needs to be fixed in
1485  // the future.
1486  int max_width = info.width;
1487  int max_height = info.height;
1488 
1489  Clip *parent = static_cast<Clip *>(ParentClip());
1490  if (parent) {
1491  if (parent->ParentTimeline()) {
1492  // Set max width/height based on parent clip's timeline (if attached to a timeline)
1493  max_width = parent->ParentTimeline()->preview_width;
1494  max_height = parent->ParentTimeline()->preview_height;
1495  }
1496  if (parent->scale == SCALE_FIT || parent->scale == SCALE_STRETCH) {
1497  // Best fit or Stretch scaling (based on max timeline size * scaling keyframes)
1498  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1499  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1500  max_width = std::max(float(max_width), max_width * max_scale_x);
1501  max_height = std::max(float(max_height), max_height * max_scale_y);
1502 
1503  } else if (parent->scale == SCALE_CROP) {
1504  // Cropping scale mode (based on max timeline size * cropped size * scaling keyframes)
1505  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1506  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1507  QSize width_size(max_width * max_scale_x,
1508  round(max_width / (float(info.width) / float(info.height))));
1509  QSize height_size(round(max_height / (float(info.height) / float(info.width))),
1510  max_height * max_scale_y);
1511  // respect aspect ratio
1512  if (width_size.width() >= max_width && width_size.height() >= max_height) {
1513  max_width = std::max(max_width, width_size.width());
1514  max_height = std::max(max_height, width_size.height());
1515  } else {
1516  max_width = std::max(max_width, height_size.width());
1517  max_height = std::max(max_height, height_size.height());
1518  }
1519 
1520  } else {
1521  // Scale video to equivalent unscaled size
1522  // Since the preview window can change sizes, we want to always
1523  // scale against the ratio of original video size to timeline size
1524  float preview_ratio = 1.0;
1525  if (parent->ParentTimeline()) {
1526  Timeline *t = (Timeline *) parent->ParentTimeline();
1527  preview_ratio = t->preview_width / float(t->info.width);
1528  }
1529  float max_scale_x = parent->scale_x.GetMaxPoint().co.Y;
1530  float max_scale_y = parent->scale_y.GetMaxPoint().co.Y;
1531  max_width = info.width * max_scale_x * preview_ratio;
1532  max_height = info.height * max_scale_y * preview_ratio;
1533  }
1534  }
1535 
1536  // Determine if image needs to be scaled (for performance reasons)
1537  int original_height = height;
1538  if (max_width != 0 && max_height != 0 && max_width < width && max_height < height) {
1539  // Override width and height (but maintain aspect ratio)
1540  float ratio = float(width) / float(height);
1541  int possible_width = round(max_height * ratio);
1542  int possible_height = round(max_width / ratio);
1543 
1544  if (possible_width <= max_width) {
1545  // use calculated width, and max_height
1546  width = possible_width;
1547  height = max_height;
1548  } else {
1549  // use max_width, and calculated height
1550  width = max_width;
1551  height = possible_height;
1552  }
1553  }
1554 
1555  // Determine required buffer size and allocate buffer
1556  const int bytes_per_pixel = 4;
1557  int buffer_size = (width * height * bytes_per_pixel) + 128;
1558  buffer = new unsigned char[buffer_size]();
1559 
1560  // Copy picture data from one AVFrame (or AVPicture) to another one.
1561  AV_COPY_PICTURE_DATA(pFrameRGB, buffer, PIX_FMT_RGBA, width, height);
1562 
1563  int scale_mode = SWS_FAST_BILINEAR;
1564  if (openshot::Settings::Instance()->HIGH_QUALITY_SCALING) {
1565  scale_mode = SWS_BICUBIC;
1566  }
1567  SwsContext *img_convert_ctx = sws_getContext(info.width, info.height, AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx), width,
1568  height, PIX_FMT_RGBA, scale_mode, NULL, NULL, NULL);
1569 
1570  // Resize / Convert to RGB
1571  sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0,
1572  original_height, pFrameRGB->data, pFrameRGB->linesize);
1573 
1574  // Create or get the existing frame object
1575  std::shared_ptr<Frame> f = CreateFrame(current_frame);
1576 
1577  // Add Image data to frame
1578  if (!ffmpeg_has_alpha(AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx))) {
1579  // Add image with no alpha channel, Speed optimization
1580  f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888_Premultiplied, buffer);
1581  } else {
1582  // Add image with alpha channel (this will be converted to premultipled when needed, but is slower)
1583  f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888, buffer);
1584  }
1585 
1586  // Update working cache
1587  working_cache.Add(f);
1588 
1589  // Keep track of last last_video_frame
1590  last_video_frame = f;
1591 
1592  // Free the RGB image
1593  AV_FREE_FRAME(&pFrameRGB);
1594 
1595  // Remove frame and packet
1596  RemoveAVFrame(pFrame);
1597  sws_freeContext(img_convert_ctx);
1598 
1599  // Get video PTS in seconds
1600  video_pts_seconds = (double(video_pts) * info.video_timebase.ToDouble()) + pts_offset_seconds;
1601 
1602  // Debug output
1603  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessVideoPacket (After)", "requested_frame", requested_frame, "current_frame", current_frame, "f->number", f->number, "video_pts_seconds", video_pts_seconds);
1604 }
1605 
1606 // Process an audio packet
1607 void FFmpegReader::ProcessAudioPacket(int64_t requested_frame) {
1608  AudioLocation location;
1609  // Calculate location of current audio packet
1610  if (packet && packet->pts != AV_NOPTS_VALUE) {
1611  // Determine related video frame and starting sample # from audio PTS
1612  location = GetAudioPTSLocation(packet->pts);
1613 
1614  // Track 1st audio packet after a successful seek
1615  if (!seek_audio_frame_found && is_seeking)
1616  seek_audio_frame_found = location.frame;
1617  }
1618 
1619  // Create or get the existing frame object. Requested frame needs to be created
1620  // in working_cache at least once. Seek can clear the working_cache, so we must
1621  // add the requested frame back to the working_cache here. If it already exists,
1622  // it will be moved to the top of the working_cache.
1623  working_cache.Add(CreateFrame(requested_frame));
1624 
1625  // Debug output
1626  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (Before)",
1627  "requested_frame", requested_frame,
1628  "target_frame", location.frame,
1629  "starting_sample", location.sample_start);
1630 
1631  // Init an AVFrame to hold the decoded audio samples
1632  int frame_finished = 0;
1633  AVFrame *audio_frame = AV_ALLOCATE_FRAME();
1634  AV_RESET_FRAME(audio_frame);
1635 
1636  int packet_samples = 0;
1637  int data_size = 0;
1638 
1639 #if IS_FFMPEG_3_2
1640  int send_packet_err = avcodec_send_packet(aCodecCtx, packet);
1641  if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1642  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (Packet not sent)");
1643  }
1644  else {
1645  int receive_frame_err = avcodec_receive_frame(aCodecCtx, audio_frame);
1646  if (receive_frame_err >= 0) {
1647  frame_finished = 1;
1648  }
1649  if (receive_frame_err == AVERROR_EOF) {
1650  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (EOF detected from decoder)");
1651  packet_status.audio_eof = true;
1652  }
1653  if (receive_frame_err == AVERROR(EINVAL) || receive_frame_err == AVERROR_EOF) {
1654  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (invalid frame received or EOF from decoder)");
1655  avcodec_flush_buffers(aCodecCtx);
1656  }
1657  if (receive_frame_err != 0) {
1658  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (frame not ready yet from decoder)");
1659  }
1660  }
1661 #else
1662  int used = avcodec_decode_audio4(aCodecCtx, audio_frame, &frame_finished, packet);
1663 #endif
1664 
1665  if (frame_finished) {
1666  packet_status.audio_decoded++;
1667 
1668  // This can be different than the current packet, so we need to look
1669  // at the current AVFrame from the audio decoder. This timestamp should
1670  // be used for the remainder of this function
1671  audio_pts = audio_frame->pts;
1672 
1673  // Determine related video frame and starting sample # from audio PTS
1674  location = GetAudioPTSLocation(audio_pts);
1675 
1676  // determine how many samples were decoded
1677  int plane_size = -1;
1678 #if HAVE_CH_LAYOUT
1679  int nb_channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout.nb_channels;
1680 #else
1681  int nb_channels = AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channels;
1682 #endif
1683  data_size = av_samples_get_buffer_size(&plane_size, nb_channels,
1684  audio_frame->nb_samples, (AVSampleFormat) (AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx)), 1);
1685 
1686  // Calculate total number of samples
1687  packet_samples = audio_frame->nb_samples * nb_channels;
1688  } else {
1689  if (audio_frame) {
1690  // Free audio frame
1691  AV_FREE_FRAME(&audio_frame);
1692  }
1693  }
1694 
1695  // Estimate the # of samples and the end of this packet's location (to prevent GAPS for the next timestamp)
1696  int pts_remaining_samples = packet_samples / info.channels; // Adjust for zero based array
1697 
1698  // Bail if no samples found
1699  if (pts_remaining_samples == 0) {
1700  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (No samples, bailing)",
1701  "packet_samples", packet_samples,
1702  "info.channels", info.channels,
1703  "pts_remaining_samples", pts_remaining_samples);
1704  return;
1705  }
1706 
1707  while (pts_remaining_samples) {
1708  // Get Samples per frame (for this frame number)
1709  int samples_per_frame = Frame::GetSamplesPerFrame(previous_packet_location.frame, info.fps, info.sample_rate, info.channels);
1710 
1711  // Calculate # of samples to add to this frame
1712  int samples = samples_per_frame - previous_packet_location.sample_start;
1713  if (samples > pts_remaining_samples)
1714  samples = pts_remaining_samples;
1715 
1716  // Decrement remaining samples
1717  pts_remaining_samples -= samples;
1718 
1719  if (pts_remaining_samples > 0) {
1720  // next frame
1721  previous_packet_location.frame++;
1722  previous_packet_location.sample_start = 0;
1723  } else {
1724  // Increment sample start
1725  previous_packet_location.sample_start += samples;
1726  }
1727  }
1728 
1729  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (ReSample)",
1730  "packet_samples", packet_samples,
1731  "info.channels", info.channels,
1732  "info.sample_rate", info.sample_rate,
1733  "aCodecCtx->sample_fmt", AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx));
1734 
1735  // Create output frame
1736  AVFrame *audio_converted = AV_ALLOCATE_FRAME();
1737  AV_RESET_FRAME(audio_converted);
1738  audio_converted->nb_samples = audio_frame->nb_samples;
1739  av_samples_alloc(audio_converted->data, audio_converted->linesize, info.channels, audio_frame->nb_samples, AV_SAMPLE_FMT_FLTP, 0);
1740 
1741  SWRCONTEXT *avr = NULL;
1742 
1743  // setup resample context
1744  avr = SWR_ALLOC();
1745 #if HAVE_CH_LAYOUT
1746  av_opt_set_chlayout(avr, "in_chlayout", &AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout, 0);
1747  av_opt_set_chlayout(avr, "out_chlayout", &AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->ch_layout, 0);
1748 #else
1749  av_opt_set_int(avr, "in_channel_layout", AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout, 0);
1750  av_opt_set_int(avr, "out_channel_layout", AV_GET_CODEC_ATTRIBUTES(aStream, aCodecCtx)->channel_layout, 0);
1751  av_opt_set_int(avr, "in_channels", info.channels, 0);
1752  av_opt_set_int(avr, "out_channels", info.channels, 0);
1753 #endif
1754  av_opt_set_int(avr, "in_sample_fmt", AV_GET_SAMPLE_FORMAT(aStream, aCodecCtx), 0);
1755  av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
1756  av_opt_set_int(avr, "in_sample_rate", info.sample_rate, 0);
1757  av_opt_set_int(avr, "out_sample_rate", info.sample_rate, 0);
1758  SWR_INIT(avr);
1759 
1760  // Convert audio samples
1761  int nb_samples = SWR_CONVERT(avr, // audio resample context
1762  audio_converted->data, // output data pointers
1763  audio_converted->linesize[0], // output plane size, in bytes. (0 if unknown)
1764  audio_converted->nb_samples, // maximum number of samples that the output buffer can hold
1765  audio_frame->data, // input data pointers
1766  audio_frame->linesize[0], // input plane size, in bytes (0 if unknown)
1767  audio_frame->nb_samples); // number of input samples to convert
1768 
1769  // Deallocate resample buffer
1770  SWR_CLOSE(avr);
1771  SWR_FREE(&avr);
1772  avr = NULL;
1773 
1774  int64_t starting_frame_number = -1;
1775  for (int channel_filter = 0; channel_filter < info.channels; channel_filter++) {
1776  // Array of floats (to hold samples for each channel)
1777  starting_frame_number = location.frame;
1778  int channel_buffer_size = nb_samples;
1779  auto *channel_buffer = (float *) (audio_converted->data[channel_filter]);
1780 
1781  // Loop through samples, and add them to the correct frames
1782  int start = location.sample_start;
1783  int remaining_samples = channel_buffer_size;
1784  while (remaining_samples > 0) {
1785  // Get Samples per frame (for this frame number)
1786  int samples_per_frame = Frame::GetSamplesPerFrame(starting_frame_number, info.fps, info.sample_rate, info.channels);
1787 
1788  // Calculate # of samples to add to this frame
1789  int samples = std::fmin(samples_per_frame - start, remaining_samples);
1790 
1791  // Create or get the existing frame object
1792  std::shared_ptr<Frame> f = CreateFrame(starting_frame_number);
1793 
1794  // Add samples for current channel to the frame.
1795  f->AddAudio(true, channel_filter, start, channel_buffer, samples, 1.0f);
1796 
1797  // Debug output
1798  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (f->AddAudio)",
1799  "frame", starting_frame_number,
1800  "start", start,
1801  "samples", samples,
1802  "channel", channel_filter,
1803  "samples_per_frame", samples_per_frame);
1804 
1805  // Add or update cache
1806  working_cache.Add(f);
1807 
1808  // Decrement remaining samples
1809  remaining_samples -= samples;
1810 
1811  // Increment buffer (to next set of samples)
1812  if (remaining_samples > 0)
1813  channel_buffer += samples;
1814 
1815  // Increment frame number
1816  starting_frame_number++;
1817 
1818  // Reset starting sample #
1819  start = 0;
1820  }
1821  }
1822 
1823  // Free AVFrames
1824  av_free(audio_converted->data[0]);
1825  AV_FREE_FRAME(&audio_converted);
1826  AV_FREE_FRAME(&audio_frame);
1827 
1828  // Get audio PTS in seconds
1829  audio_pts_seconds = (double(audio_pts) * info.audio_timebase.ToDouble()) + pts_offset_seconds;
1830 
1831  // Debug output
1832  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::ProcessAudioPacket (After)",
1833  "requested_frame", requested_frame,
1834  "starting_frame", location.frame,
1835  "end_frame", starting_frame_number - 1,
1836  "audio_pts_seconds", audio_pts_seconds);
1837 
1838 }
1839 
1840 
1841 // Seek to a specific frame. This is not always frame accurate, it's more of an estimation on many codecs.
1842 void FFmpegReader::Seek(int64_t requested_frame) {
1843  // Adjust for a requested frame that is too small or too large
1844  if (requested_frame < 1)
1845  requested_frame = 1;
1846  if (requested_frame > info.video_length)
1847  requested_frame = info.video_length;
1848  if (requested_frame > largest_frame_processed && packet_status.end_of_file) {
1849  // Not possible to search past largest_frame once EOF is reached (no more packets)
1850  return;
1851  }
1852 
1853  // Debug output
1854  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::Seek",
1855  "requested_frame", requested_frame,
1856  "seek_count", seek_count,
1857  "last_frame", last_frame);
1858 
1859  // Clear working cache (since we are seeking to another location in the file)
1860  working_cache.Clear();
1861 
1862  // Reset the last frame variable
1863  video_pts = 0.0;
1864  video_pts_seconds = NO_PTS_OFFSET;
1865  audio_pts = 0.0;
1866  audio_pts_seconds = NO_PTS_OFFSET;
1867  hold_packet = false;
1868  last_frame = 0;
1869  current_video_frame = 0;
1870  largest_frame_processed = 0;
1871  bool has_audio_override = info.has_audio;
1872  bool has_video_override = info.has_video;
1873 
1874  // Init end-of-file detection variables
1875  packet_status.reset(false);
1876 
1877  // Increment seek count
1878  seek_count++;
1879 
1880  // If seeking near frame 1, we need to close and re-open the file (this is more reliable than seeking)
1881  int buffer_amount = std::max(max_concurrent_frames, 8);
1882  if (requested_frame - buffer_amount < 20) {
1883  // prevent Open() from seeking again
1884  is_seeking = true;
1885 
1886  // Close and re-open file (basically seeking to frame 1)
1887  Close();
1888  Open();
1889 
1890  // Update overrides (since closing and re-opening might update these)
1891  info.has_audio = has_audio_override;
1892  info.has_video = has_video_override;
1893 
1894  // Not actually seeking, so clear these flags
1895  is_seeking = false;
1896  if (seek_count == 1) {
1897  // Don't redefine this on multiple seek attempts for a specific frame
1898  seeking_frame = 1;
1899  seeking_pts = ConvertFrameToVideoPTS(1);
1900  }
1901  seek_audio_frame_found = 0; // used to detect which frames to throw away after a seek
1902  seek_video_frame_found = 0; // used to detect which frames to throw away after a seek
1903 
1904  } else {
1905  // Seek to nearest key-frame (aka, i-frame)
1906  bool seek_worked = false;
1907  int64_t seek_target = 0;
1908 
1909  // Seek video stream (if any), except album arts
1910  if (!seek_worked && info.has_video && !HasAlbumArt()) {
1911  seek_target = ConvertFrameToVideoPTS(requested_frame - buffer_amount);
1912  if (av_seek_frame(pFormatCtx, info.video_stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
1913  fprintf(stderr, "%s: error while seeking video stream\n", pFormatCtx->AV_FILENAME);
1914  } else {
1915  // VIDEO SEEK
1916  is_video_seek = true;
1917  seek_worked = true;
1918  }
1919  }
1920 
1921  // Seek audio stream (if not already seeked... and if an audio stream is found)
1922  if (!seek_worked && info.has_audio) {
1923  seek_target = ConvertFrameToAudioPTS(requested_frame - buffer_amount);
1924  if (av_seek_frame(pFormatCtx, info.audio_stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
1925  fprintf(stderr, "%s: error while seeking audio stream\n", pFormatCtx->AV_FILENAME);
1926  } else {
1927  // AUDIO SEEK
1928  is_video_seek = false;
1929  seek_worked = true;
1930  }
1931  }
1932 
1933  // Was the seek successful?
1934  if (seek_worked) {
1935  // Flush audio buffer
1936  if (info.has_audio)
1937  avcodec_flush_buffers(aCodecCtx);
1938 
1939  // Flush video buffer
1940  if (info.has_video)
1941  avcodec_flush_buffers(pCodecCtx);
1942 
1943  // Reset previous audio location to zero
1944  previous_packet_location.frame = -1;
1945  previous_packet_location.sample_start = 0;
1946 
1947  // init seek flags
1948  is_seeking = true;
1949  if (seek_count == 1) {
1950  // Don't redefine this on multiple seek attempts for a specific frame
1951  seeking_pts = seek_target;
1952  seeking_frame = requested_frame;
1953  }
1954  seek_audio_frame_found = 0; // used to detect which frames to throw away after a seek
1955  seek_video_frame_found = 0; // used to detect which frames to throw away after a seek
1956 
1957  } else {
1958  // seek failed
1959  seeking_pts = 0;
1960  seeking_frame = 0;
1961 
1962  // prevent Open() from seeking again
1963  is_seeking = true;
1964 
1965  // Close and re-open file (basically seeking to frame 1)
1966  Close();
1967  Open();
1968 
1969  // Not actually seeking, so clear these flags
1970  is_seeking = false;
1971 
1972  // disable seeking for this reader (since it failed)
1973  enable_seek = false;
1974 
1975  // Update overrides (since closing and re-opening might update these)
1976  info.has_audio = has_audio_override;
1977  info.has_video = has_video_override;
1978  }
1979  }
1980 }
1981 
1982 // Get the PTS for the current video packet
1983 int64_t FFmpegReader::GetPacketPTS() {
1984  if (packet) {
1985  int64_t current_pts = packet->pts;
1986  if (current_pts == AV_NOPTS_VALUE && packet->dts != AV_NOPTS_VALUE)
1987  current_pts = packet->dts;
1988 
1989  // Return adjusted PTS
1990  return current_pts;
1991  } else {
1992  // No packet, return NO PTS
1993  return AV_NOPTS_VALUE;
1994  }
1995 }
1996 
1997 // Update PTS Offset (if any)
1998 void FFmpegReader::UpdatePTSOffset() {
1999  if (pts_offset_seconds != NO_PTS_OFFSET) {
2000  // Skip this method if we have already set PTS offset
2001  return;
2002  }
2003  pts_offset_seconds = 0.0;
2004  double video_pts_offset_seconds = 0.0;
2005  double audio_pts_offset_seconds = 0.0;
2006 
2007  bool has_video_pts = false;
2008  if (!info.has_video) {
2009  // Mark as checked
2010  has_video_pts = true;
2011  }
2012  bool has_audio_pts = false;
2013  if (!info.has_audio) {
2014  // Mark as checked
2015  has_audio_pts = true;
2016  }
2017 
2018  // Loop through the stream (until a packet from all streams is found)
2019  while (!has_video_pts || !has_audio_pts) {
2020  // Get the next packet (if any)
2021  if (GetNextPacket() < 0)
2022  // Break loop when no more packets found
2023  break;
2024 
2025  // Get PTS of this packet
2026  int64_t pts = GetPacketPTS();
2027 
2028  // Video packet
2029  if (!has_video_pts && packet->stream_index == videoStream) {
2030  // Get the video packet start time (in seconds)
2031  video_pts_offset_seconds = 0.0 - (video_pts * info.video_timebase.ToDouble());
2032 
2033  // Is timestamp close to zero (within X seconds)
2034  // Ignore wildly invalid timestamps (i.e. -234923423423)
2035  if (std::abs(video_pts_offset_seconds) <= 10.0) {
2036  has_video_pts = true;
2037  }
2038  }
2039  else if (!has_audio_pts && packet->stream_index == audioStream) {
2040  // Get the audio packet start time (in seconds)
2041  audio_pts_offset_seconds = 0.0 - (pts * info.audio_timebase.ToDouble());
2042 
2043  // Is timestamp close to zero (within X seconds)
2044  // Ignore wildly invalid timestamps (i.e. -234923423423)
2045  if (std::abs(audio_pts_offset_seconds) <= 10.0) {
2046  has_audio_pts = true;
2047  }
2048  }
2049  }
2050 
2051  // Do we have all valid timestamps to determine PTS offset?
2052  if (has_video_pts && has_audio_pts) {
2053  // Set PTS Offset to the smallest offset
2054  // [ video timestamp ]
2055  // [ audio timestamp ]
2056  //
2057  // ** SHIFT TIMESTAMPS TO ZERO **
2058  //
2059  //[ video timestamp ]
2060  // [ audio timestamp ]
2061  //
2062  // Since all offsets are negative at this point, we want the max value, which
2063  // represents the closest to zero
2064  pts_offset_seconds = std::max(video_pts_offset_seconds, audio_pts_offset_seconds);
2065  }
2066 }
2067 
2068 // Convert PTS into Frame Number
2069 int64_t FFmpegReader::ConvertVideoPTStoFrame(int64_t pts) {
2070  // Apply PTS offset
2071  int64_t previous_video_frame = current_video_frame;
2072 
2073  // Get the video packet start time (in seconds)
2074  double video_seconds = (double(pts) * info.video_timebase.ToDouble()) + pts_offset_seconds;
2075 
2076  // Divide by the video timebase, to get the video frame number (frame # is decimal at this point)
2077  int64_t frame = round(video_seconds * info.fps.ToDouble()) + 1;
2078 
2079  // Keep track of the expected video frame #
2080  if (current_video_frame == 0)
2081  current_video_frame = frame;
2082  else {
2083 
2084  // Sometimes frames are duplicated due to identical (or similar) timestamps
2085  if (frame == previous_video_frame) {
2086  // return -1 frame number
2087  frame = -1;
2088  } else {
2089  // Increment expected frame
2090  current_video_frame++;
2091  }
2092  }
2093 
2094  // Return frame #
2095  return frame;
2096 }
2097 
2098 // Convert Frame Number into Video PTS
2099 int64_t FFmpegReader::ConvertFrameToVideoPTS(int64_t frame_number) {
2100  // Get timestamp of this frame (in seconds)
2101  double seconds = (double(frame_number - 1) / info.fps.ToDouble()) + pts_offset_seconds;
2102 
2103  // Calculate the # of video packets in this timestamp
2104  int64_t video_pts = round(seconds / info.video_timebase.ToDouble());
2105 
2106  // Apply PTS offset (opposite)
2107  return video_pts;
2108 }
2109 
2110 // Convert Frame Number into Video PTS
2111 int64_t FFmpegReader::ConvertFrameToAudioPTS(int64_t frame_number) {
2112  // Get timestamp of this frame (in seconds)
2113  double seconds = (double(frame_number - 1) / info.fps.ToDouble()) + pts_offset_seconds;
2114 
2115  // Calculate the # of audio packets in this timestamp
2116  int64_t audio_pts = round(seconds / info.audio_timebase.ToDouble());
2117 
2118  // Apply PTS offset (opposite)
2119  return audio_pts;
2120 }
2121 
2122 // Calculate Starting video frame and sample # for an audio PTS
2123 AudioLocation FFmpegReader::GetAudioPTSLocation(int64_t pts) {
2124  // Get the audio packet start time (in seconds)
2125  double audio_seconds = (double(pts) * info.audio_timebase.ToDouble()) + pts_offset_seconds;
2126 
2127  // Divide by the video timebase, to get the video frame number (frame # is decimal at this point)
2128  double frame = (audio_seconds * info.fps.ToDouble()) + 1;
2129 
2130  // Frame # as a whole number (no more decimals)
2131  int64_t whole_frame = int64_t(frame);
2132 
2133  // Remove the whole number, and only get the decimal of the frame
2134  double sample_start_percentage = frame - double(whole_frame);
2135 
2136  // Get Samples per frame
2137  int samples_per_frame = Frame::GetSamplesPerFrame(whole_frame, info.fps, info.sample_rate, info.channels);
2138 
2139  // Calculate the sample # to start on
2140  int sample_start = round(double(samples_per_frame) * sample_start_percentage);
2141 
2142  // Protect against broken (i.e. negative) timestamps
2143  if (whole_frame < 1)
2144  whole_frame = 1;
2145  if (sample_start < 0)
2146  sample_start = 0;
2147 
2148  // Prepare final audio packet location
2149  AudioLocation location = {whole_frame, sample_start};
2150 
2151  // Compare to previous audio packet (and fix small gaps due to varying PTS timestamps)
2152  if (previous_packet_location.frame != -1) {
2153  if (location.is_near(previous_packet_location, samples_per_frame, samples_per_frame)) {
2154  int64_t orig_frame = location.frame;
2155  int orig_start = location.sample_start;
2156 
2157  // Update sample start, to prevent gaps in audio
2158  location.sample_start = previous_packet_location.sample_start;
2159  location.frame = previous_packet_location.frame;
2160 
2161  // Debug output
2162  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);
2163 
2164  } else {
2165  // Debug output
2166  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);
2167  }
2168  }
2169 
2170  // Set previous location
2171  previous_packet_location = location;
2172 
2173  // Return the associated video frame and starting sample #
2174  return location;
2175 }
2176 
2177 // Create a new Frame (or return an existing one) and add it to the working queue.
2178 std::shared_ptr<Frame> FFmpegReader::CreateFrame(int64_t requested_frame) {
2179  // Check working cache
2180  std::shared_ptr<Frame> output = working_cache.GetFrame(requested_frame);
2181 
2182  if (!output) {
2183  // (re-)Check working cache
2184  output = working_cache.GetFrame(requested_frame);
2185  if(output) return output;
2186 
2187  // Create a new frame on the working cache
2188  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);
2189  output->SetPixelRatio(info.pixel_ratio.num, info.pixel_ratio.den); // update pixel ratio
2190  output->ChannelsLayout(info.channel_layout); // update audio channel layout from the parent reader
2191  output->SampleRate(info.sample_rate); // update the frame's sample rate of the parent reader
2192 
2193  working_cache.Add(output);
2194 
2195  // Set the largest processed frame (if this is larger)
2196  if (requested_frame > largest_frame_processed)
2197  largest_frame_processed = requested_frame;
2198  }
2199  // Return frame
2200  return output;
2201 }
2202 
2203 // Determine if frame is partial due to seek
2204 bool FFmpegReader::IsPartialFrame(int64_t requested_frame) {
2205 
2206  // Sometimes a seek gets partial frames, and we need to remove them
2207  bool seek_trash = false;
2208  int64_t max_seeked_frame = seek_audio_frame_found; // determine max seeked frame
2209  if (seek_video_frame_found > max_seeked_frame) {
2210  max_seeked_frame = seek_video_frame_found;
2211  }
2212  if ((info.has_audio && seek_audio_frame_found && max_seeked_frame >= requested_frame) ||
2213  (info.has_video && seek_video_frame_found && max_seeked_frame >= requested_frame)) {
2214  seek_trash = true;
2215  }
2216 
2217  return seek_trash;
2218 }
2219 
2220 // Check the working queue, and move finished frames to the finished queue
2221 void FFmpegReader::CheckWorkingFrames(int64_t requested_frame) {
2222 
2223  // Prevent async calls to the following code
2224  const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
2225 
2226  // Get a list of current working queue frames in the cache (in-progress frames)
2227  std::vector<std::shared_ptr<openshot::Frame>> working_frames = working_cache.GetFrames();
2228  std::vector<std::shared_ptr<openshot::Frame>>::iterator working_itr;
2229 
2230  // Loop through all working queue frames (sorted by frame #)
2231  for(working_itr = working_frames.begin(); working_itr != working_frames.end(); ++working_itr)
2232  {
2233  // Get working frame
2234  std::shared_ptr<Frame> f = *working_itr;
2235 
2236  // Was a frame found? Is frame requested yet?
2237  if (!f || f->number > requested_frame) {
2238  // If not, skip to next one
2239  continue;
2240  }
2241 
2242  // Calculate PTS in seconds (of working frame), and the most recent processed pts value
2243  double frame_pts_seconds = (double(f->number - 1) / info.fps.ToDouble()) + pts_offset_seconds;
2244  double recent_pts_seconds = std::max(video_pts_seconds, audio_pts_seconds);
2245 
2246  // Determine if video and audio are ready (based on timestamps)
2247  bool is_video_ready = false;
2248  bool is_audio_ready = false;
2249  double recent_pts_diff = recent_pts_seconds - frame_pts_seconds;
2250  if ((frame_pts_seconds <= video_pts_seconds)
2251  || (recent_pts_diff > 1.5)
2252  || packet_status.video_eof || packet_status.end_of_file) {
2253  // Video stream is past this frame (so it must be done)
2254  // OR video stream is too far behind, missing, or end-of-file
2255  is_video_ready = true;
2256  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (video ready)",
2257  "frame_number", f->number,
2258  "frame_pts_seconds", frame_pts_seconds,
2259  "video_pts_seconds", video_pts_seconds,
2260  "recent_pts_diff", recent_pts_diff);
2261  if (info.has_video && !f->has_image_data) {
2262  // Frame has no image data (copy from previous frame)
2263  // Loop backwards through final frames (looking for the nearest, previous frame image)
2264  for (int64_t previous_frame = requested_frame - 1; previous_frame > 0; previous_frame--) {
2265  std::shared_ptr<Frame> previous_frame_instance = final_cache.GetFrame(previous_frame);
2266  if (previous_frame_instance && previous_frame_instance->has_image_data) {
2267  // Copy image from last decoded frame
2268  f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2269  break;
2270  }
2271  }
2272 
2273  if (last_video_frame && !f->has_image_data) {
2274  // Copy image from last decoded frame
2275  f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2276  } else if (!f->has_image_data) {
2277  f->AddColor("#000000");
2278  }
2279  }
2280  }
2281 
2282  double audio_pts_diff = audio_pts_seconds - frame_pts_seconds;
2283  if ((frame_pts_seconds < audio_pts_seconds && audio_pts_diff > 1.0)
2284  || (recent_pts_diff > 1.5)
2285  || packet_status.audio_eof || packet_status.end_of_file) {
2286  // Audio stream is past this frame (so it must be done)
2287  // OR audio stream is too far behind, missing, or end-of-file
2288  // Adding a bit of margin here, to allow for partial audio packets
2289  is_audio_ready = true;
2290  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (audio ready)",
2291  "frame_number", f->number,
2292  "frame_pts_seconds", frame_pts_seconds,
2293  "audio_pts_seconds", audio_pts_seconds,
2294  "audio_pts_diff", audio_pts_diff,
2295  "recent_pts_diff", recent_pts_diff);
2296  }
2297  bool is_seek_trash = IsPartialFrame(f->number);
2298 
2299  // Adjust for available streams
2300  if (!info.has_video) is_video_ready = true;
2301  if (!info.has_audio) is_audio_ready = true;
2302 
2303  // Debug output
2304  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames",
2305  "frame_number", f->number,
2306  "is_video_ready", is_video_ready,
2307  "is_audio_ready", is_audio_ready,
2308  "video_eof", packet_status.video_eof,
2309  "audio_eof", packet_status.audio_eof,
2310  "end_of_file", packet_status.end_of_file);
2311 
2312  // Check if working frame is final
2313  if ((!packet_status.end_of_file && is_video_ready && is_audio_ready) || packet_status.end_of_file || is_seek_trash) {
2314  // Debug output
2315  ZmqLogger::Instance()->AppendDebugMethod("FFmpegReader::CheckWorkingFrames (mark frame as final)",
2316  "requested_frame", requested_frame,
2317  "f->number", f->number,
2318  "is_seek_trash", is_seek_trash,
2319  "Working Cache Count", working_cache.Count(),
2320  "Final Cache Count", final_cache.Count(),
2321  "end_of_file", packet_status.end_of_file);
2322 
2323  if (!is_seek_trash) {
2324  // Move frame to final cache
2325  final_cache.Add(f);
2326 
2327  // Remove frame from working cache
2328  working_cache.Remove(f->number);
2329 
2330  // Update last frame processed
2331  last_frame = f->number;
2332  } else {
2333  // Seek trash, so delete the frame from the working cache, and never add it to the final cache.
2334  working_cache.Remove(f->number);
2335  }
2336 
2337  }
2338  }
2339 
2340  // Clear vector of frames
2341  working_frames.clear();
2342  working_frames.shrink_to_fit();
2343 }
2344 
2345 // Check for the correct frames per second (FPS) value by scanning the 1st few seconds of video packets.
2346 void FFmpegReader::CheckFPS() {
2347  if (check_fps) {
2348  // Do not check FPS more than 1 time
2349  return;
2350  } else {
2351  check_fps = true;
2352  }
2353 
2354  int frames_per_second[3] = {0,0,0};
2355  int max_fps_index = sizeof(frames_per_second) / sizeof(frames_per_second[0]);
2356  int fps_index = 0;
2357 
2358  int all_frames_detected = 0;
2359  int starting_frames_detected = 0;
2360 
2361  // Loop through the stream
2362  while (true) {
2363  // Get the next packet (if any)
2364  if (GetNextPacket() < 0)
2365  // Break loop when no more packets found
2366  break;
2367 
2368  // Video packet
2369  if (packet->stream_index == videoStream) {
2370  // Get the video packet start time (in seconds)
2371  double video_seconds = (double(GetPacketPTS()) * info.video_timebase.ToDouble()) + pts_offset_seconds;
2372  fps_index = int(video_seconds); // truncate float timestamp to int (second 1, second 2, second 3)
2373 
2374  // Is this video packet from the first few seconds?
2375  if (fps_index >= 0 && fps_index < max_fps_index) {
2376  // Yes, keep track of how many frames per second (over the first few seconds)
2377  starting_frames_detected++;
2378  frames_per_second[fps_index]++;
2379  }
2380 
2381  // Track all video packets detected
2382  all_frames_detected++;
2383  }
2384  }
2385 
2386  // Calculate FPS (based on the first few seconds of video packets)
2387  float avg_fps = 30.0;
2388  if (starting_frames_detected > 0 && fps_index > 0) {
2389  avg_fps = float(starting_frames_detected) / std::min(fps_index, max_fps_index);
2390  }
2391 
2392  // Verify average FPS is a reasonable value
2393  if (avg_fps < 8.0) {
2394  // Invalid FPS assumed, so switching to a sane default FPS instead
2395  avg_fps = 30.0;
2396  }
2397 
2398  // Update FPS (truncate average FPS to Integer)
2399  info.fps = Fraction(int(avg_fps), 1);
2400 
2401  // Update Duration and Length
2402  if (all_frames_detected > 0) {
2403  // Use all video frames detected to calculate # of frames
2404  info.video_length = all_frames_detected;
2405  info.duration = all_frames_detected / avg_fps;
2406  } else {
2407  // Use previous duration to calculate # of frames
2408  info.video_length = info.duration * avg_fps;
2409  }
2410 
2411  // Update video bit rate
2413 }
2414 
2415 // Remove AVFrame from cache (and deallocate its memory)
2416 void FFmpegReader::RemoveAVFrame(AVFrame *remove_frame) {
2417  // Remove pFrame (if exists)
2418  if (remove_frame) {
2419  // Free memory
2420  av_freep(&remove_frame->data[0]);
2421 #ifndef WIN32
2422  AV_FREE_FRAME(&remove_frame);
2423 #endif
2424  }
2425 }
2426 
2427 // Remove AVPacket from cache (and deallocate its memory)
2428 void FFmpegReader::RemoveAVPacket(AVPacket *remove_packet) {
2429  // deallocate memory for packet
2430  AV_FREE_PACKET(remove_packet);
2431 
2432  // Delete the object
2433  delete remove_packet;
2434 }
2435 
2436 // Generate JSON string of this object
2437 std::string FFmpegReader::Json() const {
2438 
2439  // Return formatted string
2440  return JsonValue().toStyledString();
2441 }
2442 
2443 // Generate Json::Value for this object
2444 Json::Value FFmpegReader::JsonValue() const {
2445 
2446  // Create root json object
2447  Json::Value root = ReaderBase::JsonValue(); // get parent properties
2448  root["type"] = "FFmpegReader";
2449  root["path"] = path;
2450 
2451  // return JsonValue
2452  return root;
2453 }
2454 
2455 // Load JSON string into this object
2456 void FFmpegReader::SetJson(const std::string value) {
2457 
2458  // Parse JSON string into JSON objects
2459  try {
2460  const Json::Value root = openshot::stringToJson(value);
2461  // Set all values that match
2462  SetJsonValue(root);
2463  }
2464  catch (const std::exception& e) {
2465  // Error parsing JSON (or missing keys)
2466  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
2467  }
2468 }
2469 
2470 // Load Json::Value into this object
2471 void FFmpegReader::SetJsonValue(const Json::Value root) {
2472 
2473  // Set parent data
2475 
2476  // Set data from Json (if key is found)
2477  if (!root["path"].isNull())
2478  path = root["path"].asString();
2479 
2480  // Re-Open path, and re-init everything (if needed)
2481  if (is_open) {
2482  Close();
2483  Open();
2484  }
2485 }
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:221
AV_FIND_DECODER_CODEC_ID
#define AV_FIND_DECODER_CODEC_ID(av_stream)
Definition: FFmpegUtilities.h:211
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:71
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:235
FFmpegUtilities.h
Header file for FFmpegUtilities.
openshot::ReaderBase::JsonValue
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
Definition: ReaderBase.cpp:107
openshot::InvalidCodec
Exception when no valid codec is found for a file.
Definition: Exceptions.h:172
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:44
openshot::PacketStatus::reset
void reset(bool eof)
Definition: FFmpegReader.h:68
openshot::CacheMemory::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)
Get a frame from the cache.
Definition: CacheMemory.cpp:80
openshot::FFmpegReader::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t requested_frame) override
Definition: FFmpegReader.cpp:974
AV_COPY_PICTURE_DATA
#define AV_COPY_PICTURE_DATA(av_frame, buffer, pix_fmt, width, height)
Definition: FFmpegUtilities.h:223
openshot::CacheMemory::Add
void Add(std::shared_ptr< openshot::Frame > frame)
Add a Frame to the cache.
Definition: CacheMemory.cpp:46
PixelFormat
#define PixelFormat
Definition: FFmpegUtilities.h:107
AV_ALLOCATE_FRAME
#define AV_ALLOCATE_FRAME()
Definition: FFmpegUtilities.h:203
openshot::ReaderBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ReaderBase.cpp:162
SWR_CONVERT
#define SWR_CONVERT(ctx, out, linesize, out_count, in, linesize2, in_count)
Definition: FFmpegUtilities.h:149
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
FF_NUM_PROCESSORS
#define FF_NUM_PROCESSORS
Definition: OpenMPUtilities.h:24
openshot::Clip::scale_y
openshot::Keyframe scale_y
Curve representing the vertical scaling in percent (0 to 1)
Definition: Clip.h:307
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::Clip
This class represents a clip (used to arrange readers on the timeline)
Definition: Clip.h:89
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:207
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:398
openshot::FFmpegReader::~FFmpegReader
virtual ~FFmpegReader()
Destructor.
Definition: FFmpegReader.cpp:100
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:154
AV_FREE_PACKET
#define AV_FREE_PACKET(av_packet)
Definition: FFmpegUtilities.h:208
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:2444
openshot::PacketStatus::audio_read
int64_t audio_read
Definition: FFmpegReader.h:49
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:2456
openshot::PacketStatus::packets_eof
bool packets_eof
Definition: FFmpegReader.h:55
hw_de_av_pix_fmt_global
AVPixelFormat hw_de_av_pix_fmt_global
Definition: FFmpegReader.cpp:67
openshot::PacketStatus::audio_decoded
int64_t audio_decoded
Definition: FFmpegReader.h:50
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:47
hw_de_on
int hw_de_on
Definition: FFmpegReader.cpp:65
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:30
AV_ALLOCATE_IMAGE
#define AV_ALLOCATE_IMAGE(av_frame, pix_fmt, width, height)
Definition: FFmpegUtilities.h:204
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:306
AV_GET_CODEC_ATTRIBUTES
#define AV_GET_CODEC_ATTRIBUTES(av_stream, av_context)
Definition: FFmpegUtilities.h:218
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:68
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:53
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:206
openshot::AudioLocation::is_near
bool is_near(AudioLocation location, int samples_per_frame, int64_t amount)
Definition: FFmpegReader.cpp:107
SWR_CLOSE
#define SWR_CLOSE(ctx)
Definition: FFmpegUtilities.h:152
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:74
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:217
openshot::FFmpegReader::enable_seek
bool enable_seek
Definition: FFmpegReader.h:232
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:148
openshot::FFmpegReader::Open
void Open() override
Open File - which is called by the constructor automatically.
Definition: FFmpegReader.cpp:207
openshot::OutOfMemory
Exception when memory could not be allocated.
Definition: Exceptions.h:348
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:154
SWRCONTEXT
#define SWRCONTEXT
Definition: FFmpegUtilities.h:155
openshot::PacketStatus::audio_eof
bool audio_eof
Definition: FFmpegReader.h:54
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:228
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
openshot::ReaderInfo::metadata
std::map< std::string, std::string > metadata
An optional map/dictionary of metadata for this reader.
Definition: ReaderBase.h:65
path
path
Definition: FFmpegWriter.cpp:1476
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:187
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::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:632
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:58
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:63
AV_GET_CODEC_TYPE
#define AV_GET_CODEC_TYPE(av_stream)
Definition: FFmpegUtilities.h:210
openshot::ReaderClosed
Exception when a reader is closed, and a frame is requested.
Definition: Exceptions.h:363
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:209
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:219
AVCODEC_REGISTER_ALL
#define AVCODEC_REGISTER_ALL
Definition: FFmpegUtilities.h:199
SWR_FREE
#define SWR_FREE(ctx)
Definition: FFmpegUtilities.h:153
openshot::Settings::DE_LIMIT_WIDTH_MAX
int DE_LIMIT_WIDTH_MAX
Maximum columns that hardware decode can handle.
Definition: Settings.h:77
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:221
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:56
openshot::Clip::scale
openshot::ScaleType scale
The scale determines how a clip should be resized to fit its parent.
Definition: Clip.h:168
openshot::ReaderInfo::top_field_first
bool top_field_first
Definition: ReaderBase.h:57
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:151
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:198
openshot::CacheMemory::GetFrames
std::vector< std::shared_ptr< openshot::Frame > > GetFrames()
Get an array of all Frames.
Definition: CacheMemory.cpp:96
AV_GET_CODEC_CONTEXT
#define AV_GET_CODEC_CONTEXT(av_stream, av_codec)
Definition: FFmpegUtilities.h:212
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:2471
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:285
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:2437
openshot::FFmpegReader::GetIsDurationKnown
bool GetIsDurationKnown()
Return true if frame can be read with GetFrame()
Definition: FFmpegReader.cpp:970
openshot::PacketStatus::video_decoded
int64_t video_decoded
Definition: FFmpegReader.h:48
opts
AVDictionary * opts
Definition: FFmpegWriter.cpp:1483
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:80
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:245