--------------------------------------------------------------------------- Core decode + resample logic (shared by file and memory paths) ---------------------------------------------------------------------------
| 154 | // Core decode + resample logic (shared by file and memory paths) |
| 155 | // --------------------------------------------------------------------------- |
| 156 | bool AudioReader::decode_audio(AVFormatContext* format_ctx, |
| 157 | audio_data_t& out_audio, |
| 158 | int target_sample_rate, |
| 159 | MonoDownmixMode downmix) |
| 160 | { |
| 161 | if (avformat_find_stream_info(format_ctx, nullptr) < 0) { |
| 162 | std::cerr << "Error: could not find stream information" << std::endl; |
| 163 | return false; |
| 164 | } |
| 165 | |
| 166 | // Find the first audio stream |
| 167 | int audio_stream_idx = -1; |
| 168 | for (unsigned i = 0; i < format_ctx->nb_streams; ++i) { |
| 169 | if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { |
| 170 | audio_stream_idx = static_cast<int>(i); |
| 171 | break; |
| 172 | } |
| 173 | } |
| 174 | if (audio_stream_idx < 0) { |
| 175 | std::cerr << "Error: no audio stream found" << std::endl; |
| 176 | return false; |
| 177 | } |
| 178 | |
| 179 | AVStream* audio_stream = format_ctx->streams[audio_stream_idx]; |
| 180 | AVCodecParameters* codec_params = audio_stream->codecpar; |
| 181 | |
| 182 | // Stash original metadata before decoding |
| 183 | const int original_sample_rate = codec_params->sample_rate; |
| 184 | const int original_channels = codec_params->ch_layout.nb_channels; |
| 185 | |
| 186 | // Open decoder |
| 187 | const AVCodec* codec = avcodec_find_decoder(codec_params->codec_id); |
| 188 | if (!codec) { |
| 189 | std::cerr << "Error: unsupported audio codec" << std::endl; |
| 190 | return false; |
| 191 | } |
| 192 | |
| 193 | AVCodecContext* codec_ctx = avcodec_alloc_context3(codec); |
| 194 | if (!codec_ctx) { |
| 195 | std::cerr << "Error: could not allocate codec context" << std::endl; |
| 196 | return false; |
| 197 | } |
| 198 | |
| 199 | if (avcodec_parameters_to_context(codec_ctx, codec_params) < 0) { |
| 200 | avcodec_free_context(&codec_ctx); |
| 201 | std::cerr << "Error: could not copy codec parameters" << std::endl; |
| 202 | return false; |
| 203 | } |
| 204 | |
| 205 | if (avcodec_open2(codec_ctx, codec, nullptr) < 0) { |
| 206 | avcodec_free_context(&codec_ctx); |
| 207 | std::cerr << "Error: could not open audio codec" << std::endl; |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | // Setup resampler: any input → mono float32 at target_sample_rate |
| 212 | SwrContext* swr_ctx = swr_alloc(); |
| 213 | if (!swr_ctx) { |