summaryrefslogtreecommitdiffstats
path: root/dom/media/encoder/TrackEncoder.cpp
blob: f62f6248754c877b6a211c15c124da0559476c65 (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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
/* 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 "TrackEncoder.h"

#include "AudioChannelFormat.h"
#include "DriftCompensation.h"
#include "MediaTrackGraph.h"
#include "MediaTrackListener.h"
#include "mozilla/AbstractThread.h"
#include "mozilla/Logging.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/RollingMean.h"
#include "VideoUtils.h"
#include "mozilla/Telemetry.h"

namespace mozilla {

LazyLogModule gTrackEncoderLog("TrackEncoder");
#define TRACK_LOG(type, msg) MOZ_LOG(gTrackEncoderLog, type, msg)

constexpr int DEFAULT_CHANNELS = 1;
constexpr int DEFAULT_FRAME_WIDTH = 640;
constexpr int DEFAULT_FRAME_HEIGHT = 480;
constexpr int DEFAULT_FRAME_RATE = 30;
// 10 second threshold if the audio encoder cannot be initialized.
constexpr int AUDIO_INIT_FAILED_DURATION = 10;
// 30 second threshold if the video encoder cannot be initialized.
constexpr int VIDEO_INIT_FAILED_DURATION = 30;
constexpr int FRAMERATE_DETECTION_ROLLING_WINDOW = 3;
constexpr size_t FRAMERATE_DETECTION_MIN_CHUNKS = 5;
constexpr int FRAMERATE_DETECTION_MAX_DURATION_S = 6;

TrackEncoder::TrackEncoder(TrackRate aTrackRate,
                           MediaQueue<EncodedFrame>& aEncodedDataQueue)
    : mInitialized(false),
      mStarted(false),
      mEndOfStream(false),
      mCanceled(false),
      mInitCounter(0),
      mSuspended(false),
      mTrackRate(aTrackRate),
      mEncodedDataQueue(aEncodedDataQueue) {}

bool TrackEncoder::IsInitialized() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mInitialized;
}

bool TrackEncoder::IsStarted() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mStarted;
}

bool TrackEncoder::IsEncodingComplete() const {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mEncodedDataQueue.IsFinished();
}

void TrackEncoder::SetInitialized() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  if (mInitialized) {
    return;
  }

  mInitialized = true;

  for (auto& l : mListeners.Clone()) {
    l->Initialized(this);
  }
}

void TrackEncoder::SetStarted() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  if (mStarted) {
    return;
  }

  mStarted = true;

  for (auto& l : mListeners.Clone()) {
    l->Started(this);
  }
}

void TrackEncoder::OnError() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  Cancel();

  for (auto& l : mListeners.Clone()) {
    l->Error(this);
  }
}

void TrackEncoder::RegisterListener(TrackEncoderListener* aListener) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  MOZ_ASSERT(!mListeners.Contains(aListener));
  mListeners.AppendElement(aListener);
}

bool TrackEncoder::UnregisterListener(TrackEncoderListener* aListener) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mListeners.RemoveElement(aListener);
}

void TrackEncoder::SetWorkerThread(AbstractThread* aWorkerThread) {
  mWorkerThread = aWorkerThread;
}

void AudioTrackEncoder::Suspend() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info, ("[AudioTrackEncoder %p]: Suspend(), was %s", this,
                             mSuspended ? "suspended" : "live"));

  if (mSuspended) {
    return;
  }

  mSuspended = true;
}

void AudioTrackEncoder::Resume() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info, ("[AudioTrackEncoder %p]: Resume(), was %s", this,
                             mSuspended ? "suspended" : "live"));

  if (!mSuspended) {
    return;
  }

  mSuspended = false;
}

void AudioTrackEncoder::AppendAudioSegment(AudioSegment&& aSegment) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  AUTO_PROFILER_LABEL("AudioTrackEncoder::AppendAudioSegment", OTHER);
  TRACK_LOG(LogLevel::Verbose,
            ("[AudioTrackEncoder %p]: AppendAudioSegment() duration=%" PRIu64,
             this, aSegment.GetDuration()));

  if (mCanceled) {
    return;
  }

  if (mEndOfStream) {
    return;
  }

  TryInit(mOutgoingBuffer, aSegment.GetDuration());

  if (mSuspended) {
    return;
  }

  SetStarted();
  mOutgoingBuffer.AppendFrom(&aSegment);

  if (!mInitialized) {
    return;
  }

  if (NS_FAILED(Encode(&mOutgoingBuffer))) {
    OnError();
    return;
  }

  MOZ_ASSERT_IF(IsEncodingComplete(), mOutgoingBuffer.IsEmpty());
}

void AudioTrackEncoder::TryInit(const AudioSegment& aSegment,
                                TrackTime aDuration) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  if (mInitialized) {
    return;
  }

  mInitCounter++;
  TRACK_LOG(LogLevel::Debug,
            ("[AudioTrackEncoder %p]: Inited the audio encoder %d times", this,
             mInitCounter));

  for (AudioSegment::ConstChunkIterator iter(aSegment); !iter.IsEnded();
       iter.Next()) {
    // The number of channels is determined by the first non-null chunk, and
    // thus the audio encoder is initialized at this time.
    if (iter->IsNull()) {
      continue;
    }

    nsresult rv = Init(iter->mChannelData.Length());

    if (NS_SUCCEEDED(rv)) {
      TRACK_LOG(LogLevel::Info,
                ("[AudioTrackEncoder %p]: Successfully initialized!", this));
      return;
    } else {
      TRACK_LOG(
          LogLevel::Error,
          ("[AudioTrackEncoder %p]: Failed to initialize the encoder!", this));
      OnError();
      return;
    }
    break;
  }

  mNotInitDuration += aDuration;
  if (!mInitialized &&
      ((mNotInitDuration - 1) / mTrackRate >= AUDIO_INIT_FAILED_DURATION) &&
      mInitCounter > 1) {
    // Perform a best effort initialization since we haven't gotten any
    // data yet. Motivated by issues like Bug 1336367
    TRACK_LOG(LogLevel::Warning,
              ("[AudioTrackEncoder]: Initialize failed for %ds. Attempting to "
               "init with %d (default) channels!",
               AUDIO_INIT_FAILED_DURATION, DEFAULT_CHANNELS));
    nsresult rv = Init(DEFAULT_CHANNELS);
    if (NS_FAILED(rv)) {
      TRACK_LOG(LogLevel::Error,
                ("[AudioTrackEncoder %p]: Default-channel-init failed.", this));
      OnError();
      return;
    }
  }
}

void AudioTrackEncoder::Cancel() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info, ("[AudioTrackEncoder %p]: Cancel()", this));
  mCanceled = true;
  mEndOfStream = true;
  mOutgoingBuffer.Clear();
  mEncodedDataQueue.Finish();
}

void AudioTrackEncoder::NotifyEndOfStream() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info,
            ("[AudioTrackEncoder %p]: NotifyEndOfStream()", this));

  if (!mCanceled && !mInitialized) {
    // If source audio track is completely silent till the end of encoding,
    // initialize the encoder with a default channel count.
    Init(DEFAULT_CHANNELS);
  }

  if (mEndOfStream) {
    return;
  }

  mEndOfStream = true;

  if (NS_FAILED(Encode(&mOutgoingBuffer))) {
    mOutgoingBuffer.Clear();
    OnError();
  }

  MOZ_ASSERT(mOutgoingBuffer.GetDuration() == 0);
}

/*static*/
void AudioTrackEncoder::InterleaveTrackData(AudioChunk& aChunk,
                                            int32_t aDuration,
                                            uint32_t aOutputChannels,
                                            AudioDataValue* aOutput) {
  uint32_t numChannelsToCopy = std::min(
      aOutputChannels, static_cast<uint32_t>(aChunk.mChannelData.Length()));
  switch (aChunk.mBufferFormat) {
    case AUDIO_FORMAT_S16: {
      AutoTArray<const int16_t*, 2> array;
      array.SetLength(numChannelsToCopy);
      for (uint32_t i = 0; i < array.Length(); i++) {
        array[i] = static_cast<const int16_t*>(aChunk.mChannelData[i]);
      }
      InterleaveTrackData(array, aDuration, aOutputChannels, aOutput,
                          aChunk.mVolume);
      break;
    }
    case AUDIO_FORMAT_FLOAT32: {
      AutoTArray<const float*, 2> array;
      array.SetLength(numChannelsToCopy);
      for (uint32_t i = 0; i < array.Length(); i++) {
        array[i] = static_cast<const float*>(aChunk.mChannelData[i]);
      }
      InterleaveTrackData(array, aDuration, aOutputChannels, aOutput,
                          aChunk.mVolume);
      break;
    }
    case AUDIO_FORMAT_SILENCE: {
      MOZ_ASSERT(false, "To implement.");
    }
  };
}

/*static*/
void AudioTrackEncoder::DeInterleaveTrackData(AudioDataValue* aInput,
                                              int32_t aDuration,
                                              int32_t aChannels,
                                              AudioDataValue* aOutput) {
  for (int32_t i = 0; i < aChannels; ++i) {
    for (int32_t j = 0; j < aDuration; ++j) {
      aOutput[i * aDuration + j] = aInput[i + j * aChannels];
    }
  }
}

size_t AudioTrackEncoder::SizeOfExcludingThis(
    mozilla::MallocSizeOf aMallocSizeOf) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mOutgoingBuffer.SizeOfExcludingThis(aMallocSizeOf);
}

