Initialize AVFormatContext from buffer data

时间:2019-04-23 15:11:37

标签: c++ ffmpeg streaming

I am streaming AAC audio over network, and I need to use ffmpeg to decode the stream. I have tried in local and everything works fine, but over the network I am not sure how to initialize my AVFormatContext.

I have had a look at the functions av_probe_input_buffer* and av_probe_input_format* but it doesn't look like these functions are suited for what I want to do. My AVFormatContext is always incomplete, and I cannot find an audio stream, which prevents me from getting a codec context and initializing my decoder.

The problematic piece of code looks more or less like this:

AVFormatContext *pFormatCtx = avformat_alloc_context();

AVFrame   *pFrame = av_frame_alloc();
AVPacket  *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
av_init_packet(packet);
packet->buf = NULL;
packet->data = NULL;

pFormatCtx->flags |= AVFMT_FLAG_CUSTOM_IO;

// Read 10 packets to give ffmpeg some hint about the data
for (int i = 0; i < 10; i++) {
  uint32_t packet_size;
  fread(&packet_size, 1, sizeof(packet_size), f);

  uint8_t *pdata = (uint8_t*)malloc(packet_size);
  int len = fread(pdata, 1, packet_size, f);

  AVProbeData probeData;
  probeData.buf = pdata;
  probeData.buf_size = packet_size - 1;
  probeData.filename = "";
  pFormatCtx->iformat = av_probe_input_format(&probeData, 1);
}

// This is working, no error here
if (avformat_find_stream_info(pFormatCtx, NULL) < 0){
  printf("Error finding stream info!");
}

int audioStream = -1;
for (int i = 0; i < pFormatCtx->nb_streams; i++)
  if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){
    audioStream = i;
    break;
  }

// I get this error, so actually no audio stream is detected
if (audioStream == -1){
  printf("Didn't find a audio stream.\n");
  return -1;
}
printf("Audio stream found at index %d\n", audioStream);

// I do not get here, because an audio stream is not detected.
AVCodecContext *pCodecCtx = pFormatCtx->streams[audioStream]->codec; 

// This is where I want to be!
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
  printf("Codec not found.\n");
  return -1;
}

// Open codec
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
  printf("Could not open codec.\n");
  return -1;
}

0 个答案:

没有答案