Recherche avancée

Médias (1)

Mot : - Tags -/Christian Nold

Autres articles (80)

  • MediaSPIP 0.1 Beta version

    25 avril 2011, par

    MediaSPIP 0.1 beta is the first version of MediaSPIP proclaimed as "usable".
    The zip file provided here only contains the sources of MediaSPIP in its standalone version.
    To get a working installation, you must manually install all-software dependencies on the server.
    If you want to use this archive for an installation in "farm mode", you will also need to proceed to other manual (...)

  • MediaSPIP version 0.1 Beta

    16 avril 2011, par

    MediaSPIP 0.1 beta est la première version de MediaSPIP décrétée comme "utilisable".
    Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
    Pour avoir une installation fonctionnelle, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
    Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...)

  • De l’upload à la vidéo finale [version standalone]

    31 janvier 2010, par

    Le chemin d’un document audio ou vidéo dans SPIPMotion est divisé en trois étapes distinctes.
    Upload et récupération d’informations de la vidéo source
    Dans un premier temps, il est nécessaire de créer un article SPIP et de lui joindre le document vidéo "source".
    Au moment où ce document est joint à l’article, deux actions supplémentaires au comportement normal sont exécutées : La récupération des informations techniques des flux audio et video du fichier ; La génération d’une vignette : extraction d’une (...)