VideoTrackEncoder::VideoTrackEncoder(
    RefPtr<DriftCompensator> aDriftCompensator, TrackRate aTrackRate,
    MediaQueue<EncodedFrame>& aEncodedDataQueue,
    FrameDroppingMode aFrameDroppingMode)
    : TrackEncoder(aTrackRate, aEncodedDataQueue),
      mDriftCompensator(std::move(aDriftCompensator)),
      mEncodedTicks(0),
      mVideoBitrate(0),
      mFrameDroppingMode(aFrameDroppingMode),
      mEnabled(true) {
  mLastChunk.mDuration = 0;
}

void VideoTrackEncoder::Suspend(const TimeStamp& aTime) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info,
            ("[VideoTrackEncoder %p]: Suspend() at %.3fs, was %s", this,
             mStartTime.IsNull() ? 0.0 : (aTime - mStartTime).ToSeconds(),
             mSuspended ? "suspended" : "live"));

  if (mSuspended) {
    return;
  }

  mSuspended = true;
  mSuspendTime = aTime;
}

void VideoTrackEncoder::Resume(const TimeStamp& aTime) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  if (!mSuspended) {
    return;
  }

  TRACK_LOG(
      LogLevel::Info,
      ("[VideoTrackEncoder %p]: Resume() after %.3fs, was %s", this,
       (aTime - mSuspendTime).ToSeconds(), mSuspended ? "suspended" : "live"));

  mSuspended = false;

  TimeDuration suspendDuration = aTime - mSuspendTime;
  if (!mLastChunk.mTimeStamp.IsNull()) {
    VideoChunk* nextChunk = mIncomingBuffer.FindChunkContaining(aTime);
    MOZ_ASSERT_IF(nextChunk, nextChunk->mTimeStamp <= aTime);
    if (nextChunk) {
      nextChunk->mTimeStamp = aTime;
    }
    mLastChunk.mTimeStamp += suspendDuration;
  }
  if (!mStartTime.IsNull()) {
    mStartTime += suspendDuration;
  }

  mSuspendTime = TimeStamp();
}

