[Libav-user] Restarting the libav library

Isaac Wang isaac.wang at visorcorp.com
Tue Oct 25 00:51:47 CEST 2011


Hello,
I'm having trouble 'restarting' the libav library.  Currently, I'm using 
libav to listen to a UDP video stream and I'm able to decode the video 
just fine.  However, when I close the data structures and reinitialize 
them, many times libav will throw an error.  Here is how I initialize my 
objects:

ret = ffmpeg::avformat_open_input(&formatCtx, 
path.toStdString().c_str(), NULL, NULL);
     if (ret != 0)
     {
         qDebug() << "Could not open input file";
         return;
     }

     // Retrieve stream information
     if (ffmpeg::av_find_stream_info(formatCtx) < 0)
     {
         qDebug() << "Stream info could not be found";
         return;
     }

     // Find the first video stream
     videoStream = -1;
     for (unsigned int i = 0; i < formatCtx->nb_streams; i++)
     {
         if (formatCtx->streams[i]->codec->codec_type == 
ffmpeg::AVMEDIA_TYPE_VIDEO)
         {
             videoStream = i;
             break;
         }
     }

     // Check if video stream is found
     if (videoStream == -1)
     {
         qDebug() << "Video stream not found";
         return;
     }

     // Get a pointer to the codec context for the video stream
     stream = formatCtx->streams[videoStream];
     codecCtx = formatCtx->streams[videoStream]->codec;

     // Find the decoder for the video stream
     codec = ffmpeg::avcodec_find_decoder(codecCtx->codec_id);
     if (codec == NULL)
     {
         qDebug() << "Could not find decoder";
         return;
     }

     // Open codec
     if (ffmpeg::avcodec_open(codecCtx, codec)<0)
     {
         qDebug() << "Could not open codec";
         return;
     }

     // Allocate video frame
     frame = ffmpeg::avcodec_alloc_frame();

     // Determine required buffer size and allocate buffer
     numBytes = ffmpeg::avpicture_get_size(ffmpeg::PIX_FMT_RGB24, 
codecCtx->width, codecCtx->height);
     if (numBytes < 0)
     {
         qDebug() << "Number of Bytes is " << numBytes;
         return;
     }

Here is the code that I use to close the objects:
// Free the YUV frame
     if (frame)
         ffmpeg::av_free(frame);
     if (frameRGB)
         ffmpeg::av_free(frame);

     // Close the codec
     if (codecCtx)
         ffmpeg::avcodec_close(codecCtx);

     // Close the video file
     if (formatCtx)
         ffmpeg::av_close_input_file(formatCtx);

I notice that sometimes when I reinitialize my libav objects, the codec 
context object will have a width and height of 0 after I call 
avcodec_open().  If anyone could shed some light on how to 'restart' 
libav or why I receive a width and height of 0 when I call 
avcodec_open() multiple times, I'd greatly appreciate it!


More information about the Libav-user mailing list