| 1 | // Copyright (c) 2010 Thomas Goyne <[email protected]> |
| 2 | // |
| 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | // of this software and associated documentation files (the "Software"), to deal |
| 5 | // in the Software without restriction, including without limitation the rights |
| 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | // copies of the Software, and to permit persons to whom the Software is |
| 8 | // furnished to do so, subject to the following conditions: |
| 9 | // |
| 10 | // The above copyright notice and this permission notice shall be included in |
| 11 | // all copies or substantial portions of the Software. |
| 12 | // |
| 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | // THE SOFTWARE. |
| 20 | |
| 21 | #include "audiosource.h" |
| 22 | |
| 23 | #include "indexing.h" |
| 24 | |
| 25 | #include <algorithm> |
| 26 | #include <cassert> |
| 27 | |
| 28 | extern "C" { |
| 29 | #include <libavutil/channel_layout.h> |
| 30 | } |
| 31 | |
| 32 | namespace { |
| 33 | #define MAPPER(m, n) OptionMapper<FFMS_ResampleOptions>(n, &FFMS_ResampleOptions::m) |
| 34 | OptionMapper<FFMS_ResampleOptions> resample_options[] = { |
| 35 | MAPPER(ChannelLayout, "out_channel_layout"), |
| 36 | MAPPER(SampleFormat, "out_sample_fmt"), |
| 37 | MAPPER(SampleRate, "out_sample_rate"), |
| 38 | MAPPER(MixingCoefficientType, "mix_coeff_type"), |
| 39 | MAPPER(CenterMixLevel, "center_mix_level"), |
| 40 | MAPPER(SurroundMixLevel, "surround_mix_level"), |
| 41 | MAPPER(LFEMixLevel, "lfe_mix_level"), |
| 42 | MAPPER(Normalize, "normalize_mix_level"), |
| 43 | MAPPER(ForceResample, "force_resampling"), |
| 44 | MAPPER(ResampleFilterSize, "filter_size"), |
| 45 | MAPPER(ResamplePhaseShift, "phase_shift"), |
| 46 | MAPPER(LinearInterpolation, "linear_interp"), |
| 47 | MAPPER(CutoffFrequencyRatio, "cutoff"), |
| 48 | MAPPER(MatrixedStereoEncoding, "matrix_encoding"), |
| 49 | MAPPER(FilterType, "filter_type"), |
| 50 | MAPPER(KaiserBeta, "kaiser_beta"), |
| 51 | MAPPER(DitherMethod, "dither_method") |
| 52 | }; |
| 53 | #undef MAPPER |
| 54 | } |
| 55 | |
| 56 | FFMS_AudioSource::FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, int Track, int DelayMode, int FillGaps, double DrcScale) |
| 57 | : DrcScale(DrcScale), LastValidTS(AV_NOPTS_VALUE), SourceFile(SourceFile), ResampleContext{ swr_alloc() }, TrackNumber(Track) { |
| 58 | try { |
| 59 | if (FillGaps < -1 || FillGaps > 1) |
| 60 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 61 | "Invalid gap fill mode"); |
| 62 | |
| 63 | if (Track < 0 || Track >= static_cast<int>(Index.size())) |
| 64 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 65 | "Out of bounds track index selected"); |
| 66 | |
| 67 | if (Index[Track].TT != FFMS_TYPE_AUDIO) |
| 68 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 69 | "Not an audio track"); |
| 70 | |
| 71 | if (Index[Track].empty()) |
| 72 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 73 | "Audio track contains no audio frames"); |
| 74 | |
| 75 | if (!Index.CompareFileSignature(SourceFile)) |
| 76 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_FILE_MISMATCH, |
| 77 | "The index does not match the source file"); |
| 78 | |
| 79 | Frames = Index[Track]; |
| 80 | LAVFOpts = Index.LAVFOpts; |
| 81 | |
| 82 | DecodeFrame = av_frame_alloc(); |
| 83 | if (!DecodeFrame) |
| 84 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED, |
| 85 | "Couldn't allocate frame"); |
| 86 | OpenFile(); |
| 87 | |
| 88 | if (FillGaps == 1 || (FillGaps == -1 && (!strcmp(FormatContext->iformat->name, "flv")))) |
| 89 | Frames.FillAudioGaps(); |
| 90 | |
| 91 | if (Frames.back().PTS == Frames.front().PTS) |
| 92 | SeekOffset = -1; |
| 93 | else |
| 94 | SeekOffset = 10; |
| 95 | |
| 96 | Init(Index, DelayMode); |
| 97 | } catch (...) { |
| 98 | Free(); |
| 99 | throw; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | |
| 104 | #define EXCESSIVE_CACHE_SIZE 400 |
| 105 | |
| 106 | void FFMS_AudioSource::Init(const FFMS_Index &Index, int DelayMode) { |
| 107 | // Decode the first packet to ensure all properties are initialized |
| 108 | // Don't cache it since it might be in the wrong format |
| 109 | for (size_t i = 0; i < Frames.size(); i++) { |
| 110 | if (DecodeNextBlock()) |
| 111 | break; |
| 112 | } |
| 113 | |
| 114 | // Read properties of the audio which may not be available until the first |
| 115 | // frame has been decoded |
| 116 | FillAP(AP, CodecContext, Frames); |
| 117 | |
| 118 | if (AP.SampleRate <= 0 || AP.BitsPerSample <= 0) |
| 119 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, |
| 120 | "Codec returned zero size audio"); |
| 121 | |
| 122 | auto opt = CreateResampleOptions(); |
| 123 | SetOutputFormat(*opt); |
| 124 | |
| 125 | if (DelayMode < FFMS_DELAY_NO_SHIFT) |
| 126 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 127 | "Bad audio delay compensation mode"); |
| 128 | |
| 129 | if (DelayMode == FFMS_DELAY_NO_SHIFT) return; |
| 130 | |
| 131 | if (DelayMode > (signed)Index.size()) |
| 132 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 133 | "Out of bounds track index selected for audio delay compensation"); |
| 134 | |
| 135 | if (DelayMode >= 0 && Index[DelayMode].TT != FFMS_TYPE_VIDEO) |
| 136 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 137 | "Audio delay compensation must be relative to a video track"); |
| 138 | |
| 139 | if (DelayMode == FFMS_DELAY_FIRST_VIDEO_TRACK) { |
| 140 | for (size_t i = 0; i < Index.size(); ++i) { |
| 141 | if (Index[i].TT == FFMS_TYPE_VIDEO && !Index[i].empty()) { |
| 142 | DelayMode = static_cast<int>(i); |
| 143 | break; |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | if (DelayMode >= 0) { |
| 149 | const FFMS_Track &VTrack = Index[DelayMode]; |
| 150 | Delay = -(VTrack[0].PTS * VTrack.TB.Num * AP.SampleRate / (VTrack.TB.Den * 1000)); |
| 151 | } |
| 152 | |
| 153 | if (Frames.HasTS) { |
| 154 | int i = 0; |
| 155 | while (Frames[i].PTS == AV_NOPTS_VALUE) ++i; |
| 156 | Delay += Frames[i].PTS * Frames.TB.Num * AP.SampleRate / (Frames.TB.Den * 1000); |
| 157 | for (; i > 0; --i) |
| 158 | Delay -= Frames[i].SampleCount; |
| 159 | } |
| 160 | |
| 161 | AP.NumSamples += Delay; |
| 162 | } |
| 163 | |
| 164 | void FFMS_AudioSource::CacheBeginning() { |
| 165 | // Nothing to do if the cache is already populated |
| 166 | if (!Cache.empty()) return; |
| 167 | |
| 168 | // The first packet after a seek is often decoded incorrectly, which |
| 169 | // makes it impossible to ever correctly seek back to the beginning, so |
| 170 | // store the first block now |
| 171 | |
| 172 | // In addition, anything with the same PTS as the first packet can't be |
| 173 | // distinguished from the first packet and so can't be seeked to, so |
| 174 | // store those as well |
| 175 | |
| 176 | // Some of LAVF's splitters don't like to seek to the beginning of the |
| 177 | // file (ts and?), so cache a few blocks even if PTSes are unique |
| 178 | // Packet 7 is the last packet I've had be unseekable to, so cache up to |
| 179 | // 10 for a bit of an extra buffer |
| 180 | auto end = Cache.end(); |
| 181 | while (PacketNumber < Frames.size() && |
| 182 | ((Frames[0].PTS != AV_NOPTS_VALUE && Frames[PacketNumber].PTS == Frames[0].PTS) || |
| 183 | Cache.size() < 10)) { |
| 184 | |
| 185 | // Vorbis in particular seems to like having 60+ packets at the start |
| 186 | // of the file with a PTS of 0, so we might need to expand the search |
| 187 | // range to account for that. |
| 188 | // Expanding slightly before it's strictly needed to ensure there's a |
| 189 | // bit of space for an actual cache |
| 190 | if (Cache.size() >= MaxCacheBlocks - 5) { |
| 191 | if (MaxCacheBlocks >= EXCESSIVE_CACHE_SIZE) |
| 192 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED, |
| 193 | "Exceeded the search range for an initial valid audio PTS"); |
| 194 | MaxCacheBlocks *= 2; |
| 195 | } |
| 196 | |
| 197 | DecodeNextBlock(&end); |
| 198 | } |
| 199 | // Store the iterator to the last element of the cache which is used for |
| 200 | // correctness rather than speed, so that when looking for one to delete |
| 201 | // we know how much to skip |
| 202 | CacheNoDelete = Cache.end(); |
| 203 | --CacheNoDelete; |
| 204 | } |
| 205 | |
| 206 | static int PopCount(int64_t v) { |
| 207 | int c = 0; |
| 208 | for (size_t i = 0; i < 64; i++) { |
| 209 | if (v & 1) |
| 210 | c++; |
| 211 | v >>= 1; |
| 212 | } |
| 213 | return c; |
| 214 | } |
| 215 | |
| 216 | void FFMS_AudioSource::SetOutputFormat(FFMS_ResampleOptions const& opt) { |
| 217 | if (opt.SampleRate != AP.SampleRate) |
| 218 | throw FFMS_Exception(FFMS_ERROR_RESAMPLING, FFMS_ERROR_UNSUPPORTED, |
| 219 | "Sample rate changes are currently unsupported."); |
| 220 | |
| 221 | // Cache stores audio in the output format, so clear it and reopen the file |
| 222 | Cache.clear(); |
| 223 | PacketNumber = 0; |
| 224 | OpenFile(); |
| 225 | avcodec_flush_buffers(CodecContext); |
| 226 | |
| 227 | BytesPerSample = av_get_bytes_per_sample(static_cast<AVSampleFormat>(opt.SampleFormat)) * PopCount(opt.ChannelLayout); |
| 228 | NeedsResample = |
| 229 | opt.SampleFormat != (int)CodecContext->sample_fmt || |
| 230 | opt.SampleRate != AP.SampleRate || |
| 231 | opt.ChannelLayout != AP.ChannelLayout || |
| 232 | opt.ForceResample; |
| 233 | |
| 234 | if (!NeedsResample) return; |
| 235 | |
| 236 | SwrContext *rawCtx = swr_alloc(); |
| 237 | |
| 238 | AVChannelLayout ChLayoutOut = { AV_CHANNEL_ORDER_NATIVE, PopCount(opt.ChannelLayout), static_cast<uint64_t>(opt.ChannelLayout), nullptr }; |
| 239 | AVChannelLayout ChLayoutIn = { AV_CHANNEL_ORDER_NATIVE, PopCount(AP.ChannelLayout), static_cast<uint64_t>(AP.ChannelLayout), nullptr }; |
| 240 | swr_alloc_set_opts2(&rawCtx, &ChLayoutOut, (AVSampleFormat)opt.SampleFormat, opt.SampleRate, &ChLayoutIn, CodecContext->sample_fmt, AP.SampleRate, 0, nullptr); |
| 241 | |
| 242 | FFResampleContext newContext{ rawCtx }; |
| 243 | |
| 244 | SetOptions(opt, newContext.get(), resample_options); |
| 245 | |
| 246 | if (swr_init(newContext.get())) |
| 247 | throw FFMS_Exception(FFMS_ERROR_RESAMPLING, FFMS_ERROR_UNKNOWN, |
| 248 | "Could not open avresample context"); |
| 249 | newContext.swap(ResampleContext); |
| 250 | } |
| 251 | |
| 252 | std::unique_ptr<FFMS_ResampleOptions> FFMS_AudioSource::CreateResampleOptions() const { |
| 253 | auto ret = ReadOptions(ResampleContext.get(), resample_options); |
| 254 | ret->SampleRate = AP.SampleRate; |
| 255 | ret->SampleFormat = static_cast<FFMS_SampleFormat>(AP.SampleFormat); |
| 256 | ret->ChannelLayout = AP.ChannelLayout; |
| 257 | return ret; |
| 258 | } |
| 259 | |
| 260 | void FFMS_AudioSource::ResampleAndCache(CacheIterator pos) { |
| 261 | AudioBlock& block = *pos; |
| 262 | |
| 263 | size_t size = DecodeFrame->nb_samples * BytesPerSample; |
| 264 | auto dst = block.Grow(size); |
| 265 | |
| 266 | uint8_t *OutPlanes[1] = { dst }; |
| 267 | |
| 268 | swr_convert(ResampleContext.get(), OutPlanes, DecodeFrame->nb_samples, (const uint8_t **)DecodeFrame->extended_data, DecodeFrame->nb_samples); |
| 269 | } |
| 270 | |
| 271 | FFMS_AudioSource::AudioBlock *FFMS_AudioSource::CacheBlock(CacheIterator &pos) { |
| 272 | // If the previous block has the same Start sample as this one, then |
| 273 | // we got multiple frames of audio out of a single packet and should |
| 274 | // combine them |
| 275 | auto block = pos; |
| 276 | if (pos == Cache.begin() || (--block)->Start != CurrentSample) |
| 277 | block = Cache.emplace(pos, CurrentSample); |
| 278 | |
| 279 | block->Samples += DecodeFrame->nb_samples; |
| 280 | |
| 281 | if (NeedsResample) |
| 282 | ResampleAndCache(block); |
| 283 | else { |
| 284 | const uint8_t *data = DecodeFrame->extended_data[0]; |
| 285 | auto dst = block->Grow(DecodeFrame->nb_samples * BytesPerSample); |
| 286 | memcpy(dst, data, DecodeFrame->nb_samples * BytesPerSample); |
| 287 | } |
| 288 | |
| 289 | if (Cache.size() >= MaxCacheBlocks) { |
| 290 | // Kill the oldest one |
| 291 | auto min = CacheNoDelete; |
| 292 | // Never drop the first one as the first packet decoded after a seek |
| 293 | // is often decoded incorrectly and we can't seek to before the first one |
| 294 | ++min; |
| 295 | for (auto it = min; it != Cache.end(); ++it) |
| 296 | if (it->Age < min->Age) min = it; |
| 297 | if (min == pos) ++pos; |
| 298 | Cache.erase(min); |
| 299 | } |
| 300 | return &*block; |
| 301 | } |
| 302 | |
| 303 | int FFMS_AudioSource::DecodeNextBlock(CacheIterator *pos) { |
| 304 | AVPacket *Packet = av_packet_alloc(); |
| 305 | if (!Packet) |
| 306 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_ALLOCATION_FAILED, |
| 307 | "Could not allocate packet."); |
| 308 | if (!ReadPacket(Packet)) { |
| 309 | av_packet_free(&Packet); |
| 310 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_UNKNOWN, |
| 311 | "ReadPacket unexpectedly failed to read a packet"); |
| 312 | } |
| 313 | |
| 314 | CurrentFrame = &Frames[PacketNumber]; |
| 315 | CurrentSample = CurrentFrame->SampleStart; |
| 316 | |
| 317 | // Value code intentionally ignored, combined with the checks when indexing this mostly gives the expected behavior |
| 318 | avcodec_send_packet(CodecContext, Packet); |
| 319 | |
| 320 | int NumberOfSamples = 0; |
| 321 | AudioBlock *CachedBlock = nullptr; |
| 322 | |
| 323 | while (true) { |
| 324 | av_frame_unref(DecodeFrame); |
| 325 | int Ret = avcodec_receive_frame(CodecContext, DecodeFrame); |
| 326 | if (Ret == 0) { |
| 327 | NumberOfSamples += DecodeFrame->nb_samples; |
| 328 | if (DecodeFrame->nb_samples > 0) { |
| 329 | if (pos) |
| 330 | CachedBlock = CacheBlock(*pos); |
| 331 | } |
| 332 | break; |
| 333 | } else if (Ret == AVERROR(EAGAIN)) { |
| 334 | if (!ReadPacket(Packet)) { |
| 335 | av_packet_free(&Packet); |
| 336 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_UNKNOWN, |
| 337 | "ReadPacket unexpectedly failed to read a packet"); |
| 338 | } |
| 339 | avcodec_send_packet(CodecContext, Packet); |
| 340 | } else if (Ret == AVERROR_EOF) { |
| 341 | break; |
| 342 | } else { |
| 343 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, "Audio decoding error"); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | av_packet_free(&Packet); |
| 348 | |
| 349 | // Zero sample packets aren't included in the index |
| 350 | if (!NumberOfSamples) |
| 351 | return NumberOfSamples; |
| 352 | ++PacketNumber; |
| 353 | |
| 354 | // Add padding after the packet, if needed |
| 355 | if (!CachedBlock || CachedBlock->Samples == CurrentFrame->SampleCount) |
| 356 | return NumberOfSamples; |
| 357 | |
| 358 | const int64_t MissingSamples = static_cast<int64_t>(CurrentFrame->SampleCount - CachedBlock->Samples); |
| 359 | // This can apparently happen in some rare circumstances, caused by inaccurate seeking? |
| 360 | if (MissingSamples <= 0) |
| 361 | return NumberOfSamples; |
| 362 | CachedBlock->Samples += MissingSamples; |
| 363 | const int64_t MissingBytes = MissingSamples * BytesPerSample; |
| 364 | if (MissingSamples > 200 || MissingSamples > CachedBlock->Samples - MissingSamples) |
| 365 | memset(CachedBlock->Grow(MissingBytes), 0, MissingBytes); |
| 366 | else { |
| 367 | auto ptr = CachedBlock->Grow(MissingBytes); |
| 368 | memcpy(ptr, ptr - MissingBytes, MissingBytes); |
| 369 | } |
| 370 | return NumberOfSamples; |
| 371 | } |
| 372 | |
| 373 | static bool SampleStartComp(const FrameInfo &a, const FrameInfo &b) { |
| 374 | return a.SampleStart < b.SampleStart; |
| 375 | } |
| 376 | |
| 377 | void FFMS_AudioSource::GetAudio(void *Buf, int64_t Start, int64_t Count) { |
| 378 | if (Start < 0 || Start + Count > AP.NumSamples || Count < 0) |
| 379 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_INVALID_ARGUMENT, |
| 380 | "Out of bounds audio samples requested"); |
| 381 | |
| 382 | CacheBeginning(); |
| 383 | |
| 384 | uint8_t *Dst = static_cast<uint8_t*>(Buf); |
| 385 | |
| 386 | // Apply audio delay (if any) and fill any samples before the start time with zero |
| 387 | Start -= Delay; |
| 388 | if (Start < 0) { |
| 389 | size_t Bytes = static_cast<size_t>(BytesPerSample * FFMIN(-Start, Count)); |
| 390 | memset(Dst, 0, Bytes); |
| 391 | |
| 392 | Count += Start; |
| 393 | // Entire request was before the start of the audio |
| 394 | if (Count <= 0) return; |
| 395 | |
| 396 | Start = 0; |
| 397 | Dst += Bytes; |
| 398 | } |
| 399 | |
| 400 | auto it = Cache.begin(); |
| 401 | |
| 402 | while (Count > 0) { |
| 403 | // Find first useful cache block |
| 404 | while (it != Cache.end() && it->Start + it->Samples <= Start) ++it; |
| 405 | |
| 406 | // Cache has the next block we want |
| 407 | if (it != Cache.end() && it->Start <= Start) { |
| 408 | int64_t SrcOffset = FFMAX(0, Start - it->Start); |
| 409 | int64_t DstOffset = FFMAX(0, it->Start - Start); |
| 410 | int64_t CopySamples = FFMIN(it->Samples - SrcOffset, Count - DstOffset); |
| 411 | size_t Bytes = static_cast<size_t>(CopySamples * BytesPerSample); |
| 412 | |
| 413 | memcpy(Dst + DstOffset * BytesPerSample, it->Data.get() + SrcOffset * BytesPerSample, Bytes); |
| 414 | Start += CopySamples; |
| 415 | Count -= CopySamples; |
| 416 | Dst += Bytes; |
| 417 | ++it; |
| 418 | } |
| 419 | // Decode another block |
| 420 | else { |
| 421 | if (Start < CurrentSample && SeekOffset == -1) |
| 422 | throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Audio stream is not seekable"); |
| 423 | |
| 424 | if (SeekOffset >= 0 && (Start < CurrentSample || Start > CurrentSample + DecodeFrame->nb_samples * 5)) { |
| 425 | FrameInfo f; |
| 426 | f.SampleStart = Start; |
| 427 | size_t NewPacketNumber = std::distance( |
| 428 | Frames.begin(), |
| 429 | std::lower_bound(Frames.begin(), Frames.end(), f, SampleStartComp)); |
| 430 | NewPacketNumber = NewPacketNumber > static_cast<size_t>(SeekOffset + 15) |
| 431 | ? NewPacketNumber - SeekOffset - 15 |
| 432 | : 0; |
| 433 | while (NewPacketNumber > 0 && !Frames[NewPacketNumber].KeyFrame) --NewPacketNumber; |
| 434 | |
| 435 | // Only seek forward if it'll actually result in moving forward |
| 436 | if (Start < CurrentSample || static_cast<size_t>(NewPacketNumber) > PacketNumber) { |
| 437 | PacketNumber = NewPacketNumber; |
| 438 | CurrentSample = -1; |
| 439 | av_frame_unref(DecodeFrame); |
| 440 | avcodec_flush_buffers(CodecContext); |
| 441 | Seek(); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // Decode until we hit the block we want |
| 446 | if (PacketNumber >= Frames.size()) |
| 447 | throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Seeking is severely broken"); |
| 448 | while (CurrentSample + CurrentFrame->SampleCount <= Start && PacketNumber < Frames.size()) |
| 449 | DecodeNextBlock(&it); |
| 450 | if (CurrentSample > Start) |
| 451 | throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Seeking is severely broken"); |
| 452 | |
| 453 | // The block we want is now in the cache immediately before it |
| 454 | --it; |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | size_t FFMS_AudioSource::GetSeekablePacketNumber(FFMS_Track const& Frames, size_t PacketNumber) { |
| 460 | // Packets don't always have unique PTSes, so we may not be able to |
| 461 | // uniquely identify the packet we want. This function attempts to find |
| 462 | // a PTS we can seek to which will let us figure out which packet we're |
| 463 | // on before we get to the packet we actually wanted |
| 464 | |
| 465 | // MatroskaAudioSource doesn't need this, as it seeks by byte offset |
| 466 | // rather than PTS. LAVF theoretically can seek by byte offset, but we |
| 467 | // don't use it as not all demuxers support it and it's broken in some of |
| 468 | // those that claim to support it |
| 469 | |
| 470 | // However much we might wish to, we can't seek to before packet zero |
| 471 | if (PacketNumber == 0) return PacketNumber; |
| 472 | |
| 473 | // Desired packet's PTS is unique, so don't do anything |
| 474 | if (Frames[PacketNumber].PTS != Frames[PacketNumber - 1].PTS && |
| 475 | (PacketNumber + 1 == Frames.size() || Frames[PacketNumber].PTS != Frames[PacketNumber + 1].PTS)) |
| 476 | return PacketNumber; |
| 477 | |
| 478 | // When decoding, we only reliably know what packet we're at when the |
| 479 | // newly parsed packet has a different PTS from the previous one. As such, |
| 480 | // we walk backwards until we hit a different PTS and then seek to there, |
| 481 | // so that we can then decode until we hit the PTS group we actually wanted |
| 482 | // (and thereby know that we're at the first packet in the group rather |
| 483 | // than whatever the splitter happened to choose) |
| 484 | |
| 485 | // This doesn't work if our desired packet has the same PTS as the first |
| 486 | // packet, but this scenario should never come up anyway; we permanently |
| 487 | // cache the decoded results from those packets, so there's no need to ever |
| 488 | // seek to them |
| 489 | int64_t PTS = Frames[PacketNumber].PTS; |
| 490 | while (PacketNumber > 0 && PTS == Frames[PacketNumber].PTS) |
| 491 | --PacketNumber; |
| 492 | return PacketNumber; |
| 493 | } |
| 494 | |
| 495 | void FFMS_AudioSource::OpenFile() { |
| 496 | avcodec_free_context(&CodecContext); |
| 497 | avformat_close_input(&FormatContext); |
| 498 | |
| 499 | LAVFOpenFile(SourceFile.c_str(), FormatContext, TrackNumber, LAVFOpts); |
| 500 | |
| 501 | auto *Codec = avcodec_find_decoder(FormatContext->streams[TrackNumber]->codecpar->codec_id); |
| 502 | if (Codec == nullptr) |
| 503 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, |
| 504 | "Audio codec not found"); |
| 505 | |
| 506 | CodecContext = avcodec_alloc_context3(Codec); |
| 507 | if (CodecContext == nullptr) |
| 508 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED, |
| 509 | "Could not allocate audio decoding context"); |
| 510 | |
| 511 | if (avcodec_parameters_to_context(CodecContext, FormatContext->streams[TrackNumber]->codecpar) < 0) |
| 512 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, |
| 513 | "Could not copy audio codec parameters"); |
| 514 | |
| 515 | AVDictionary *CodecDict = nullptr; |
| 516 | if (Codec->id == AV_CODEC_ID_AC3 || Codec->id == AV_CODEC_ID_EAC3) |
| 517 | av_dict_set(&CodecDict, "drc_scale", std::to_string(DrcScale).c_str(), 0); |
| 518 | |
| 519 | if (avcodec_open2(CodecContext, Codec, &CodecDict) < 0) |
| 520 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, |
| 521 | "Could not open audio codec"); |
| 522 | |
| 523 | av_dict_free(&CodecDict); |
| 524 | } |
| 525 | |
| 526 | void FFMS_AudioSource::Free() { |
| 527 | av_frame_free(&DecodeFrame); |
| 528 | avcodec_free_context(&CodecContext); |
| 529 | avformat_close_input(&FormatContext); |
| 530 | } |
| 531 | |
| 532 | FFMS_AudioSource::~FFMS_AudioSource() { |
| 533 | Free(); |
| 534 | } |
| 535 | |
| 536 | int64_t FFMS_AudioSource::FrameTS(size_t Packet) const { |
| 537 | return Frames.HasTS ? Frames[Packet].PTS : Frames[Packet].FilePos; |
| 538 | } |
| 539 | |
| 540 | void FFMS_AudioSource::Seek() { |
| 541 | size_t TargetPacket = GetSeekablePacketNumber(Frames, PacketNumber); |
| 542 | LastValidTS = AV_NOPTS_VALUE; |
| 543 | |
| 544 | int Flags = Frames.HasTS ? AVSEEK_FLAG_BACKWARD : AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_BYTE; |
| 545 | |
| 546 | if (av_seek_frame(FormatContext, TrackNumber, FrameTS(TargetPacket), Flags) < 0) |
| 547 | av_seek_frame(FormatContext, TrackNumber, FrameTS(TargetPacket), Flags | AVSEEK_FLAG_ANY); |
| 548 | |
| 549 | if (TargetPacket != PacketNumber) { |
| 550 | // Decode until the PTS changes so we know where we are |
| 551 | int64_t LastPTS = FrameTS(PacketNumber); |
| 552 | while (LastPTS == FrameTS(PacketNumber)) DecodeNextBlock(); |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | bool FFMS_AudioSource::ReadPacket(AVPacket *Packet) { |
| 557 | while (av_read_frame(FormatContext, Packet) >= 0) { |
| 558 | if (Packet->stream_index == TrackNumber) { |
| 559 | // Required because not all audio packets, especially in ogg, have a pts. Use the previous valid packet's pts instead. |
| 560 | if (Packet->pts == AV_NOPTS_VALUE) |
| 561 | Packet->pts = LastValidTS; |
| 562 | else |
| 563 | LastValidTS = Packet->pts; |
| 564 | |
| 565 | // This only happens if a really shitty demuxer seeks to a packet without pts *hrm* ogg *hrm* so read until a valid pts is reached |
| 566 | int64_t PacketTS = Frames.HasTS ? Packet->pts : Packet->pos; |
| 567 | if (PacketTS != AV_NOPTS_VALUE) { |
| 568 | while (PacketNumber > 0 && FrameTS(PacketNumber) > PacketTS) --PacketNumber; |
| 569 | while (FrameTS(PacketNumber) < PacketTS) ++PacketNumber; |
| 570 | return true; |
| 571 | } |
| 572 | } |
| 573 | av_packet_unref(Packet); |
| 574 | } |
| 575 | return false; |
| 576 | } |
| 577 |