Crash on ffmpeg avcodec_encode_video in a Console app [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I want make an encoder which encode a raw image into h263 format.But after loading and initializing ffmpeg library I got crash on avcodec_encode_video for a demo image.
int _tmain(int argc, _TCHAR* argv[]) {
avcodec_register_all();
AVCodec *codec;
AVCodecContext *c= NULL;
int i, ret, x, y, got_output;
FILE *f;
AVFrame *frame;
AVPacket pkt;
int out_size, size, outbuf_size;
AVFrame *picture;
uint8_t *outbuf, *picture_buf;
AVRational rp;
rp.den = 1;
rp.num = 25;
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
codec = avcodec_find_encoder(CODEC_ID_H263);
c = avcodec_alloc_context3(codec);
picture= avcodec_alloc_frame();
c->bit_rate = 400000;
/* resolution must be a multiple of two */
c->width = 352;
c->height = 288;
/* frames per second */
//c->time_base= (AVRational){1,25};
c->time_base = rp;
c->gop_size = 10; /* emit one intra frame every ten frames */
c->max_b_frames=1;
c->pix_fmt = PIX_FMT_YUV420P;
avcodec_open(c, codec);
outbuf_size = 100000;
outbuf = (uint8_t*)malloc(outbuf_size);
size = c->width * c->height;
picture_buf = (uint8_t*)malloc((size * 3) / 2); /* size for YUV 420 */
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;
/* encode 1 second of video */
for(i=0;i<25;i++) {
fflush(stdout);
/* prepare a dummy image */
/* Y */
for(y=0;y<c->height;y++) {
for(x=0;x<c->width;x++) {
picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
}
}
/* Cb and Cr */
for(y=0;y<c->height/2;y++) {
for(x=0;x<c->width/2;x++) {
picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
}
}
/* encode the image */
**Crash is here** ---> ///////////////////////////////////////////////////
out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
printf("encoding frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
}
/* get the delayed frames */
for(; out_size; i++) {
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
printf("write frame %3d (size=%5d)\n", i, out_size);
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);
printf("\n");
return 0;
}

My problem solved by adding new library of ffmpeg.
Hope it helps other.Please be up to date.

Related

Access violation writing location 0x00BB9000

I'm currently working on PNG formats. And, I'm trying to understand its characteristics:
width, height, bytewidth, bytes per width, RGB pixel (red, green, blue)
Refering to this and this, width is the resolution width of the image in pixels, height is the resolution height of the image in pixels, bytes per width takes only 8 or 16 as value, RGB pixel's three items takes 0 to 255 as integer value.
But, I cannot understand what's a bytewidth?
Because when I try to convert one bmp image to a png one in C++ I get the following error:
Unhandled exception at 0x01038F6C in Project.exe: 0xC0000005: Access violation writing location 0x00BB9000.
I get this when I initialize the output png characteristics to:
width = 1600,
height = 900,
bytewidth = 1,
bytes per width = 1,
RGB pixel (red = 255, green = 255, blue = 255)
using this code:
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_DEPRECATE
#include <png.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
typedef struct _RGBPixel {
uint8_t blue;
uint8_t green;
uint8_t red;
} RGBPixel;
/* Structure for containing decompressed bitmaps. */
typedef struct _RGBBitmap {
RGBPixel *pixels;
size_t width;
size_t height;
size_t bytewidth;
uint8_t bytes_per_pixel;
} RGBBitmap;
/* Returns pixel of bitmap at given point. */
#define RGBPixelAtPoint(image, x, y) \
*(((image)->pixels) + (((image)->bytewidth * (y)) \
+ ((x) * (image)->bytes_per_pixel)))
/* Attempts to save PNG to file; returns 0 on success, non-zero on error. */
int save_png_to_file(RGBBitmap *bitmap, const char *path)
{
FILE *fp = fopen(path, "wb");
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
size_t x, y;
png_uint_32 bytes_per_row;
png_byte **row_pointers = NULL;
if (fp == NULL) return -1;
/* Initialize the write struct. */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
fclose(fp);
return -1;
}
/* Initialize the info struct. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
return -1;
}
/* Set up error handling. */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return -1;
}
/* Set image attributes. */
png_set_IHDR(png_ptr,
info_ptr,
bitmap->width,
bitmap->height,
8,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
/* Initialize rows of PNG. */
bytes_per_row = bitmap->width * bitmap->bytes_per_pixel;
row_pointers = (png_byte **)png_malloc(png_ptr, bitmap->height * sizeof(png_byte *));
for (y = 0; y < bitmap->height; ++y) {
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel);
row_pointers[y] = (png_byte *)row;
for (x = 0; x < bitmap->width; ++x) {
RGBPixel color = RGBPixelAtPoint(bitmap, x, y);
*row++ = color.red;
*row++ = color.green; /************* MARKED LINE ***************/
*row++ = color.blue;
}
}
/* Actually write the image data. */
png_init_io(png_ptr, fp);
png_set_rows(png_ptr, info_ptr, row_pointers);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* Cleanup. */
for (y = 0; y < bitmap->height; y++) {
png_free(png_ptr, row_pointers[y]);
}
png_free(png_ptr, row_pointers);
/* Finish writing. */
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return 0;
}
int main()
{
RGBBitmap rgbbitmap;
rgbbitmap.height = 1600;
rgbbitmap.width = 900;
rgbbitmap.bytes_per_pixel = 1;
rgbbitmap.bytewidth = 1;
RGBPixel rgbpixel;
rgbpixel.blue = 255;
rgbpixel.green = 255;
rgbpixel.red = 255;
rgbbitmap.pixels = &rgbpixel;
save_png_to_file(&rgbbitmap, "abc.bmp");
return 0;
}
I'm actually getting that error on the marked line.
Any brilliant suggestion, please?
After setting
rgbbitmap.bytes_per_pixel = 3; // was 1 which is probably wrong
Surely
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel);
must be
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel*bitmap->width);
, i.e. each row must hold enough space for all bytes in that row ;-), which is 3 bytes per pixel times pixels in a row. You actually compute that value, bytes_per_row, but for some reason fail to use it.
This
uint8_t *row = (uint8_t *)png_malloc(png_ptr, sizeof(uint8_t)* bitmap->bytes_per_pixel);
looks suspicious - I don't know how png_malloc() works, but I guess you're allocating sizeof(uint8_t) * BytesPerPixel (which is probably sizeof(uint8_t) * 4) instead of sizeof(uint8_t) * NumberOfPixels (which should be considerably larger).
I think your rgbbitmap.bytes_per_pixel = 1 is wrong.
If your work in RGB8 your bytes_per_pixel = 3, in RGBA8 is 4 and so on.

