RuiChen0101
RuiChen0101

Reputation: 11

ffmpeg AVStream::codecpar is null

I'm trying to make a simple audio decoder by using libav, and I encounter a problem. I cannot get AVCodecParameters from AVStream, codepar always is null.

here is my code.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
}

int main(int argc, char** argv) {
  if (argc != 2) {
    fprintf(stderr, "usage: %s input_file > output_file\n", argv[0]);
    exit(1);
  }

  const int out_channels = 2, out_samples = 512, sample_rate = 44100;

  int max_buffer_size;

  // register supported formats and codecs
  av_register_all();

  // allocate empty format context
  // provides methods for reading input packets
  AVFormatContext* fmt_ctx = avformat_alloc_context();

  // determine input file type and initialize format context
  if (avformat_open_input(&fmt_ctx, argv[1], NULL, NULL) != 0) {
      fprintf(stderr, "error: avformat_open_input()\n");
      exit(1);
  }

  // determine supported codecs for input file streams and add
  // them to format context
  if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
    fprintf(stderr, "error: avformat_find_stream_info()\n");
    exit(1);
  }

  AVCodec* codec = NULL;
  int stream = 0;

  // find audio stream in format context
    
  fprintf(stderr, "%d\n", fmt_ctx->nb_streams);
  for (int i = 0; i < fmt_ctx->nb_streams; i++) {
    AVCodecParameters* avCodecParameters = NULL;
    avCodecParameters = fmt_ctx->streams[i]->codecpar;
    if(!avCodecParameters){
      fprintf(stderr, "error: CodecParameters\n");// always fail here
      exit(1);
    }
    if(avCodecParameters->codec_type == AVMEDIA_TYPE_AUDIO){
      stream = i;
      codec = avcodec_find_decoder(avCodecParameters->codec_id);
      if (!codec) {
          fprintf(stderr, "error: avcodec_find_decoder()\n");
          exit(1);
      }
      break;
    }
  }

  if (stream == fmt_ctx->nb_streams) {
    fprintf(stderr, "error: no audio stream found\n");
    exit(1);
  }
  return 0;
}

For the input file format, I have tried .wav and .m4a file

and the output always is

1
error: CodecParameters

Dose anyone has the same problem?

How to solve it?

thanks!

Upvotes: 1

Views: 1621

Answers (1)

CHICOTILA
CHICOTILA

Reputation: 1

It seems the code does not explicitly convert const AVCodecParameters to AVCodecParameters discarded const resulting in a warning. Try like this:

AVCodecParameters* avCodecParameters = NULL;

Upvotes: 0

Related Questions