Recherche avancée

Médias (2)

Mot : - Tags -/doc2img

Autres articles (38)

  • La sauvegarde automatique de canaux SPIP

    1er avril 2010, par

    Dans le cadre de la mise en place d’une plateforme ouverte, il est important pour les hébergeurs de pouvoir disposer de sauvegardes assez régulières pour parer à tout problème éventuel.
    Pour réaliser cette tâche on se base sur deux plugins SPIP : Saveauto qui permet une sauvegarde régulière de la base de donnée sous la forme d’un dump mysql (utilisable dans phpmyadmin) mes_fichiers_2 qui permet de réaliser une archive au format zip des données importantes du site (les documents, les éléments (...)

  • MediaSPIP v0.2

    21 juin 2013, par

    MediaSPIP 0.2 est la première version de MediaSPIP stable.
    Sa date de sortie officielle est le 21 juin 2013 et est annoncée ici.
    Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
    Comme pour la version précédente, 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 (...)

  • Mise à disposition des fichiers

    14 avril 2011, par

    Par défaut, lors de son initialisation, MediaSPIP ne permet pas aux visiteurs de télécharger les fichiers qu’ils soient originaux ou le résultat de leur transformation ou encodage. Il permet uniquement de les visualiser.
    Cependant, il est possible et facile d’autoriser les visiteurs à avoir accès à ces documents et ce sous différentes formes.
    Tout cela se passe dans la page de configuration du squelette. Il vous faut aller dans l’espace d’administration du canal, et choisir dans la navigation (...)

Sur d’autres sites (4896)

  • FFmpeg encoding in c

    25 décembre 2012, par barisatbas

    I have been working on a project about video summarization on android platfrom. and I am stuck in encoding. I think ;
    first I must convert my frame into RGB Frame, then convert that RGB FRame into YUV Frame. Then encode the frame. After this operations, The output video was so weird. I think I missed something. Here is my las optimized code. Maybe someone has an experiement in this subject.

    Its syntax is changed according to android ndk syntax :

    jint Java_com_test_Test_encodeVideo(JNIEnv* env, jobject javaThis)
    {
        char *flname, *err, *info;
        AVCodec *codec;
        AVCodecContext *c= NULL;
        int i,out_size, size, x, y,z, outbuf_size;
        int frameCount=99;
        FILE *f;
        AVFrame *picture, *yuvFrame;
        uint8_t *outbuf, *picture_buf;
        PPMImage *img;
        const char *destfilename = "/sdcard/new.mp4";
        int             numBytes;
        uint8_t         *buffer;

        av_register_all();
        // must be called before using avcodec lib
        avcodec_init();

        // register all the codecs
        avcodec_register_all();
        log_message("Video encoding\n");

        // find the H263 video encoder
        codec = avcodec_find_encoder(CODEC_ID_H263);
        if (!codec) {
            sprintf(err, "codec not found\n");
            log_message(err);
        }

        c= avcodec_alloc_context();
        picture= avcodec_alloc_frame();
        yuvFrame= avcodec_alloc_frame();

        // get first ppm context. it is because I need width and height values.
        img = getPPM("/sdcard/frame1.ppm");

        c->bit_rate = 400000;
        // resolution must be a multiple of two

        c->width = img->x;
        c->height = img->y;
        free(img);
        // frames per second
        c->time_base= (AVRational){1,25};
        c->gop_size = 10; // emit one intra frame every ten frames
        //c->max_b_frames=1;
        c->pix_fmt = PIX_FMT_YUV420P;
        // open it
        if (avcodec_open(c, codec) < 0){
       log_message("codec couldn't open");
       return -1;
        }
        //destfilename = (*env)->GetStringUTFChars(env, dst, 0);
        f = fopen(destfilename, "wb");
        log_message(destfilename);
        if (!f) {
            sprintf(err, "could not open %s", destfilename);
            log_message(err);
        }

        log_message("after destination file opening");
        // alloc image and output buffer
        outbuf_size = 100000;
        outbuf = malloc(outbuf_size);
        size = c->width * c->height;
        picture_buf = malloc(size * 3); // size for RGB
        picture->data[0] = picture_buf;
        picture->data[1] = picture->data[0] + size;
        picture->data[2] = picture->data[1] + size / 4;
        picture->linesize[0] = c->width;
        picture->linesize[1] = c->width / 2;
        picture->linesize[2] = c->width / 2;

        numBytes=avpicture_get_size(PIX_FMT_YUV420P, c->width,
                 c->height);

        buffer=malloc(numBytes);

             // Assign appropriate parts of buffer to image planes in FrameYUV
        avpicture_fill((AVPicture *)yuvFrame, buffer, PIX_FMT_YUV420P,
                 c->width, c->height);
        // encode the video
        log_message("before for loop");
        for(z=1;zsdcard/frame%d.ppm",z);
                            // read the ppm file
                            img = getPPM(flname);
                            picture->data[0] = img->data;
                            // convert the rgb frame into yuv frame
                            rgb2yuv(picture,yuvFrame,c);
                            log_message("translation completed.");
                            // encode the image
                            out_size = avcodec_encode_video(c, outbuf, outbuf_size, yuvFrame);
                            sprintf(info,"encoding frame %3d (size=%5d)\n", z, out_size);
                            log_message(info);
                            fwrite(outbuf, 1, out_size, f);
                            free(img);
        }

        // get the delayed frames
        for(; out_size; i++) {
            //fflush(stdout);
            out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
            sprintf(info,"write frame %3d (size=%5d)\n", i, out_size);
                log_message(info);
            fwrite(outbuf, 1, out_size, f);
        }

        // add sequence end code to have a real mpeg file
        outbuf[0] = 0x00;
        outbuf[1] = 0x00;
        outbuf[2] = 0x01;
        outbuf[3] = 0xb7;
        fwrite(outbuf, 1, 4, f);
        fclose(f);
        free(picture_buf);
        free(outbuf);

        avcodec_close(c);
        av_free(c);
        av_free(picture);
        av_free(yuvFrame);
    }

    int rgb2yuv(AVFrame *frameRGB, AVFrame *frameYUV, AVCodecContext *c)
    {
           char *err;
           static struct SwsContext *img_convert_ctx;


           log_message("conversion starts");
           // Convert the image into YUV format from RGB format
           if(img_convert_ctx == NULL) {
                   int w = c->width;
                   int h = c->height;

                   img_convert_ctx = sws_getContext(w, h, PIX_FMT_RGB24,w, h, c->pix_fmt, SWS_BICUBIC,NULL, NULL, NULL);

                   if(img_convert_ctx == NULL) {
                           sprintf(err, "Cannot initialize the conversion context!\n");
                           log_message(err);
                           return -1;
                   }
           }
     int ret = sws_scale(img_convert_ctx,frameRGB->data, frameRGB->linesize , 0,c->height,frameYUV->data, frameYUV->linesize );
           return;
    }
  • libavcodec : how to encode with h264 codec ,with mp4 container using controllable frame rate and bitrate(through c code)

    26 mai 2016, par musimbate

    I am trying to record the screen of a pc and encode the recorded frames using h264 encoder
    and wrap them into a mp4 container.I want to do this because this super user link http://superuser.com/questions/300897/what-is-a-codec-e-g-divx-and-how-does-it-differ-from-a-file-format-e-g-mp/300997#300997 suggests it allows good trade-off between size and quality of the output file.

    The application I am working on should allow users to record a few hours of video and have the minimum output file size with decent quality.

    The code I have cooked up so far allows me to record and save .mpg(container) files with the mpeg1video encoder

    Running :

    ffmpeg -i test.mpg

    on the output file gives the following output :

    [mpegvideo @ 028c7400] Estimating duration from bitrate, this may be inaccurate
    Input #0, mpegvideo, from 'test.mpg':
     Duration: 00:00:00.29, bitrate: 104857 kb/s
       Stream #0:0: Video: mpeg1video, yuv420p(tv), 1366x768 [SAR 1:1 DAR 683:384], 104857 kb/s, 25 fps, 25 tbr, 1200k tbn, 25 tbc

    I have these settings for my output :

    const char * filename="test.mpg";
       int codec_id= AV_CODEC_ID_MPEG1VIDEO;
       AVCodec *codec11;
       AVCodecContext *outContext= NULL;
       int got_output;
       FILE *f;
       AVPacket pkt;
       uint8_t endcode[] = { 0, 0, 1, 0xb7 };

       /* put sample parameters */
       outContext->bit_rate = 400000;
       /* resolution must be a multiple of two */
       outContext->width=pCodecCtx->width;
       outContext->height=pCodecCtx->height;
       /* frames per second */
       outContext->time_base.num=1;
       outContext->time_base.den=25;
       /* emit one intra frame every ten frames
        * check frame pict_type before passing frame
        * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
        * then gop_size is ignored and the output of encoder
        * will always be I frame irrespective to gop_size
        */
       outContext->gop_size = 10;
       outContext->max_b_frames = 1;
       outContext->pix_fmt = AV_PIX_FMT_YUV420P;

    When I change int codec_id= AV_CODEC_ID_MPEG1VIDEO to int codec_id= AV_CODEC_ID_H264 i get a file that does not play with vlc.

    I have read that writing the

    uint8_t endcode[] = { 0, 0, 1, 0xb7 };

    array at the end of your file when finished encoding makes your file a legitimate mpeg file.It is written like this :

    fwrite(endcode, 1, sizeof(endcode), f);
       fclose(f);

    in my code. Should I do the same thing when I change my encoder to AV_CODEC_ID_H264 ?

    I am capturing using gdi input like this :

    AVDictionary* options = NULL;
       //Set some options
       //grabbing frame rate
       av_dict_set(&options,"framerate","30",0);
       AVInputFormat *ifmt=av_find_input_format("gdigrab");
       if(avformat_open_input(&pFormatCtx,"desktop",ifmt,&options)!=0){
           printf("Couldn't open input stream.\n");
           return -1;
           }

    I want to be able to modify my grabbing rate to optimize for the outptut file size
    but When I change it to 20 for example I get a video that plays so fast.How do
    I get a video that plays with normal speed with frames captured at 20 fps or any
    lower frame rate value ?

    While recording I get the following output on the standard error output :

    [gdigrab @ 00cdb8e0] Capturing whole desktop as 1366x768x32 at (0,0)
    Input #0, gdigrab, from '(null)':
     Duration: N/A, start: 1420718663.655713, bitrate: 1006131 kb/s
       Stream #0:0: Video: bmp, bgra, 1366x768, 1006131 kb/s, 29.97 tbr, 1000k tbn, 29.97 tbc
    [swscaler @ 00d24120] Warning: data is not aligned! This can lead to a speedloss
    [mpeg1video @ 00cdd160] AVFrame.format is not set
    [mpeg1video @ 00cdd160] AVFrame.width or height is not set
    [mpeg1video @ 00cdd160] AVFrame.format is not set
    [mpeg1video @ 00cdd160] AVFrame.width or height is not set
    [mpeg1video @ 00cdd160] AVFrame.format is not set

    How do I get rid of this error in my code ?

    In summary :
    1) How do I encode h264 video wrapped into mp4 container ?

    2) How do I capture at lower frame rates and still play
    the encoded video at normal speed ?

    3) How do I set the format(and which format—depends on the codec ?)
    and width and height info on the frames I write ?

    The code I am using in its entirety is shown below

    extern "C"
    {
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
    #include "libswscale/swscale.h"
    #include "libavdevice/avdevice.h"


    #include <libavutil></libavutil>opt.h>
    #include <libavutil></libavutil>channel_layout.h>
    #include <libavutil></libavutil>common.h>
    #include <libavutil></libavutil>imgutils.h>
    #include <libavutil></libavutil>mathematics.h>
    #include <libavutil></libavutil>samplefmt.h>
    //SDL
    #include "SDL.h"
    #include "SDL_thread.h"
    }

    //Output YUV420P
    #define OUTPUT_YUV420P 0
    //'1' Use Dshow
    //'0' Use GDIgrab
    #define USE_DSHOW 0

    int main(int argc, char* argv[])
    {

       //1.WE HAVE THE FORMAT CONTEXT
       //THIS IS FROM THE DESKTOP GRAB STREAM.
       AVFormatContext *pFormatCtx;
       int             i, videoindex;
       AVCodecContext  *pCodecCtx;
       AVCodec         *pCodec;

       av_register_all();
       avformat_network_init();

       //ASSIGN STH TO THE FORMAT CONTEXT.
       pFormatCtx = avformat_alloc_context();

       //Register Device
       avdevice_register_all();
       //Windows
    #ifdef _WIN32
    #if USE_DSHOW
       //Use dshow
       //
       //Need to Install screen-capture-recorder
       //screen-capture-recorder
       //Website: http://sourceforge.net/projects/screencapturer/
       //
       AVInputFormat *ifmt=av_find_input_format("dshow");
       //if(avformat_open_input(&amp;pFormatCtx,"video=screen-capture-recorder",ifmt,NULL)!=0){
       if(avformat_open_input(&amp;pFormatCtx,"video=UScreenCapture",ifmt,NULL)!=0){
           printf("Couldn't open input stream.\n");
           return -1;
       }
    #else
       //Use gdigrab
       AVDictionary* options = NULL;
       //Set some options
       //grabbing frame rate
       av_dict_set(&amp;options,"framerate","30",0);
       //The distance from the left edge of the screen or desktop
       //av_dict_set(&amp;options,"offset_x","20",0);
       //The distance from the top edge of the screen or desktop
       //av_dict_set(&amp;options,"offset_y","40",0);
       //Video frame size. The default is to capture the full screen
       //av_dict_set(&amp;options,"video_size","640x480",0);
       AVInputFormat *ifmt=av_find_input_format("gdigrab");
       if(avformat_open_input(&amp;pFormatCtx,"desktop",ifmt,&amp;options)!=0){
           printf("Couldn't open input stream.\n");
           return -1;
       }

    #endif
    #endif//FOR THE WIN32 THING.

       if(avformat_find_stream_info(pFormatCtx,NULL)&lt;0)
       {
           printf("Couldn't find stream information.\n");
           return -1;
       }
       videoindex=-1;
       for(i=0; inb_streams; i++)
           if(pFormatCtx->streams[i]->codec->codec_type
                   ==AVMEDIA_TYPE_VIDEO)
           {
               videoindex=i;
               break;
           }
       if(videoindex==-1)
       {
           printf("Didn't find a video stream.\n");
           return -1;
       }
       pCodecCtx=pFormatCtx->streams[videoindex]->codec;
       pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
       if(pCodec==NULL)
       {
           printf("Codec not found.\n");
           return -1;
       }
       if(avcodec_open2(pCodecCtx, pCodec,NULL)&lt;0)
       {
           printf("Could not open codec.\n");
           return -1;
       }

       //THIS IS WHERE YOU CONTROL THE FORMAT(THROUGH FRAMES).
       AVFrame *pFrame;

       pFrame=av_frame_alloc();

       int ret, got_picture;

       AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));

       //TRY TO INIT THE PACKET HERE
        av_init_packet(packet);


       //Output Information-----------------------------
       printf("File Information---------------------\n");
       av_dump_format(pFormatCtx,0,NULL,0);
       printf("-------------------------------------------------\n");


    //&lt;&lt;--FOR WRITING MPG FILES
       //&lt;&lt;--START:PREPARE TO WRITE YOUR MPG FILE.

       const char * filename="test.mpg";
       int codec_id= AV_CODEC_ID_MPEG1VIDEO;



       AVCodec *codec11;
       AVCodecContext *outContext= NULL;
       int got_output;
       FILE *f;
       AVPacket pkt;
       uint8_t endcode[] = { 0, 0, 1, 0xb7 };

       printf("Encode video file %s\n", filename);

       /* find the mpeg1 video encoder */
       codec11 = avcodec_find_encoder((AVCodecID)codec_id);
       if (!codec11) {
           fprintf(stderr, "Codec not found\n");
           exit(1);
       }

       outContext = avcodec_alloc_context3(codec11);
       if (!outContext) {
           fprintf(stderr, "Could not allocate video codec context\n");
           exit(1);
       }

       /* put sample parameters */
       outContext->bit_rate = 400000;
       /* resolution must be a multiple of two */

       outContext->width=pCodecCtx->width;
       outContext->height=pCodecCtx->height;


       /* frames per second */
       outContext->time_base.num=1;
       outContext->time_base.den=25;

       /* emit one intra frame every ten frames
        * check frame pict_type before passing frame
        * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
        * then gop_size is ignored and the output of encoder
        * will always be I frame irrespective to gop_size
        */
       outContext->gop_size = 10;
       outContext->max_b_frames = 1;
       outContext->pix_fmt = AV_PIX_FMT_YUV420P;

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

       /* open it */
       if (avcodec_open2(outContext, codec11, NULL) &lt; 0) {
           fprintf(stderr, "Could not open codec\n");
           exit(1);
       }

       f = fopen(filename, "wb");
       if (!f) {
           fprintf(stderr, "Could not open %s\n", filename);
           exit(1);
       }


       AVFrame *outframe = av_frame_alloc();
       int nbytes = avpicture_get_size(outContext->pix_fmt,
                                      outContext->width,
                                      outContext->height);

       uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes);

      //ASSOCIATE THE FRAME TO THE ALLOCATED BUFFER.
       avpicture_fill((AVPicture*)outframe, outbuffer,
                      AV_PIX_FMT_YUV420P,
                      outContext->width, outContext->height);

       SwsContext* swsCtx_ ;
       swsCtx_= sws_getContext(pCodecCtx->width,
                               pCodecCtx->height,
                               pCodecCtx->pix_fmt,
                               outContext->width, outContext->height,
                               outContext->pix_fmt,
                               SWS_BICUBIC, NULL, NULL, NULL);


       //HERE WE START PULLING PACKETS FROM THE SPECIFIED FORMAT CONTEXT.
       while(av_read_frame(pFormatCtx, packet)>=0)
       {
           if(packet->stream_index==videoindex)
           {
               ret= avcodec_decode_video2(pCodecCtx,
                                            pFrame,
                                            &amp;got_picture,packet );
               if(ret &lt; 0)
               {
                   printf("Decode Error.\n");
                   return -1;
               }
               if(got_picture)
               {

               sws_scale(swsCtx_, pFrame->data, pFrame->linesize,
                     0, pCodecCtx->height, outframe->data,
                     outframe->linesize);


               av_init_packet(&amp;pkt);
               pkt.data = NULL;    // packet data will be allocated by the encoder
               pkt.size = 0;


               ret = avcodec_encode_video2(outContext, &amp;pkt, outframe, &amp;got_output);
               if (ret &lt; 0) {
                  fprintf(stderr, "Error encoding frame\n");
                  exit(1);
                 }

               if (got_output) {
                   printf("Write frame %3d (size=%5d)\n", i, pkt.size);
                   fwrite(pkt.data, 1, pkt.size, f);
                   av_free_packet(&amp;pkt);
                  }

               }
           }

           av_free_packet(packet);
       }//THE LOOP TO PULL PACKETS FROM THE FORMAT CONTEXT ENDS HERE.



       //
       /* get the delayed frames */
       for (got_output = 1; got_output; i++) {
           //fflush(stdout);

           ret = avcodec_encode_video2(outContext, &amp;pkt, NULL, &amp;got_output);
           if (ret &lt; 0) {
               fprintf(stderr, "Error encoding frame\n");
               exit(1);
           }

           if (got_output) {
               printf("Write frame %3d (size=%5d)\n", i, pkt.size);
               fwrite(pkt.data, 1, pkt.size, f);
               av_free_packet(&amp;pkt);
           }
       }



       /* add sequence end code to have a real mpeg file */
       fwrite(endcode, 1, sizeof(endcode), f);
       fclose(f);

       avcodec_close(outContext);
       av_free(outContext);
       //av_freep(&amp;frame->data[0]);
       //av_frame_free(&amp;frame);

       //THIS WAS ADDED LATER
       av_free(outbuffer);

       avcodec_close(pCodecCtx);
       avformat_close_input(&amp;pFormatCtx);

       return 0;
    }

    Thank you for your time.

  • FFMPEG Encoding Issues

    16 octobre 2014, par madprogrammer2015

    I am having issues encoding screen captures, into a h.264 file for viewing. The program below is cobbled together from examples here and here. The first example, uses an older version of the ffmpeg api. So I tried to update that example for use in my program. The file is created and has something written to it, but when I view the file. The encoded images are all distorted. I am able to run the video encoding example from the ffmpeg api successfully. This is my first time posting, so if I missed anything please let me know.

    I appreciate any assistance that is given.

    My program :

    #include
    #include <string>
    #include <sstream>
    #include
    #include <iostream>
    #include

    extern "C"{
    #include
    #include <libavcodec></libavcodec>avcodec.h>
    #include <libavutil></libavutil>imgutils.h>
    #include <libswscale></libswscale>swscale.h>
    #include <libavutil></libavutil>opt.h>
    }

    using namespace std;

    void ScreenShot(const char* BmpName, uint8_t *frame)
    {
       HWND DesktopHwnd = GetDesktopWindow();
       RECT DesktopParams;
       HDC DevC = GetDC(DesktopHwnd);
       GetWindowRect(DesktopHwnd,&amp;DesktopParams);
       DWORD Width = DesktopParams.right - DesktopParams.left;
       DWORD Height = DesktopParams.bottom - DesktopParams.top;

       DWORD FileSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+(sizeof(RGBTRIPLE)+1*(Width*Height*4));
       char *BmpFileData = (char*)GlobalAlloc(0x0040,FileSize);

       PBITMAPFILEHEADER BFileHeader = (PBITMAPFILEHEADER)BmpFileData;
       PBITMAPINFOHEADER  BInfoHeader = (PBITMAPINFOHEADER)&amp;BmpFileData[sizeof(BITMAPFILEHEADER)];

       BFileHeader->bfType = 0x4D42; // BM
       BFileHeader->bfSize = sizeof(BITMAPFILEHEADER);
       BFileHeader->bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

       BInfoHeader->biSize = sizeof(BITMAPINFOHEADER);
       BInfoHeader->biPlanes = 1;
       BInfoHeader->biBitCount = 32;
       BInfoHeader->biCompression = BI_RGB;
       BInfoHeader->biHeight = Height;
       BInfoHeader->biWidth = Width;

       RGBTRIPLE *Image = (RGBTRIPLE*)&amp;BmpFileData[sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)];
       RGBTRIPLE color;
       //pPixels = (RGBQUAD **)new RGBQUAD[sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)];
       int start = clock();

       HDC CaptureDC = CreateCompatibleDC(DevC);
       HBITMAP CaptureBitmap = CreateCompatibleBitmap(DevC,Width,Height);
       SelectObject(CaptureDC,CaptureBitmap);
       BitBlt(CaptureDC,0,0,Width,Height,DevC,0,0,SRCCOPY|CAPTUREBLT);
       GetDIBits(CaptureDC,CaptureBitmap,0,Height,frame,(LPBITMAPINFO)BInfoHeader, DIB_RGB_COLORS);

       int end = clock();

       cout &lt;&lt; "it took " &lt;&lt; end - start &lt;&lt; " to capture a frame" &lt;&lt; endl;

       DWORD Junk;
       HANDLE FH = CreateFileA(BmpName,GENERIC_WRITE,FILE_SHARE_WRITE,0,CREATE_ALWAYS,0,0);
       WriteFile(FH,BmpFileData,FileSize,&amp;Junk,0);
       CloseHandle(FH);
       GlobalFree(BmpFileData);
    }

    void video_encode_example(const char *filename, int codec_id)
    {
       AVCodec *codec;
       AVCodecContext *c= NULL;
       int i, ret, x, y, got_output;
       FILE *f;
       AVFrame *frame;
       AVPacket pkt;
       uint8_t endcode[] = { 0, 0, 1, 0xb7 };

       printf("Encode video file %s\n", filename);

       /* find the mpeg1 video encoder */
       codec = avcodec_find_encoder(AV_CODEC_ID_H264);
       if (!codec) {
           fprintf(stderr, "Codec not found\n");
           cin.get();
           exit(1);
       }

       c = avcodec_alloc_context3(codec);
       if (!c) {
           fprintf(stderr, "Could not allocate video codec context\n");
           cin.get();
           exit(1);
       }

       /* put sample parameters */
       c->bit_rate = 400000;
       /* resolution must be a multiple of two */
       c->width = 352;
       c->height = 288;
       /* frames per second */
       c->time_base.num=1;
       c->time_base.den = 25;
       c->gop_size = 10; /* emit one intra frame every ten frames */
       c->max_b_frames=1;
       c->pix_fmt = AV_PIX_FMT_YUV420P;

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

       /* open it */
       if (avcodec_open2(c, codec, NULL) &lt; 0) {
           fprintf(stderr, "Could not open codec\n");
           exit(1);
       }

       f = fopen(filename, "wb");
       if (!f) {
           fprintf(stderr, "Could not open %s\n", filename);
           exit(1);
       }

       frame = av_frame_alloc();
       if (!frame) {
           fprintf(stderr, "Could not allocate video frame\n");
           exit(1);
       }

       frame->format = c->pix_fmt;
       frame->width  = c->width;
       frame->height = c->height;

       /* the image can be allocated by any means and av_image_alloc() is
       just the most convenient way if av_malloc() is to be used */
       ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height, c->pix_fmt, 32);

       if (ret &lt; 0) {
           fprintf(stderr, "Could not allocate raw picture buffer\n");
           exit(1);
       }

       /* encode 1 second of video */
       for(i=0;i&lt;250;i++) {
           av_init_packet(&amp;pkt);
           pkt.data = NULL;    // packet data will be allocated by the encoder
           pkt.size = 0;

           fflush(stdout);
           /* prepare a dummy image */
           /* Y */
           for(y=0;yheight;y++) {
               for(x=0;xwidth;x++) {
                   frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
               }
           }

           /* Cb and Cr */
           for(y=0;yheight/2;y++) {
               for(x=0;xwidth/2;x++) {
                   frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                   frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
               }
           }

           frame->pts = i;

           /* encode the image */
           ret = avcodec_encode_video2(c, &amp;pkt, frame, &amp;got_output);
           if (ret &lt; 0) {
               fprintf(stderr, "Error encoding frame\n");
               exit(1);
           }

           if (got_output) {
               printf("Write frame %3d (size=%5d)\n", i, pkt.size);
               fwrite(pkt.data, 1, pkt.size, f);
               av_free_packet(&amp;pkt);
           }
       }

       /* get the delayed frames */
       for (got_output = 1; got_output; i++) {
           fflush(stdout);

           ret = avcodec_encode_video2(c, &amp;pkt, NULL, &amp;got_output);

           if (ret &lt; 0) {
               fprintf(stderr, "Error encoding frame\n");
               exit(1);
           }

           if (got_output) {
               printf("Write frame %3d (size=%5d)\n", i, pkt.size);
               fwrite(pkt.data, 1, pkt.size, f);
               av_free_packet(&amp;pkt);
           }
       }

       /* add sequence end code to have a real mpeg file */
       fwrite(endcode, 1, sizeof(endcode), f);
       fclose(f);

        avcodec_close(c);
        av_free(c);
        av_freep(&amp;frame->data[0]);
        av_frame_free(&amp;frame);
        printf("\n");
    }

    void write_video_frame()
    {
    }

    int lineSizeOfFrame(int width)
    {
       return  (width*24 + 31)/32 * 4;//((width*24 / 8) + 3) &amp; ~3;//(width*24 + 31)/32 * 4;
    }

    int getScreenshotWithCursor(uint8_t* frame)
    {
       int successful = 0;
           HDC screen, bitmapDC;
           HBITMAP screen_bitmap;

           screen = GetDC(NULL);
           RECT DesktopParams;

           HWND desktop = GetDesktopWindow();
           GetWindowRect(desktop, &amp;DesktopParams);

           int width = DesktopParams.right;
           int height = DesktopParams.bottom;

           bitmapDC = CreateCompatibleDC(screen);
           screen_bitmap = CreateCompatibleBitmap(screen, width, height);
           SelectObject(bitmapDC, screen_bitmap);
           if (BitBlt(bitmapDC, 0, 0, width, height, screen, 0, 0, SRCCOPY))
           {
                   int pos_x, pos_y;
                   HICON hcur;
                   ICONINFO icon_info;
                   CURSORINFO cursor_info;
                   cursor_info.cbSize = sizeof(CURSORINFO);
                   if (GetCursorInfo(&amp;cursor_info))
                   {
                           if (cursor_info.flags == CURSOR_SHOWING)
                           {
                                   hcur = CopyIcon(cursor_info.hCursor);
                                   if (GetIconInfo(hcur, &amp;icon_info))
                                   {
                                           pos_x = cursor_info.ptScreenPos.x - icon_info.xHotspot;
                                           pos_y = cursor_info.ptScreenPos.y - icon_info.yHotspot;
                                           DrawIcon(bitmapDC, pos_x, pos_y, hcur);
                                           if (icon_info.hbmColor) DeleteObject(icon_info.hbmColor);
                                           if (icon_info.hbmMask) DeleteObject(icon_info.hbmMask);
                                   }
                           }
                   }
                   int header_size = sizeof(BITMAPINFOHEADER) + 256*sizeof(RGBQUAD);
                   size_t line_size = lineSizeOfFrame(width);
                   PBITMAPINFO lpbi = (PBITMAPINFO) malloc(header_size);
                   lpbi->bmiHeader.biSize = header_size;
                   lpbi->bmiHeader.biWidth = width;
                   lpbi->bmiHeader.biHeight = height;
                   lpbi->bmiHeader.biPlanes = 1;
                   lpbi->bmiHeader.biBitCount = 24;
                   lpbi->bmiHeader.biCompression = BI_RGB;
                   lpbi->bmiHeader.biSizeImage = height*line_size;
                   lpbi->bmiHeader.biXPelsPerMeter = 0;
                   lpbi->bmiHeader.biYPelsPerMeter = 0;
                   lpbi->bmiHeader.biClrUsed = 0;
                   lpbi->bmiHeader.biClrImportant = 0;
                   if (GetDIBits(bitmapDC, screen_bitmap, 0, height, (LPVOID)frame, lpbi, DIB_RGB_COLORS))
                   {
                       int i;
                       uint8_t *buf_begin = frame;
                       uint8_t *buf_end = frame + line_size*(lpbi->bmiHeader.biHeight - 1);
                       void *temp = malloc(line_size);
                       for (i = 0; i &lt; lpbi->bmiHeader.biHeight / 2; ++i)
                       {
                           memcpy(temp, buf_begin, line_size);
                           memcpy(buf_begin, buf_end, line_size);
                           memcpy(buf_end, temp, line_size);
                           buf_begin += line_size;
                           buf_end -= line_size;
                       }
                       cout &lt;&lt; *buf_begin &lt;&lt; endl;
                       free(temp);
                       successful = 1;
                   }
                   free(lpbi);
           }
           DeleteObject(screen_bitmap);
           DeleteDC(bitmapDC);
           ReleaseDC(NULL, screen);
           return successful;
    }

    int main()
    {
       RECT DesktopParams;

       HWND desktop = GetDesktopWindow();
       GetWindowRect(desktop, &amp;DesktopParams);

       int width = DesktopParams.right;
       int height = DesktopParams.bottom;
       uint8_t *frame = (uint8_t *)malloc(width * height);

       AVCodec *codec;
       AVCodecContext *codecContext = NULL;
       AVPacket packet;
       FILE *f;
       AVFrame *pictureYUV = NULL;
       AVFrame *pictureRGB;

       avcodec_register_all();

       codec = avcodec_find_encoder(AV_CODEC_ID_H264);

       if(!codec)
       {
           cout &lt;&lt; "codec not found!" &lt;&lt; endl;
           cin.get();
           return 1;
       }
       else
       {
           cout &lt;&lt; "codec h265 found!" &lt;&lt; endl;
       }

       codecContext = avcodec_alloc_context3(codec);

       codecContext->bit_rate = width * height * 4;
       codecContext->width = width;
       codecContext->height = height;
       codecContext->time_base.num = 1;
       codecContext->time_base.den = 250;
       codecContext->gop_size = 10;
       codecContext->max_b_frames = 1;
       codecContext->keyint_min = 1;
       codecContext->i_quant_factor = (float)0.71;                        // qscale factor between P and I frames
       codecContext->b_frame_strategy = 20;                               ///// find out exactly what this does
       codecContext->qcompress = (float)0.6;                              ///// find out exactly what this does
       codecContext->qmin = 20;                                           // minimum quantizer
       codecContext->qmax = 51;                                           // maximum quantizer
       codecContext->max_qdiff = 4;                                       // maximum quantizer difference between frames
       codecContext->refs = 4;                                            // number of reference frames
       codecContext->trellis = 1;
       codecContext->pix_fmt = AV_PIX_FMT_YUV420P;
       codecContext->codec_id = AV_CODEC_ID_H264;
       codecContext->codec_type = AVMEDIA_TYPE_VIDEO;

       if(avcodec_open2(codecContext, codec, NULL) &lt; 0)
       {
           cout &lt;&lt; "couldn't open codec" &lt;&lt; endl;
           cout &lt;&lt; stderr &lt;&lt; endl;
           cin.get();
           return 1;
       }
       else
       {
           cout &lt;&lt; "opened h265 codec!" &lt;&lt; endl;
           cin.get();
       }

       f = fopen("test.h264", "wb");

       if(!f)
       {
           cout &lt;&lt; "Unable to open file" &lt;&lt; endl;
           return 1;
       }



       struct SwsContext *img_convert_ctx = sws_getContext(codecContext->width, codecContext->height, PIX_FMT_RGB32, codecContext->width,
           codecContext->height, codecContext->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL);

       int got_output = 0, i = 0;
       uint8_t encode[] = { 0, 0, 1, 0xb7 };

       try
       {
           for(i = 0; i &lt; codecContext->time_base.den; i++)
           {
               av_init_packet(&amp;packet);
               packet.data = NULL;
               packet.size = 0;

               pictureRGB = av_frame_alloc();
               pictureYUV = av_frame_alloc();

               getScreenshotWithCursor(frame);
               //ScreenShot("example.bmp", frame);

               int nbytes = avpicture_get_size(AV_PIX_FMT_YUV420P, codecContext->width, codecContext->height);                                    // allocating outbuffer
               uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes*sizeof(uint8_t));

               pictureRGB = av_frame_alloc();
               pictureYUV = av_frame_alloc();

               avpicture_fill((AVPicture*)pictureRGB, frame, PIX_FMT_RGB32, codecContext->width, codecContext->height);                   // fill image with input screenshot
               avpicture_fill((AVPicture*)pictureYUV, outbuffer, PIX_FMT_YUV420P, codecContext->width, codecContext->height);
               av_image_alloc(pictureYUV->data, pictureYUV->linesize, codecContext->width, codecContext->height, codecContext->pix_fmt, 32);

               sws_scale(img_convert_ctx, pictureRGB->data, pictureRGB->linesize, 0, codecContext->height, pictureYUV->data, pictureYUV->linesize);

               pictureYUV->pts = i;

               avcodec_encode_video2(codecContext, &amp;packet, pictureYUV, &amp;got_output);

               if(got_output)
               {
                   printf("Write frame %3d (size=%5d)\n", i, packet.size);
                   fwrite(packet.data, 1, packet.size, f);
                   av_free_packet(&amp;packet);
               }

               //av_frame_free(&amp;pictureRGB);
               //av_frame_free(&amp;pictureYUV);
           }

           for(got_output = 1; got_output; i++)
           {
               fflush(stdout);

               avcodec_encode_video2(codecContext, &amp;packet, NULL, &amp;got_output);

               if (got_output) {
                   printf("Write frame %3d (size=%5d)\n", i, packet.size);
                   fwrite(packet.data, 1, packet.size, f);
                   av_free_packet(&amp;packet);
               }
           }
       }
       catch(std::exception ex)
       {
           cout &lt;&lt; ex.what() &lt;&lt; endl;
       }

       avcodec_close(codecContext);
       av_free(codecContext);
       av_freep(&amp;pictureYUV->data[0]);
       //av_frame_free(&amp;picture);
       fwrite(encode, 1, sizeof(encode), f);
       fclose(f);

       cin.get();

       return 0;
    }
    </iostream></sstream></string>