Access violation reading location 0x000000148965F000

I tried to encode BMP Images, which i get from a buffer and store it as a H264 Video. I am stuck with these errors the arrive randomly and repeatedly
I am using Visual Studio 2012
1) Access violation reading location 0x000000148965F000.
2)Heap corruption
The debug shows the error at this point
struct SwsContext* fooContext = sws_getContext(_imgWidth,_imgHeight,PIX_FMT_RGB32,c->width,c->height,PIX_FMT_YUV420P, SWS_FAST_BILINEAR,NULL,NULL,NULL);
sws_scale(fooContext, inpic->data, inpic->linesize, 0, c->height, outpic->data, outpic->linesize); // converting frame size and format
I guess the read violation happens due to non - pre initialized values. But i couldnt exactly understand why. I have also attached part of the code below
PagedImage *inImg = getUpdatedInputImage(0);
ML_CHECK(inImg);
ImageVector imgExt = inImg->getImageExtent();
if ((imgExt.x == _imgWidth) && (imgExt.y == _imgHeight))
{
if (((imgExt.x % 4) == 0) && ((imgExt.y % 4) == 0))
{
_numFramesFld->setIntValue(_numFramesFld->getIntValue() + 1);
MLFree(unicodeFilename);
// configure header
//BITMAPINFO bitmapInfo
// read out input image and write output image into video
// get input image as an array
void* imgData = NULL;
SubImageBox imageBox(imgExt); // get the whole image
getTile(inImg, imageBox, MLuint8Type, &imgData);
MLuint8* iData = (MLuint8*)imgData;
// since we have only images with
// a z-ext of 1, we can compute the c stride as follows
int cStride = _imgWidth * _imgHeight;
int offset = 0;
MLuint8 r=0, g=0, b=0;
// pointer into the bitmap that is
// used to write images into an video
UCHAR* dst = (UCHAR*)_bits;
for (int y = _imgHeight-1; y >= 0; y--)
{ // reversely scan the image. if y-rows of DIB are set in normal order, no compression will be available.
offset = _imgWidth * y;
for (int x = 0; x < _imgWidth; x++)
{
if (_isGreyValueImage)
{
r = iData[offset + x];
*dst++ = (UCHAR)r;
*dst++ = (UCHAR)r;
*dst++ = (UCHAR)r;
}
else
{
b = iData[offset + x]; // windows bitmap need reverse order: bgr instead of rgb
g = iData[offset + x + cStride ];
r = iData[offset + x + cStride + cStride];
*dst++ = (UCHAR)r;
*dst++ = (UCHAR)g;
*dst++ = (UCHAR)b;
}
// alpha channel in input image is ignored
}
}
outbuf_size = 100000 + c->width*c->height*(32>>3); // allocate output buffer
outbuf = static_cast<uint8_t *>(malloc(outbuf_size));
fileName_ = (_outputFilenameFld->getStringValue()).c_str();
FILE* f = fopen(fileName_,"wb"); // opening video file for writing
if(!f)
{
_messageFld->setStringValue("Cannot open file");
}
else _messageFld->setStringValue("Opened video file for writing\n");
//for(i=0;i<_numFramesFld->getIntValue();i++)
//{
fflush(stdout);
int nbytes = avpicture_get_size(PIX_FMT_YUV420P, c->width, c->height); // allocating outbuffer
uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes*sizeof(uint8_t));
AVFrame* inpic = avcodec_alloc_frame(); // mandatory frame allocation
AVFrame* outpic = avcodec_alloc_frame();
//outpic->pts = (int64_t)((float)i * (1000.0/((float)(c->time_base.den))) * 90); // setting frame pts
avpicture_fill((AVPicture*)inpic,(uint8_t*)dst, PIX_FMT_RGB32, c->width, c->height); // fill image with input screenshot
avpicture_fill((AVPicture*)outpic, outbuffer, PIX_FMT_YUV420P, c->width, c->height); // clear output picture for buffer copy
av_image_alloc(outpic->data, outpic->linesize, c->width, c->height, c->pix_fmt, 1);
inpic->data[0] += inpic->linesize[0]*(c->height-1); // flipping frame
inpic->linesize[0] = -inpic->linesize[0]; // flipping frame
struct SwsContext* fooContext = sws_getContext(_imgWidth,_imgHeight,PIX_FMT_RGB32,c->width,c->height,PIX_FMT_YUV420P, SWS_FAST_BILINEAR,NULL,NULL,NULL);
sws_scale(fooContext, inpic->data, inpic->linesize, 0, c->height, outpic->data, outpic->linesize); // converting frame size and format
out_size = avcodec_encode_video(c, outbuf, outbuf_size, outpic); // encoding video
_messageFld->setStringValue("Encoding frame %3d (size=%5d)\n");
fwrite(outbuf, 1, out_size, f);
delete [] dst; // freeing memory
av_free(outbuffer);
av_free(inpic);
av_free(outpic);
av_free(fooContext);
DeleteObject(_hbitmap);
for(int Z = 0; Z<out_size; i++)
{
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, outpic); // encode the delayed frames
fwrite(outbuf, 1, out_size, f);
}
//outbuf[0] = 0x00;
//outbuf[1] = 0x00; // add sequence end code to have a real mpeg file
//outbuf[2] = 0x01;
//outbuf[3] = 0xb7;
//fwrite(outbuf, 1, 4, f);
fclose(f);
avcodec_close(c); // freeing memory
free(outbuf);
av_free(c);
printf("Closed codec and Freed\n");
}
}
Access violation could be tricky to debug.
Since you have a Read Access Violation, it could be that somewhere you have run over your pointers with data and only now, when you try to read from there, you get the exception.
I recommend you use GFLAGS with Full PageHeap to pinpoint exactly the location of your AccessViolation:
gflags /p /enable ImageFileName /full.
GFlags and PageHeap
I hope this will help