void VideoTrackEncoder::Disable(const TimeStamp& aTime) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Debug, ("[VideoTrackEncoder %p]: Disable()", this));

  if (mStartTime.IsNull()) {
    // We haven't started yet. No need to touch future frames.
    mEnabled = false;
    return;
  }

  // Advancing currentTime to process any frames in mIncomingBuffer between
  // mCurrentTime and aTime.
  AdvanceCurrentTime(aTime);
  if (!mLastChunk.mTimeStamp.IsNull()) {
    // Insert a black frame at t=aTime into mIncomingBuffer, to trigger the
    // shift to black at the right moment.
    VideoSegment tempSegment;
    tempSegment.AppendFrom(&mIncomingBuffer);
    mIncomingBuffer.AppendFrame(do_AddRef(mLastChunk.mFrame.GetImage()),
                                mLastChunk.mFrame.GetIntrinsicSize(),
                                mLastChunk.mFrame.GetPrincipalHandle(), true,
                                aTime);
    mIncomingBuffer.AppendFrom(&tempSegment);
  }
  mEnabled = false;
}

void VideoTrackEncoder::Enable(const TimeStamp& aTime) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Debug, ("[VideoTrackEncoder %p]: Enable()", this));

  if (mStartTime.IsNull()) {
    // We haven't started yet. No need to touch future frames.
    mEnabled = true;
    return;
  }

  // Advancing currentTime to process any frames in mIncomingBuffer between
  // mCurrentTime and aTime.
  AdvanceCurrentTime(aTime);
  if (!mLastChunk.mTimeStamp.IsNull()) {
    // Insert a real frame at t=aTime into mIncomingBuffer, to trigger the
    // shift from black at the right moment.
    VideoSegment tempSegment;
    tempSegment.AppendFrom(&mIncomingBuffer);
    mIncomingBuffer.AppendFrame(do_AddRef(mLastChunk.mFrame.GetImage()),
                                mLastChunk.mFrame.GetIntrinsicSize(),
                                mLastChunk.mFrame.GetPrincipalHandle(),
                                mLastChunk.mFrame.GetForceBlack(), aTime);
    mIncomingBuffer.AppendFrom(&tempSegment);
  }
  mEnabled = true;
}

