开发环境vs2010 环境比较老。一下程序要求输出一个pcm数据,使用yuv工具可以打开播放。在这里简单介绍ffmpeg的api调用。后面还会写个整个video的播放,会提供统一的工程。
AVFormatContext *pFormatCtx;
int i, videoindex;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVFrame *pFrame,*pFrameYUV;
uint8_t *out_buffer;
AVPacket *packet;
int ret, got_picture;
- 定义变量
struct SwsContext *img_convert_ctx;
char filepath[]="屌丝男士.mov";
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();
if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0){
printf("Couldn't open input stream.\n");
return -1;
}
- 初始化变量,初始化ffmpeg。
if(avformat_find_stream_info(pFormatCtx,NULL)<0){
printf("Couldn't find stream information.\n");
return -1;
}
videoindex=-1;
for(i=0; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
videoindex=i;
break;
}
}
- 找到视频流封装器。
pCodecCtx=pFormatCtx->streams[videoindex]->codec;
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){
printf("Could not open codec.\n");
return -1;
}
- 找到视频流解码器
pFrame=av_frame_alloc();
pFrameYUV=av_frame_alloc();
out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
- 准备buff等,准备输出工作
FILE *pFile=NULL;
pFile=fopen("output.yuv", "wb");
- 准备一个输出的file
while(av_read_frame(pFormatCtx, packet)>=0){
if(packet->stream_index==videoindex){
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if(got_picture){
sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
fwrite( pFrameYUV->data[0],, 1, pFrameYUV->linesize[0], pFile);//y,yuv,主意格式
fwrite( pFrameYUV->data[1],, 1, pFrameYUV->linesize[1], pFile);//u
fwrite( pFrameYUV->data[2],, 1, pFrameYUV->linesize[2], pFile);//v
/*fwrite( pFrameYUV->data[0],, 1,pCodecCtx->width*pCodecCtx->height , pFile);//y,yuv,主意格式
fwrite( pFrameYUV->data[1],, 1, pCodecCtx->width*pCodecCtx->height/4, pFile);//u
fwrite( pFrameYUV->data[2],, 1, pCodecCtx->width*pCodecCtx->height/4, pFile);//v
*/
}
}
av_free_packet(packet);
}
- 输出
sws_freeContext(img_convert_ctx);
//--------------
av_frame_free(&pFrameYUV);
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
- 释放资源
相关文章
Android 音视频学习基础–1.1 音视频基础知识
Android 音视频学习基础–1.2 需要认识的一些工具
Android 音视频学习基础–1.3 主流的开源项目
Android 音视频学习基础–1.4 ffmpeg pcm输出
Android 音视频学习基础–1.5 ffmpeg yuv输出
Android 音视频学习基础–1.6 ffmpeg 简单视频播放器
Android 音视频学习基础–1.7 Android最简单的音频播放器
Android 音视频学习基础–1.8 Android最简单的音频播放器
Android 音视频学习基础–1.9 Android最简单的视频播放器
Android 音视频学习基础–1.10 Android自制简单音视频播放器
欢迎大家批评指正