1
我想用ffmpeg庫的幫助編碼一個圖像..其實我想編碼實時視頻,但現在我開始編碼圖像.. 這是我的代碼這..無法用ffmpeg編碼圖像
av_register_all();
avcodec_init();
avcodec_register_all();
avformat_alloc_context();
AVCodec *codec;
AVCodecContext *ctx= NULL;
int out_size, size, outbuf_size;
AVFrame *picture;
uint8_t *outbuf;
unsigned char *flvdata = malloc(sizeof(unsigned char) * 30);
outbuf_size = 100000;
outbuf = malloc(outbuf_size);
printf("Video encoding\n");
codec = avcodec_find_encoder(CODEC_ID_FLV1);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
ctx= avcodec_alloc_context();
picture= avcodec_alloc_frame();
ctx->width = 320;
ctx->height = 240;
ctx -> sample_rate = 11025;
ctx -> time_base.den = 1000;
ctx -> time_base.num = 23976;
ctx -> codec_id = CODEC_ID_FLV1;
ctx -> codec_type = CODEC_TYPE_VIDEO;
ctx->pix_fmt = PIX_FMT_YUV420P;
if (avcodec_open(ctx, codec) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
outbuf_size = 100000;
outbuf = malloc(outbuf_size);
size = ctx->width * ctx->height;
AVFrame* outpic = avcodec_alloc_frame();
int nbytes = avpicture_get_size(PIX_FMT_YUV420P, ctx->width, ctx->height);
uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes);
fflush(stdout);
int numBytes = avpicture_get_size(PIX_FMT_YUV420P, ctx->width, ctx->height);
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"0.jpg"]];
CGImageRef newCgImage = [image CGImage];
CGDataProviderRef dataProvider = CGImageGetDataProvider(newCgImage);
CFDataRef bitmapData = CGDataProviderCopyData(dataProvider);
long dataLength = CFDataGetLength(bitmapData);
uint8_t *buffer = (uint8_t *)av_malloc(dataLength);
buffer = (uint8_t *)CFDataGetBytePtr(bitmapData);
for(int i = 0; i < dataLength; i++)
{
if((i + 1) % 16 == 1 && i != 1)
printf("\n");
printf("%X\t",buffer[i]); // getting something different than the actual hex value of the image
}
outpic -> pts = 0;
avpicture_fill((AVPicture*)picture, buffer, PIX_FMT_RGB8, ctx->width, ctx->height);
avpicture_fill((AVPicture*)outpic, outbuffer, PIX_FMT_YUV420P, ctx->width, ctx->height);
struct SwsContext* fooContext = sws_getContext(ctx->width, ctx->height,
PIX_FMT_RGB8,
ctx->width, ctx->height,
PIX_FMT_YUV420P,
SWS_FAST_BILINEAR, NULL, NULL, NULL);
sws_scale(fooContext, picture->data, picture->linesize, 0, ctx->height, outpic->data, outpic->linesize);
printf("abcdefghijklmnop");
out_size = avcodec_encode_video(ctx, outbuf, outbuf_size, outpic);
printf("\n\n out_size %d outbuf_size %d",out_size,outbuf_size);
使圖像的大小爲29 KB和avcodec_encode_video將返回20143 ..因此,它是正確的嗎?我的意思是我編碼,所以它的大小也應該減少...並且我已經在十六進制模式下打開該圖像,並且我得到的數據不同於緩衝區中的數據(如代碼所示)。所以我認爲緩衝區沒有得到正確的數據。對? 任何人都可以請幫我用我的代碼? 預先感謝您...