void VideoTrackEncoder::AppendVideoSegment(VideoSegment&& aSegment) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Verbose,
            ("[VideoTrackEncoder %p]: AppendVideoSegment()", this));

  if (mCanceled) {
    return;
  }

  if (mEndOfStream) {
    return;
  }

  for (VideoSegment::ConstChunkIterator iter(aSegment); !iter.IsEnded();
       iter.Next()) {
    if (iter->IsNull()) {
      // A null image was sent. This is a signal from the source that we should
      // clear any images buffered in the future.
      mIncomingBuffer.Clear();
      continue;  // Don't append iter, as it is null.
    }
    if (VideoChunk* c = mIncomingBuffer.GetLastChunk()) {
      if (iter->mTimeStamp < c->mTimeStamp) {
        // Time went backwards. This can happen when a MediaDecoder seeks.
        // We need to handle this by removing any frames buffered in the future
        // and start over at iter->mTimeStamp.
        mIncomingBuffer.Clear();
      }
    }
    SetStarted();
    mIncomingBuffer.AppendFrame(do_AddRef(iter->mFrame.GetImage()),
                                iter->mFrame.GetIntrinsicSize(),
                                iter->mFrame.GetPrincipalHandle(),
                                iter->mFrame.GetForceBlack(), iter->mTimeStamp);
  }
  aSegment.Clear();
}

