32 #define ENABLE_VAAPI 0
35 #define MAX_SUPPORTED_WIDTH 1950
36 #define MAX_SUPPORTED_HEIGHT 1100
39 #include "libavutil/hwcontext_vaapi.h"
41 typedef struct VAAPIDecodeContext {
43 VAEntrypoint va_entrypoint;
45 VAContextID va_context;
47 #if FF_API_STRUCT_VAAPI_CONTEXT
50 struct vaapi_context *old_context;
51 AVBufferRef *device_ref;
55 AVHWDeviceContext *device;
56 AVVAAPIDeviceContext *hwctx;
58 AVHWFramesContext *frames;
59 AVVAAPIFramesContext *hwfc;
61 enum AVPixelFormat surface_format;
64 #endif // ENABLE_VAAPI
65 #endif // USE_HW_ACCEL
78 static AVPixelFormat NormalizeDeprecatedPixFmt(AVPixelFormat pix_fmt,
bool& is_full_range) {
80 case AV_PIX_FMT_YUVJ420P:
82 return AV_PIX_FMT_YUV420P;
83 case AV_PIX_FMT_YUVJ422P:
85 return AV_PIX_FMT_YUV422P;
86 case AV_PIX_FMT_YUVJ444P:
88 return AV_PIX_FMT_YUV444P;
89 case AV_PIX_FMT_YUVJ440P:
91 return AV_PIX_FMT_YUV440P;
92 #ifdef AV_PIX_FMT_YUVJ411P
93 case AV_PIX_FMT_YUVJ411P:
95 return AV_PIX_FMT_YUV411P;
106 :
path(
path), pFormatCtx(NULL), videoStream(-1), audioStream(-1), pCodecCtx(NULL), aCodecCtx(NULL),
107 pStream(NULL), aStream(NULL), packet(NULL), pFrame(NULL), is_open(false), is_duration_known(false),
108 check_interlace(false), check_fps(false), duration_strategy(duration_strategy), previous_packet_location{-1, 0},
109 is_seeking(
false), seeking_pts(0), seeking_frame(0), is_video_seek(
true), seek_count(0),
110 seek_audio_frame_found(0), seek_video_frame_found(0), last_seek_max_frame(-1), seek_stagnant_count(0),
111 last_frame(0), largest_frame_processed(0), current_video_frame(0), audio_pts(0), video_pts(0),
112 hold_packet(
false), pts_offset_seconds(0.0), audio_pts_seconds(0.0), video_pts_seconds(0.0),
113 NO_PTS_OFFSET(-99999), enable_seek(
true) {
120 pts_offset_seconds = NO_PTS_OFFSET;
121 video_pts_seconds = NO_PTS_OFFSET;
122 audio_pts_seconds = NO_PTS_OFFSET;
127 working_cache.SetMaxBytesFromInfo(init_working_cache_frames, info.width, info.height, info.sample_rate, info.channels);
128 final_cache.SetMaxBytesFromInfo(init_final_cache_frames, info.width, info.height, info.sample_rate, info.channels);
131 if (inspect_reader) {
153 if (abs(diff) <= amount)
164 static enum AVPixelFormat get_hw_dec_format(AVCodecContext *ctx,
const enum AVPixelFormat *pix_fmts)
166 const enum AVPixelFormat *p;
171 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
173 #if defined(__linux__)
175 case AV_PIX_FMT_VAAPI:
182 case AV_PIX_FMT_VDPAU:
192 case AV_PIX_FMT_DXVA2_VLD:
199 case AV_PIX_FMT_D3D11:
207 #if defined(__APPLE__)
209 case AV_PIX_FMT_VIDEOTOOLBOX:
218 case AV_PIX_FMT_CUDA:
238 return AV_PIX_FMT_NONE;
241 int FFmpegReader::IsHardwareDecodeSupported(
int codecid)
245 case AV_CODEC_ID_H264:
246 case AV_CODEC_ID_MPEG2VIDEO:
247 case AV_CODEC_ID_VC1:
248 case AV_CODEC_ID_WMV1:
249 case AV_CODEC_ID_WMV2:
250 case AV_CODEC_ID_WMV3:
259 #endif // USE_HW_ACCEL
265 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
271 hw_decode_failed =
false;
272 hw_decode_error_count = 0;
273 hw_decode_succeeded =
false;
278 if (avformat_open_input(&pFormatCtx,
path.c_str(), NULL, NULL) != 0)
282 if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
289 packet_status.
reset(
true);
292 for (
unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
294 if (
AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_VIDEO && videoStream < 0) {
301 if (
AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_AUDIO && audioStream < 0) {
308 if (videoStream == -1 && audioStream == -1)
312 if (videoStream != -1) {
317 pStream = pFormatCtx->streams[videoStream];
323 const AVCodec *pCodec = avcodec_find_decoder(codecId);
324 AVDictionary *
opts = NULL;
325 int retry_decode_open = 2;
330 if (
hw_de_on && (retry_decode_open==2)) {
332 hw_de_supported = IsHardwareDecodeSupported(pCodecCtx->codec_id);
335 retry_decode_open = 0;
340 if (pCodec == NULL) {
341 throw InvalidCodec(
"A valid video codec could not be found for this file.",
path);
345 av_dict_set(&
opts,
"strict",
"experimental", 0);
349 int i_decoder_hw = 0;
351 char *adapter_ptr = NULL;
357 pCodecCtx->get_format = get_hw_dec_format;
359 if (adapter_num < 3 && adapter_num >=0) {
360 #if defined(__linux__)
361 snprintf(adapter,
sizeof(adapter),
"/dev/dri/renderD%d", adapter_num+128);
362 adapter_ptr = adapter;
364 switch (i_decoder_hw) {
366 hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
369 hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
372 hw_de_av_device_type = AV_HWDEVICE_TYPE_VDPAU;
375 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
378 hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
382 #elif defined(_WIN32)
385 switch (i_decoder_hw) {
387 hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
390 hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
393 hw_de_av_device_type = AV_HWDEVICE_TYPE_D3D11VA;
396 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
399 hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
402 #elif defined(__APPLE__)
405 switch (i_decoder_hw) {
407 hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
410 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
413 hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
423 #if defined(__linux__)
424 if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
425 #elif defined(_WIN32)
426 if( adapter_ptr != NULL ) {
427 #elif defined(__APPLE__)
428 if( adapter_ptr != NULL ) {
437 hw_device_ctx = NULL;
439 if (av_hwdevice_ctx_create(&hw_device_ctx, hw_de_av_device_type, adapter_ptr, NULL, 0) >= 0) {
440 const char* hw_name = av_hwdevice_get_type_name(hw_de_av_device_type);
441 std::string hw_msg =
"HW decode active: ";
442 hw_msg += (hw_name ? hw_name :
"unknown");
444 if (!(pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx))) {
480 #endif // USE_HW_ACCEL
487 pCodecCtx->thread_type &= ~FF_THREAD_FRAME;
491 int avcodec_return = avcodec_open2(pCodecCtx, pCodec, &
opts);
492 if (avcodec_return < 0) {
493 std::stringstream avcodec_error_msg;
494 avcodec_error_msg <<
"A video codec was found, but could not be opened. Error: " << av_err2string(avcodec_return);
500 AVHWFramesConstraints *constraints = NULL;
501 void *hwconfig = NULL;
502 hwconfig = av_hwdevice_hwconfig_alloc(hw_device_ctx);
506 ((AVVAAPIHWConfig *)hwconfig)->config_id = ((VAAPIDecodeContext *)(pCodecCtx->priv_data))->va_config;
507 constraints = av_hwdevice_get_hwframe_constraints(hw_device_ctx,hwconfig);
508 #endif // ENABLE_VAAPI
510 if (pCodecCtx->coded_width < constraints->min_width ||
511 pCodecCtx->coded_height < constraints->min_height ||
512 pCodecCtx->coded_width > constraints->max_width ||
513 pCodecCtx->coded_height > constraints->max_height) {
516 retry_decode_open = 1;
519 av_buffer_unref(&hw_device_ctx);
520 hw_device_ctx = NULL;
525 ZmqLogger::Instance()->
AppendDebugMethod(
"\nDecode hardware acceleration is used\n",
"Min width :", constraints->min_width,
"Min Height :", constraints->min_height,
"MaxWidth :", constraints->max_width,
"MaxHeight :", constraints->max_height,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
526 retry_decode_open = 0;
528 av_hwframe_constraints_free(&constraints);
541 if (pCodecCtx->coded_width < 0 ||
542 pCodecCtx->coded_height < 0 ||
543 pCodecCtx->coded_width > max_w ||
544 pCodecCtx->coded_height > max_h ) {
545 ZmqLogger::Instance()->
AppendDebugMethod(
"DIMENSIONS ARE TOO LARGE for hardware acceleration\n",
"Max Width :", max_w,
"Max Height :", max_h,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
547 retry_decode_open = 1;
550 av_buffer_unref(&hw_device_ctx);
551 hw_device_ctx = NULL;
555 ZmqLogger::Instance()->
AppendDebugMethod(
"\nDecode hardware acceleration is used\n",
"Max Width :", max_w,
"Max Height :", max_h,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
556 retry_decode_open = 0;
564 retry_decode_open = 0;
565 #endif // USE_HW_ACCEL
566 }
while (retry_decode_open);
575 if (audioStream != -1) {
580 aStream = pFormatCtx->streams[audioStream];
586 const AVCodec *aCodec = avcodec_find_decoder(codecId);
592 bool audio_opened =
false;
593 if (aCodec != NULL) {
595 AVDictionary *
opts = NULL;
596 av_dict_set(&
opts,
"strict",
"experimental", 0);
599 audio_opened = (avcodec_open2(aCodecCtx, aCodec, &
opts) >= 0);
610 const bool invalid_audio_info =
615 (aCodecCtx->sample_fmt == AV_SAMPLE_FMT_NONE);
616 if (invalid_audio_info) {
618 "FFmpegReader::Open (Disable invalid audio stream)",
623 "sample_fmt",
static_cast<int>(aCodecCtx ? aCodecCtx->sample_fmt : AV_SAMPLE_FMT_NONE));
629 if (avcodec_is_open(aCodecCtx)) {
630 avcodec_flush_buffers(aCodecCtx);
640 "FFmpegReader::Open (Audio codec unavailable; disabling audio)",
641 "audioStream", audioStream);
657 "FFmpegReader::Open (Invalid FPS detected; applying fallback)",
665 "FFmpegReader::Open (Invalid video_timebase detected; applying fallback)",
672 AVDictionaryEntry *tag = NULL;
673 while ((tag = av_dict_get(pFormatCtx->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
674 QString str_key = tag->key;
675 QString str_value = tag->value;
676 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
680 for (
unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
681 AVStream* st = pFormatCtx->streams[i];
682 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
683 size_t side_data_size = 0;
684 const uint8_t *displaymatrix = ffmpeg_stream_get_side_data(
685 st, AV_PKT_DATA_DISPLAYMATRIX, &side_data_size);
687 side_data_size >= 9 *
sizeof(int32_t) &&
689 double rotation = -av_display_rotation_get(
690 reinterpret_cast<const int32_t *
>(displaymatrix));
691 if (std::isnan(rotation))
696 const uint8_t *spherical = ffmpeg_stream_get_side_data(
697 st, AV_PKT_DATA_SPHERICAL, &side_data_size);
698 if (spherical && side_data_size >=
sizeof(AVSphericalMapping)) {
701 const AVSphericalMapping *map =
702 reinterpret_cast<const AVSphericalMapping *
>(spherical);
703 const char *proj_name = av_spherical_projection_name(map->projection);
704 info.
metadata[
"spherical_projection"] = proj_name ? proj_name :
"unknown";
706 auto to_deg = [](int32_t v) {
707 return static_cast<double>(v) / 65536.0;
709 info.
metadata[
"spherical_yaw"] = std::to_string(to_deg(map->yaw));
710 info.
metadata[
"spherical_pitch"] = std::to_string(to_deg(map->pitch));
711 info.
metadata[
"spherical_roll"] = std::to_string(to_deg(map->roll));
718 previous_packet_location.
frame = -1;
752 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
758 AVPacket *recent_packet = packet;
763 int max_attempts = 128;
768 "attempts", attempts);
780 RemoveAVPacket(recent_packet);
785 if(avcodec_is_open(pCodecCtx)) {
786 avcodec_flush_buffers(pCodecCtx);
792 av_buffer_unref(&hw_device_ctx);
793 hw_device_ctx = NULL;
796 #endif // USE_HW_ACCEL
797 if (img_convert_ctx) {
798 sws_freeContext(img_convert_ctx);
799 img_convert_ctx =
nullptr;
801 if (pFrameRGB_cached) {
808 if(avcodec_is_open(aCodecCtx)) {
809 avcodec_flush_buffers(aCodecCtx);
821 working_cache.
Clear();
824 avformat_close_input(&pFormatCtx);
825 av_freep(&pFormatCtx);
832 largest_frame_processed = 0;
833 seek_audio_frame_found = 0;
834 seek_video_frame_found = 0;
835 current_video_frame = 0;
836 last_video_frame.reset();
837 last_final_video_frame.reset();
841 bool FFmpegReader::HasAlbumArt() {
845 return pFormatCtx && videoStream >= 0 && pFormatCtx->streams[videoStream]
846 && (pFormatCtx->streams[videoStream]->disposition & AV_DISPOSITION_ATTACHED_PIC);
849 double FFmpegReader::PickDurationSeconds()
const {
850 auto has_value = [](
double value) {
return value > 0.0; };
852 switch (duration_strategy) {
854 if (has_value(video_stream_duration_seconds))
855 return video_stream_duration_seconds;
856 if (has_value(audio_stream_duration_seconds))
857 return audio_stream_duration_seconds;
858 if (has_value(format_duration_seconds))
859 return format_duration_seconds;
862 if (has_value(audio_stream_duration_seconds))
863 return audio_stream_duration_seconds;
864 if (has_value(video_stream_duration_seconds))
865 return video_stream_duration_seconds;
866 if (has_value(format_duration_seconds))
867 return format_duration_seconds;
872 double longest = 0.0;
873 if (has_value(video_stream_duration_seconds))
874 longest = std::max(longest, video_stream_duration_seconds);
875 if (has_value(audio_stream_duration_seconds))
876 longest = std::max(longest, audio_stream_duration_seconds);
877 if (has_value(format_duration_seconds))
878 longest = std::max(longest, format_duration_seconds);
879 if (has_value(longest))
885 if (has_value(format_duration_seconds))
886 return format_duration_seconds;
887 if (has_value(inferred_duration_seconds))
888 return inferred_duration_seconds;
893 void FFmpegReader::ApplyDurationStrategy() {
895 const double chosen_seconds = PickDurationSeconds();
897 if (chosen_seconds <= 0.0 || fps_value <= 0.0) {
900 is_duration_known =
false;
904 const int64_t frames =
static_cast<int64_t
>(std::llround(chosen_seconds * fps_value));
908 is_duration_known =
false;
913 info.
duration =
static_cast<float>(
static_cast<double>(frames) / fps_value);
914 is_duration_known =
true;
917 void FFmpegReader::UpdateAudioInfo() {
927 AVChannelLayout audio_ch_layout = ffmpeg_get_valid_channel_layout(
929 if (audio_ch_layout.nb_channels > 0) {
932 codec_channels = audio_ch_layout.nb_channels;
944 auto record_duration = [](
double &target,
double seconds) {
946 target = std::max(target, seconds);
951 info.
file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
982 if (aStream->duration > 0) {
985 if (pFormatCtx->duration > 0) {
987 record_duration(format_duration_seconds,
static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
1019 ApplyDurationStrategy();
1022 AVDictionaryEntry *tag = NULL;
1023 while ((tag = av_dict_get(aStream->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
1024 QString str_key = tag->key;
1025 QString str_value = tag->value;
1026 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
1029 av_channel_layout_uninit(&audio_ch_layout);
1033 void FFmpegReader::UpdateVideoInfo() {
1039 auto record_duration = [](
double &target,
double seconds) {
1041 target = std::max(target, seconds);
1046 info.
file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
1053 AVRational framerate = av_guess_frame_rate(pFormatCtx, pStream, NULL);
1065 if (pStream->sample_aspect_ratio.num != 0) {
1088 if (!check_interlace) {
1089 check_interlace =
true;
1091 switch(field_order) {
1092 case AV_FIELD_PROGRESSIVE:
1105 case AV_FIELD_UNKNOWN:
1107 check_interlace =
false;
1122 if (pFormatCtx->duration >= 0) {
1124 record_duration(format_duration_seconds,
static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
1134 if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1135 pStream->duration == AV_NOPTS_VALUE && pFormatCtx->duration == AV_NOPTS_VALUE) {
1137 record_duration(video_stream_duration_seconds, 60 * 60 * 1);
1141 if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1142 pFormatCtx && pFormatCtx->iformat && strcmp(pFormatCtx->iformat->name,
"gif") == 0) {
1143 record_duration(video_stream_duration_seconds, 60 * 60 * 1);
1147 ApplyDurationStrategy();
1153 const bool likely_still_codec =
1154 codec_id == AV_CODEC_ID_MJPEG ||
1155 codec_id == AV_CODEC_ID_PNG ||
1156 codec_id == AV_CODEC_ID_BMP ||
1157 codec_id == AV_CODEC_ID_TIFF ||
1158 codec_id == AV_CODEC_ID_WEBP ||
1159 codec_id == AV_CODEC_ID_JPEG2000;
1160 const bool likely_image_demuxer =
1161 pFormatCtx && pFormatCtx->iformat && pFormatCtx->iformat->name &&
1162 strstr(pFormatCtx->iformat->name,
"image2");
1163 const bool has_attached_pic = HasAlbumArt();
1164 const bool single_frame_stream =
1165 (pStream && pStream->nb_frames > 0 && pStream->nb_frames <= 1);
1168 const bool is_still_image_video =
1170 ((single_frame_stream || single_frame_clip) &&
1171 (likely_still_codec || likely_image_demuxer));
1173 if (is_still_image_video) {
1178 if (audioStream < 0) {
1179 record_duration(video_stream_duration_seconds, 60 * 60 * 1);
1182 ApplyDurationStrategy();
1187 AVDictionaryEntry *tag = NULL;
1188 while ((tag = av_dict_get(pStream->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
1189 QString str_key = tag->key;
1190 QString str_value = tag->value;
1191 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
1196 return this->is_duration_known;
1200 last_seek_max_frame = -1;
1201 seek_stagnant_count = 0;
1204 throw ReaderClosed(
"The FFmpegReader is closed. Call Open() before calling this method.",
path);
1207 if (requested_frame < 1)
1208 requested_frame = 1;
1213 throw InvalidFile(
"Could not detect the duration of the video or audio stream.",
path);
1228 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1241 int64_t diff = requested_frame - last_frame;
1242 if (diff >= 1 && diff <= 20) {
1244 frame = ReadStream(requested_frame);
1249 Seek(requested_frame);
1258 frame = ReadStream(requested_frame);
1266 std::shared_ptr<Frame> FFmpegReader::ReadStream(int64_t requested_frame) {
1268 bool check_seek =
false;
1269 int packet_error = -1;
1270 int64_t no_progress_count = 0;
1271 int64_t prev_packets_read = packet_status.
packets_read();
1274 double prev_video_pts_seconds = video_pts_seconds;
1284 CheckWorkingFrames(requested_frame);
1289 if (is_cache_found) {
1293 if (!hold_packet || !packet) {
1295 packet_error = GetNextPacket();
1296 if (packet_error < 0 && !packet) {
1307 check_seek = CheckSeek();
1319 if ((
info.
has_video && packet && packet->stream_index == videoStream) ||
1323 ProcessVideoPacket(requested_frame);
1324 if (ReopenWithoutHardwareDecode(requested_frame)) {
1329 if ((
info.
has_audio && packet && packet->stream_index == audioStream) ||
1333 ProcessAudioPacket(requested_frame);
1338 if ((!
info.
has_video && packet && packet->stream_index == videoStream) ||
1339 (!
info.
has_audio && packet && packet->stream_index == audioStream)) {
1341 if (packet->stream_index == videoStream) {
1343 }
else if (packet->stream_index == audioStream) {
1349 RemoveAVPacket(packet);
1359 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::ReadStream (force EOF)",
"packets_read", packet_status.
packets_read(),
"packets_decoded", packet_status.
packets_decoded(),
"packets_eof", packet_status.
packets_eof,
"video_eof", packet_status.
video_eof,
"audio_eof", packet_status.
audio_eof,
"end_of_file", packet_status.
end_of_file);
1372 const bool has_progress =
1376 (video_pts_seconds != prev_video_pts_seconds);
1379 no_progress_count = 0;
1381 no_progress_count++;
1382 if (no_progress_count >= 2000
1387 "requested_frame", requested_frame,
1388 "no_progress_count", no_progress_count,
1402 prev_video_pts_seconds = video_pts_seconds;
1410 "largest_frame_processed", largest_frame_processed,
1411 "Working Cache Count", working_cache.
Count());
1420 CheckWorkingFrames(requested_frame);
1436 std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1437 if (frame->has_image_data) {
1438 f->AddImage(std::make_shared<QImage>(frame->GetImage()->copy()));
1442 if (!frame->has_image_data) {
1447 f->AddAudioSilence(samples_in_frame);
1453 std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1454 if (last_final_video_frame && last_final_video_frame->has_image_data
1455 && last_final_video_frame->number <= requested_frame) {
1456 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
1457 }
else if (last_video_frame && last_video_frame->has_image_data
1458 && last_video_frame->number <= requested_frame) {
1459 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
1463 f->AddAudioSilence(samples_in_frame);
1471 int FFmpegReader::GetNextPacket() {
1472 int found_packet = 0;
1473 AVPacket *next_packet;
1474 next_packet =
new AVPacket();
1475 found_packet = av_read_frame(pFormatCtx, next_packet);
1479 RemoveAVPacket(packet);
1482 if (found_packet >= 0) {
1484 packet = next_packet;
1487 if (packet->stream_index == videoStream) {
1489 }
else if (packet->stream_index == audioStream) {
1498 return found_packet;
1502 bool FFmpegReader::GetAVFrame() {
1503 int frameFinished = 0;
1504 auto note_hw_decode_failure = [&](
int err,
const char* stage) {
1506 if (!
hw_de_on || !hw_de_supported || force_sw_decode) {
1509 if (err == AVERROR_INVALIDDATA && packet_status.
video_decoded == 0) {
1510 hw_decode_error_count++;
1512 std::string(
"FFmpegReader::GetAVFrame (hardware decode failure candidate during ") + stage +
")",
1513 "error_count", hw_decode_error_count,
1515 if (hw_decode_error_count >= 3) {
1516 hw_decode_failed =
true;
1529 int send_packet_err = 0;
1530 int64_t send_packet_pts = 0;
1531 if ((packet && packet->stream_index == videoStream) || !packet) {
1532 send_packet_err = avcodec_send_packet(pCodecCtx, packet);
1534 if (packet && send_packet_err >= 0) {
1535 send_packet_pts = GetPacketPTS();
1536 hold_packet =
false;
1545 #endif // USE_HW_ACCEL
1546 if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1547 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: Not sent [" + av_err2string(send_packet_err) +
"])",
"send_packet_err", send_packet_err,
"send_packet_pts", send_packet_pts);
1548 note_hw_decode_failure(send_packet_err,
"send_packet");
1549 if (send_packet_err == AVERROR(EAGAIN)) {
1551 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(EAGAIN): user must read output with avcodec_receive_frame()",
"send_packet_pts", send_packet_pts);
1553 if (send_packet_err == AVERROR(EINVAL)) {
1554 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(EINVAL): codec not opened, it is an encoder, or requires flush",
"send_packet_pts", send_packet_pts);
1556 if (send_packet_err == AVERROR(ENOMEM)) {
1557 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(ENOMEM): failed to add packet to internal queue, or legitimate decoding errors",
"send_packet_pts", send_packet_pts);
1564 int receive_frame_err = 0;
1565 AVFrame *decoded_frame = next_frame;
1566 AVFrame *next_frame2;
1572 #endif // USE_HW_ACCEL
1574 next_frame2 = next_frame;
1577 while (receive_frame_err >= 0) {
1578 receive_frame_err = avcodec_receive_frame(pCodecCtx, next_frame2);
1580 if (receive_frame_err != 0) {
1581 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (receive frame: frame not ready yet from decoder [\" + av_err2string(receive_frame_err) + \"])",
"receive_frame_err", receive_frame_err,
"send_packet_pts", send_packet_pts);
1582 note_hw_decode_failure(receive_frame_err,
"receive_frame");
1584 if (receive_frame_err == AVERROR_EOF) {
1586 "FFmpegReader::GetAVFrame (receive frame: AVERROR_EOF: EOF detected from decoder, flushing buffers)",
"send_packet_pts", send_packet_pts);
1587 avcodec_flush_buffers(pCodecCtx);
1590 if (receive_frame_err == AVERROR(EINVAL)) {
1592 "FFmpegReader::GetAVFrame (receive frame: AVERROR(EINVAL): invalid frame received, flushing buffers)",
"send_packet_pts", send_packet_pts);
1593 avcodec_flush_buffers(pCodecCtx);
1595 if (receive_frame_err == AVERROR(EAGAIN)) {
1597 "FFmpegReader::GetAVFrame (receive frame: AVERROR(EAGAIN): output is not available in this state - user must try to send new input)",
"send_packet_pts", send_packet_pts);
1599 if (receive_frame_err == AVERROR_INPUT_CHANGED) {
1601 "FFmpegReader::GetAVFrame (receive frame: AVERROR_INPUT_CHANGED: current decoded frame has changed parameters with respect to first decoded frame)",
"send_packet_pts", send_packet_pts);
1612 if (next_frame2->format == hw_de_av_pix_fmt) {
1613 if ((err = av_hwframe_transfer_data(next_frame, next_frame2, 0)) < 0) {
1615 "FFmpegReader::GetAVFrame (Failed to transfer data to output frame)",
1618 note_hw_decode_failure(AVERROR_INVALIDDATA,
"hwframe_transfer");
1621 if ((err = av_frame_copy_props(next_frame, next_frame2)) < 0) {
1623 "FFmpegReader::GetAVFrame (Failed to copy props to output frame)",
1626 note_hw_decode_failure(AVERROR_INVALIDDATA,
"hwframe_copy_props");
1629 if (next_frame->format == AV_PIX_FMT_NONE) {
1630 next_frame->format = pCodecCtx->sw_pix_fmt;
1632 if (next_frame->width <= 0) {
1633 next_frame->width = next_frame2->width;
1635 if (next_frame->height <= 0) {
1636 next_frame->height = next_frame2->height;
1638 decoded_frame = next_frame;
1641 decoded_frame = next_frame2;
1645 #endif // USE_HW_ACCEL
1647 decoded_frame = next_frame2;
1650 if (!decoded_frame->data[0]) {
1652 "FFmpegReader::GetAVFrame (Decoded frame missing image data)",
1653 "format", decoded_frame->format,
1654 "width", decoded_frame->width,
1655 "height", decoded_frame->height);
1656 note_hw_decode_failure(AVERROR_INVALIDDATA,
"decoded_frame_empty");
1663 hw_decode_error_count = 0;
1665 if (
hw_de_on && hw_de_supported && !force_sw_decode) {
1666 hw_decode_succeeded =
true;
1672 AVPixelFormat decoded_pix_fmt = (AVPixelFormat)(decoded_frame->format);
1673 if (decoded_pix_fmt == AV_PIX_FMT_NONE)
1674 decoded_pix_fmt = (AVPixelFormat)(pStream->codecpar->format);
1678 av_image_copy(pFrame->data, pFrame->linesize, (
const uint8_t**)decoded_frame->data, decoded_frame->linesize,
1680 pFrame->format = decoded_pix_fmt;
1683 pFrame->color_range = decoded_frame->color_range;
1684 pFrame->colorspace = decoded_frame->colorspace;
1685 pFrame->color_primaries = decoded_frame->color_primaries;
1686 pFrame->color_trc = decoded_frame->color_trc;
1687 pFrame->chroma_location = decoded_frame->chroma_location;
1693 if (decoded_frame->pts != AV_NOPTS_VALUE) {
1696 video_pts = decoded_frame->pts;
1697 }
else if (decoded_frame->pkt_dts != AV_NOPTS_VALUE) {
1699 video_pts = decoded_frame->pkt_dts;
1703 "FFmpegReader::GetAVFrame (Successful frame received)",
"video_pts", video_pts,
"send_packet_pts", send_packet_pts);
1709 if (
hw_de_on && hw_de_supported && next_frame2 != next_frame) {
1712 #endif // USE_HW_ACCEL
1714 avcodec_decode_video2(pCodecCtx, next_frame, &frameFinished, packet);
1720 if (frameFinished) {
1724 av_picture_copy((AVPicture *) pFrame, (AVPicture *) next_frame, pCodecCtx->pix_fmt,
info.
width,
1727 #endif // IS_FFMPEG_3_2
1733 return frameFinished;
1736 bool FFmpegReader::ReopenWithoutHardwareDecode(int64_t requested_frame) {
1738 if (!hw_decode_failed || force_sw_decode) {
1743 "FFmpegReader::ReopenWithoutHardwareDecode (falling back to software decode)",
1744 "requested_frame", requested_frame,
1745 "video_packets_read", packet_status.
video_read,
1747 "hw_decode_error_count", hw_decode_error_count);
1749 force_sw_decode =
true;
1750 hw_decode_failed =
false;
1751 hw_decode_error_count = 0;
1755 Seek(requested_frame);
1758 (void) requested_frame;
1765 return hw_decode_succeeded;
1772 bool FFmpegReader::CheckSeek() {
1775 const int64_t kSeekRetryMax = 5;
1776 const int kSeekStagnantMax = 2;
1780 if ((is_video_seek && !seek_video_frame_found) || (!is_video_seek && !seek_audio_frame_found))
1788 int64_t max_seeked_frame = std::max(seek_audio_frame_found, seek_video_frame_found);
1790 if (max_seeked_frame == last_seek_max_frame) {
1791 seek_stagnant_count++;
1793 last_seek_max_frame = max_seeked_frame;
1794 seek_stagnant_count = 0;
1798 if (max_seeked_frame >= seeking_frame) {
1801 "is_video_seek", is_video_seek,
1802 "max_seeked_frame", max_seeked_frame,
1803 "seeking_frame", seeking_frame,
1804 "seeking_pts", seeking_pts,
1805 "seek_video_frame_found", seek_video_frame_found,
1806 "seek_audio_frame_found", seek_audio_frame_found);
1809 if (seek_count < kSeekRetryMax) {
1810 Seek(seeking_frame - (10 * seek_count * seek_count));
1811 }
else if (seek_stagnant_count >= kSeekStagnantMax) {
1813 Seek(seeking_frame - (10 * kSeekRetryMax * kSeekRetryMax));
1816 Seek(seeking_frame - (10 * seek_count * seek_count));
1821 "is_video_seek", is_video_seek,
1822 "packet->pts", GetPacketPTS(),
1823 "seeking_pts", seeking_pts,
1824 "seeking_frame", seeking_frame,
1825 "seek_video_frame_found", seek_video_frame_found,
1826 "seek_audio_frame_found", seek_audio_frame_found);
1840 void FFmpegReader::ProcessVideoPacket(int64_t requested_frame) {
1843 int frame_finished = GetAVFrame();
1846 if (!frame_finished) {
1849 RemoveAVFrame(pFrame);
1855 int64_t current_frame = ConvertVideoPTStoFrame(video_pts);
1858 if (!seek_video_frame_found && is_seeking)
1859 seek_video_frame_found = current_frame;
1865 working_cache.
Add(CreateFrame(requested_frame));
1871 AVPixelFormat decoded_pix_fmt = (pFrame && pFrame->format != AV_PIX_FMT_NONE)
1872 ?
static_cast<AVPixelFormat
>(pFrame->format)
1874 bool src_full_range = (pFrame && pFrame->color_range == AVCOL_RANGE_JPEG);
1875 AVPixelFormat src_pix_fmt = NormalizeDeprecatedPixFmt(decoded_pix_fmt, src_full_range);
1876 int src_width = (pFrame && pFrame->width > 0) ? pFrame->width :
info.
width;
1877 int src_height = (pFrame && pFrame->height > 0) ? pFrame->height :
info.
height;
1878 int height = src_height;
1879 int width = src_width;
1881 AVFrame *pFrameRGB = pFrameRGB_cached;
1884 if (pFrameRGB ==
nullptr)
1886 pFrameRGB_cached = pFrameRGB;
1889 uint8_t *buffer =
nullptr;
1910 max_width = std::max(
float(max_width), max_width * max_scale_x);
1911 max_height = std::max(
float(max_height), max_height * max_scale_y);
1917 QSize width_size(max_width * max_scale_x,
1920 max_height * max_scale_y);
1922 if (width_size.width() >= max_width && width_size.height() >= max_height) {
1923 max_width = std::max(max_width, width_size.width());
1924 max_height = std::max(max_height, width_size.height());
1926 max_width = std::max(max_width, height_size.width());
1927 max_height = std::max(max_height, height_size.height());
1934 float preview_ratio = 1.0;
1941 max_width =
info.
width * max_scale_x * preview_ratio;
1942 max_height =
info.
height * max_scale_y * preview_ratio;
1950 QSize bounded_size(max_width, max_height);
1952 if (bounded_size.width() > max_decode_size.width() ||
1953 bounded_size.height() > max_decode_size.height()) {
1954 bounded_size.scale(max_decode_size, Qt::KeepAspectRatio);
1955 max_width = bounded_size.width();
1956 max_height = bounded_size.height();
1961 int original_height = src_height;
1962 if (max_width != 0 && max_height != 0 && max_width < width && max_height < height) {
1964 float ratio = float(width) / float(height);
1965 int possible_width = round(max_height * ratio);
1966 int possible_height = round(max_width / ratio);
1968 if (possible_width <= max_width) {
1970 width = possible_width;
1971 height = max_height;
1975 height = possible_height;
1980 const int bytes_per_pixel = 4;
1981 int raw_buffer_size = (width * height * bytes_per_pixel) + 128;
1984 constexpr
size_t ALIGNMENT = 32;
1985 int buffer_size = ((raw_buffer_size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT;
1986 buffer = (
unsigned char*) aligned_malloc(buffer_size, ALIGNMENT);
1991 int scale_mode = SWS_FAST_BILINEAR;
1993 scale_mode = SWS_BICUBIC;
1995 img_convert_ctx = sws_getCachedContext(img_convert_ctx, src_width, src_height, src_pix_fmt, width, height,
PIX_FMT_RGBA, scale_mode, NULL, NULL, NULL);
1996 if (!img_convert_ctx)
1998 const int *src_coeff = sws_getCoefficients(SWS_CS_DEFAULT);
1999 const int *dst_coeff = sws_getCoefficients(SWS_CS_DEFAULT);
2000 const int dst_full_range = 1;
2001 sws_setColorspaceDetails(img_convert_ctx, src_coeff, src_full_range ? 1 : 0,
2002 dst_coeff, dst_full_range, 0, 1 << 16, 1 << 16);
2004 if (!pFrame || !pFrame->data[0] || pFrame->linesize[0] <= 0) {
2006 if (
hw_de_on && hw_de_supported && !force_sw_decode) {
2007 hw_decode_failed =
true;
2009 "FFmpegReader::ProcessVideoPacket (Invalid source frame; forcing software fallback)",
2010 "requested_frame", requested_frame,
2011 "current_frame", current_frame,
2012 "src_pix_fmt", src_pix_fmt,
2013 "src_width", src_width,
2014 "src_height", src_height);
2018 RemoveAVFrame(pFrame);
2025 const int scaled_lines = sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0,
2026 original_height, pFrameRGB->data, pFrameRGB->linesize);
2027 if (scaled_lines <= 0) {
2029 if (
hw_de_on && hw_de_supported && !force_sw_decode) {
2030 hw_decode_failed =
true;
2032 "FFmpegReader::ProcessVideoPacket (sws_scale failed; forcing software fallback)",
2033 "requested_frame", requested_frame,
2034 "current_frame", current_frame,
2035 "scaled_lines", scaled_lines,
2036 "src_pix_fmt", src_pix_fmt,
2037 "src_width", src_width,
2038 "src_height", src_height);
2043 RemoveAVFrame(pFrame);
2049 std::shared_ptr<Frame> f = CreateFrame(current_frame);
2052 if (!ffmpeg_has_alpha(src_pix_fmt)) {
2054 f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888_Premultiplied, buffer);
2057 f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888, buffer);
2061 working_cache.
Add(f);
2064 last_video_frame = f;
2070 RemoveAVFrame(pFrame);
2076 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::ProcessVideoPacket (After)",
"requested_frame", requested_frame,
"current_frame", current_frame,
"f->number", f->number,
"video_pts_seconds", video_pts_seconds);
2080 void FFmpegReader::ProcessAudioPacket(int64_t requested_frame) {
2083 if (packet && packet->pts != AV_NOPTS_VALUE) {
2085 location = GetAudioPTSLocation(packet->pts);
2088 if (!seek_audio_frame_found && is_seeking)
2089 seek_audio_frame_found = location.
frame;
2096 working_cache.
Add(CreateFrame(requested_frame));
2100 "requested_frame", requested_frame,
2101 "target_frame", location.
frame,
2105 int frame_finished = 0;
2109 int packet_samples = 0;
2113 int send_packet_err = avcodec_send_packet(aCodecCtx, packet);
2114 if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
2118 int receive_frame_err = avcodec_receive_frame(aCodecCtx, audio_frame);
2119 if (receive_frame_err >= 0) {
2122 if (receive_frame_err == AVERROR_EOF) {
2126 if (receive_frame_err == AVERROR(EINVAL) || receive_frame_err == AVERROR_EOF) {
2128 avcodec_flush_buffers(aCodecCtx);
2130 if (receive_frame_err != 0) {
2135 int used = avcodec_decode_audio4(aCodecCtx, audio_frame, &frame_finished, packet);
2138 if (frame_finished) {
2144 audio_pts = audio_frame->pts;
2147 location = GetAudioPTSLocation(audio_pts);
2150 int plane_size = -1;
2156 data_size = av_samples_get_buffer_size(&plane_size, nb_channels,
2160 packet_samples = audio_frame->nb_samples * nb_channels;
2169 int pts_remaining_samples = packet_samples /
info.
channels;
2172 if (pts_remaining_samples == 0) {
2174 "packet_samples", packet_samples,
2176 "pts_remaining_samples", pts_remaining_samples);
2180 while (pts_remaining_samples) {
2185 int samples = samples_per_frame - previous_packet_location.
sample_start;
2186 if (samples > pts_remaining_samples)
2187 samples = pts_remaining_samples;
2190 pts_remaining_samples -= samples;
2192 if (pts_remaining_samples > 0) {
2194 previous_packet_location.
frame++;
2203 "packet_samples", packet_samples,
2211 audio_converted->nb_samples = audio_frame->nb_samples;
2212 av_samples_alloc(audio_converted->data, audio_converted->linesize,
info.
channels, audio_frame->nb_samples, AV_SAMPLE_FMT_FLTP, 0);
2219 AVChannelLayout input_layout = ffmpeg_get_valid_channel_layout(
2221 AVChannelLayout output_layout = ffmpeg_get_valid_channel_layout(
2223 int in_layout_err = av_opt_set_chlayout(avr,
"in_chlayout", &input_layout, 0);
2224 int out_layout_err = av_opt_set_chlayout(avr,
"out_chlayout", &output_layout, 0);
2232 av_opt_set_int(avr,
"out_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
2237 av_channel_layout_uninit(&input_layout);
2238 av_channel_layout_uninit(&output_layout);
2239 if (in_layout_err < 0 || out_layout_err < 0 || swr_init_err < 0) {
2241 throw InvalidChannels(
"Could not initialize FFmpeg audio channel layout or resampler.",
path);
2244 if (swr_init_err < 0) {
2254 audio_converted->data,
2255 audio_converted->linesize[0],
2256 audio_converted->nb_samples,
2258 audio_frame->linesize[0],
2259 audio_frame->nb_samples);
2262 int64_t starting_frame_number = -1;
2263 for (
int channel_filter = 0; channel_filter <
info.
channels; channel_filter++) {
2265 starting_frame_number = location.
frame;
2266 int channel_buffer_size = nb_samples;
2267 auto *channel_buffer = (
float *) (audio_converted->data[channel_filter]);
2271 int remaining_samples = channel_buffer_size;
2272 while (remaining_samples > 0) {
2277 int samples = std::fmin(samples_per_frame - start, remaining_samples);
2280 std::shared_ptr<Frame> f = CreateFrame(starting_frame_number);
2283 f->AddAudio(
true, channel_filter, start, channel_buffer, samples, 1.0f);
2287 "frame", starting_frame_number,
2290 "channel", channel_filter,
2291 "samples_per_frame", samples_per_frame);
2294 working_cache.
Add(f);
2297 remaining_samples -= samples;
2300 if (remaining_samples > 0)
2301 channel_buffer += samples;
2304 starting_frame_number++;
2312 av_free(audio_converted->data[0]);
2321 "requested_frame", requested_frame,
2322 "starting_frame", location.
frame,
2323 "end_frame", starting_frame_number - 1,
2324 "audio_pts_seconds", audio_pts_seconds);
2330 void FFmpegReader::Seek(int64_t requested_frame) {
2332 if (requested_frame < 1)
2333 requested_frame = 1;
2336 if (requested_frame > largest_frame_processed && packet_status.
end_of_file) {
2343 "requested_frame", requested_frame,
2344 "seek_count", seek_count,
2345 "last_frame", last_frame);
2348 working_cache.
Clear();
2352 video_pts_seconds = NO_PTS_OFFSET;
2354 audio_pts_seconds = NO_PTS_OFFSET;
2355 hold_packet =
false;
2357 current_video_frame = 0;
2358 largest_frame_processed = 0;
2359 last_final_video_frame.reset();
2364 packet_status.
reset(
false);
2370 int buffer_amount = 12;
2371 if (requested_frame - buffer_amount < 20) {
2385 if (seek_count == 1) {
2388 seeking_pts = ConvertFrameToVideoPTS(1);
2390 seek_audio_frame_found = 0;
2391 seek_video_frame_found = 0;
2395 bool seek_worked =
false;
2396 int64_t seek_target = 0;
2400 seek_target = ConvertFrameToVideoPTS(requested_frame - buffer_amount);
2405 is_video_seek =
true;
2412 seek_target = ConvertFrameToAudioPTS(requested_frame - buffer_amount);
2417 is_video_seek =
false;
2426 avcodec_flush_buffers(aCodecCtx);
2430 avcodec_flush_buffers(pCodecCtx);
2433 previous_packet_location.
frame = -1;
2438 if (seek_count == 1) {
2440 seeking_pts = seek_target;
2441 seeking_frame = requested_frame;
2443 seek_audio_frame_found = 0;
2444 seek_video_frame_found = 0;
2472 int64_t FFmpegReader::GetPacketPTS() {
2474 int64_t current_pts = packet->pts;
2475 if (current_pts == AV_NOPTS_VALUE && packet->dts != AV_NOPTS_VALUE)
2476 current_pts = packet->dts;
2482 return AV_NOPTS_VALUE;
2487 void FFmpegReader::UpdatePTSOffset() {
2488 if (pts_offset_seconds != NO_PTS_OFFSET) {
2492 pts_offset_seconds = 0.0;
2493 double video_pts_offset_seconds = 0.0;
2494 double audio_pts_offset_seconds = 0.0;
2496 bool has_video_pts =
false;
2499 has_video_pts =
true;
2501 bool has_audio_pts =
false;
2504 has_audio_pts =
true;
2508 while (!has_video_pts || !has_audio_pts) {
2510 if (GetNextPacket() < 0)
2515 int64_t pts = GetPacketPTS();
2518 if (!has_video_pts && packet->stream_index == videoStream) {
2524 if (std::abs(video_pts_offset_seconds) <= 10.0) {
2525 has_video_pts =
true;
2528 else if (!has_audio_pts && packet->stream_index == audioStream) {
2534 if (std::abs(audio_pts_offset_seconds) <= 10.0) {
2535 has_audio_pts =
true;
2545 pts_offset_seconds = video_pts_offset_seconds;
2547 pts_offset_seconds = audio_pts_offset_seconds;
2548 }
else if (has_video_pts && has_audio_pts) {
2550 pts_offset_seconds = video_pts_offset_seconds;
2555 int64_t FFmpegReader::ConvertVideoPTStoFrame(int64_t pts) {
2557 int64_t previous_video_frame = current_video_frame;
2559 const double video_timebase_value =
2565 double video_seconds = (double(pts) * video_timebase_value) + pts_offset_seconds;
2568 int64_t frame = round(video_seconds * fps_value) + 1;
2571 if (current_video_frame == 0)
2572 current_video_frame = frame;
2576 if (frame == previous_video_frame) {
2581 current_video_frame++;
2590 int64_t FFmpegReader::ConvertFrameToVideoPTS(int64_t frame_number) {
2592 const double video_timebase_value =
2598 double seconds = (double(frame_number - 1) / fps_value) + pts_offset_seconds;
2601 int64_t video_pts = round(seconds / video_timebase_value);
2608 int64_t FFmpegReader::ConvertFrameToAudioPTS(int64_t frame_number) {
2610 const double audio_timebase_value =
2616 double seconds = (double(frame_number - 1) / fps_value) + pts_offset_seconds;
2619 int64_t audio_pts = round(seconds / audio_timebase_value);
2626 AudioLocation FFmpegReader::GetAudioPTSLocation(int64_t pts) {
2627 const double audio_timebase_value =
2634 double audio_seconds = (double(pts) * audio_timebase_value) + pts_offset_seconds;
2637 double frame = (audio_seconds * fps_value) + 1;
2640 int64_t whole_frame = int64_t(frame);
2643 double sample_start_percentage = frame - double(whole_frame);
2649 int sample_start = round(
double(samples_per_frame) * sample_start_percentage);
2652 if (whole_frame < 1)
2654 if (sample_start < 0)
2661 if (previous_packet_location.
frame != -1) {
2662 if (location.
is_near(previous_packet_location, samples_per_frame, samples_per_frame)) {
2663 int64_t orig_frame = location.
frame;
2668 location.
frame = previous_packet_location.
frame;
2671 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);
2680 previous_packet_location = location;
2687 std::shared_ptr<Frame> FFmpegReader::CreateFrame(int64_t requested_frame) {
2689 std::shared_ptr<Frame> output = working_cache.
GetFrame(requested_frame);
2693 output = working_cache.
GetFrame(requested_frame);
2694 if(output)
return output;
2702 working_cache.
Add(output);
2705 if (requested_frame > largest_frame_processed)
2706 largest_frame_processed = requested_frame;
2713 bool FFmpegReader::IsPartialFrame(int64_t requested_frame) {
2716 bool seek_trash =
false;
2717 int64_t max_seeked_frame = seek_audio_frame_found;
2718 if (seek_video_frame_found > max_seeked_frame) {
2719 max_seeked_frame = seek_video_frame_found;
2721 if ((
info.
has_audio && seek_audio_frame_found && max_seeked_frame >= requested_frame) ||
2722 (
info.
has_video && seek_video_frame_found && max_seeked_frame >= requested_frame)) {
2730 void FFmpegReader::CheckWorkingFrames(int64_t requested_frame) {
2733 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
2736 std::vector<std::shared_ptr<openshot::Frame>> working_frames = working_cache.
GetFrames();
2737 std::vector<std::shared_ptr<openshot::Frame>>::iterator working_itr;
2740 for(working_itr = working_frames.begin(); working_itr != working_frames.end(); ++working_itr)
2743 std::shared_ptr<Frame> f = *working_itr;
2746 if (!f || f->number > requested_frame) {
2752 double frame_pts_seconds = (double(f->number - 1) /
info.
fps.
ToDouble()) + pts_offset_seconds;
2753 double recent_pts_seconds = std::max(video_pts_seconds, audio_pts_seconds);
2756 bool is_video_ready =
false;
2757 bool is_audio_ready =
false;
2758 double recent_pts_diff = recent_pts_seconds - frame_pts_seconds;
2759 if ((frame_pts_seconds <= video_pts_seconds)
2760 || (recent_pts_diff > 1.5)
2764 is_video_ready =
true;
2766 "frame_number", f->number,
2767 "frame_pts_seconds", frame_pts_seconds,
2768 "video_pts_seconds", video_pts_seconds,
2769 "recent_pts_diff", recent_pts_diff);
2775 if (previous_frame_instance && previous_frame_instance->has_image_data) {
2776 f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2780 if (!f->has_image_data
2781 && last_final_video_frame
2782 && last_final_video_frame->has_image_data
2783 && last_final_video_frame->number <= f->number) {
2784 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2788 if (!f->has_image_data
2790 && last_video_frame->has_image_data
2791 && last_video_frame->number <= f->number) {
2792 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2796 if (!f->has_image_data) {
2798 "FFmpegReader::CheckWorkingFrames (no previous image found; using black frame)",
2799 "frame_number", f->number);
2800 f->AddColor(
"#000000");
2805 double audio_pts_diff = audio_pts_seconds - frame_pts_seconds;
2806 if ((frame_pts_seconds < audio_pts_seconds && audio_pts_diff > 1.0)
2807 || (recent_pts_diff > 1.5)
2812 is_audio_ready =
true;
2814 "frame_number", f->number,
2815 "frame_pts_seconds", frame_pts_seconds,
2816 "audio_pts_seconds", audio_pts_seconds,
2817 "audio_pts_diff", audio_pts_diff,
2818 "recent_pts_diff", recent_pts_diff);
2820 bool is_seek_trash = IsPartialFrame(f->number);
2828 "frame_number", f->number,
2829 "is_video_ready", is_video_ready,
2830 "is_audio_ready", is_audio_ready,
2837 && !packet_status.
end_of_file && !is_seek_trash) {
2842 if (previous_frame_instance && previous_frame_instance->has_image_data) {
2843 f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2845 if (!f->has_image_data
2846 && last_final_video_frame
2847 && last_final_video_frame->has_image_data
2848 && last_final_video_frame->number <= f->number) {
2849 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2851 if (!f->has_image_data
2853 && last_video_frame->has_image_data
2854 && last_video_frame->number <= f->number) {
2855 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2862 if (!f->has_image_data && is_video_ready && is_audio_ready) {
2864 if (previous_frame_instance && previous_frame_instance->has_image_data) {
2865 f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2867 if (!f->has_image_data
2868 && last_final_video_frame
2869 && last_final_video_frame->has_image_data
2870 && last_final_video_frame->number <= f->number) {
2871 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2873 if (!f->has_image_data
2875 && last_video_frame->has_image_data
2876 && last_video_frame->number <= f->number) {
2877 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2883 if (!f->has_image_data) {
2887 if ((!packet_status.
end_of_file && is_video_ready && is_audio_ready) || packet_status.
end_of_file || is_seek_trash) {
2890 "requested_frame", requested_frame,
2891 "f->number", f->number,
2892 "is_seek_trash", is_seek_trash,
2893 "Working Cache Count", working_cache.
Count(),
2897 if (!is_seek_trash) {
2900 if (f->has_image_data) {
2901 last_final_video_frame = f;
2905 working_cache.
Remove(f->number);
2908 last_frame = f->number;
2911 working_cache.
Remove(f->number);
2918 working_frames.clear();
2919 working_frames.shrink_to_fit();
2923 void FFmpegReader::CheckFPS() {
2931 int frames_per_second[3] = {0,0,0};
2932 int max_fps_index =
sizeof(frames_per_second) /
sizeof(frames_per_second[0]);
2935 int all_frames_detected = 0;
2936 int starting_frames_detected = 0;
2941 if (GetNextPacket() < 0)
2946 if (packet->stream_index == videoStream) {
2949 fps_index = int(video_seconds);
2952 if (fps_index >= 0 && fps_index < max_fps_index) {
2954 starting_frames_detected++;
2955 frames_per_second[fps_index]++;
2959 all_frames_detected++;
2964 float avg_fps = 30.0;
2965 if (starting_frames_detected > 0 && fps_index > 0) {
2966 avg_fps = float(starting_frames_detected) / std::min(fps_index, max_fps_index);
2970 if (avg_fps < 8.0) {
2979 if (all_frames_detected > 0) {
2993 void FFmpegReader::RemoveAVFrame(AVFrame *remove_frame) {
2997 av_freep(&remove_frame->data[0]);
3005 void FFmpegReader::RemoveAVPacket(AVPacket *remove_packet) {
3010 delete remove_packet;
3025 root[
"type"] =
"FFmpegReader";
3026 root[
"path"] =
path;
3027 switch (duration_strategy) {
3029 root[
"duration_strategy"] =
"VideoPreferred";
3032 root[
"duration_strategy"] =
"AudioPreferred";
3036 root[
"duration_strategy"] =
"LongestStream";
3053 catch (
const std::exception& e) {
3055 throw InvalidJSON(
"JSON is invalid (missing keys or invalid data types)");
3066 if (!root[
"path"].isNull())
3067 path = root[
"path"].asString();
3068 if (!root[
"duration_strategy"].isNull()) {
3069 const std::string strategy = root[
"duration_strategy"].asString();
3070 if (strategy ==
"VideoPreferred") {
3072 }
else if (strategy ==
"AudioPreferred") {