[Libav-user] Encountering exception while reading all frames of an MKV video file

Vaughn Treude vaughn.treude at puretechsystems.com
Thu Sep 28 01:55:38 EEST 2023

Hello all,
I'm using the FFMPEG libraries within an FFmpeg-Autogen C# wrapper in Windows Framework 4.8 to decode a video from an MKV (Matroska) container.
I open the file and initialize the stream using the following sequence:
            ffmpeg.avformat_open_input(&pFormatContext, url, null, null).ThrowExceptionIfError();
            ffmpeg.avformat_find_stream_info(_pFormatContext, null).ThrowExceptionIfError();
            AVCodec* codec = null;
            _streamIndex = ffmpeg
                .av_find_best_stream(_pFormatContext, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0)
            _pCodecContext = ffmpeg.avcodec_alloc_context3(codec);
            ffmpeg.avcodec_parameters_to_context(_pCodecContext, _pFormatContext->streams[_streamIndex]->codecpar)
            ffmpeg.avcodec_open2(_pCodecContext, codec, null).ThrowExceptionIfError();

After initializing, I can read each frame of the video stream using av_read_frame. I was assuming that at the end, av_read_frame would return an EOF error code. But it doesn't return any kind of error, so I continue with the process, calling avcodec_send_packet with the packet of frame data I've supposedly just read, which gives me an illegal memory access exception.
My normal approach would be to get the length of the video in frames and not read beyond this number. Unfortunately, I've been unable to find a way to determine the length of an MKV video in frames.
The nb_frames member of the stream object is never set to anything but zero. Alternately, I could multiply the duration in seconds by the frame rate, but the duration member is always set to a large-valued negative number.
How can I read all the frames in the file and exit gracefully at the end of the stream?

Thank you kindly for any hints you can give me,
Vaughn T.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://ffmpeg.org/pipermail/libav-user/attachments/20230927/0f7aeaa1/attachment.htm>

More information about the Libav-user mailing list