void VideoTrackEncoder::Init(const VideoSegment& aSegment,
                             const TimeStamp& aTime,
                             size_t aFrameRateDetectionMinChunks) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  MOZ_ASSERT(!aTime.IsNull());

  if (mInitialized) {
    return;
  }

  mInitCounter++;
  TRACK_LOG(LogLevel::Debug,
            ("[VideoTrackEncoder %p]: Init the video encoder %d times", this,
             mInitCounter));

  Maybe<float> framerate;
  if (!aSegment.IsEmpty()) {
    // The number of whole frames, i.e., with known duration.
    size_t frameCount = 0;
    RollingMean<TimeDuration, TimeDuration> meanDuration(
        FRAMERATE_DETECTION_ROLLING_WINDOW);
    VideoSegment::ConstChunkIterator iter(aSegment);
    TimeStamp previousChunkTime = iter->mTimeStamp;
    iter.Next();
    for (; !iter.IsEnded(); iter.Next(), ++frameCount) {
      meanDuration.insert(iter->mTimeStamp - previousChunkTime);
      previousChunkTime = iter->mTimeStamp;
    }
    TRACK_LOG(LogLevel::Debug, ("[VideoTrackEncoder %p]: Init() frameCount=%zu",
                                this, frameCount));
    if (frameCount >= aFrameRateDetectionMinChunks) {
      if (meanDuration.empty()) {
        // No whole frames available, use aTime as end time.
        framerate = Some(1.0f / (aTime - mStartTime).ToSeconds());
      } else {
        // We want some frames for estimating the framerate.
        framerate = Some(1.0f / meanDuration.mean().ToSeconds());
      }
    } else if ((aTime - mStartTime).ToSeconds() >
               FRAMERATE_DETECTION_MAX_DURATION_S) {
      // Instead of failing init after the fail-timeout, we fallback to a very
      // low rate.
      framerate = Some(static_cast<float>(frameCount) /
                       (aTime - mStartTime).ToSeconds());
    }
  }

  if (framerate) {
    for (VideoSegment::ConstChunkIterator iter(aSegment); !iter.IsEnded();
         iter.Next()) {
      if (iter->IsNull()) {
        continue;
      }

      gfx::IntSize imgsize = iter->mFrame.GetImage()->GetSize();
      gfx::IntSize intrinsicSize = iter->mFrame.GetIntrinsicSize();
      nsresult rv = Init(imgsize.width, imgsize.height, intrinsicSize.width,
                         intrinsicSize.height, *framerate);

      if (NS_SUCCEEDED(rv)) {
        TRACK_LOG(LogLevel::Info,
                  ("[VideoTrackEncoder %p]: Successfully initialized!", this));
        return;
      }

      TRACK_LOG(
          LogLevel::Error,
          ("[VideoTrackEncoder %p]: Failed to initialize the encoder!", this));
      OnError();
      break;
    }
  }

  if (((aTime - mStartTime).ToSeconds() > VIDEO_INIT_FAILED_DURATION) &&
      mInitCounter > 1) {
    TRACK_LOG(LogLevel::Warning,
              ("[VideoTrackEncoder %p]: No successful init for %ds.", this,
               VIDEO_INIT_FAILED_DURATION));
    OnError();
    return;
  }
}

void VideoTrackEncoder::Cancel() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  TRACK_LOG(LogLevel::Info, ("[VideoTrackEncoder %p]: Cancel()", this));
  mCanceled = true;
  mEndOfStream = true;
  mIncomingBuffer.Clear();
  mOutgoingBuffer.Clear();
  mLastChunk.SetNull(0);
  mEncodedDataQueue.Finish();
}

void VideoTrackEncoder::NotifyEndOfStream() {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());

  if (mCanceled) {
    return;
  }

  if (mEndOfStream) {
    // We have already been notified.
    return;
  }

  mEndOfStream = true;
  TRACK_LOG(LogLevel::Info,
            ("[VideoTrackEncoder %p]: NotifyEndOfStream()", this));

  if (!mLastChunk.IsNull()) {
    RefPtr<layers::Image> lastImage = mLastChunk.mFrame.GetImage();
    const TimeStamp now = TimeStamp::Now();
    TimeStamp currentTime = mSuspended ? mSuspendTime : mCurrentTime;
    currentTime = mDriftCompensator->GetVideoTime(now, currentTime);
    TimeDuration absoluteEndTime = currentTime - mStartTime;
    CheckedInt64 duration =
        UsecsToFrames(absoluteEndTime.ToMicroseconds(), mTrackRate) -
        mEncodedTicks;
    if (duration.isValid() && duration.value() > 0) {
      mEncodedTicks += duration.value();
      TRACK_LOG(LogLevel::Debug,
                ("[VideoTrackEncoder %p]: Appending last video frame %p at pos "
                 "%.3fs, "
                 "track-end=%.3fs",
                 this, lastImage.get(),
                 (mLastChunk.mTimeStamp - mStartTime).ToSeconds(),
                 absoluteEndTime.ToSeconds()));
      mOutgoingBuffer.AppendFrame(
          lastImage.forget(), mLastChunk.mFrame.GetIntrinsicSize(),
          PRINCIPAL_HANDLE_NONE, mLastChunk.mFrame.GetForceBlack() || !mEnabled,
          mLastChunk.mTimeStamp);
      mOutgoingBuffer.ExtendLastFrameBy(duration.value());
    }

    if (!mInitialized) {
      // Try to init without waiting for an accurate framerate.
      Init(mOutgoingBuffer, currentTime, 0);
    }
  }

  mIncomingBuffer.Clear();
  mLastChunk.SetNull(0);

  if (NS_WARN_IF(!mInitialized)) {
    // Still not initialized. There was probably no real frame at all, perhaps
    // by muting. Initialize the encoder with default frame width, frame
    // height, and frame rate.
    Init(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT, DEFAULT_FRAME_WIDTH,
         DEFAULT_FRAME_HEIGHT, DEFAULT_FRAME_RATE);
  }

  if (NS_FAILED(Encode(&mOutgoingBuffer))) {
    OnError();
  }

  MOZ_ASSERT(mOutgoingBuffer.IsEmpty());
}

