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