Android 音视频学习基础--1.5 ffmpeg yuv输出

开发环境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);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容