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