From 7be71674af58d35d61928d2af6750efc5536bab6 Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Thu, 19 Apr 2018 00:59:47 +0200 Subject: [PATCH] Correct FFmpeg audio PTS. The PTS should come from received (decoded) samples, not what we send into the codec -- if there's codec delay, the difference could be significant. --- ffmpeg_capture.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ffmpeg_capture.cpp b/ffmpeg_capture.cpp index c79ecf3..4f6e168 100644 --- a/ffmpeg_capture.cpp +++ b/ffmpeg_capture.cpp @@ -597,6 +597,7 @@ AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCo AVFrameWithDeleter video_avframe = av_frame_alloc_unique(); bool eof = false; *audio_pts = -1; + bool has_audio = false; do { AVPacket pkt; unique_ptr pkt_cleanup( @@ -615,9 +616,7 @@ AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCo return AVFrameWithDeleter(nullptr); } } else if (pkt.stream_index == audio_stream_index) { - if (*audio_pts == -1) { - *audio_pts = pkt.pts; - } + has_audio = true; if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) { fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str()); *error = true; @@ -629,10 +628,13 @@ AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCo } // Decode audio, if any. - if (*audio_pts != -1) { + if (has_audio) { for ( ;; ) { int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get()); if (err == 0) { + if (*audio_pts == -1) { + *audio_pts = audio_avframe->pts; + } convert_audio(audio_avframe.get(), audio_frame, audio_format); } else if (err == AVERROR(EAGAIN)) { break; -- 2.39.2