Encoding a screenshot into a video using FFMPEG

I'm trying to get the pixels from the screen, and encode the screenshot into a video using ffmpeg. I've seen a couple of examples but they either assume you already have the pixel data, or use image file input. It seems like whether I use sws_scale() or not (which is included in the examples I've seen), or whether I'm typecasting a HBITMAP or RGBQUAD* it's telling me that the image src data is bad and is encoding a blank image rather than the screenshot. Is there something I'm missing here?
AVCodec* codec;
AVCodecContext* c = NULL;
AVFrame* inpic;
uint8_t* outbuf, *picture_buf;
int i, out_size, size, outbuf_size;
HBITMAP hBmp;
//int x,y;
avcodec_register_all();
printf("Video encoding\n");
// Find the mpeg1 video encoder
codec = avcodec_find_encoder(CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
else printf("H264 codec found\n");
c = avcodec_alloc_context3(codec);
inpic = avcodec_alloc_frame();
c->bit_rate = 400000;
c->width = screenWidth; // resolution must be a multiple of two
c->height = screenHeight;
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 = PIX_FMT_YUV420P;
c->codec_id = CODEC_ID_H264;
//c->codec_type = AVMEDIA_TYPE_VIDEO;
//av_opt_set(c->priv_data, "preset", "slow", 0);
//printf("Setting presets to slow for performance\n");
// Open the encoder
if (avcodec_open2(c, codec,NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
else printf("H264 codec opened\n");
outbuf_size = 100000 + 12*c->width*c->height; // alloc image and output buffer
//outbuf_size = 100000;
outbuf = static_cast<uint8_t *>(malloc(outbuf_size));
size = c->width * c->height;
picture_buf = static_cast<uint8_t*>(malloc((size*3)/2));
printf("Setting buffer size to: %d\n",outbuf_size);
FILE* f = fopen("example.mpg","wb");
if(!f) printf("x - Cannot open video file for writing\n");
else printf("Opened video file for writing\n");
/*inpic->data[0] = picture_buf;
inpic->data[1] = inpic->data[0] + size;
inpic->data[2] = inpic->data[1] + size / 4;
inpic->linesize[0] = c->width;
inpic->linesize[1] = c->width / 2;
inpic->linesize[2] = c->width / 2;*/
//int x,y;
// encode 1 second of video
for(i=0;i<c->time_base.den;i++) {
fflush(stdout);
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
hBmp = CreateCompatibleBitmap(GetDC(0), screenWidth, screenHeight);
SelectObject(hCaptureDC, hBmp);
BitBlt(hCaptureDC, 0, 0, screenWidth, screenHeight, hDesktopDC, 0, 0, SRCCOPY|CAPTUREBLT);
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = screenWidth;
bmi.bmiHeader.biHeight = screenHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
RGBQUAD *pPixels = new RGBQUAD[screenWidth*screenHeight];
GetDIBits(hCaptureDC,hBmp,0,screenHeight,pPixels,&bmi,DIB_RGB_COLORS);
inpic->pts = (float) i * (1000.0/(float)(c->time_base.den))*90;
avpicture_fill((AVPicture*)inpic, (uint8_t*)pPixels, PIX_FMT_BGR32, c->width, c->height); // Fill picture with image
av_image_alloc(inpic->data, inpic->linesize, c->width, c->height, c->pix_fmt, 1);
//printf("Allocated frame\n");
//SaveBMPFile(L"screenshot.bmp",hBmp,hDc,screenWidth,screenHeight);
ReleaseDC(hDesktopWnd,hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hBmp);
// encode the image
out_size = avcodec_encode_video(c, outbuf, outbuf_size, inpic);
printf("Encoding frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
}
// get the delayed frames
for(; out_size; i++) {
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
printf("Writing frame %3d (size=%5d)\n", i, out_size);
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(inpic);
printf("Closed codec and Freed\n");
I managed to get it working after quite a bit of trial-and-error. I was allocating the image after filling it, which was the first problem. The second problem was that the screenshot was not being created properly, and should have been casted as a COLORREF* rather than an RGBQUAD.
AVCodec* codec;
AVCodecContext* c = NULL;
uint8_t* outbuf;
int i, out_size, outbuf_size;
avcodec_register_all(); // mandatory to register ffmpeg functions
printf("Video encoding\n");
codec = avcodec_find_encoder(CODEC_ID_H264); // finding the H264 encoder
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
else printf("H264 codec found\n");
c = avcodec_alloc_context3(codec);
c->bit_rate = 400000;
c->width = 1280; // resolution must be a multiple of two (1280x720),(1900x1080),(720x480)
c->height = 720;
c->time_base.num = 1; // framerate numerator
c->time_base.den = 25; // framerate denominator
c->gop_size = 10; // emit one intra frame every ten frames
c->max_b_frames = 1; // maximum number of b-frames between non b-frames
c->keyint_min = 1; // minimum GOP size
c->i_quant_factor = (float)0.71; // qscale factor between P and I frames
c->b_frame_strategy = 20; ///// find out exactly what this does
c->qcompress = (float)0.6; ///// find out exactly what this does
c->qmin = 20; // minimum quantizer
c->qmax = 51; // maximum quantizer
c->max_qdiff = 4; // maximum quantizer difference between frames
c->refs = 4; // number of reference frames
c->trellis = 1; // trellis RD Quantization
c->pix_fmt = PIX_FMT_YUV420P; // universal pixel format for video encoding
c->codec_id = CODEC_ID_H264;
c->codec_type = AVMEDIA_TYPE_VIDEO;
if (avcodec_open2(c, codec,NULL) < 0) {
fprintf(stderr, "Could not open codec\n"); // opening the codec
exit(1);
}
else printf("H264 codec opened\n");
outbuf_size = 100000 + c->width*c->height*(32>>3); // allocate output buffer
outbuf = static_cast<uint8_t *>(malloc(outbuf_size));
printf("Setting buffer size to: %d\n",outbuf_size);
FILE* f = fopen("example.mpg","wb"); // opening video file for writing
if(!f) printf("x - Cannot open video file for writing\n");
else printf("Opened video file for writing\n");
// encode video
for(i=0;i<STREAM_FRAME_RATE*STREAM_DURATION;i++) {
fflush(stdout);
screenCap(); // taking screenshot
int nbytes = avpicture_get_size(PIX_FMT_YUV420P, c->width, c->height); // allocating outbuffer
uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes*sizeof(uint8_t));
AVFrame* inpic = avcodec_alloc_frame(); // mandatory frame allocation
AVFrame* outpic = avcodec_alloc_frame();
outpic->pts = (int64_t)((float)i * (1000.0/((float)(c->time_base.den))) * 90); // setting frame pts
avpicture_fill((AVPicture*)inpic, (uint8_t*)pPixels, PIX_FMT_RGB32, c->width, c->height); // fill image with input screenshot
avpicture_fill((AVPicture*)outpic, outbuffer, PIX_FMT_YUV420P, c->width, c->height); // clear output picture for buffer copy
av_image_alloc(outpic->data, outpic->linesize, c->width, c->height, c->pix_fmt, 1);
inpic->data[0] += inpic->linesize[0]*(screenHeight-1); // flipping frame
inpic->linesize[0] = -inpic->linesize[0]; // flipping frame
struct SwsContext* fooContext = sws_getContext(screenWidth, screenHeight, PIX_FMT_RGB32, c->width, c->height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
sws_scale(fooContext, inpic->data, inpic->linesize, 0, c->height, outpic->data, outpic->linesize); // converting frame size and format
out_size = avcodec_encode_video(c, outbuf, outbuf_size, outpic); // encoding video
printf("Encoding frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
delete [] pPixels; // freeing memory
av_free(outbuffer);
av_free(inpic);
av_free(outpic);
}
for(; out_size; i++) {
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL); // encode the delayed frames
printf("Writing frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
}
outbuf[0] = 0x00;
outbuf[1] = 0x00; // add sequence end code to have a real mpeg file
outbuf[2] = 0x01;
outbuf[3] = 0xb7;
fwrite(outbuf, 1, 4, f);
fclose(f);
avcodec_close(c); // freeing memory
free(outbuf);
av_free(c);
printf("Closed codec and Freed\n");

FFMpeg encoded video will only play in FFPlay

I've been debugging my program for a couple of weeks now with the output video only showing a blank screen (was testing with VLC, WMP and WMPClassic). I happened to try using FFPlay and lo and behold the video works perfectly. I've read that this is usually caused by an incorrect pixel format, and that switching to PIX_FMT_YUV420P will make it work universally...but I'm already using that pixel format in the encoding process. Is there anything else that is causing this?
AVCodec* codec;
AVCodecContext* c = NULL;
uint8_t* outbuf;
int i, out_size, outbuf_size;
avcodec_register_all();
printf("Video encoding\n");
// Find the mpeg1 video encoder
codec = avcodec_find_encoder(CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
else printf("H264 codec found\n");
c = avcodec_alloc_context3(codec);
c->bit_rate = 400000;
c->width = 1920; // resolution must be a multiple of two (1280x720),(1900x1080),(720x480)
c->height = 1200;
c->time_base.num = 1; // framerate numerator
c->time_base.den = 25; // framerate denominator
c->gop_size = 10; // emit one intra frame every ten frames
c->max_b_frames = 1; // maximum number of b-frames between non b-frames
//c->keyint_min = 1; // minimum GOP size
//c->i_quant_factor = (float)0.71; // qscale factor between P and I frames
//c->b_frame_strategy = 20;
//c->qcompress = (float)0.6;
//c->qmin = 20; // minimum quantizer
//c->qmax = 51; // maximum quantizer
//c->max_qdiff = 4; // maximum quantizer difference between frames
//c->refs = 4; // number of reference frames
//c->trellis = 1; // trellis RD Quantization
c->pix_fmt = PIX_FMT_YUV420P;
c->codec_id = CODEC_ID_H264;
//c->codec_type = AVMEDIA_TYPE_VIDEO;
// Open the encoder
if (avcodec_open2(c, codec,NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
else printf("H264 codec opened\n");
outbuf_size = 100000 + c->width*c->height*(32>>3);//*(32>>3); // alloc image and output buffer
outbuf = static_cast<uint8_t *>(malloc(outbuf_size));
printf("Setting buffer size to: %d\n",outbuf_size);
FILE* f = fopen("example.mpg","wb");
if(!f) printf("x - Cannot open video file for writing\n");
else printf("Opened video file for writing\n");
// encode 5 seconds of video
for(i=0;i<STREAM_FRAME_RATE*STREAM_DURATION;i++) {
fflush(stdout);
screenCap();
int nbytes = avpicture_get_size(PIX_FMT_YUV420P, c->width, c->height);
uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes*sizeof(uint8_t));
AVFrame* inpic = avcodec_alloc_frame();
AVFrame* outpic = avcodec_alloc_frame();
outpic->pts = (int64_t)((float)i * (1000.0/((float)(c->time_base.den))) * 90);
avpicture_fill((AVPicture*)inpic, (uint8_t*)pPixels, PIX_FMT_RGB32, c->width, c->height); // Fill picture with image
avpicture_fill((AVPicture*)outpic, outbuffer, PIX_FMT_YUV420P, c->width, c->height);
av_image_alloc(outpic->data, outpic->linesize, c->width, c->height, c->pix_fmt, 1);
inpic->data[0] += inpic->linesize[0]*(screenHeight-1); // Flipping frame
inpic->linesize[0] = -inpic->linesize[0]; // Flipping frame
struct SwsContext* fooContext = sws_getContext(screenWidth, screenHeight, PIX_FMT_RGB32, c->width, c->height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
sws_scale(fooContext, inpic->data, inpic->linesize, 0, c->height, outpic->data, outpic->linesize);
// encode the image
out_size = avcodec_encode_video(c, outbuf, outbuf_size, outpic);
printf("Encoding frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
delete [] pPixels;
av_free(outbuffer);
av_free(inpic);
av_free(outpic);
}
// get the delayed frames
for(; out_size; i++) {
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
printf("Writing frame %3d (size=%5d)\n", i, out_size);
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);
avcodec_close(c);
free(outbuf);
av_free(c);
printf("Closed codec and Freed\n");
Try saving your file as example.h264, instead of example.mpg.

Problems encoding to .MP4 using ffmpeg

So I'm kind of new to this, I'm writing a WIN32 app that records video to .AVI, then I planned to use ffmpeg to encode to .MP4. Based on a sample I found, I got this far. It compiles and says that it encoded and wrote the file but the output file can't be opened and played. I tried using MPEG1 encoding like the original sample was using but it only gives me weird colors for a few seconds.
Am I missing something that should be done with the file?
Anyone with experience in encoding/ffmpeg, some pointers, advice or help would make me outmost grateful. Thanks in advance!
int _tmain(int argc, _TCHAR* argv[])
{
AVFormatContext *pFormatCtx;
int codec_id = CODEC_ID_MPEG4;
char filename [] ="C:\\wav\\test2.flv";
// Open video file
AVCodec *codec;
AVCodecContext *c= NULL;
int i, out_size, x, y, outbuf_size;
FILE *f;
AVFrame *picture;
uint8_t *outbuf;
int had_output=0;
av_register_all();
printf("Encode video file %s\n", filename);
codec = avcodec_find_encoder(CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
picture= avcodec_alloc_frame();
/* put sample parameters */
c->bit_rate = 40000;
//c->bit_rate_tolerance=30;
/* resolution must be a multiple of two */
c->width = 352;
c->height = 288;
/* frames per second */
c->time_base.den= 25;
c->time_base.num= 1;
c->gop_size = 10; /* emit one intra frame every ten frames */
c->max_b_frames=1;
c->pix_fmt = PIX_FMT_YUV420P;
if(codec_id == CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
/* open it */
if (avcodec_open2(c, codec, NULL) < 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);
}
/* alloc image and output buffer */
outbuf_size = 100000 + 12*c->width*c->height;
outbuf = (uint8_t*)malloc(outbuf_size); //CHANGED
/* 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 */
av_image_alloc(picture->data, picture->linesize,
c->width, c->height, c->pix_fmt, 1);
/* encode 1 second of video */
for(i=0;i<25;i++) {
fflush(stdout);
/* prepare a dummy image */
/* Y */
for(y=0;y<c->height;y++) {
for(x=0;x<c->width;x++) {
picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
}
}
/* Cb and Cr */
for(y=0;y<c->height/2;y++) {
for(x=0;x<c->width/2;x++) {
picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
}
}
/* encode the image */
out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
had_output |= out_size;
printf("encoding frame %3d (size=%5d)\n", i, out_size);
fwrite(outbuf, 1, out_size, f);
}
/* get the delayed frames */
for(; out_size || !had_output; i++) {
fflush(stdout);
out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
had_output |= out_size;
printf("write frame %3d (size=%5d)\n", i, out_size);
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);
fclose(p);
free(outbuf);
avcodec_close(c);
av_free(c);
av_free(picture->data[0]);
av_free(picture);
printf("\n");
return 0;
}
You are not writing .MP4, .flv nor AVI file. You are writing raw H.264 video stream without any container. Most players won't be able to play it, but it works fine with ffplay and mplayer.
It seems to be working as intended. It encodes 25 frames of weird color gradients. Though, due to low bitrate, it might look like some garbage.
All you need to do, is to put this stream into some container using libavformat. And, provide some real video frames to encode.