Sur d’autres sites (10489)

  • Screen Recording with FFmpeg-Lib with c++

    27 janvier 2020, par Baschdel

    I’m trying to record the whole desktop stream with FFmpeg on Windows.
    I found a working example here. The Problem is that some og the functions depricated. So I tried to replace them with the updated ones.

    But there are some slight problems. The error "has triggered a breakpoint." occurse and also "not able to read the location."
    The bigger problem is that I don’t know if this is the right way to do this..

    My code looks like this :

    using namespace std;

    /* initialize the resources*/
    Recorder::Recorder()
    {

       av_register_all();
       avcodec_register_all();
       avdevice_register_all();
       cout<<"\nall required functions are registered successfully";
    }

    /* uninitialize the resources */
    Recorder::~Recorder()
    {

       avformat_close_input(&pAVFormatContext);
       if( !pAVFormatContext )
       {
           cout<<"\nfile closed sucessfully";
       }
       else
       {
           cout<<"\nunable to close the file";
           exit(1);
       }

       avformat_free_context(pAVFormatContext);
       if( !pAVFormatContext )
       {
           cout<<"\navformat free successfully";
       }
       else
       {
           cout<<"\nunable to free avformat context";
           exit(1);
       }

    }

    /* establishing the connection between camera or screen through its respective folder */
    int Recorder::openCamera()
    {

       value = 0;
       options = NULL;
       pAVFormatContext = NULL;

       pAVFormatContext = avformat_alloc_context();//Allocate an AVFormatContext.

       openScreen(pAVFormatContext);

       /* set frame per second */
       value = av_dict_set( &options,"framerate","30",0 );
       if(value < 0)
       {
         cout<<"\nerror in setting dictionary value";
          exit(1);
       }

       value = av_dict_set( &options, "preset", "medium", 0 );
       if(value < 0)
       {
         cout<<"\nerror in setting preset values";
         exit(1);
       }

    //  value = avformat_find_stream_info(pAVFormatContext,NULL);
       if(value < 0)
       {
         cout<<"\nunable to find the stream information";
         exit(1);
       }

       VideoStreamIndx = -1;

       /* find the first video stream index . Also there is an API available to do the below operations */
       for(int i = 0; i < pAVFormatContext->nb_streams; i++ ) // find video stream posistion/index.
       {
         if( pAVFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO )
         {
            VideoStreamIndx = i;
            break;
         }

       }

       if( VideoStreamIndx == -1)
       {
         cout<<"\nunable to find the video stream index. (-1)";
         exit(1);
       }

       // assign pAVFormatContext to VideoStreamIndx
       pAVCodecContext = pAVFormatContext->streams[VideoStreamIndx]->codec;

       pAVCodec = avcodec_find_decoder(pAVCodecContext->codec_id);
       if( pAVCodec == NULL )
       {
         cout<<"\nunable to find the decoder";
         exit(1);
       }

       value = avcodec_open2(pAVCodecContext , pAVCodec , NULL);//Initialize the AVCodecContext to use the given AVCodec.
       if( value < 0 )
       {
         cout<<"\nunable to open the av codec";
         exit(1);
       }
    }

    /* initialize the video output file and its properties  */
    int Recorder::init_outputfile()
    {
       outAVFormatContext = NULL;
       value = 0;
       output_file = "output.mp4";

       avformat_alloc_output_context2(&outAVFormatContext, NULL, NULL, output_file);
       if (!outAVFormatContext)
       {
           cout<<"\nerror in allocating av format output context";
           exit(1);
       }

    /* Returns the output format in the list of registered output formats which best matches the provided parameters, or returns NULL if there is no match. */
       output_format = av_guess_format(NULL, output_file ,NULL);
       if( !output_format )
       {
        cout<<"\nerror in guessing the video format. try with correct format";
        exit(1);
       }

       video_st = avformat_new_stream(outAVFormatContext ,NULL);
       if( !video_st )
       {
           cout<<"\nerror in creating a av format new stream";
           exit(1);
       }

       if (codec_id == AV_CODEC_ID_H264)
       {
           av_opt_set(outAVCodecContext->priv_data, "preset", "slow", 0);
       }

       outAVCodec = avcodec_find_encoder(AV_CODEC_ID_MPEG4);
       if (!outAVCodec)
       {
           cout << "\nerror in finding the av codecs. try again with correct codec";
           exit(1);
       }

       outAVCodecContext = avcodec_alloc_context3(outAVCodec);
       if( !outAVCodecContext )
       {
           cout<<"\nerror in allocating the codec contexts";
           exit(1);
       }

       /* set property of the video file */
       outAVCodecContext = video_st->codec;
       outAVCodecContext->codec_id = AV_CODEC_ID_MPEG4;// AV_CODEC_ID_MPEG4; // AV_CODEC_ID_H264 // AV_CODEC_ID_MPEG1VIDEO
       outAVCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
       outAVCodecContext->pix_fmt  = AV_PIX_FMT_YUV420P;
       outAVCodecContext->bit_rate = 400000; // 2500000
       outAVCodecContext->width = 1920;
       outAVCodecContext->height = 1080;
       outAVCodecContext->gop_size = 3;
       outAVCodecContext->max_b_frames = 2;
       outAVCodecContext->time_base.num = 1;
       outAVCodecContext->time_base.den = 30; //15fps


       /* Some container formats (like MP4) require global headers to be present
          Mark the encoder so that it behaves accordingly. */

       if ( outAVFormatContext->oformat->flags & AVFMT_GLOBALHEADER)
       {
           outAVCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
       }

       value = avcodec_open2(outAVCodecContext, outAVCodec, NULL);
       if( value < 0)
       {
           cout<<"\nerror in opening the avcodec";
           exit(1);
       }

       /* create empty video file */
       if ( !(outAVFormatContext->flags & AVFMT_NOFILE) )
       {
        if( avio_open2(&outAVFormatContext->pb , output_file , AVIO_FLAG_WRITE ,NULL, NULL) < 0 )
        {
         cout<<"\nerror in creating the video file";
         exit(1);
        }
       }

       if(!outAVFormatContext->nb_streams)
       {
           cout<<"\noutput file dose not contain any stream";
           exit(1);
       }

       /* imp: mp4 container or some advanced container file required header information*/
       value = avformat_write_header(outAVFormatContext , &options);
       if(value < 0)
       {
           cout<<"\nerror in writing the header context";
           exit(1);
       }

       /*
       // uncomment here to view the complete video file informations
       cout<<"\n\nOutput file information :\n\n";
       av_dump_format(outAVFormatContext , 0 ,output_file ,1);
       */
    }

    int Recorder::stop() {
       threading = false;

       demux->join();
       rescale->join();
       mux->join();

       return 0;
    }

    int Recorder::start() {
       initVideoThreads();
       return 0;
    }

    int Recorder::initVideoThreads() {
       demux = new thread(&Recorder::demuxVideoStream, this, pAVCodecContext, pAVFormatContext, VideoStreamIndx);

       rescale = new thread(&Recorder::rescaleVideoStream, this, pAVCodecContext, outAVCodecContext);

       demux = new thread(&Recorder::encodeVideoStream, this, outAVCodecContext);
       return 0;
    }

    void Recorder::demuxVideoStream(AVCodecContext* codecContext, AVFormatContext* formatContext, int streamIndex)
    {
       // init packet
       AVPacket* packet = (AVPacket*)av_malloc(sizeof(AVPacket));
       av_init_packet(packet);

       int ctr = 0;

       while (threading)
       {
           if (av_read_frame(formatContext, packet) < 0) {
               exit(1);
           }

           if (packet->stream_index == streamIndex)
           {
               int return_value; // = 0;
               ctr++;

               do
               {
                   return_value = avcodec_send_packet(codecContext, packet);
               } while (return_value == AVERROR(EAGAIN) && threading);

               //int i = avcodec_send_packet(codecContext, packet);
               if (return_value < 0 && threading) { // call Decoder
                   cout << "unable to decode video";
                   exit(1);
               }
           }
       }

       avcodec_send_packet(codecContext, NULL); // flush decoder

       // return 0;
    }

    void Recorder::rescaleVideoStream(AVCodecContext* inCodecContext, AVCodecContext* outCodecContext)
    {
       bool closing = false;
       AVFrame* inFrame = av_frame_alloc();
       if (!inFrame)
       {
           cout << "\nunable to release the avframe resources";
           exit(1);
       }

       int nbytes = av_image_get_buffer_size(outAVCodecContext->pix_fmt, outAVCodecContext->width, outAVCodecContext->height, 32);
       uint8_t* video_outbuf = (uint8_t*)av_malloc(nbytes);
       if (video_outbuf == NULL)
       {
           cout << "\nunable to allocate memory";
           exit(1);
       }

       AVFrame* outFrame = av_frame_alloc();//Allocate an AVFrame and set its fields to default values.
       if (!outFrame)
       {
           cout << "\nunable to release the avframe resources for outframe";
           exit(1);
       }

       // Setup the data pointers and linesizes based on the specified image parameters and the provided array.
       int value = av_image_fill_arrays(outFrame->data, outFrame->linesize, video_outbuf, AV_PIX_FMT_YUV420P, outAVCodecContext->width, outAVCodecContext->height, 1); // returns : the size in bytes required for src
       if (value < 0)
       {
           cout << "\nerror in filling image array";
       }
       int ctr = 0;

       while (threading || !closing) {
           int value = avcodec_receive_frame(inCodecContext, inFrame);
           if (value == 0) {
               ctr++;
               SwsContext* swsCtx_ = sws_getContext(inCodecContext->width,
                   inCodecContext->height,
                   inCodecContext->pix_fmt,
                   outAVCodecContext->width,
                   outAVCodecContext->height,
                   outAVCodecContext->pix_fmt,
                   SWS_BICUBIC, NULL, NULL, NULL);
               sws_scale(swsCtx_, inFrame->data, inFrame->linesize, 0, inCodecContext->height, outFrame->data, outFrame->linesize);


               int return_value;
               do
               {
                   return_value = avcodec_send_frame(outCodecContext, outFrame);
               } while (return_value == AVERROR(EAGAIN) && threading);
           }
           closing = (value == AVERROR_EOF);
       }
       avcodec_send_frame(outCodecContext, NULL);


       // av_free(video_outbuf);

       // return 0;
    }

    void Recorder::encodeVideoStream(AVCodecContext* codecContext)
    {
       bool closing = true;
       AVPacket* packet = (AVPacket*)av_malloc(sizeof(AVPacket));
       av_init_packet(packet);

       int ctr = 0;

       while (threading || !closing) {
           packet->data = NULL;    // packet data will be allocated by the encoder
           packet->size = 0;
           ctr++;
           int value = avcodec_receive_packet(codecContext, packet);
           if (value == 0) {
               if (packet->pts != AV_NOPTS_VALUE)
                   packet->pts = av_rescale_q(packet->pts, video_st->codec->time_base, video_st->time_base);
               if (packet->dts != AV_NOPTS_VALUE)
                   packet->dts = av_rescale_q(packet->dts, video_st->codec->time_base, video_st->time_base);

               //printf("Write frame %3d (size= %2d)\n", j++, packet->size / 1000);
               if (av_write_frame(outAVFormatContext, packet) != 0)
               {
                   cout << "\nerror in writing video frame";
               }
           }

           closing = (value == AVERROR_EOF);
       }

       value = av_write_trailer(outAVFormatContext);
       if (value < 0)
       {
           cout << "\nerror in writing av trailer";
           exit(1);
       }

       // av_free(packet);

       // return 0;
    }


    int Recorder::openScreen(AVFormatContext* pFormatCtx) {
       /*

       X11 video input device.
       To enable this input device during configuration you need libxcb installed on your system. It will be automatically detected during configuration.
       This device allows one to capture a region of an X11 display.
       refer : https://www.ffmpeg.org/ffmpeg-devices.html#x11grab
       */
       /* current below is for screen recording. to connect with camera use v4l2 as a input parameter for av_find_input_format */
       pAVInputFormat = av_find_input_format("gdigrab");
       //value = avformat_open_input(&pAVFormatContext, ":0.0+10,250", pAVInputFormat, NULL);

       value = avformat_open_input(&pAVFormatContext, "desktop", pAVInputFormat, NULL);
       if (value != 0)
       {
           cout << "\nerror in opening input device";
           exit(1);
       }
       return 0;
    }
  • ffmpeg avcodec_encode_video2 hangs when using Quick Sync h264_qsv encoder

    9 juin 2020, par Mike Simpson

    When I use the mpeg4 or h264 encoders, I am able to successfully encode images to make a valid AVI file using the API for ffmpeg 3.1.0. However, when I use the Quick Sync encoder (h264_qsv), avcodec_encode_video2 will hang some of the time. I found that when using images that are 1920x1080, it was rare that avcodec_encode_video2 would hang. When using 256x256 images, it was very likely that the function would hang.

    



    I have created the test code below that demonstrates the hang of avcodec_encode_video2. The code will create a 1000 frame, 256x256 AVI with a bit rate of 400000. The frames are simply allocated, so the output video should just be green frames.

    



    The problem was observed using Windows 7 and Windows 10, using the 32-bit or 64-bit test application.

    



    If anyone has any idea on how I can avoid the avcodec_encode_video2 hang I would be very grateful ! Thanks in advance for any assistance.

    



    extern "C"&#xA;{&#xA;#ifndef __STDC_CONSTANT_MACROS&#xA;#define __STDC_CONSTANT_MACROS&#xA;#endif&#xA;#include "avcodec.h"&#xA;#include "avformat.h"&#xA;#include "swscale.h"&#xA;#include "avutil.h"&#xA;#include "imgutils.h"&#xA;#include "opt.h"&#xA;#include &#xA;}&#xA;&#xA;#include <iostream>&#xA;&#xA;&#xA;// Globals&#xA;AVCodec* m_pCodec = NULL;&#xA;AVStream *m_pStream = NULL;&#xA;AVOutputFormat* m_pFormat = NULL;&#xA;AVFormatContext* m_pFormatContext = NULL;&#xA;AVCodecContext* m_pCodecContext = NULL;&#xA;AVFrame* m_pFrame = NULL;&#xA;int m_frameIndex;&#xA;&#xA;// Output format&#xA;AVPixelFormat m_pixType = AV_PIX_FMT_NV12;&#xA;// Use for mpeg4&#xA;//AVPixelFormat m_pixType = AV_PIX_FMT_YUV420P;&#xA;&#xA;// Output frame rate&#xA;int m_frameRate = 30;&#xA;// Output image dimensions&#xA;int m_imageWidth = 256;&#xA;int m_imageHeight = 256;&#xA;// Number of frames to export&#xA;int m_frameCount = 1000;&#xA;// Output file name&#xA;const char* m_fileName = "c:/test/test.avi";&#xA;// Output file type&#xA;const char* m_fileType = "AVI";&#xA;// Codec name used to encode&#xA;const char* m_encoderName = "h264_qsv";&#xA;// use for mpeg4&#xA;//const char* m_encoderName = "mpeg4";&#xA;// Target bit rate&#xA;int m_targetBitRate = 400000;&#xA;&#xA;void addVideoStream()&#xA;{&#xA;    m_pStream = avformat_new_stream( m_pFormatContext, m_pCodec );&#xA;    m_pStream->id = m_pFormatContext->nb_streams - 1;&#xA;    m_pStream->time_base = m_pCodecContext->time_base;&#xA;    m_pStream->codec->pix_fmt = m_pixType;&#xA;    m_pStream->codec->flags = m_pCodecContext->flags;&#xA;    m_pStream->codec->width = m_pCodecContext->width;&#xA;    m_pStream->codec->height = m_pCodecContext->height;&#xA;    m_pStream->codec->time_base = m_pCodecContext->time_base;&#xA;    m_pStream->codec->bit_rate = m_pCodecContext->bit_rate;&#xA;}&#xA;&#xA;AVFrame* allocatePicture( enum AVPixelFormat pix_fmt, int width, int height )&#xA;{&#xA;    AVFrame *frame;&#xA;&#xA;    frame = av_frame_alloc();&#xA;&#xA;    if ( !frame )&#xA;    {&#xA;        return NULL;&#xA;    }&#xA;&#xA;    frame->format = pix_fmt;&#xA;    frame->width  = width;&#xA;    frame->height = height;&#xA;&#xA;    int checkImage = av_image_alloc( frame->data, frame->linesize, width, height, pix_fmt, 32 );&#xA;&#xA;    if ( checkImage &lt; 0 )&#xA;    {&#xA;        return NULL;&#xA;    }&#xA;&#xA;    return frame;&#xA;}&#xA;&#xA;bool initialize()&#xA;{&#xA;    AVRational frameRate;&#xA;    frameRate.den = m_frameRate;&#xA;    frameRate.num = 1;&#xA;&#xA;    av_register_all();&#xA;&#xA;    m_pCodec = avcodec_find_encoder_by_name(m_encoderName);&#xA;&#xA;    if( !m_pCodec )&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    m_pCodecContext = avcodec_alloc_context3( m_pCodec );&#xA;    m_pCodecContext->width = m_imageWidth;&#xA;    m_pCodecContext->height = m_imageHeight;&#xA;    m_pCodecContext->time_base = frameRate;&#xA;    m_pCodecContext->gop_size = 0;&#xA;    m_pCodecContext->pix_fmt = m_pixType;&#xA;    m_pCodecContext->codec_id = m_pCodec->id;&#xA;    m_pCodecContext->bit_rate = m_targetBitRate;&#xA;&#xA;    av_opt_set( m_pCodecContext->priv_data, "&#x2B;CBR", "", 0 );&#xA;&#xA;    return true;&#xA;}&#xA;&#xA;bool startExport()&#xA;{&#xA;    m_frameIndex = 0;&#xA;    char fakeFileName[512]; &#xA;    int checkAllocContext = avformat_alloc_output_context2( &amp;m_pFormatContext, NULL, m_fileType, fakeFileName );&#xA;&#xA;    if ( checkAllocContext &lt; 0 )&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    if ( !m_pFormatContext ) &#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    m_pFormat = m_pFormatContext->oformat;&#xA;&#xA;    if ( m_pFormat->video_codec != AV_CODEC_ID_NONE ) &#xA;    {&#xA;        addVideoStream();&#xA;&#xA;        int checkOpen = avcodec_open2( m_pCodecContext, m_pCodec, NULL );&#xA;&#xA;        if ( checkOpen &lt; 0 )&#xA;        {&#xA;            return false;&#xA;        }&#xA;&#xA;        m_pFrame = allocatePicture( m_pCodecContext->pix_fmt, m_pCodecContext->width, m_pCodecContext->height );                &#xA;        if( !m_pFrame ) &#xA;        {&#xA;            return false;&#xA;        }&#xA;        m_pFrame->pts = 0;&#xA;    }&#xA;&#xA;    int checkOpen = avio_open( &amp;m_pFormatContext->pb, m_fileName, AVIO_FLAG_WRITE );&#xA;    if ( checkOpen &lt; 0 )&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    av_dict_set( &amp;(m_pFormatContext->metadata), "title", "QS Test", 0 );&#xA;&#xA;    int checkHeader = avformat_write_header( m_pFormatContext, NULL );&#xA;    if ( checkHeader &lt; 0 )&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    return true;&#xA;}&#xA;&#xA;int processFrame( AVPacket&amp; avPacket )&#xA;{&#xA;    avPacket.stream_index = 0;&#xA;    avPacket.pts = av_rescale_q( m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base );&#xA;    avPacket.dts = av_rescale_q( m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base );&#xA;    m_pFrame->pts&#x2B;&#x2B;;&#xA;&#xA;    int retVal = av_interleaved_write_frame( m_pFormatContext, &amp;avPacket );&#xA;    return retVal;&#xA;}&#xA;&#xA;bool exportFrame()&#xA;{&#xA;    int success = 1;&#xA;    int result = 0;&#xA;&#xA;    AVPacket avPacket;&#xA;&#xA;    av_init_packet( &amp;avPacket );&#xA;    avPacket.data = NULL;&#xA;    avPacket.size = 0;&#xA;&#xA;    fflush(stdout);&#xA;&#xA;    std::cout &lt;&lt; "Before avcodec_encode_video2 for frame: " &lt;&lt; m_frameIndex &lt;&lt; std::endl;&#xA;    success = avcodec_encode_video2( m_pCodecContext, &amp;avPacket, m_pFrame, &amp;result );&#xA;    std::cout &lt;&lt; "After avcodec_encode_video2 for frame: " &lt;&lt; m_frameIndex &lt;&lt; std::endl;&#xA;&#xA;    if( result )&#xA;    { &#xA;        success = processFrame( avPacket );&#xA;    }&#xA;&#xA;    av_packet_unref( &amp;avPacket );&#xA;&#xA;    m_frameIndex&#x2B;&#x2B;;&#xA;    return ( success == 0 );&#xA;}&#xA;&#xA;void endExport()&#xA;{&#xA;    int result = 0;&#xA;    int success = 0;&#xA;&#xA;    if (m_pFrame)&#xA;    {&#xA;        while ( success == 0 )&#xA;        {&#xA;            AVPacket avPacket;&#xA;            av_init_packet( &amp;avPacket );&#xA;            avPacket.data = NULL;&#xA;            avPacket.size = 0;&#xA;&#xA;            fflush(stdout);&#xA;            success = avcodec_encode_video2( m_pCodecContext, &amp;avPacket, NULL, &amp;result );&#xA;&#xA;            if( result )&#xA;            { &#xA;                success = processFrame( avPacket );&#xA;            }&#xA;            av_packet_unref( &amp;avPacket );&#xA;&#xA;            if (!result)&#xA;            {&#xA;                break;&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    if (m_pFormatContext)&#xA;    {&#xA;        av_write_trailer( m_pFormatContext );&#xA;&#xA;        if( m_pFrame )&#xA;        {&#xA;            av_frame_free( &amp;m_pFrame );&#xA;        }&#xA;&#xA;        avio_closep( &amp;m_pFormatContext->pb );&#xA;        avformat_free_context( m_pFormatContext );&#xA;        m_pFormatContext = NULL;&#xA;    }&#xA;}&#xA;&#xA;void cleanup()&#xA;{&#xA;    if( m_pFrame || m_pCodecContext )&#xA;    {&#xA;        if( m_pFrame )&#xA;        {&#xA;            av_frame_free( &amp;m_pFrame );&#xA;        }&#xA;&#xA;        if( m_pCodecContext )&#xA;        {&#xA;            avcodec_close( m_pCodecContext );&#xA;            av_free( m_pCodecContext );&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;int main()&#xA;{&#xA;    bool success = true;&#xA;    if (initialize())&#xA;    {&#xA;        if (startExport())&#xA;        {&#xA;            for (int loop = 0; loop &lt; m_frameCount; loop&#x2B;&#x2B;)&#xA;            {&#xA;                if (!exportFrame())&#xA;                {&#xA;                    std::cout &lt;&lt; "Failed to export frame\n";&#xA;                    success = false;&#xA;                    break;&#xA;                }&#xA;            }&#xA;            endExport();&#xA;        }&#xA;        else&#xA;        {&#xA;            std::cout &lt;&lt; "Failed to start export\n";&#xA;            success = false;&#xA;        }&#xA;&#xA;        cleanup();&#xA;    }&#xA;    else&#xA;    {&#xA;        std::cout &lt;&lt; "Failed to initialize export\n";&#xA;        success = false;&#xA;    }&#xA;&#xA;    if (success)&#xA;    {&#xA;        std::cout &lt;&lt; "Successfully exported file\n";&#xA;    }&#xA;    return 1;&#xA;}&#xA;</iostream>

    &#xA;

  • avcodec_encode_video2 the memory usage is very high

    9 juin 2020, par 陆骁剑

    code :&#xA; ```&#xA; #include "pch.h"&#xA; #include

    &#xA;&#xA;

    extern "C"&#xA;{&#xA;#ifndef __STDC_CONSTANT_MACROS&#xA;#define __STDC_CONSTANT_MACROS&#xA;#endif&#xA;#include <libavcodec></libavcodec>avcodec.h>&#xA;#include "libavformat/avformat.h"&#xA;#include "libswscale/swscale.h"&#xA;#include "libavutil/avutil.h"&#xA;#include "libavutil/imgutils.h"&#xA;#include "libavutil/opt.h"&#xA;#include <libavutil></libavutil>rational.h>&#xA;//#include "libavutil/avassert.h"&#xA;&#xA;&#xA;//#include "libavutil/attributes.h"&#xA;//#include "libavutil/avassert.h"&#xA;//#include "libavutil/frame.h"&#xA;//#include "libavutil/imgutils.h"&#xA;//#include "internal1.h"&#xA;//#include "libavutil/samplefmt.h"&#xA;}&#xA;#include &#xA;//#include "avcodec.h"&#xA;//#include "frame_thread_encoder.h"&#xA;//#include "internal.h"&#xA;&#xA;// Globals&#xA;AVCodec* m_pCodec = NULL;&#xA;AVStream *m_pStream = NULL;&#xA;AVOutputFormat* m_pFormat = NULL;&#xA;AVFormatContext* m_pFormatContext = NULL;&#xA;AVCodecContext* m_pCodecContext = NULL;&#xA;AVFrame* m_pFrame = NULL;&#xA;int m_frameIndex;&#xA;&#xA;// Output format&#xA;AVPixelFormat m_pixType = AV_PIX_FMT_NV12;&#xA;// Use for mpeg4&#xA;//AVPixelFormat m_pixType = AV_PIX_FMT_YUV420P;&#xA;&#xA;// Output frame rate&#xA;int m_frameRate = 30;&#xA;// Output image dimensions&#xA;int m_imageWidth = 256;&#xA;int m_imageHeight = 1537;&#xA;// Number of frames to export&#xA;int m_frameCount = 20000;&#xA;// Output file name&#xA;const char* m_fileName = "test.h264";&#xA;// Output file type&#xA;const char* m_fileType = "H264";&#xA;// Codec name used to encode&#xA;const char* m_encoderName = "h264_qsv";&#xA;// use for mpeg4&#xA;//const char* m_encoderName = "mpeg4";&#xA;// Target bit rate&#xA;int m_targetBitRate = 400000;&#xA;&#xA;void addVideoStream()&#xA;{&#xA;    m_pStream = avformat_new_stream(m_pFormatContext, m_pCodec);&#xA;    m_pStream->id = m_pFormatContext->nb_streams - 1;&#xA;    m_pStream->time_base = m_pCodecContext->time_base;&#xA;    m_pStream->codec->pix_fmt = m_pixType;&#xA;    m_pStream->codec->flags = m_pCodecContext->flags;&#xA;    m_pStream->codec->width = m_pCodecContext->width;&#xA;    m_pStream->codec->height = m_pCodecContext->height;&#xA;    m_pStream->codec->time_base = m_pCodecContext->time_base;&#xA;    m_pStream->codec->bit_rate = m_pCodecContext->bit_rate;&#xA;}&#xA;&#xA;AVFrame* allocatePicture(enum AVPixelFormat pix_fmt, int width, int height)&#xA;{&#xA;    AVFrame *frame;&#xA;&#xA;    frame = av_frame_alloc();&#xA;&#xA;    if (!frame)&#xA;    {&#xA;        return NULL;&#xA;    }&#xA;&#xA;    frame->format = pix_fmt;&#xA;    frame->width = width;&#xA;    frame->height = height;&#xA;&#xA;    int checkImage = av_image_alloc(frame->data, frame->linesize, width, height, pix_fmt, 32);&#xA;&#xA;    if (checkImage &lt; 0)&#xA;    {&#xA;        return NULL;&#xA;    }&#xA;&#xA;    return frame;&#xA;}&#xA;&#xA;bool initialize()&#xA;{&#xA;    AVRational frameRate;&#xA;    frameRate.den = m_frameRate;&#xA;    frameRate.num = 1;&#xA;&#xA;    av_register_all();&#xA;&#xA;    m_pCodec = avcodec_find_encoder_by_name(m_encoderName);&#xA;&#xA;    if (!m_pCodec)&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    m_pCodecContext = avcodec_alloc_context3(m_pCodec);&#xA;    m_pCodecContext->width = m_imageWidth;&#xA;    m_pCodecContext->height = m_imageHeight;&#xA;    m_pCodecContext->time_base = frameRate;&#xA;    m_pCodecContext->gop_size = 0;&#xA;    m_pCodecContext->pix_fmt = m_pixType;&#xA;    m_pCodecContext->codec_id = m_pCodec->id;&#xA;    m_pCodecContext->bit_rate = m_targetBitRate;&#xA;&#xA;    av_opt_set(m_pCodecContext->priv_data, "&#x2B;CBR", "", 0);&#xA;&#xA;    return true;&#xA;}&#xA;&#xA;bool startExport()&#xA;{&#xA;    m_frameIndex = 0;&#xA;    char fakeFileName[512];&#xA;    int checkAllocContext = avformat_alloc_output_context2(&amp;m_pFormatContext, NULL, m_fileType, fakeFileName);&#xA;&#xA;    if (checkAllocContext &lt; 0)&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    if (!m_pFormatContext)&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    m_pFormat = m_pFormatContext->oformat;&#xA;&#xA;    if (m_pFormat->video_codec != AV_CODEC_ID_NONE)&#xA;    {&#xA;        addVideoStream();&#xA;&#xA;        int checkOpen = avcodec_open2(m_pCodecContext, m_pCodec, NULL);&#xA;&#xA;        if (checkOpen &lt; 0)&#xA;        {&#xA;            return false;&#xA;        }&#xA;&#xA;        m_pFrame = allocatePicture(m_pCodecContext->pix_fmt, m_pCodecContext->width, m_pCodecContext->height);&#xA;        if (!m_pFrame)&#xA;        {&#xA;            return false;&#xA;        }&#xA;        m_pFrame->pts = 0;&#xA;    }&#xA;&#xA;    int checkOpen = avio_open(&amp;m_pFormatContext->pb, m_fileName, AVIO_FLAG_WRITE);&#xA;    if (checkOpen &lt; 0)&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    av_dict_set(&amp;(m_pFormatContext->metadata), "title", "QS Test", 0);&#xA;&#xA;    int checkHeader = avformat_write_header(m_pFormatContext, NULL);&#xA;    if (checkHeader &lt; 0)&#xA;    {&#xA;        return false;&#xA;    }&#xA;&#xA;    return true;&#xA;}&#xA;&#xA;int processFrame(AVPacket&amp; avPacket)&#xA;{&#xA;    avPacket.stream_index = 0;&#xA;    avPacket.pts = av_rescale_q(m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base);&#xA;    avPacket.dts = av_rescale_q(m_pFrame->pts, m_pStream->codec->time_base, m_pStream->time_base);&#xA;    m_pFrame->pts&#x2B;&#x2B;;&#xA;&#xA;    int retVal = av_interleaved_write_frame(m_pFormatContext, &amp;avPacket);&#xA;    return retVal;&#xA;}&#xA;&#xA;bool exportFrame()&#xA;{&#xA;    int success = 1;&#xA;    int result = 0;&#xA;&#xA;    AVPacket avPacket;&#xA;&#xA;    av_init_packet(&amp;avPacket);&#xA;    avPacket.data = NULL;&#xA;    avPacket.size = 0;&#xA;&#xA;    AVPacket* avPacket1 = new AVPacket();&#xA;&#xA;    av_init_packet(avPacket1);&#xA;    avPacket1->data = NULL;&#xA;    avPacket1->size = 0;&#xA;&#xA;    fflush(stdout);&#xA;&#xA;    std::cout &lt;&lt; "Before avcodec_encode_video2 for frame: " &lt;&lt; m_frameIndex &lt;&lt; std::endl;&#xA;    success = avcodec_encode_video2(m_pCodecContext, &amp;avPacket, m_pFrame, &amp;result);&#xA;    std::cout &lt;&lt; "After avcodec_encode_video2 for frame: " &lt;&lt; m_frameIndex &lt;&lt; std::endl;&#xA;&#xA;    if (result)&#xA;    {&#xA;        success = processFrame(avPacket);&#xA;    }&#xA;&#xA;    av_packet_unref(&amp;avPacket);&#xA;&#xA;    av_free_packet(&amp;avPacket);&#xA;    //av_frame_free(&amp;m_pFrame);&#xA;&#xA;    m_frameIndex&#x2B;&#x2B;;&#xA;    return (success == 0);&#xA;}&#xA;&#xA;void endExport()&#xA;{&#xA;    int result = 0;&#xA;    int success = 0;&#xA;&#xA;    if (m_pFrame)&#xA;    {&#xA;        while (success == 0)&#xA;        {&#xA;            AVPacket avPacket;&#xA;            av_init_packet(&amp;avPacket);&#xA;            avPacket.data = NULL;&#xA;            avPacket.size = 0;&#xA;&#xA;            fflush(stdout);&#xA;            success = avcodec_encode_video2(m_pCodecContext, &amp;avPacket, NULL, &amp;result);&#xA;&#xA;            if (result)&#xA;            {&#xA;                success = processFrame(avPacket);&#xA;            }&#xA;            av_packet_unref(&amp;avPacket);&#xA;&#xA;            if (!result)&#xA;            {&#xA;                break;&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    if (m_pFormatContext)&#xA;    {&#xA;        av_write_trailer(m_pFormatContext);&#xA;&#xA;        if (m_pFrame)&#xA;        {&#xA;            av_frame_free(&amp;m_pFrame);&#xA;        }&#xA;&#xA;        avio_closep(&amp;m_pFormatContext->pb);&#xA;        avformat_free_context(m_pFormatContext);&#xA;        m_pFormatContext = NULL;&#xA;    }&#xA;}&#xA;&#xA;void cleanup()&#xA;{&#xA;    if (m_pFrame || m_pCodecContext)&#xA;    {&#xA;        if (m_pFrame)&#xA;        {&#xA;            av_frame_free(&amp;m_pFrame);&#xA;        }&#xA;&#xA;        if (m_pCodecContext)&#xA;        {&#xA;            avcodec_close(m_pCodecContext);&#xA;            av_free(m_pCodecContext);&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;int main()&#xA;{&#xA;    bool success = true;&#xA;    if (initialize())&#xA;    {&#xA;        if (startExport())&#xA;        {&#xA;            for (int loop = 0; loop &lt; m_frameCount; loop&#x2B;&#x2B;)&#xA;            {&#xA;                if (!exportFrame())&#xA;                {&#xA;                    std::cout &lt;&lt; "Failed to export frame\n";&#xA;                    success = false;&#xA;                    break;&#xA;                }&#xA;            }&#xA;            endExport();&#xA;        }&#xA;        else&#xA;        {&#xA;            std::cout &lt;&lt; "Failed to start export\n";&#xA;            success = false;&#xA;        }&#xA;&#xA;        cleanup();&#xA;    }&#xA;    else&#xA;    {&#xA;        std::cout &lt;&lt; "Failed to initialize export\n";&#xA;        success = false;&#xA;    }&#xA;&#xA;    if (success)&#xA;    {&#xA;        std::cout &lt;&lt; "Successfully exported file\n";&#xA;    }&#xA;    return 1;&#xA;}&#xA;&#xA;&#xA;    ```&#xA;

    &#xA;&#xA;

    When I set the m_imageHeight to 1536, the memory usage is very high. But when set to 1535 or 1537 or other values, the memory usage is normal, can you tell me why ?&#xA;I have navigated to avcodec_encode_video2&#xA;enter link description here&#xA;I am using the code from the link&#xA;I have updated to the latest Intel® Graphics Driver

    &#xA;