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
80 : last_frame(0), is_seeking(0), seeking_pts(0), seeking_frame(0), seek_count(0), NO_PTS_OFFSET(-99999),
81 path(
path), is_video_seek(true), check_interlace(false), check_fps(false), enable_seek(true), is_open(false),
82 seek_audio_frame_found(0), seek_video_frame_found(0),
83 last_seek_max_frame(-1), seek_stagnant_count(0),
84 is_duration_known(false), largest_frame_processed(0),
85 current_video_frame(0), packet(NULL), duration_strategy(duration_strategy),
86 audio_pts(0), video_pts(0), pFormatCtx(NULL), videoStream(-1), audioStream(-1), pCodecCtx(NULL), aCodecCtx(NULL),
87 pStream(NULL), aStream(NULL), pFrame(NULL), previous_packet_location{-1,0},
95 pts_offset_seconds = NO_PTS_OFFSET;
96 video_pts_seconds = NO_PTS_OFFSET;
97 audio_pts_seconds = NO_PTS_OFFSET;
102 working_cache.SetMaxBytesFromInfo(init_working_cache_frames, info.width, info.height, info.sample_rate, info.channels);
103 final_cache.SetMaxBytesFromInfo(init_final_cache_frames, info.width, info.height, info.sample_rate, info.channels);
106 if (inspect_reader) {
128 if (abs(diff) <= amount)
139 static enum AVPixelFormat get_hw_dec_format(AVCodecContext *ctx,
const enum AVPixelFormat *pix_fmts)
141 const enum AVPixelFormat *p;
146 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
148 #if defined(__linux__)
150 case AV_PIX_FMT_VAAPI:
157 case AV_PIX_FMT_VDPAU:
167 case AV_PIX_FMT_DXVA2_VLD:
174 case AV_PIX_FMT_D3D11:
182 #if defined(__APPLE__)
184 case AV_PIX_FMT_VIDEOTOOLBOX:
193 case AV_PIX_FMT_CUDA:
213 return AV_PIX_FMT_NONE;
216 int FFmpegReader::IsHardwareDecodeSupported(
int codecid)
220 case AV_CODEC_ID_H264:
221 case AV_CODEC_ID_MPEG2VIDEO:
222 case AV_CODEC_ID_VC1:
223 case AV_CODEC_ID_WMV1:
224 case AV_CODEC_ID_WMV2:
225 case AV_CODEC_ID_WMV3:
234 #endif // USE_HW_ACCEL
240 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
250 if (avformat_open_input(&pFormatCtx,
path.c_str(), NULL, NULL) != 0)
254 if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
261 packet_status.
reset(
true);
264 for (
unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
266 if (
AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_VIDEO && videoStream < 0) {
273 if (
AV_GET_CODEC_TYPE(pFormatCtx->streams[i]) == AVMEDIA_TYPE_AUDIO && audioStream < 0) {
280 if (videoStream == -1 && audioStream == -1)
284 if (videoStream != -1) {
289 pStream = pFormatCtx->streams[videoStream];
295 const AVCodec *pCodec = avcodec_find_decoder(codecId);
296 AVDictionary *
opts = NULL;
297 int retry_decode_open = 2;
302 if (
hw_de_on && (retry_decode_open==2)) {
304 hw_de_supported = IsHardwareDecodeSupported(pCodecCtx->codec_id);
307 retry_decode_open = 0;
312 if (pCodec == NULL) {
313 throw InvalidCodec(
"A valid video codec could not be found for this file.",
path);
317 av_dict_set(&
opts,
"strict",
"experimental", 0);
321 int i_decoder_hw = 0;
323 char *adapter_ptr = NULL;
329 pCodecCtx->get_format = get_hw_dec_format;
331 if (adapter_num < 3 && adapter_num >=0) {
332 #if defined(__linux__)
333 snprintf(adapter,
sizeof(adapter),
"/dev/dri/renderD%d", adapter_num+128);
334 adapter_ptr = adapter;
336 switch (i_decoder_hw) {
338 hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
341 hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
344 hw_de_av_device_type = AV_HWDEVICE_TYPE_VDPAU;
347 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
350 hw_de_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
354 #elif defined(_WIN32)
357 switch (i_decoder_hw) {
359 hw_de_av_device_type = AV_HWDEVICE_TYPE_CUDA;
362 hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
365 hw_de_av_device_type = AV_HWDEVICE_TYPE_D3D11VA;
368 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
371 hw_de_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
374 #elif defined(__APPLE__)
377 switch (i_decoder_hw) {
379 hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
382 hw_de_av_device_type = AV_HWDEVICE_TYPE_QSV;
385 hw_de_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
395 #if defined(__linux__)
396 if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
397 #elif defined(_WIN32)
398 if( adapter_ptr != NULL ) {
399 #elif defined(__APPLE__)
400 if( adapter_ptr != NULL ) {
409 hw_device_ctx = NULL;
411 if (av_hwdevice_ctx_create(&hw_device_ctx, hw_de_av_device_type, adapter_ptr, NULL, 0) >= 0) {
412 const char* hw_name = av_hwdevice_get_type_name(hw_de_av_device_type);
413 std::string hw_msg =
"HW decode active: ";
414 hw_msg += (hw_name ? hw_name :
"unknown");
416 if (!(pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx))) {
452 #endif // USE_HW_ACCEL
459 pCodecCtx->thread_type &= ~FF_THREAD_FRAME;
463 int avcodec_return = avcodec_open2(pCodecCtx, pCodec, &
opts);
464 if (avcodec_return < 0) {
465 std::stringstream avcodec_error_msg;
466 avcodec_error_msg <<
"A video codec was found, but could not be opened. Error: " << av_err2string(avcodec_return);
472 AVHWFramesConstraints *constraints = NULL;
473 void *hwconfig = NULL;
474 hwconfig = av_hwdevice_hwconfig_alloc(hw_device_ctx);
478 ((AVVAAPIHWConfig *)hwconfig)->config_id = ((VAAPIDecodeContext *)(pCodecCtx->priv_data))->va_config;
479 constraints = av_hwdevice_get_hwframe_constraints(hw_device_ctx,hwconfig);
480 #endif // ENABLE_VAAPI
482 if (pCodecCtx->coded_width < constraints->min_width ||
483 pCodecCtx->coded_height < constraints->min_height ||
484 pCodecCtx->coded_width > constraints->max_width ||
485 pCodecCtx->coded_height > constraints->max_height) {
488 retry_decode_open = 1;
491 av_buffer_unref(&hw_device_ctx);
492 hw_device_ctx = NULL;
497 ZmqLogger::Instance()->
AppendDebugMethod(
"\nDecode hardware acceleration is used\n",
"Min width :", constraints->min_width,
"Min Height :", constraints->min_height,
"MaxWidth :", constraints->max_width,
"MaxHeight :", constraints->max_height,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
498 retry_decode_open = 0;
500 av_hwframe_constraints_free(&constraints);
513 if (pCodecCtx->coded_width < 0 ||
514 pCodecCtx->coded_height < 0 ||
515 pCodecCtx->coded_width > max_w ||
516 pCodecCtx->coded_height > max_h ) {
517 ZmqLogger::Instance()->
AppendDebugMethod(
"DIMENSIONS ARE TOO LARGE for hardware acceleration\n",
"Max Width :", max_w,
"Max Height :", max_h,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
519 retry_decode_open = 1;
522 av_buffer_unref(&hw_device_ctx);
523 hw_device_ctx = NULL;
527 ZmqLogger::Instance()->
AppendDebugMethod(
"\nDecode hardware acceleration is used\n",
"Max Width :", max_w,
"Max Height :", max_h,
"Frame width :", pCodecCtx->coded_width,
"Frame height :", pCodecCtx->coded_height);
528 retry_decode_open = 0;
536 retry_decode_open = 0;
537 #endif // USE_HW_ACCEL
538 }
while (retry_decode_open);
547 if (audioStream != -1) {
552 aStream = pFormatCtx->streams[audioStream];
558 const AVCodec *aCodec = avcodec_find_decoder(codecId);
564 if (aCodec == NULL) {
565 throw InvalidCodec(
"A valid audio codec could not be found for this file.",
path);
569 AVDictionary *
opts = NULL;
570 av_dict_set(&
opts,
"strict",
"experimental", 0);
573 if (avcodec_open2(aCodecCtx, aCodec, &
opts) < 0)
574 throw InvalidCodec(
"An audio codec was found, but could not be opened.",
path);
584 AVDictionaryEntry *tag = NULL;
585 while ((tag = av_dict_get(pFormatCtx->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
586 QString str_key = tag->key;
587 QString str_value = tag->value;
588 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
592 for (
unsigned int i = 0; i < pFormatCtx->nb_streams; i++) {
593 AVStream* st = pFormatCtx->streams[i];
594 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
596 for (
int j = 0; j < st->nb_side_data; j++) {
597 AVPacketSideData *sd = &st->side_data[j];
600 if (sd->type == AV_PKT_DATA_DISPLAYMATRIX &&
601 sd->size >= 9 *
sizeof(int32_t) &&
604 double rotation = -av_display_rotation_get(
605 reinterpret_cast<int32_t *
>(sd->data));
606 if (std::isnan(rotation)) rotation = 0;
610 else if (sd->type == AV_PKT_DATA_SPHERICAL) {
615 const AVSphericalMapping* map =
616 reinterpret_cast<const AVSphericalMapping*
>(sd->data);
619 const char* proj_name = av_spherical_projection_name(map->projection);
625 auto to_deg = [](int32_t v){
626 return (
double)v / 65536.0;
628 info.
metadata[
"spherical_yaw"] = std::to_string(to_deg(map->yaw));
629 info.
metadata[
"spherical_pitch"] = std::to_string(to_deg(map->pitch));
630 info.
metadata[
"spherical_roll"] = std::to_string(to_deg(map->roll));
638 previous_packet_location.
frame = -1;
672 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
678 AVPacket *recent_packet = packet;
683 int max_attempts = 128;
688 "attempts", attempts);
700 RemoveAVPacket(recent_packet);
705 if(avcodec_is_open(pCodecCtx)) {
706 avcodec_flush_buffers(pCodecCtx);
712 av_buffer_unref(&hw_device_ctx);
713 hw_device_ctx = NULL;
716 #endif // USE_HW_ACCEL
717 if (img_convert_ctx) {
718 sws_freeContext(img_convert_ctx);
719 img_convert_ctx =
nullptr;
721 if (pFrameRGB_cached) {
728 if(avcodec_is_open(aCodecCtx)) {
729 avcodec_flush_buffers(aCodecCtx);
741 working_cache.
Clear();
744 avformat_close_input(&pFormatCtx);
745 av_freep(&pFormatCtx);
752 largest_frame_processed = 0;
753 seek_audio_frame_found = 0;
754 seek_video_frame_found = 0;
755 current_video_frame = 0;
756 last_video_frame.reset();
757 last_final_video_frame.reset();
761 bool FFmpegReader::HasAlbumArt() {
765 return pFormatCtx && videoStream >= 0 && pFormatCtx->streams[videoStream]
766 && (pFormatCtx->streams[videoStream]->disposition & AV_DISPOSITION_ATTACHED_PIC);
769 double FFmpegReader::PickDurationSeconds()
const {
770 auto has_value = [](
double value) {
return value > 0.0; };
772 switch (duration_strategy) {
774 if (has_value(video_stream_duration_seconds))
775 return video_stream_duration_seconds;
776 if (has_value(audio_stream_duration_seconds))
777 return audio_stream_duration_seconds;
778 if (has_value(format_duration_seconds))
779 return format_duration_seconds;
782 if (has_value(audio_stream_duration_seconds))
783 return audio_stream_duration_seconds;
784 if (has_value(video_stream_duration_seconds))
785 return video_stream_duration_seconds;
786 if (has_value(format_duration_seconds))
787 return format_duration_seconds;
792 double longest = 0.0;
793 if (has_value(video_stream_duration_seconds))
794 longest = std::max(longest, video_stream_duration_seconds);
795 if (has_value(audio_stream_duration_seconds))
796 longest = std::max(longest, audio_stream_duration_seconds);
797 if (has_value(format_duration_seconds))
798 longest = std::max(longest, format_duration_seconds);
799 if (has_value(longest))
805 if (has_value(format_duration_seconds))
806 return format_duration_seconds;
807 if (has_value(inferred_duration_seconds))
808 return inferred_duration_seconds;
813 void FFmpegReader::ApplyDurationStrategy() {
815 const double chosen_seconds = PickDurationSeconds();
817 if (chosen_seconds <= 0.0 || fps_value <= 0.0) {
820 is_duration_known =
false;
824 const int64_t frames =
static_cast<int64_t
>(std::llround(chosen_seconds * fps_value));
828 is_duration_known =
false;
833 info.
duration =
static_cast<float>(
static_cast<double>(frames) / fps_value);
834 is_duration_known =
true;
837 void FFmpegReader::UpdateAudioInfo() {
852 auto record_duration = [](
double &target,
double seconds) {
854 target = std::max(target, seconds);
859 info.
file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
890 if (aStream->duration > 0) {
893 if (pFormatCtx->duration > 0) {
895 record_duration(format_duration_seconds,
static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
925 ApplyDurationStrategy();
928 AVDictionaryEntry *tag = NULL;
929 while ((tag = av_dict_get(aStream->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
930 QString str_key = tag->key;
931 QString str_value = tag->value;
932 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
936 void FFmpegReader::UpdateVideoInfo() {
942 auto record_duration = [](
double &target,
double seconds) {
944 target = std::max(target, seconds);
949 info.
file_size = pFormatCtx->pb ? avio_size(pFormatCtx->pb) : -1;
956 AVRational framerate = av_guess_frame_rate(pFormatCtx, pStream, NULL);
968 if (pStream->sample_aspect_ratio.num != 0) {
991 if (!check_interlace) {
992 check_interlace =
true;
994 switch(field_order) {
995 case AV_FIELD_PROGRESSIVE:
1008 case AV_FIELD_UNKNOWN:
1010 check_interlace =
false;
1025 if (pFormatCtx->duration >= 0) {
1027 record_duration(format_duration_seconds,
static_cast<double>(pFormatCtx->duration) / AV_TIME_BASE);
1037 if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1038 pStream->duration == AV_NOPTS_VALUE && pFormatCtx->duration == AV_NOPTS_VALUE) {
1040 record_duration(video_stream_duration_seconds, 60 * 60 * 1);
1044 if (video_stream_duration_seconds <= 0.0 && format_duration_seconds <= 0.0 &&
1045 pFormatCtx && pFormatCtx->iformat && strcmp(pFormatCtx->iformat->name,
"gif") == 0) {
1046 record_duration(video_stream_duration_seconds, 60 * 60 * 1);
1050 ApplyDurationStrategy();
1053 AVDictionaryEntry *tag = NULL;
1054 while ((tag = av_dict_get(pStream->metadata,
"", tag, AV_DICT_IGNORE_SUFFIX))) {
1055 QString str_key = tag->key;
1056 QString str_value = tag->value;
1057 info.
metadata[str_key.toStdString()] = str_value.trimmed().toStdString();
1062 return this->is_duration_known;
1066 last_seek_max_frame = -1;
1067 seek_stagnant_count = 0;
1070 throw ReaderClosed(
"The FFmpegReader is closed. Call Open() before calling this method.",
path);
1073 if (requested_frame < 1)
1074 requested_frame = 1;
1079 throw InvalidFile(
"Could not detect the duration of the video or audio stream.",
path);
1095 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1109 int64_t diff = requested_frame - last_frame;
1110 if (diff >= 1 && diff <= 20) {
1112 frame = ReadStream(requested_frame);
1117 Seek(requested_frame);
1126 frame = ReadStream(requested_frame);
1134 std::shared_ptr<Frame> FFmpegReader::ReadStream(int64_t requested_frame) {
1136 bool check_seek =
false;
1137 int packet_error = -1;
1138 int64_t no_progress_count = 0;
1139 int64_t prev_packets_read = packet_status.
packets_read();
1142 double prev_video_pts_seconds = video_pts_seconds;
1152 CheckWorkingFrames(requested_frame);
1157 if (is_cache_found) {
1161 if (!hold_packet || !packet) {
1163 packet_error = GetNextPacket();
1164 if (packet_error < 0 && !packet) {
1175 check_seek = CheckSeek();
1187 if ((
info.
has_video && packet && packet->stream_index == videoStream) ||
1191 ProcessVideoPacket(requested_frame);
1194 if ((
info.
has_audio && packet && packet->stream_index == audioStream) ||
1198 ProcessAudioPacket(requested_frame);
1203 if ((!
info.
has_video && packet && packet->stream_index == videoStream) ||
1204 (!
info.
has_audio && packet && packet->stream_index == audioStream)) {
1206 if (packet->stream_index == videoStream) {
1208 }
else if (packet->stream_index == audioStream) {
1214 RemoveAVPacket(packet);
1224 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::ReadStream (force EOF)",
"packets_read", packet_status.
packets_read(),
"packets_decoded", packet_status.
packets_decoded(),
"packets_eof", packet_status.
packets_eof,
"video_eof", packet_status.
video_eof,
"audio_eof", packet_status.
audio_eof,
"end_of_file", packet_status.
end_of_file);
1237 const bool has_progress =
1241 (video_pts_seconds != prev_video_pts_seconds);
1244 no_progress_count = 0;
1246 no_progress_count++;
1247 if (no_progress_count >= 2000
1252 "requested_frame", requested_frame,
1253 "no_progress_count", no_progress_count,
1267 prev_video_pts_seconds = video_pts_seconds;
1275 "largest_frame_processed", largest_frame_processed,
1276 "Working Cache Count", working_cache.
Count());
1285 CheckWorkingFrames(requested_frame);
1301 std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1304 if (!frame->has_image_data) {
1309 frame->AddAudioSilence(samples_in_frame);
1315 std::shared_ptr<Frame> f = CreateFrame(largest_frame_processed);
1316 if (last_final_video_frame && last_final_video_frame->has_image_data
1317 && last_final_video_frame->number <= requested_frame) {
1318 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
1319 }
else if (last_video_frame && last_video_frame->has_image_data
1320 && last_video_frame->number <= requested_frame) {
1321 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
1325 f->AddAudioSilence(samples_in_frame);
1333 int FFmpegReader::GetNextPacket() {
1334 int found_packet = 0;
1335 AVPacket *next_packet;
1336 next_packet =
new AVPacket();
1337 found_packet = av_read_frame(pFormatCtx, next_packet);
1341 RemoveAVPacket(packet);
1344 if (found_packet >= 0) {
1346 packet = next_packet;
1349 if (packet->stream_index == videoStream) {
1351 }
else if (packet->stream_index == audioStream) {
1360 return found_packet;
1364 bool FFmpegReader::GetAVFrame() {
1365 int frameFinished = 0;
1371 int send_packet_err = 0;
1372 int64_t send_packet_pts = 0;
1373 if ((packet && packet->stream_index == videoStream) || !packet) {
1374 send_packet_err = avcodec_send_packet(pCodecCtx, packet);
1376 if (packet && send_packet_err >= 0) {
1377 send_packet_pts = GetPacketPTS();
1378 hold_packet =
false;
1387 #endif // USE_HW_ACCEL
1388 if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1389 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: Not sent [" + av_err2string(send_packet_err) +
"])",
"send_packet_err", send_packet_err,
"send_packet_pts", send_packet_pts);
1390 if (send_packet_err == AVERROR(EAGAIN)) {
1392 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(EAGAIN): user must read output with avcodec_receive_frame()",
"send_packet_pts", send_packet_pts);
1394 if (send_packet_err == AVERROR(EINVAL)) {
1395 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(EINVAL): codec not opened, it is an encoder, or requires flush",
"send_packet_pts", send_packet_pts);
1397 if (send_packet_err == AVERROR(ENOMEM)) {
1398 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (send packet: AVERROR(ENOMEM): failed to add packet to internal queue, or legitimate decoding errors",
"send_packet_pts", send_packet_pts);
1405 int receive_frame_err = 0;
1406 AVFrame *next_frame2;
1412 #endif // USE_HW_ACCEL
1414 next_frame2 = next_frame;
1417 while (receive_frame_err >= 0) {
1418 receive_frame_err = avcodec_receive_frame(pCodecCtx, next_frame2);
1420 if (receive_frame_err != 0) {
1421 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAVFrame (receive frame: frame not ready yet from decoder [\" + av_err2string(receive_frame_err) + \"])",
"receive_frame_err", receive_frame_err,
"send_packet_pts", send_packet_pts);
1423 if (receive_frame_err == AVERROR_EOF) {
1425 "FFmpegReader::GetAVFrame (receive frame: AVERROR_EOF: EOF detected from decoder, flushing buffers)",
"send_packet_pts", send_packet_pts);
1426 avcodec_flush_buffers(pCodecCtx);
1429 if (receive_frame_err == AVERROR(EINVAL)) {
1431 "FFmpegReader::GetAVFrame (receive frame: AVERROR(EINVAL): invalid frame received, flushing buffers)",
"send_packet_pts", send_packet_pts);
1432 avcodec_flush_buffers(pCodecCtx);
1434 if (receive_frame_err == AVERROR(EAGAIN)) {
1436 "FFmpegReader::GetAVFrame (receive frame: AVERROR(EAGAIN): output is not available in this state - user must try to send new input)",
"send_packet_pts", send_packet_pts);
1438 if (receive_frame_err == AVERROR_INPUT_CHANGED) {
1440 "FFmpegReader::GetAVFrame (receive frame: AVERROR_INPUT_CHANGED: current decoded frame has changed parameters with respect to first decoded frame)",
"send_packet_pts", send_packet_pts);
1451 if (next_frame2->format == hw_de_av_pix_fmt) {
1452 next_frame->format = AV_PIX_FMT_YUV420P;
1453 if ((err = av_hwframe_transfer_data(next_frame,next_frame2,0)) < 0) {
1456 if ((err = av_frame_copy_props(next_frame,next_frame2)) < 0) {
1462 #endif // USE_HW_ACCEL
1464 next_frame = next_frame2;
1476 av_image_copy(pFrame->data, pFrame->linesize, (
const uint8_t**)next_frame->data, next_frame->linesize,
1483 if (next_frame->pts != AV_NOPTS_VALUE) {
1486 video_pts = next_frame->pts;
1487 }
else if (next_frame->pkt_dts != AV_NOPTS_VALUE) {
1489 video_pts = next_frame->pkt_dts;
1493 "FFmpegReader::GetAVFrame (Successful frame received)",
"video_pts", video_pts,
"send_packet_pts", send_packet_pts);
1502 #endif // USE_HW_ACCEL
1504 avcodec_decode_video2(pCodecCtx, next_frame, &frameFinished, packet);
1510 if (frameFinished) {
1514 av_picture_copy((AVPicture *) pFrame, (AVPicture *) next_frame, pCodecCtx->pix_fmt,
info.
width,
1517 #endif // IS_FFMPEG_3_2
1523 return frameFinished;
1527 bool FFmpegReader::CheckSeek() {
1530 const int64_t kSeekRetryMax = 5;
1531 const int kSeekStagnantMax = 2;
1535 if ((is_video_seek && !seek_video_frame_found) || (!is_video_seek && !seek_audio_frame_found))
1543 int64_t max_seeked_frame = std::max(seek_audio_frame_found, seek_video_frame_found);
1545 if (max_seeked_frame == last_seek_max_frame) {
1546 seek_stagnant_count++;
1548 last_seek_max_frame = max_seeked_frame;
1549 seek_stagnant_count = 0;
1553 if (max_seeked_frame >= seeking_frame) {
1556 "is_video_seek", is_video_seek,
1557 "max_seeked_frame", max_seeked_frame,
1558 "seeking_frame", seeking_frame,
1559 "seeking_pts", seeking_pts,
1560 "seek_video_frame_found", seek_video_frame_found,
1561 "seek_audio_frame_found", seek_audio_frame_found);
1564 if (seek_count < kSeekRetryMax) {
1565 Seek(seeking_frame - (10 * seek_count * seek_count));
1566 }
else if (seek_stagnant_count >= kSeekStagnantMax) {
1568 Seek(seeking_frame - (10 * kSeekRetryMax * kSeekRetryMax));
1571 Seek(seeking_frame - (10 * seek_count * seek_count));
1576 "is_video_seek", is_video_seek,
1577 "packet->pts", GetPacketPTS(),
1578 "seeking_pts", seeking_pts,
1579 "seeking_frame", seeking_frame,
1580 "seek_video_frame_found", seek_video_frame_found,
1581 "seek_audio_frame_found", seek_audio_frame_found);
1595 void FFmpegReader::ProcessVideoPacket(int64_t requested_frame) {
1598 int frame_finished = GetAVFrame();
1601 if (!frame_finished) {
1604 RemoveAVFrame(pFrame);
1610 int64_t current_frame = ConvertVideoPTStoFrame(video_pts);
1613 if (!seek_video_frame_found && is_seeking)
1614 seek_video_frame_found = current_frame;
1620 working_cache.
Add(CreateFrame(requested_frame));
1632 AVFrame *pFrameRGB = pFrameRGB_cached;
1635 if (pFrameRGB ==
nullptr)
1637 pFrameRGB_cached = pFrameRGB;
1640 uint8_t *buffer =
nullptr;
1661 max_width = std::max(
float(max_width), max_width * max_scale_x);
1662 max_height = std::max(
float(max_height), max_height * max_scale_y);
1668 QSize width_size(max_width * max_scale_x,
1671 max_height * max_scale_y);
1673 if (width_size.width() >= max_width && width_size.height() >= max_height) {
1674 max_width = std::max(max_width, width_size.width());
1675 max_height = std::max(max_height, width_size.height());
1677 max_width = std::max(max_width, height_size.width());
1678 max_height = std::max(max_height, height_size.height());
1685 float preview_ratio = 1.0;
1692 max_width =
info.
width * max_scale_x * preview_ratio;
1693 max_height =
info.
height * max_scale_y * preview_ratio;
1701 int original_height = height;
1702 if (max_width != 0 && max_height != 0 && max_width < width && max_height < height) {
1704 float ratio = float(width) / float(height);
1705 int possible_width = round(max_height * ratio);
1706 int possible_height = round(max_width / ratio);
1708 if (possible_width <= max_width) {
1710 width = possible_width;
1711 height = max_height;
1715 height = possible_height;
1720 const int bytes_per_pixel = 4;
1721 int raw_buffer_size = (width * height * bytes_per_pixel) + 128;
1724 constexpr
size_t ALIGNMENT = 32;
1725 int buffer_size = ((raw_buffer_size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT;
1726 buffer = (
unsigned char*) aligned_malloc(buffer_size, ALIGNMENT);
1731 int scale_mode = SWS_FAST_BILINEAR;
1733 scale_mode = SWS_BICUBIC;
1735 img_convert_ctx = sws_getCachedContext(img_convert_ctx,
info.
width,
info.
height,
AV_GET_CODEC_PIXEL_FORMAT(pStream, pCodecCtx), width, height,
PIX_FMT_RGBA, scale_mode, NULL, NULL, NULL);
1736 if (!img_convert_ctx)
1740 sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0,
1741 original_height, pFrameRGB->data, pFrameRGB->linesize);
1744 std::shared_ptr<Frame> f = CreateFrame(current_frame);
1749 f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888_Premultiplied, buffer);
1752 f->AddImage(width, height, bytes_per_pixel, QImage::Format_RGBA8888, buffer);
1756 working_cache.
Add(f);
1759 last_video_frame = f;
1765 RemoveAVFrame(pFrame);
1771 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::ProcessVideoPacket (After)",
"requested_frame", requested_frame,
"current_frame", current_frame,
"f->number", f->number,
"video_pts_seconds", video_pts_seconds);
1775 void FFmpegReader::ProcessAudioPacket(int64_t requested_frame) {
1778 if (packet && packet->pts != AV_NOPTS_VALUE) {
1780 location = GetAudioPTSLocation(packet->pts);
1783 if (!seek_audio_frame_found && is_seeking)
1784 seek_audio_frame_found = location.
frame;
1791 working_cache.
Add(CreateFrame(requested_frame));
1795 "requested_frame", requested_frame,
1796 "target_frame", location.
frame,
1800 int frame_finished = 0;
1804 int packet_samples = 0;
1808 int send_packet_err = avcodec_send_packet(aCodecCtx, packet);
1809 if (send_packet_err < 0 && send_packet_err != AVERROR_EOF) {
1813 int receive_frame_err = avcodec_receive_frame(aCodecCtx, audio_frame);
1814 if (receive_frame_err >= 0) {
1817 if (receive_frame_err == AVERROR_EOF) {
1821 if (receive_frame_err == AVERROR(EINVAL) || receive_frame_err == AVERROR_EOF) {
1823 avcodec_flush_buffers(aCodecCtx);
1825 if (receive_frame_err != 0) {
1830 int used = avcodec_decode_audio4(aCodecCtx, audio_frame, &frame_finished, packet);
1833 if (frame_finished) {
1839 audio_pts = audio_frame->pts;
1842 location = GetAudioPTSLocation(audio_pts);
1845 int plane_size = -1;
1851 data_size = av_samples_get_buffer_size(&plane_size, nb_channels,
1855 packet_samples = audio_frame->nb_samples * nb_channels;
1864 int pts_remaining_samples = packet_samples /
info.
channels;
1867 if (pts_remaining_samples == 0) {
1869 "packet_samples", packet_samples,
1871 "pts_remaining_samples", pts_remaining_samples);
1875 while (pts_remaining_samples) {
1880 int samples = samples_per_frame - previous_packet_location.
sample_start;
1881 if (samples > pts_remaining_samples)
1882 samples = pts_remaining_samples;
1885 pts_remaining_samples -= samples;
1887 if (pts_remaining_samples > 0) {
1889 previous_packet_location.
frame++;
1898 "packet_samples", packet_samples,
1906 audio_converted->nb_samples = audio_frame->nb_samples;
1907 av_samples_alloc(audio_converted->data, audio_converted->linesize,
info.
channels, audio_frame->nb_samples, AV_SAMPLE_FMT_FLTP, 0);
1923 av_opt_set_int(avr,
"out_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
1932 audio_converted->data,
1933 audio_converted->linesize[0],
1934 audio_converted->nb_samples,
1936 audio_frame->linesize[0],
1937 audio_frame->nb_samples);
1940 int64_t starting_frame_number = -1;
1941 for (
int channel_filter = 0; channel_filter <
info.
channels; channel_filter++) {
1943 starting_frame_number = location.
frame;
1944 int channel_buffer_size = nb_samples;
1945 auto *channel_buffer = (
float *) (audio_converted->data[channel_filter]);
1949 int remaining_samples = channel_buffer_size;
1950 while (remaining_samples > 0) {
1955 int samples = std::fmin(samples_per_frame - start, remaining_samples);
1958 std::shared_ptr<Frame> f = CreateFrame(starting_frame_number);
1961 f->AddAudio(
true, channel_filter, start, channel_buffer, samples, 1.0f);
1965 "frame", starting_frame_number,
1968 "channel", channel_filter,
1969 "samples_per_frame", samples_per_frame);
1972 working_cache.
Add(f);
1975 remaining_samples -= samples;
1978 if (remaining_samples > 0)
1979 channel_buffer += samples;
1982 starting_frame_number++;
1990 av_free(audio_converted->data[0]);
1999 "requested_frame", requested_frame,
2000 "starting_frame", location.
frame,
2001 "end_frame", starting_frame_number - 1,
2002 "audio_pts_seconds", audio_pts_seconds);
2008 void FFmpegReader::Seek(int64_t requested_frame) {
2010 if (requested_frame < 1)
2011 requested_frame = 1;
2014 if (requested_frame > largest_frame_processed && packet_status.
end_of_file) {
2021 "requested_frame", requested_frame,
2022 "seek_count", seek_count,
2023 "last_frame", last_frame);
2026 working_cache.
Clear();
2030 video_pts_seconds = NO_PTS_OFFSET;
2032 audio_pts_seconds = NO_PTS_OFFSET;
2033 hold_packet =
false;
2035 current_video_frame = 0;
2036 largest_frame_processed = 0;
2037 last_final_video_frame.reset();
2042 packet_status.
reset(
false);
2048 int buffer_amount = 12;
2049 if (requested_frame - buffer_amount < 20) {
2063 if (seek_count == 1) {
2066 seeking_pts = ConvertFrameToVideoPTS(1);
2068 seek_audio_frame_found = 0;
2069 seek_video_frame_found = 0;
2073 bool seek_worked =
false;
2074 int64_t seek_target = 0;
2078 seek_target = ConvertFrameToVideoPTS(requested_frame - buffer_amount);
2083 is_video_seek =
true;
2090 seek_target = ConvertFrameToAudioPTS(requested_frame - buffer_amount);
2095 is_video_seek =
false;
2104 avcodec_flush_buffers(aCodecCtx);
2108 avcodec_flush_buffers(pCodecCtx);
2111 previous_packet_location.
frame = -1;
2116 if (seek_count == 1) {
2118 seeking_pts = seek_target;
2119 seeking_frame = requested_frame;
2121 seek_audio_frame_found = 0;
2122 seek_video_frame_found = 0;
2150 int64_t FFmpegReader::GetPacketPTS() {
2152 int64_t current_pts = packet->pts;
2153 if (current_pts == AV_NOPTS_VALUE && packet->dts != AV_NOPTS_VALUE)
2154 current_pts = packet->dts;
2160 return AV_NOPTS_VALUE;
2165 void FFmpegReader::UpdatePTSOffset() {
2166 if (pts_offset_seconds != NO_PTS_OFFSET) {
2170 pts_offset_seconds = 0.0;
2171 double video_pts_offset_seconds = 0.0;
2172 double audio_pts_offset_seconds = 0.0;
2174 bool has_video_pts =
false;
2177 has_video_pts =
true;
2179 bool has_audio_pts =
false;
2182 has_audio_pts =
true;
2186 while (!has_video_pts || !has_audio_pts) {
2188 if (GetNextPacket() < 0)
2193 int64_t pts = GetPacketPTS();
2196 if (!has_video_pts && packet->stream_index == videoStream) {
2202 if (std::abs(video_pts_offset_seconds) <= 10.0) {
2203 has_video_pts =
true;
2206 else if (!has_audio_pts && packet->stream_index == audioStream) {
2212 if (std::abs(audio_pts_offset_seconds) <= 10.0) {
2213 has_audio_pts =
true;
2219 if (has_video_pts && has_audio_pts) {
2231 pts_offset_seconds = std::max(video_pts_offset_seconds, audio_pts_offset_seconds);
2236 int64_t FFmpegReader::ConvertVideoPTStoFrame(int64_t pts) {
2238 int64_t previous_video_frame = current_video_frame;
2247 if (current_video_frame == 0)
2248 current_video_frame = frame;
2252 if (frame == previous_video_frame) {
2257 current_video_frame++;
2266 int64_t FFmpegReader::ConvertFrameToVideoPTS(int64_t frame_number) {
2268 double seconds = (double(frame_number - 1) /
info.
fps.
ToDouble()) + pts_offset_seconds;
2278 int64_t FFmpegReader::ConvertFrameToAudioPTS(int64_t frame_number) {
2280 double seconds = (double(frame_number - 1) /
info.
fps.
ToDouble()) + pts_offset_seconds;
2290 AudioLocation FFmpegReader::GetAudioPTSLocation(int64_t pts) {
2298 int64_t whole_frame = int64_t(frame);
2301 double sample_start_percentage = frame - double(whole_frame);
2307 int sample_start = round(
double(samples_per_frame) * sample_start_percentage);
2310 if (whole_frame < 1)
2312 if (sample_start < 0)
2319 if (previous_packet_location.
frame != -1) {
2320 if (location.
is_near(previous_packet_location, samples_per_frame, samples_per_frame)) {
2321 int64_t orig_frame = location.
frame;
2326 location.
frame = previous_packet_location.
frame;
2329 ZmqLogger::Instance()->
AppendDebugMethod(
"FFmpegReader::GetAudioPTSLocation (Audio Gap Detected)",
"Source Frame", orig_frame,
"Source Audio Sample", orig_start,
"Target Frame", location.
frame,
"Target Audio Sample", location.
sample_start,
"pts", pts);
2338 previous_packet_location = location;
2345 std::shared_ptr<Frame> FFmpegReader::CreateFrame(int64_t requested_frame) {
2347 std::shared_ptr<Frame> output = working_cache.
GetFrame(requested_frame);
2351 output = working_cache.
GetFrame(requested_frame);
2352 if(output)
return output;
2360 working_cache.
Add(output);
2363 if (requested_frame > largest_frame_processed)
2364 largest_frame_processed = requested_frame;
2371 bool FFmpegReader::IsPartialFrame(int64_t requested_frame) {
2374 bool seek_trash =
false;
2375 int64_t max_seeked_frame = seek_audio_frame_found;
2376 if (seek_video_frame_found > max_seeked_frame) {
2377 max_seeked_frame = seek_video_frame_found;
2379 if ((
info.
has_audio && seek_audio_frame_found && max_seeked_frame >= requested_frame) ||
2380 (
info.
has_video && seek_video_frame_found && max_seeked_frame >= requested_frame)) {
2388 void FFmpegReader::CheckWorkingFrames(int64_t requested_frame) {
2391 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
2394 std::vector<std::shared_ptr<openshot::Frame>> working_frames = working_cache.
GetFrames();
2395 std::vector<std::shared_ptr<openshot::Frame>>::iterator working_itr;
2398 for(working_itr = working_frames.begin(); working_itr != working_frames.end(); ++working_itr)
2401 std::shared_ptr<Frame> f = *working_itr;
2404 if (!f || f->number > requested_frame) {
2410 double frame_pts_seconds = (double(f->number - 1) /
info.
fps.
ToDouble()) + pts_offset_seconds;
2411 double recent_pts_seconds = std::max(video_pts_seconds, audio_pts_seconds);
2414 bool is_video_ready =
false;
2415 bool is_audio_ready =
false;
2416 double recent_pts_diff = recent_pts_seconds - frame_pts_seconds;
2417 if ((frame_pts_seconds <= video_pts_seconds)
2418 || (recent_pts_diff > 1.5)
2422 is_video_ready =
true;
2424 "frame_number", f->number,
2425 "frame_pts_seconds", frame_pts_seconds,
2426 "video_pts_seconds", video_pts_seconds,
2427 "recent_pts_diff", recent_pts_diff);
2432 if (previous_frame_instance && previous_frame_instance->has_image_data) {
2433 f->AddImage(std::make_shared<QImage>(previous_frame_instance->GetImage()->copy()));
2437 if (!f->has_image_data
2438 && last_final_video_frame
2439 && last_final_video_frame->has_image_data
2440 && last_final_video_frame->number <= f->number) {
2441 f->AddImage(std::make_shared<QImage>(last_final_video_frame->GetImage()->copy()));
2445 if (!f->has_image_data
2447 && last_video_frame->has_image_data
2448 && last_video_frame->number <= f->number) {
2449 f->AddImage(std::make_shared<QImage>(last_video_frame->GetImage()->copy()));
2453 if (!f->has_image_data) {
2455 "FFmpegReader::CheckWorkingFrames (no previous image found; using black frame)",
2456 "frame_number", f->number);
2457 f->AddColor(
"#000000");
2462 double audio_pts_diff = audio_pts_seconds - frame_pts_seconds;
2463 if ((frame_pts_seconds < audio_pts_seconds && audio_pts_diff > 1.0)
2464 || (recent_pts_diff > 1.5)
2469 is_audio_ready =
true;
2471 "frame_number", f->number,
2472 "frame_pts_seconds", frame_pts_seconds,
2473 "audio_pts_seconds", audio_pts_seconds,
2474 "audio_pts_diff", audio_pts_diff,
2475 "recent_pts_diff", recent_pts_diff);
2477 bool is_seek_trash = IsPartialFrame(f->number);
2485 "frame_number", f->number,
2486 "is_video_ready", is_video_ready,
2487 "is_audio_ready", is_audio_ready,
2493 if ((!packet_status.
end_of_file && is_video_ready && is_audio_ready) || packet_status.
end_of_file || is_seek_trash) {
2496 "requested_frame", requested_frame,
2497 "f->number", f->number,
2498 "is_seek_trash", is_seek_trash,
2499 "Working Cache Count", working_cache.
Count(),
2503 if (!is_seek_trash) {
2506 if (f->has_image_data) {
2507 last_final_video_frame = f;
2511 working_cache.
Remove(f->number);
2514 last_frame = f->number;
2517 working_cache.
Remove(f->number);
2524 working_frames.clear();
2525 working_frames.shrink_to_fit();
2529 void FFmpegReader::CheckFPS() {
2537 int frames_per_second[3] = {0,0,0};
2538 int max_fps_index =
sizeof(frames_per_second) /
sizeof(frames_per_second[0]);
2541 int all_frames_detected = 0;
2542 int starting_frames_detected = 0;
2547 if (GetNextPacket() < 0)
2552 if (packet->stream_index == videoStream) {
2555 fps_index = int(video_seconds);
2558 if (fps_index >= 0 && fps_index < max_fps_index) {
2560 starting_frames_detected++;
2561 frames_per_second[fps_index]++;
2565 all_frames_detected++;
2570 float avg_fps = 30.0;
2571 if (starting_frames_detected > 0 && fps_index > 0) {
2572 avg_fps = float(starting_frames_detected) / std::min(fps_index, max_fps_index);
2576 if (avg_fps < 8.0) {
2585 if (all_frames_detected > 0) {
2599 void FFmpegReader::RemoveAVFrame(AVFrame *remove_frame) {
2603 av_freep(&remove_frame->data[0]);
2611 void FFmpegReader::RemoveAVPacket(AVPacket *remove_packet) {
2616 delete remove_packet;
2631 root[
"type"] =
"FFmpegReader";
2632 root[
"path"] =
path;
2633 switch (duration_strategy) {
2635 root[
"duration_strategy"] =
"VideoPreferred";
2638 root[
"duration_strategy"] =
"AudioPreferred";
2642 root[
"duration_strategy"] =
"LongestStream";
2659 catch (
const std::exception& e) {
2661 throw InvalidJSON(
"JSON is invalid (missing keys or invalid data types)");
2672 if (!root[
"path"].isNull())
2673 path = root[
"path"].asString();
2674 if (!root[
"duration_strategy"].isNull()) {
2675 const std::string strategy = root[
"duration_strategy"].asString();
2676 if (strategy ==
"VideoPreferred") {
2678 }
else if (strategy ==
"AudioPreferred") {