1.打开视频并观看的ffmpeg处理流程
av_register_all();
avformat_network_init();
AVFormatContext *pFormatCtx = avformat_alloc_context();
if(avformat_open_input(&pFormatCtx,input_str,NULL,NULL)!=0){
LOGE("Couldn't open input stream.\n");
return -1;
}
if(avformat_find_stream_info(pFormatCtx,NULL)<0){
LOGE("Couldn't find stream information.\n");
return -1;
}
int videoindex=-1;
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
videoindex=i;
break;
}
if(videoindex==-1){
LOGE("Couldn't find a video stream.\n");
return -1;
}
AVCodecContext *pCodecCtx = pFormatCtx->streams[videoindex]->codec;
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL){
LOGE("Couldn't find Codec.\n");
return -1;
}
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){
LOGE("Couldn't open codec.\n");
return -1;
}
AVFrame *pFrame,*pFrameYUV;
pFrame=av_frame_alloc();
pFrameYUV=av_frame_alloc();
AVPacket *packet = av_packet_alloc();
SwsContext *sws_ctx = sws_getContext(
codecContext->width, codecContext->height, codecContext->pix_fmt,
codecContext->width, codecContext->height, AV_PIX_FMT_RGBA,
SWS_BILINEAR, 0, 0, 0);
ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);
ANativeWindow_Buffer windowBuffer;
if (0 == nativeWindow) {
LOGE("Couldn't get native window from surface.\n");
return -1;
}
ANativeWindow_setBuffersGeometry(nativeWindow, pCodecCtx->width,
pCodecCtx->height,
WINDOW_FORMAT_RGBA_8888);
while (av_read_frame(pFormatCtx, vPacket) >= 0) {
if (vPacket->stream_index == videoindex) {
int ret = avcodec_send_packet(pCodecCtx, vPacket);
if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
LOGE("video avcodec_send_packet error %d", ret);
return -1;
}
ret = avcodec_receive_frame(pCodecCtx, vFrame);
if (ret < 0 && ret != AVERROR_EOF) {
LOGE("video avcodec_receive_frame error %d", ret);
av_packet_unref(vPacket);
continue;
}
uint8_t *dst_data[0];
int dst_linesize[0];
av_image_alloc(dst_data, dst_linesize,
codecContext->width, codecContext->height, AV_PIX_FMT_RGBA, 1);
if (packet->stream_index == vidio_stream_idx) {
sws_scale(sws_ctx,
reinterpret_cast<const uint8_t *const *>(frame->data), frame->linesize, 0,
frame->height,
dst_data, dst_linesize);
if (ANativeWindow_lock(nativeWindow, &windowBuffer, NULL) < 0) {
LOGE("cannot lock window");
} else {
av_image_alloc(dst_data, dst_linesize,
codecContext->width, codecContext->height, AV_PIX_FMT_RGBA, 1);
ANativeWindow_unlockAndPost(nativeWindow);
}
}
}
}
sws_freeContext(sws_ctx);
av_free(vPacket);
av_free(pFrameRGBA);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);