summaryrefslogtreecommitdiffstats
path: root/dom/media/mediasink/AudioDecoderInputTrack.cpp
blob: 7f970f0e4f87f4e6603cb79e83743e1c6ba63f75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "AudioDecoderInputTrack.h"

#include "MediaData.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_media.h"
#include "Tracing.h"

// Use abort() instead of exception in SoundTouch.
#define ST_NO_EXCEPTION_HANDLING 1
#include "soundtouch/SoundTouchFactory.h"

namespace mozilla {

extern LazyLogModule gMediaDecoderLog;

#define LOG(msg, ...)                        \
  MOZ_LOG(gMediaDecoderLog, LogLevel::Debug, \
          ("AudioDecoderInputTrack=%p " msg, this, ##__VA_ARGS__))

#define LOG_M(msg, this, ...)                \
  MOZ_LOG(gMediaDecoderLog, LogLevel::Debug, \
          ("AudioDecoderInputTrack=%p " msg, this, ##__VA_ARGS__))

/* static */
AudioDecoderInputTrack* AudioDecoderInputTrack::Create(
    MediaTrackGraph* aGraph, nsISerialEventTarget* aDecoderThread,
    const AudioInfo& aInfo, float aPlaybackRate, float aVolume,
    bool aPreservesPitch) {
  MOZ_ASSERT(aGraph);
  MOZ_ASSERT(aDecoderThread);
  AudioDecoderInputTrack* track =
      new AudioDecoderInputTrack(aDecoderThread, aGraph->GraphRate(), aInfo,
                                 aPlaybackRate, aVolume, aPreservesPitch);
  aGraph->AddTrack(track);
  return track;
}

AudioDecoderInputTrack::AudioDecoderInputTrack(
    nsISerialEventTarget* aDecoderThread, TrackRate aGraphRate,
    const AudioInfo& aInfo, float aPlaybackRate, float aVolume,
    bool aPreservesPitch)
    : ProcessedMediaTrack(aGraphRate, MediaSegment::AUDIO, new AudioSegment()),
      mDecoderThread(aDecoderThread),
      mResamplerChannelCount(0),
      mInitialInputChannels(aInfo.mChannels),
      mInputSampleRate(aInfo.mRate),
      mDelayedScheduler(mDecoderThread),
      mPlaybackRate(aPlaybackRate),
      mVolume(aVolume),
      mPreservesPitch(aPreservesPitch) {}

bool AudioDecoderInputTrack::ConvertAudioDataToSegment(
    AudioData* aAudio, AudioSegment& aSegment,
    const PrincipalHandle& aPrincipalHandle) {
  AssertOnDecoderThread();
  MOZ_ASSERT(aAudio);
  MOZ_ASSERT(aSegment.IsEmpty());
  if (!aAudio->Frames()) {
    LOG("Ignore audio with zero frame");
    return false;
  }

  aAudio->EnsureAudioBuffer();
  RefPtr<SharedBuffer> buffer = aAudio->mAudioBuffer;
  AudioDataValue* bufferData = static_cast<AudioDataValue*>(buffer->Data());
  AutoTArray<const AudioDataValue*, 2> channels;
  for (uint32_t i = 0; i < aAudio->mChannels; ++i) {
    channels.AppendElement(bufferData + i * aAudio->Frames());
  }
  aSegment.AppendFrames(buffer.forget(), channels, aAudio->Frames(),
                        aPrincipalHandle);
  const TrackRate newInputRate = static_cast<TrackRate>(aAudio->mRate);
  if (newInputRate != mInputSampleRate) {
    LOG("Input sample rate changed %u -> %u", mInputSampleRate, newInputRate);
    mInputSampleRate = newInputRate;
    mResampler.own(nullptr);
    mResamplerChannelCount = 0;
  }
  if (mInputSampleRate != GraphImpl()->GraphRate()) {
    aSegment.ResampleChunks(mResampler, &mResamplerChannelCount,
                            mInputSampleRate, GraphImpl()->GraphRate());
  }
  return aSegment.GetDuration() > 0;
}

void AudioDecoderInputTrack::AppendData(
    AudioData* aAudio, const PrincipalHandle& aPrincipalHandle) {
  AssertOnDecoderThread();
  MOZ_ASSERT(aAudio);
  nsTArray<RefPtr<AudioData>> audio;
  audio.AppendElement(aAudio);
  AppendData(audio, aPrincipalHandle);
}

void AudioDecoderInputTrack::AppendData(
    nsTArray<RefPtr<AudioData>>& aAudioArray,
    const PrincipalHandle& aPrincipalHandle) {
  AssertOnDecoderThread();
  MOZ_ASSERT(!mShutdownSPSCQueue);

  // Batching all new data together in order to push them as a single unit that
  // gives the SPSC queue more spaces.
  for (const auto& audio : aAudioArray) {
    BatchData(audio, aPrincipalHandle);
  }

  // If SPSC queue doesn't have much available capacity now, we would push
  // batched later.
  if (ShouldBatchData()) {
    return;
  }
  PushBatchedDataIfNeeded();
}

bool AudioDecoderInputTrack::ShouldBatchData() const {
  AssertOnDecoderThread();
  // If the SPSC queue has less available capacity than the threshold, then all
  // input audio data should be batched together, in order not to increase the
  // pressure of SPSC queue.
  static const int kThresholdNumerator = 3;
  static const int kThresholdDenominator = 10;
  return mSPSCQueue.AvailableWrite() <
         mSPSCQueue.Capacity() * kThresholdNumerator / kThresholdDenominator;
}

bool AudioDecoderInputTrack::HasBatchedData() const {
  AssertOnDecoderThread();
  return !mBatchedData.mSegment.IsEmpty();
}

void AudioDecoderInputTrack::BatchData(
    AudioData* aAudio, const PrincipalHandle& aPrincipalHandle) {
  AssertOnDecoderThread();
  AudioSegment segment;
  if (!ConvertAudioDataToSegment(aAudio, segment, aPrincipalHandle)) {
    return;
  }
  mBatchedData.mSegment.AppendFrom(&segment);
  if (!mBatchedData.mStartTime.IsValid()) {
    mBatchedData.mStartTime = aAudio->mTime;
  }
  mBatchedData.mEndTime = aAudio->GetEndTime();
  LOG("batched data [%" PRId64 ":%" PRId64 "] sz=%" PRId64,
      aAudio->mTime.ToMicroseconds(), aAudio->GetEndTime().ToMicroseconds(),
      mBatchedData.mSegment.GetDuration());
  DispatchPushBatchedDataIfNeeded();
}

void AudioDecoderInputTrack::DispatchPushBatchedDataIfNeeded() {
  AssertOnDecoderThread();
  MOZ_ASSERT(!mShutdownSPSCQueue);
  // The graph thread runs iteration around per 2~10ms. Doing this to ensure
  // that we can keep consuming data. If the producer stops pushing new data
  // due to MDSM stops decoding, which is because MDSM thinks the data stored
  // in the audio queue are enough. The way to remove those data from the
  // audio queue is driven by us, so we have to keep consuming data.
  // Otherwise, we would get stuck because those batched data would never be
  // consumed.
  static const uint8_t kTimeoutMS = 10;
  TimeStamp target =
      TimeStamp::Now() + TimeDuration::FromMilliseconds(kTimeoutMS);
  mDelayedScheduler.Ensure(
      target,
      [self = RefPtr<AudioDecoderInputTrack>(this), this]() {
        LOG("In the task of DispatchPushBatchedDataIfNeeded");
        mDelayedScheduler.CompleteRequest();
        MOZ_ASSERT(!mShutdownSPSCQueue);
        MOZ_ASSERT(HasBatchedData());
        // The capacity in SPSC is still not enough, so we can't push data now.
        // Retrigger another task to push batched data.
        if (ShouldBatchData()) {
          DispatchPushBatchedDataIfNeeded();
          return;
        }
        PushBatchedDataIfNeeded();
      },
      []() { MOZ_DIAGNOSTIC_ASSERT(false); });
}

void AudioDecoderInputTrack::PushBatchedDataIfNeeded() {
  AssertOnDecoderThread();
  if (!HasBatchedData()) {
    return;
  }
  LOG("Append batched data [%" PRId64 ":%" PRId64 "], available SPSC sz=%u",
      mBatchedData.mStartTime.ToMicroseconds(),
      mBatchedData.mEndTime.ToMicroseconds(), mSPSCQueue.AvailableWrite());
  SPSCData data({SPSCData::DecodedData(std::move(mBatchedData))});
  PushDataToSPSCQueue(data);
  MOZ_ASSERT(mBatchedData.mSegment.IsEmpty());
  // No batched data remains, we can cancel the pending tasks.
  mDelayedScheduler.Reset();
}

void AudioDecoderInputTrack::NotifyEndOfStream() {
  AssertOnDecoderThread();
  // Force to push all data before EOS. Otherwise, the track would be ended too
  // early without sending all data.
  PushBatchedDataIfNeeded();
  SPSCData data({SPSCData::EOS()});
  LOG("Set EOS, available SPSC sz=%u", mSPSCQueue.AvailableWrite());
  PushDataToSPSCQueue(data);
}

void AudioDecoderInputTrack::ClearFutureData() {
  AssertOnDecoderThread();
  // Clear the data hasn't been pushed to SPSC queue yet.
  mBatchedData.Clear();
  mDelayedScheduler.Reset();
  SPSCData data({SPSCData::ClearFutureData()});
  LOG("Set clear future data, available SPSC sz=%u",
      mSPSCQueue.AvailableWrite());
  PushDataToSPSCQueue(data);
}

void AudioDecoderInputTrack::PushDataToSPSCQueue(SPSCData& data) {
  AssertOnDecoderThread();
  const bool rv = mSPSCQueue.Enqueue(data);
  MOZ_DIAGNOSTIC_ASSERT(rv, "Failed to push data, SPSC queue is full!");
  Unused << rv;
}

void AudioDecoderInputTrack::SetVolume(float aVolume) {
  AssertOnDecoderThread();
  LOG("Set volume=%f", aVolume);
  GetMainThreadSerialEventTarget()->Dispatch(
      NS_NewRunnableFunction("AudioDecoderInputTrack::SetVolume",
                             [self = RefPtr<AudioDecoderInputTrack>(this),
                              aVolume] { self->SetVolumeImpl(aVolume); }));
}

void AudioDecoderInputTrack::SetVolumeImpl(float aVolume) {
  MOZ_ASSERT(NS_IsMainThread());
  class Message : public ControlMessage {
   public:
    Message(AudioDecoderInputTrack* aTrack, float aVolume)
        : ControlMessage(aTrack), mTrack(aTrack), mVolume(aVolume) {}
    void Run() override {
      TRACE_COMMENT("AudioDecoderInputTrack::SetVolume ControlMessage", "%f",
                    mVolume);
      LOG_M("Apply volume=%f", mTrack.get(), mVolume);
      mTrack->mVolume = mVolume;
    }

   protected:
    const RefPtr<AudioDecoderInputTrack> mTrack;
    const float mVolume;
  };
  GraphImpl()->AppendMessage(MakeUnique<Message>(this, aVolume));
}

void AudioDecoderInputTrack::SetPlaybackRate(float aPlaybackRate) {
  AssertOnDecoderThread();
  LOG("Set playback rate=%f", aPlaybackRate);
  GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction(
      "AudioDecoderInputTrack::SetPlaybackRate",
      [self = RefPtr<AudioDecoderInputTrack>(this), aPlaybackRate] {
        self->SetPlaybackRateImpl(aPlaybackRate);
      }));
}

void AudioDecoderInputTrack::SetPlaybackRateImpl(float aPlaybackRate) {
  MOZ_ASSERT(NS_IsMainThread());
  class Message : public ControlMessage {
   public:
    Message(AudioDecoderInputTrack* aTrack, float aPlaybackRate)
        : ControlMessage(aTrack),
          mTrack(aTrack),
          mPlaybackRate(aPlaybackRate) {}
    void Run() override {
      TRACE_COMMENT("AudioDecoderInputTrack::SetPlaybackRate ControlMessage",
                    "%f", mPlaybackRate);
      LOG_M("Apply playback rate=%f", mTrack.get(), mPlaybackRate);
      mTrack->mPlaybackRate = mPlaybackRate;
      mTrack->SetTempoAndRateForTimeStretcher();
    }

   protected:
    const RefPtr<AudioDecoderInputTrack> mTrack;
    const float mPlaybackRate;
  };
  GraphImpl()->AppendMessage(MakeUnique<Message>(this, aPlaybackRate));
}

void AudioDecoderInputTrack::SetPreservesPitch(bool aPreservesPitch) {
  AssertOnDecoderThread();
  LOG("Set preserves pitch=%d", aPreservesPitch);
  GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction(
      "AudioDecoderInputTrack::SetPreservesPitch",
      [self = RefPtr<AudioDecoderInputTrack>(this), aPreservesPitch] {
        self->SetPreservesPitchImpl(aPreservesPitch);
      }));
}

void AudioDecoderInputTrack::SetPreservesPitchImpl(bool aPreservesPitch) {
  MOZ_ASSERT(NS_IsMainThread());
  class Message : public ControlMessage {
   public:
    Message(AudioDecoderInputTrack* aTrack, bool aPreservesPitch)
        : ControlMessage(aTrack),
          mTrack(aTrack),
          mPreservesPitch(aPreservesPitch) {}
    void Run() override {
      TRACE_COMMENT("AudioDecoderInputTrack::SetPreservesPitch", "%s",
                    mPreservesPitch ? "true" : "false")
      LOG_M("Apply preserves pitch=%d", mTrack.get(), mPreservesPitch);
      mTrack->mPreservesPitch = mPreservesPitch;
      mTrack->SetTempoAndRateForTimeStretcher();
    }

   protected:
    const RefPtr<AudioDecoderInputTrack> mTrack;
    const bool mPreservesPitch;
  };
  GraphImpl()->AppendMessage(MakeUnique<Message>(this, aPreservesPitch));
}

void AudioDecoderInputTrack::Close() {
  AssertOnDecoderThread();
  LOG("Close");
  mShutdownSPSCQueue = true;
  mBatchedData.Clear();
  mDelayedScheduler.Reset();
}

void AudioDecoderInputTrack::DestroyImpl() {
  LOG("DestroyImpl");
  AssertOnGraphThreadOrNotRunning();
  mBufferedData.Clear();
  if (mTimeStretcher) {
    soundtouch::destroySoundTouchObj(mTimeStretcher);
  }
  ProcessedMediaTrack::DestroyImpl();
}

AudioDecoderInputTrack::~AudioDecoderInputTrack() {
  MOZ_ASSERT(mBatchedData.mSegment.IsEmpty());
  MOZ_ASSERT(mShutdownSPSCQueue);
  mResampler.own(nullptr);
}

void AudioDecoderInputTrack::ProcessInput(GraphTime aFrom, GraphTime aTo,
                                          uint32_t aFlags) {
  AssertOnGraphThread();
  if (Ended()) {
    return;
  }

  TrackTime consumedDuration = 0;
  auto notify = MakeScopeExit([this, &consumedDuration] {
    NotifyInTheEndOfProcessInput(consumedDuration);
  });

  if (mSentAllData && (aFlags & ALLOW_END)) {
    LOG("End track");
    mEnded = true;
    return;
  }

  const TrackTime expectedDuration = aTo - aFrom;
  LOG("ProcessInput [%" PRId64 " to %" PRId64 "], duration=%" PRId64, aFrom,
      aTo, expectedDuration);

  // Drain all data from SPSC queue first, because we want that the SPSC queue
  // always has capacity of accepting data from the producer. In addition, we
  // also need to check if there is any control related data that should be
  // applied to output segment, eg. `ClearFutureData`.
  SPSCData data;
  while (mSPSCQueue.Dequeue(&data, 1) > 0) {
    HandleSPSCData(data);
  }

  consumedDuration += AppendBufferedDataToOutput(expectedDuration);
  if (HasSentAllData()) {
    LOG("Sent all data, should end track in next iteration");
    mSentAllData = true;
  }
}

void AudioDecoderInputTrack::HandleSPSCData(SPSCData& aData) {
  AssertOnGraphThread();
  if (aData.IsDecodedData()) {
    MOZ_ASSERT(!mReceivedEOS);
    AudioSegment& segment = aData.AsDecodedData()->mSegment;
    LOG("popped out data [%" PRId64 ":%" PRId64 "] sz=%" PRId64,
        aData.AsDecodedData()->mStartTime.ToMicroseconds(),
        aData.AsDecodedData()->mEndTime.ToMicroseconds(),
        segment.GetDuration());
    mBufferedData.AppendFrom(&segment);
    return;
  }
  if (aData.IsEOS()) {
    MOZ_ASSERT(!Ended());
    LOG("Received EOS");
    mReceivedEOS = true;
    return;
  }
  if (aData.IsClearFutureData()) {
    LOG("Clear future data");
    mBufferedData.Clear();
    if (!Ended()) {
      LOG("Clear EOS");
      mReceivedEOS = false;
    }
    return;
  }
  MOZ_ASSERT_UNREACHABLE("unsupported SPSC data");
}

TrackTime AudioDecoderInputTrack::AppendBufferedDataToOutput(
    TrackTime aExpectedDuration) {
  AssertOnGraphThread();

  // Remove the necessary part from `mBufferedData` to create a new
  // segment in order to apply some operation without affecting all data.
  AudioSegment outputSegment;
  TrackTime consumedDuration = 0;
  if (mPlaybackRate != 1.0) {
    consumedDuration =
        AppendTimeStretchedDataToSegment(aExpectedDuration, outputSegment);
  } else {
    consumedDuration =
        AppendUnstretchedDataToSegment(aExpectedDuration, outputSegment);
  }

  // Apply any necessary change on the segement which would be outputed to the
  // graph.
  const TrackTime appendedDuration = outputSegment.GetDuration();
  outputSegment.ApplyVolume(mVolume);
  ApplyTrackDisabling(&outputSegment);
  mSegment->AppendFrom(&outputSegment);

  LOG("Appended %" PRId64 ", consumed %" PRId64
      ", remaining raw buffered %" PRId64 ", remaining time-stretched %u",
      appendedDuration, consumedDuration, mBufferedData.GetDuration(),
      mTimeStretcher ? mTimeStretcher->numSamples() : 0);
  if (auto gap = aExpectedDuration - appendedDuration; gap > 0) {
    LOG("Audio underrun, fill silence %" PRId64, gap);
    MOZ_ASSERT(mBufferedData.IsEmpty());
    mSegment->AppendNullData(gap);
  }
  return consumedDuration;
}

TrackTime AudioDecoderInputTrack::AppendTimeStretchedDataToSegment(
    TrackTime aExpectedDuration, AudioSegment& aOutput) {
  AssertOnGraphThread();
  EnsureTimeStretcher();

  MOZ_ASSERT(mPlaybackRate != 1.0f);
  MOZ_ASSERT(aExpectedDuration >= 0);
  MOZ_ASSERT(mTimeStretcher);
  MOZ_ASSERT(aOutput.IsEmpty());

  // If we don't have enough data that have been time-stretched, fill raw data
  // into the time stretcher until the amount of samples that time stretcher
  // finishes processed reaches or exceeds the expected duration.
  TrackTime consumedDuration = 0;
  if (mTimeStretcher->numSamples() < aExpectedDuration) {
    consumedDuration = FillDataToTimeStretcher(aExpectedDuration);
  }
  MOZ_ASSERT(consumedDuration >= 0);
  Unused << GetDataFromTimeStretcher(aExpectedDuration, aOutput);
  return consumedDuration;
}

TrackTime AudioDecoderInputTrack::FillDataToTimeStretcher(
    TrackTime aExpectedDuration) {
  AssertOnGraphThread();
  MOZ_ASSERT(mPlaybackRate != 1.0f);
  MOZ_ASSERT(aExpectedDuration >= 0);
  MOZ_ASSERT(mTimeStretcher);

  TrackTime consumedDuration = 0;
  const uint32_t channels = GetChannelCountForTimeStretcher();
  mBufferedData.IterateOnChunks([&](AudioChunk* aChunk) {
    MOZ_ASSERT(aChunk);
    if (aChunk->IsNull() && aChunk->GetDuration() == 0) {
      // Skip this chunk and wait for next one.
      return false;
    }
    const uint32_t bufferLength = channels * aChunk->GetDuration();
    if (bufferLength > mInterleavedBuffer.Capacity()) {
      mInterleavedBuffer.SetCapacity(bufferLength);
    }
    mInterleavedBuffer.SetLengthAndRetainStorage(bufferLength);
    if (aChunk->IsNull()) {
      MOZ_ASSERT(aChunk->GetDuration(), "chunk with only silence");
      memset(mInterleavedBuffer.Elements(), 0, mInterleavedBuffer.Length());
    } else {
      // Do the up-mix/down-mix first if necessary that forces to change the
      // data's channel count to the time stretcher's channel count. Then
      // perform a transformation from planar to interleaved.
      switch (aChunk->mBufferFormat) {
        case AUDIO_FORMAT_S16:
          WriteChunk<int16_t>(*aChunk, channels, 1.0f,
                              mInterleavedBuffer.Elements());
          break;
        case AUDIO_FORMAT_FLOAT32:
          WriteChunk<float>(*aChunk, channels, 1.0f,
                            mInterleavedBuffer.Elements());
          break;
        default:
          MOZ_ASSERT_UNREACHABLE("Not expected format");
      }
    }
    mTimeStretcher->putSamples(mInterleavedBuffer.Elements(),
                               aChunk->GetDuration());
    consumedDuration += aChunk->GetDuration();
    return mTimeStretcher->numSamples() >= aExpectedDuration;
  });
  mBufferedData.RemoveLeading(consumedDuration);
  return consumedDuration;
}

TrackTime AudioDecoderInputTrack::AppendUnstretchedDataToSegment(
    TrackTime aExpectedDuration, AudioSegment& aOutput) {
  AssertOnGraphThread();
  MOZ_ASSERT(mPlaybackRate == 1.0f);
  MOZ_ASSERT(aExpectedDuration >= 0);
  MOZ_ASSERT(aOutput.IsEmpty());

  const TrackTime drained =
      DrainStretchedDataIfNeeded(aExpectedDuration, aOutput);
  const TrackTime available =
      std::min(aExpectedDuration - drained, mBufferedData.GetDuration());
  aOutput.AppendSlice(mBufferedData, 0, available);
  MOZ_ASSERT(aOutput.GetDuration() <= aExpectedDuration);
  mBufferedData.RemoveLeading(available);
  return available;
}

TrackTime AudioDecoderInputTrack::DrainStretchedDataIfNeeded(
    TrackTime aExpectedDuration, AudioSegment& aOutput) {
  AssertOnGraphThread();
  MOZ_ASSERT(mPlaybackRate == 1.0f);
  MOZ_ASSERT(aExpectedDuration >= 0);

  if (!mTimeStretcher) {
    return 0;
  }
  if (mTimeStretcher->numSamples() == 0) {
    return 0;
  }
  return GetDataFromTimeStretcher(aExpectedDuration, aOutput);
}

TrackTime AudioDecoderInputTrack::GetDataFromTimeStretcher(
    TrackTime aExpectedDuration, AudioSegment& aOutput) {
  AssertOnGraphThread();
  MOZ_ASSERT(mTimeStretcher);
  MOZ_ASSERT(aExpectedDuration >= 0);

  if (HasSentAllData() && mTimeStretcher->numUnprocessedSamples()) {
    mTimeStretcher->flush();
    LOG("Flush %u frames from the time stretcher",
        mTimeStretcher->numSamples());
  }

  const TrackTime available =
      std::min((TrackTime)mTimeStretcher->numSamples(), aExpectedDuration);
  if (available == 0) {
    // Either running out of stretched data, or the raw data we filled into
    // the time stretcher were not enough for producing stretched data.
    return 0;
  }

  // Retrieve interleaved data from the time stretcher.
  const uint32_t channelCount = GetChannelCountForTimeStretcher();
  const uint32_t bufferLength = channelCount * available;
  if (bufferLength > mInterleavedBuffer.Capacity()) {
    mInterleavedBuffer.SetCapacity(bufferLength);
  }
  mInterleavedBuffer.SetLengthAndRetainStorage(bufferLength);
  mTimeStretcher->receiveSamples(mInterleavedBuffer.Elements(), available);

  // Perform a transformation from interleaved to planar.
  CheckedInt<size_t> bufferSize(sizeof(AudioDataValue));
  bufferSize *= bufferLength;
  RefPtr<SharedBuffer> buffer = SharedBuffer::Create(bufferSize);
  AudioDataValue* bufferData = static_cast<AudioDataValue*>(buffer->Data());
  AutoTArray<AudioDataValue*, 2> planarBuffer;
  planarBuffer.SetLength(channelCount);
  for (size_t idx = 0; idx < channelCount; idx++) {
    planarBuffer[idx] = bufferData + idx * available;
  }
  DeinterleaveAndConvertBuffer(mInterleavedBuffer.Elements(), available,
                               channelCount, planarBuffer.Elements());
  AutoTArray<const AudioDataValue*, 2> outputChannels;
  outputChannels.AppendElements(planarBuffer);
  aOutput.AppendFrames(buffer.forget(), outputChannels,
                       static_cast<int32_t>(available),
                       mBufferedData.GetOldestPrinciple());
  return available;
}

void AudioDecoderInputTrack::NotifyInTheEndOfProcessInput(
    TrackTime aFillDuration) {
  AssertOnGraphThread();
  mWrittenFrames += aFillDuration;
  LOG("Notify, fill=%" PRId64 ", total written=%" PRId64 ", ended=%d",
      aFillDuration, mWrittenFrames, Ended());
  if (aFillDuration > 0) {
    mOnOutput.Notify(mWrittenFrames);
  }
  if (Ended()) {
    mOnEnd.Notify();
  }
}

bool AudioDecoderInputTrack::HasSentAllData() const {
  AssertOnGraphThread();
  return mReceivedEOS && mSPSCQueue.AvailableRead() == 0 &&
         mBufferedData.IsEmpty();
}

uint32_t AudioDecoderInputTrack::NumberOfChannels() const {
  AssertOnGraphThread();
  const uint32_t maxChannelCount = GetData<AudioSegment>()->MaxChannelCount();
  return maxChannelCount ? maxChannelCount : mInitialInputChannels;
}

void AudioDecoderInputTrack::EnsureTimeStretcher() {
  AssertOnGraphThread();
  if (!mTimeStretcher) {
    mTimeStretcher = soundtouch::createSoundTouchObj();
    mTimeStretcher->setSampleRate(GraphImpl()->GraphRate());
    mTimeStretcher->setChannels(GetChannelCountForTimeStretcher());
    mTimeStretcher->setPitch(1.0);

    // SoundTouch v2.1.2 uses automatic time-stretch settings with the following
    // values:
    // Tempo 0.5: 90ms sequence, 20ms seekwindow, 8ms overlap
    // Tempo 2.0: 40ms sequence, 15ms seekwindow, 8ms overlap
    // We are going to use a smaller 10ms sequence size to improve speech
    // clarity, giving more resolution at high tempo and less reverb at low
    // tempo. Maintain 15ms seekwindow and 8ms overlap for smoothness.
    mTimeStretcher->setSetting(
        SETTING_SEQUENCE_MS,
        StaticPrefs::media_audio_playbackrate_soundtouch_sequence_ms());
    mTimeStretcher->setSetting(
        SETTING_SEEKWINDOW_MS,
        StaticPrefs::media_audio_playbackrate_soundtouch_seekwindow_ms());
    mTimeStretcher->setSetting(
        SETTING_OVERLAP_MS,
        StaticPrefs::media_audio_playbackrate_soundtouch_overlap_ms());
    SetTempoAndRateForTimeStretcher();
    LOG("Create TimeStretcher (channel=%d, playbackRate=%f, preservePitch=%d)",
        GetChannelCountForTimeStretcher(), mPlaybackRate, mPreservesPitch);
  }
}

void AudioDecoderInputTrack::SetTempoAndRateForTimeStretcher() {
  AssertOnGraphThread();
  if (!mTimeStretcher) {
    return;
  }
  if (mPreservesPitch) {
    mTimeStretcher->setTempo(mPlaybackRate);
    mTimeStretcher->setRate(1.0f);
  } else {
    mTimeStretcher->setTempo(1.0f);
    mTimeStretcher->setRate(mPlaybackRate);
  }
}

uint32_t AudioDecoderInputTrack::GetChannelCountForTimeStretcher() const {
  // The time stretcher MUST be initialized with a fixed channel count, but the
  // channel count in audio chunks might vary. Therefore, we always use the
  // initial input channel count to initialize the time stretcher and perform a
  // real-time down-mix/up-mix for audio chunks which have different channel
  // count than the initial input channel count.
  return mInitialInputChannels;
}

#undef LOG
}  // namespace mozilla