如何在Android用FFmpeg解码图像

2025-05-06 11:35:50
推荐回答(1个)
回答1:

在Android用FFmpeg解码图像
 for(i=0; inb_streams; i++)    if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {      videoStream=i;      break;    }  if(videoStream==-1)    return -1; // Didn't find a video stream  // Get a pointer to the codec context for the video stream  pCodecCtx=pFormatCtx->streams[videoStream]->codec;  // Find the decoder for the video stream  pCodec=avcodec_find_decoder(pCodecCtx->codec_id);  if(pCodec==NULL) {    fprintf(stderr, "Unsupported codec!\n");    return -1; // Codec not found  }  // Open codec  if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)                                                    pFrame=avcodec_alloc_frame();  // Allocate an picture structure  avpicture_alloc(&picture, PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);// Determine required buffer size and allocate buffer img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,  pCodecCtx->width, pCodecCtx->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);    if(img_convert_ctx == NULL)   {        fprintf(stderr, "Cannot initialize the conversion context!\n");        exit(1);    }  // Read frames and save first five frames to disk/*  ########################################  [4]  ########################################*/  i=0;   dirtyRegion.set(android::Rect(0x3FFF, 0x3FFF));  while(av_read_frame(pFormatCtx, &packet)>=0) {    // Is this a packet from the video stream?    if(packet.stream_index==videoStream) {      // Decode video frame      avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished,               &packet);      // Did we get a video frame?      if(frameFinished) {    // Convert the image from its native format to RGB     sws_scale(img_convert_ctx,                 pFrame->data, pFrame->linesize, 0, pCodecCtx->height,                 picture.data, picture.linesize);}    }    // Free the packet that was allocated by av_read_frame    av_free_packet(&packet);  }pFrame为解码后的数据,将它显示在画布上,就完成了FFMEPG解码