Copying avcodec parameters
Asked Answered
S

1

1

I am trying to use libav to convert an MP4 file to an MP3 file. Basically trying to achieve what ffmpeg -i filename.mp4 filename.mp3 does. I've found this official example. But when I run it with an input MP4 and an output MP3 I get an error:

Invalid audio stream. Exactly one MP3 audio stream is required.

I am not at all familiar with this library but I think I have narrowed the problem down to this line:

ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);

It seems to copy all streams for a video file but we only need one for the MP3 file? I am not sure. There doesn't seem to be a function to copy only the parameters relevant to audio. I checked the sources, avcodec_parameters_copy does a simple memcpy.

Questions:

  1. Is this the actual problem?
  2. How do I solve it?
  3. Am I on the right track to achieve the goal of extracting audio from a video file? I've seen this question (and other similar questions like this and this) on here but none seem to have a complete code example. The C API documentation for this library is also a little lacking.
Statist answered 4/6, 2020 at 12:59 Comment(5)
Does the mp4 contain an mp3 track? Or is the track using a different codec?Plug
@Plug is it possible to achieve this in the general case for any MP4?Statist
Not with the code you posted. To support any codec, you made decode and reencode.Plug
@Plug the same GitHub repository seems to have examples on decoding and encoding audio. Are these what I need to look into? If not, could you give me pointers on where I can find some kind of an example of how it's done?Statist
As with any coding project, it needs to be broken down into steps. Look up ffmpeg /libav tutorials on line and start with just the decoding step.Plug
R
2

You can have multiple audio tracks in mp4 file, but only one such track in an mp3 file. The easiest fix for the remuxing example would be to replace lines 101-103:

if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
    stream_index != 0) {

This, naturally, is relevant only if the output is mp3.

PS, make sure that your input mp4 uses the MP3 audio codec. If it does not (and most have AAC or AC3 these days), it's not enough to remux the file, you also need to decode and re-encode the audio stream.

Roshelle answered 4/6, 2020 at 16:49 Comment(1)
I could not find any up-to-date tutorials about decoding/re-encoding. Every tutorial about this library (including the official ones) seem to be incredibly outdated. How can I decode/re-encode the audio stream?Statist

© 2022 - 2024 — McMap. All rights reserved.