void VideoTrackEncoder::SetStartOffset(const TimeStamp& aStartOffset) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  MOZ_ASSERT(mCurrentTime.IsNull());
  TRACK_LOG(LogLevel::Info, ("[VideoTrackEncoder %p]: SetStartOffset()", this));
  mStartTime = aStartOffset;
  mCurrentTime = aStartOffset;
}

void VideoTrackEncoder::AdvanceCurrentTime(const TimeStamp& aTime) {
  AUTO_PROFILER_LABEL("VideoTrackEncoder::AdvanceCurrentTime", OTHER);

  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  MOZ_ASSERT(!mStartTime.IsNull());
  MOZ_ASSERT(!mCurrentTime.IsNull());

  if (mCanceled) {
    return;
  }

  if (mEndOfStream) {
    return;
  }

  if (mSuspended) {
    TRACK_LOG(
        LogLevel::Verbose,
        ("[VideoTrackEncoder %p]: AdvanceCurrentTime() suspended at %.3fs",
         this, (mCurrentTime - mStartTime).ToSeconds()));
    mCurrentTime = aTime;
    mIncomingBuffer.ForgetUpToTime(mCurrentTime);
    return;
  }

  TRACK_LOG(LogLevel::Verbose,
            ("[VideoTrackEncoder %p]: AdvanceCurrentTime() to %.3fs", this,
             (aTime - mStartTime).ToSeconds()));

  // Grab frames within the currentTime range from the incoming buffer.
  VideoSegment tempSegment;
  {
    VideoChunk* previousChunk = &mLastChunk;
    auto appendDupes = [&](const TimeStamp& aUpTo) {
      while ((aUpTo - previousChunk->mTimeStamp).ToSeconds() > 1.0) {
        // We encode at least one frame per second, even if there are none
        // flowing.
        previousChunk->mTimeStamp += TimeDuration::FromSeconds(1.0);
        tempSegment.AppendFrame(
            do_AddRef(previousChunk->mFrame.GetImage()),
            previousChunk->mFrame.GetIntrinsicSize(),
            previousChunk->mFrame.GetPrincipalHandle(),
            previousChunk->mFrame.GetForceBlack() || !mEnabled,
            previousChunk->mTimeStamp);
        TRACK_LOG(
            LogLevel::Verbose,
            ("[VideoTrackEncoder %p]: Duplicating video frame (%p) at pos %.3f",
             this, previousChunk->mFrame.GetImage(),
             (previousChunk->mTimeStamp - mStartTime).ToSeconds()));
      }
    };
    for (VideoSegment::ChunkIterator iter(mIncomingBuffer); !iter.IsEnded();
         iter.Next()) {
      MOZ_ASSERT(!iter->IsNull());
      if (!previousChunk->IsNull() &&
          iter->mTimeStamp <= previousChunk->mTimeStamp) {
        // This frame starts earlier than previousChunk. Skip.
        continue;
      }
      if (iter->mTimeStamp >= aTime) {
        // This frame starts in the future. Stop.
        break;
      }
      if (!previousChunk->IsNull()) {
        appendDupes(iter->mTimeStamp);
      }
      tempSegment.AppendFrame(
          do_AddRef(iter->mFrame.GetImage()), iter->mFrame.GetIntrinsicSize(),
          iter->mFrame.GetPrincipalHandle(),
          iter->mFrame.GetForceBlack() || !mEnabled, iter->mTimeStamp);
      TRACK_LOG(LogLevel::Verbose,
                ("[VideoTrackEncoder %p]: Taking video frame (%p) at pos %.3f",
                 this, iter->mFrame.GetImage(),
                 (iter->mTimeStamp - mStartTime).ToSeconds()));
      previousChunk = &*iter;
    }
    if (!previousChunk->IsNull()) {
      appendDupes(aTime);
    }
  }
  mCurrentTime = aTime;
  mIncomingBuffer.ForgetUpToTime(mCurrentTime);

  // Convert tempSegment timestamps to durations and add chunks with known
  // duration to mOutgoingBuffer.
  const TimeStamp now = TimeStamp::Now();
  for (VideoSegment::ConstChunkIterator iter(tempSegment); !iter.IsEnded();
       iter.Next()) {
    VideoChunk chunk = *iter;

    if (mLastChunk.mTimeStamp.IsNull()) {
      // This is the first real chunk in the track. Make it start at the
      // beginning of the track.
      MOZ_ASSERT(!iter->mTimeStamp.IsNull());

      TRACK_LOG(
          LogLevel::Verbose,
          ("[VideoTrackEncoder %p]: Got the first video frame (%p) at pos %.3f "
           "(moving it to beginning)",
           this, iter->mFrame.GetImage(),
           (iter->mTimeStamp - mStartTime).ToSeconds()));

      mLastChunk = *iter;
      mLastChunk.mTimeStamp = mStartTime;
      continue;
    }

    MOZ_ASSERT(!mLastChunk.IsNull());
    MOZ_ASSERT(!chunk.IsNull());

    TimeDuration absoluteEndTime =
        mDriftCompensator->GetVideoTime(now, chunk.mTimeStamp) - mStartTime;
    TRACK_LOG(LogLevel::Verbose,
              ("[VideoTrackEncoder %p]: Appending video frame %p, at pos %.3fs "
               "until %.3fs",
               this, mLastChunk.mFrame.GetImage(),
               (mDriftCompensator->GetVideoTime(now, mLastChunk.mTimeStamp) -
                mStartTime)
                   .ToSeconds(),
               absoluteEndTime.ToSeconds()));
    CheckedInt64 duration =
        UsecsToFrames(absoluteEndTime.ToMicroseconds(), mTrackRate) -
        mEncodedTicks;
    if (!duration.isValid()) {
      NS_ERROR("Duration overflow");
      return;
    }

    if (duration.value() <= 0) {
      // A frame either started before the last frame (can happen when
      // multiple frames are added before SetStartOffset), or
      // two frames were so close together that they ended up at the same
      // position. We handle both cases by ignoring the previous frame.

      TRACK_LOG(LogLevel::Verbose,
                ("[VideoTrackEncoder %p]: Duration from frame %p to frame %p "
                 "is %" PRId64 ". Ignoring %p",
                 this, mLastChunk.mFrame.GetImage(), iter->mFrame.GetImage(),
                 duration.value(), mLastChunk.mFrame.GetImage()));

      TimeStamp t = mLastChunk.mTimeStamp;
      mLastChunk = *iter;
      mLastChunk.mTimeStamp = t;
      continue;
    }

    mEncodedTicks += duration.value();
    mOutgoingBuffer.AppendFrame(
        do_AddRef(mLastChunk.mFrame.GetImage()),
        mLastChunk.mFrame.GetIntrinsicSize(), PRINCIPAL_HANDLE_NONE,
        mLastChunk.mFrame.GetForceBlack() || !mEnabled, mLastChunk.mTimeStamp);
    mOutgoingBuffer.ExtendLastFrameBy(duration.value());
    mLastChunk = chunk;
  }

  if (mOutgoingBuffer.IsEmpty()) {
    return;
  }

  Init(mOutgoingBuffer, mCurrentTime, FRAMERATE_DETECTION_MIN_CHUNKS);

  if (!mInitialized) {
    return;
  }

  if (NS_FAILED(Encode(&mOutgoingBuffer))) {
    OnError();
    return;
  }

  MOZ_ASSERT(mOutgoingBuffer.IsEmpty());
}

size_t VideoTrackEncoder::SizeOfExcludingThis(
    mozilla::MallocSizeOf aMallocSizeOf) {
  MOZ_ASSERT(!mWorkerThread || mWorkerThread->IsCurrentThreadIn());
  return mIncomingBuffer.SizeOfExcludingThis(aMallocSizeOf) +
         mOutgoingBuffer.SizeOfExcludingThis(aMallocSizeOf);
}

}  // namespace mozilla

#undef TRACK_LOG