lundi 28 novembre 2016

Can't write YUV Frame from ffmpeg into .yuv file

My goal is to write the frame I decode into a file. I know I capture it well because it shows in my SDL playback and I encode it afterwards without any problems. Yet it seems I can't write the frame into a file properly. Here is the code :

#define PIXFMT AV_PIX_FMT_YUV420P
#define WIDTH 1280
#define HEIGHT 720
// initialize SWS context for software scaling

sws_ctx = sws_getContext(pCodecCtx->width,
    pCodecCtx->height,
    pCodecCtx->pix_fmt,
    WIDTH,
    HEIGHT,
    PIXFMT,
    SWS_LANCZOS,
    NULL,
    NULL,
    NULL
);

FfmpegEncoder enc("rtsp://127.0.0.1:1935/live/myStream", pParser);
//SetPixelArray();

i = 0;
enc.FillYuvImage(pFrameRGB, 0, this->pCodecCtx->width, this->pCodecCtx->height);
FILE *pFile;
while (av_read_frame(pFormatCtx, &packet) >= 0 && !exit) {
    if (packet.stream_index == videoindex) {
        // Decode video frame
        avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);

        if (frameFinished) {

            i++;
            sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
            if (i < 500)
            {
                pFile = fopen(std::string("./screenshots/screen.yuv").c_str(), "a+");
                for (int y = 0; y < pCodecCtx->height; y++)
                {
                    fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, pCodecCtx->width * pCodecCtx->height, pFile);
                    fwrite(pFrame->data[1] + y * pFrame->linesize[1], 1, pCodecCtx->width * pCodecCtx->height / 4, pFile);
                    fwrite(pFrame->data[2] + y * pFrame->linesize[2], 1, pCodecCtx->width * pCodecCtx->height / 4, pFile);
                }
                fclose(pFile);
            }
            enc.encodeFrame(pFrameRGB);
        }
    }
    // Free the packet that was allocated by av_read_frame
    av_free_packet(&packet);
}

The program crashes when it tries to write the frame.

Aucun commentaire:

Enregistrer un commentaire