LCOV - code coverage report
Current view: top level - dom/media/mediasource - TrackBuffersManager.cpp (source / functions) Hit Total Coverage
Test: output.info Lines: 0 1214 0.0 %
Date: 2017-07-14 16:53:18 Functions: 0 96 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
       2             : /* vim: set ts=8 sts=2 et sw=2 tw=80: */
       3             : /* This Source Code Form is subject to the terms of the Mozilla Public
       4             :  * License, v. 2.0. If a copy of the MPL was not distributed with this
       5             :  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
       6             : 
       7             : #include "TrackBuffersManager.h"
       8             : #include "ContainerParser.h"
       9             : #include "MediaPrefs.h"
      10             : #include "MediaSourceDemuxer.h"
      11             : #include "MediaSourceUtils.h"
      12             : #include "mozilla/Preferences.h"
      13             : #include "mozilla/SizePrintfMacros.h"
      14             : #include "mozilla/StateMirroring.h"
      15             : #include "SourceBufferResource.h"
      16             : #include "SourceBuffer.h"
      17             : #include "WebMDemuxer.h"
      18             : #include "SourceBufferTask.h"
      19             : 
      20             : #ifdef MOZ_FMP4
      21             : #include "MP4Demuxer.h"
      22             : #endif
      23             : 
      24             : #include <limits>
      25             : 
      26             : extern mozilla::LogModule* GetMediaSourceLog();
      27             : 
      28             : #define MSE_DEBUG(arg, ...) MOZ_LOG(GetMediaSourceLog(), mozilla::LogLevel::Debug, ("TrackBuffersManager(%p:%s)::%s: " arg, this, mType.OriginalString().Data(), __func__, ##__VA_ARGS__))
      29             : #define MSE_DEBUGV(arg, ...) MOZ_LOG(GetMediaSourceLog(), mozilla::LogLevel::Verbose, ("TrackBuffersManager(%p:%s)::%s: " arg, this, mType.OriginalString().Data(), __func__, ##__VA_ARGS__))
      30             : 
      31           0 : mozilla::LogModule* GetMediaSourceSamplesLog()
      32             : {
      33             :   static mozilla::LazyLogModule sLogModule("MediaSourceSamples");
      34           0 :   return sLogModule;
      35             : }
      36             : #define SAMPLE_DEBUG(arg, ...) MOZ_LOG(GetMediaSourceSamplesLog(), mozilla::LogLevel::Debug, ("TrackBuffersManager(%p:%s)::%s: " arg, this, mType.OriginalString().Data(), __func__, ##__VA_ARGS__))
      37             : 
      38             : namespace mozilla {
      39             : 
      40             : using dom::SourceBufferAppendMode;
      41             : using media::TimeUnit;
      42             : using media::TimeInterval;
      43             : using media::TimeIntervals;
      44             : typedef SourceBufferTask::AppendBufferResult AppendBufferResult;
      45             : 
      46             : static const char*
      47           0 : AppendStateToStr(SourceBufferAttributes::AppendState aState)
      48             : {
      49           0 :   switch (aState) {
      50             :     case SourceBufferAttributes::AppendState::WAITING_FOR_SEGMENT:
      51           0 :       return "WAITING_FOR_SEGMENT";
      52             :     case SourceBufferAttributes::AppendState::PARSING_INIT_SEGMENT:
      53           0 :       return "PARSING_INIT_SEGMENT";
      54             :     case SourceBufferAttributes::AppendState::PARSING_MEDIA_SEGMENT:
      55           0 :       return "PARSING_MEDIA_SEGMENT";
      56             :     default:
      57           0 :       return "IMPOSSIBLE";
      58             :   }
      59             : }
      60             : 
      61             : static Atomic<uint32_t> sStreamSourceID(0u);
      62             : 
      63           0 : class DispatchKeyNeededEvent : public Runnable {
      64             : public:
      65           0 :   DispatchKeyNeededEvent(AbstractMediaDecoder* aDecoder,
      66             :                          nsTArray<uint8_t>& aInitData,
      67             :                          const nsString& aInitDataType)
      68           0 :     : Runnable("DispatchKeyNeededEvent")
      69             :     , mDecoder(aDecoder)
      70             :     , mInitData(aInitData)
      71           0 :     , mInitDataType(aInitDataType)
      72             :   {
      73           0 :   }
      74           0 :   NS_IMETHOD Run() override {
      75             :     // Note: Null check the owner, as the decoder could have been shutdown
      76             :     // since this event was dispatched.
      77           0 :     MediaDecoderOwner* owner = mDecoder->GetOwner();
      78           0 :     if (owner) {
      79           0 :       owner->DispatchEncrypted(mInitData, mInitDataType);
      80             :     }
      81           0 :     mDecoder = nullptr;
      82           0 :     return NS_OK;
      83             :   }
      84             : private:
      85             :   RefPtr<AbstractMediaDecoder> mDecoder;
      86             :   nsTArray<uint8_t> mInitData;
      87             :   nsString mInitDataType;
      88             : };
      89             : 
      90           0 : TrackBuffersManager::TrackBuffersManager(MediaSourceDecoder* aParentDecoder,
      91           0 :                                          const MediaContainerType& aType)
      92           0 :   : mInputBuffer(new MediaByteBuffer)
      93             :   , mBufferFull(false)
      94             :   , mFirstInitializationSegmentReceived(false)
      95             :   , mNewMediaSegmentStarted(false)
      96             :   , mActiveTrack(false)
      97             :   , mType(aType)
      98             :   , mParser(ContainerParser::CreateForMIMEType(aType))
      99             :   , mProcessedInput(0)
     100             :   , mTaskQueue(aParentDecoder->GetDemuxer()->GetTaskQueue())
     101             :   , mParentDecoder(
     102             :       new nsMainThreadPtrHolder<MediaSourceDecoder>(
     103           0 :         "TrackBuffersManager::mParentDecoder", aParentDecoder, false /* strict */))
     104             :   , mAbstractMainThread(aParentDecoder->AbstractMainThread())
     105             :   , mEnded(false)
     106           0 :   , mVideoEvictionThreshold(Preferences::GetUint("media.mediasource.eviction_threshold.video",
     107             :                                                  100 * 1024 * 1024))
     108           0 :   , mAudioEvictionThreshold(Preferences::GetUint("media.mediasource.eviction_threshold.audio",
     109             :                                                  20 * 1024 * 1024))
     110             :   , mEvictionState(EvictionState::NO_EVICTION_NEEDED)
     111           0 :   , mMonitor("TrackBuffersManager")
     112             : {
     113           0 :   MOZ_ASSERT(NS_IsMainThread(), "Must be instanciated on the main thread");
     114           0 : }
     115             : 
     116           0 : TrackBuffersManager::~TrackBuffersManager()
     117             : {
     118           0 :   ShutdownDemuxers();
     119           0 : }
     120             : 
     121             : RefPtr<TrackBuffersManager::AppendPromise>
     122           0 : TrackBuffersManager::AppendData(already_AddRefed<MediaByteBuffer> aData,
     123             :                                 const SourceBufferAttributes& aAttributes)
     124             : {
     125           0 :   MOZ_ASSERT(NS_IsMainThread());
     126           0 :   RefPtr<MediaByteBuffer> data(aData);
     127           0 :   MSE_DEBUG("Appending %" PRIuSIZE " bytes", data->Length());
     128             : 
     129           0 :   mEnded = false;
     130             : 
     131           0 :   return InvokeAsync(GetTaskQueue(), this, __func__,
     132           0 :     &TrackBuffersManager::DoAppendData, data.forget(), aAttributes);
     133             : }
     134             : 
     135             : RefPtr<TrackBuffersManager::AppendPromise>
     136           0 : TrackBuffersManager::DoAppendData(already_AddRefed<MediaByteBuffer> aData,
     137             :                                   const SourceBufferAttributes& aAttributes)
     138             : {
     139           0 :   RefPtr<AppendBufferTask> task = new AppendBufferTask(Move(aData), aAttributes);
     140           0 :   RefPtr<AppendPromise> p = task->mPromise.Ensure(__func__);
     141           0 :   QueueTask(task);
     142             : 
     143           0 :   return p;
     144             : }
     145             : 
     146             : void
     147           0 : TrackBuffersManager::QueueTask(SourceBufferTask* aTask)
     148             : {
     149           0 :   if (!OnTaskQueue()) {
     150           0 :     GetTaskQueue()->Dispatch(NewRunnableMethod<RefPtr<SourceBufferTask>>(
     151             :       "TrackBuffersManager::QueueTask",
     152             :       this,
     153             :       &TrackBuffersManager::QueueTask,
     154           0 :       aTask));
     155           0 :     return;
     156             :   }
     157           0 :   MOZ_ASSERT(OnTaskQueue());
     158           0 :   mQueue.Push(aTask);
     159           0 :   ProcessTasks();
     160             : }
     161             : 
     162             : void
     163           0 : TrackBuffersManager::ProcessTasks()
     164             : {
     165           0 :   MOZ_ASSERT(OnTaskQueue());
     166             :   typedef SourceBufferTask::Type Type;
     167             : 
     168           0 :   if (mCurrentTask) {
     169             :     // Already have a task pending. ProcessTask will be scheduled once the
     170             :     // current task complete.
     171           0 :     return;
     172             :   }
     173           0 :   RefPtr<SourceBufferTask> task = mQueue.Pop();
     174           0 :   if (!task) {
     175             :     // nothing to do.
     176           0 :     return;
     177             :   }
     178           0 :   switch (task->GetType()) {
     179             :     case Type::AppendBuffer:
     180           0 :       mCurrentTask = task;
     181           0 :       if (!mInputBuffer) {
     182           0 :         mInputBuffer = task->As<AppendBufferTask>()->mBuffer;
     183           0 :       } else if (!mInputBuffer->AppendElements(*task->As<AppendBufferTask>()->mBuffer, fallible)) {
     184           0 :         RejectAppend(NS_ERROR_OUT_OF_MEMORY, __func__);
     185           0 :         return;
     186             :       }
     187             :       mSourceBufferAttributes =
     188           0 :         MakeUnique<SourceBufferAttributes>(task->As<AppendBufferTask>()->mAttributes);
     189             :       mAppendWindow =
     190           0 :         TimeInterval(TimeUnit::FromSeconds(mSourceBufferAttributes->GetAppendWindowStart()),
     191           0 :                      TimeUnit::FromSeconds(mSourceBufferAttributes->GetAppendWindowEnd()));
     192           0 :       ScheduleSegmentParserLoop();
     193           0 :       break;
     194             :     case Type::RangeRemoval:
     195             :     {
     196           0 :       bool rv = CodedFrameRemoval(task->As<RangeRemovalTask>()->mRange);
     197           0 :       task->As<RangeRemovalTask>()->mPromise.Resolve(rv, __func__);
     198           0 :       break;
     199             :     }
     200             :     case Type::EvictData:
     201           0 :       DoEvictData(task->As<EvictDataTask>()->mPlaybackTime,
     202           0 :                   task->As<EvictDataTask>()->mSizeToEvict);
     203           0 :       break;
     204             :     case Type::Abort:
     205             :       // not handled yet, and probably never.
     206           0 :       break;
     207             :     case Type::Reset:
     208           0 :       CompleteResetParserState();
     209           0 :       break;
     210             :     case Type::Detach:
     211           0 :       mCurrentInputBuffer = nullptr;
     212           0 :       mTaskQueue = nullptr;
     213           0 :       MOZ_DIAGNOSTIC_ASSERT(mQueue.Length() == 0,
     214             :                             "Detach task must be the last");
     215           0 :       return;
     216             :     default:
     217           0 :       NS_WARNING("Invalid Task");
     218             :   }
     219           0 :   GetTaskQueue()->Dispatch(
     220           0 :     NewRunnableMethod("TrackBuffersManager::ProcessTasks",
     221             :                       this,
     222           0 :                       &TrackBuffersManager::ProcessTasks));
     223             : }
     224             : 
     225             : // The MSE spec requires that we abort the current SegmentParserLoop
     226             : // which is then followed by a call to ResetParserState.
     227             : // However due to our asynchronous design this causes inherent difficulties.
     228             : // As the spec behaviour is non deterministic anyway, we instead process all
     229             : // pending frames found in the input buffer.
     230             : void
     231           0 : TrackBuffersManager::AbortAppendData()
     232             : {
     233           0 :   MOZ_ASSERT(NS_IsMainThread());
     234           0 :   MSE_DEBUG("");
     235             : 
     236           0 :   QueueTask(new AbortTask());
     237           0 : }
     238             : 
     239             : void
     240           0 : TrackBuffersManager::ResetParserState(SourceBufferAttributes& aAttributes)
     241             : {
     242           0 :   MOZ_ASSERT(NS_IsMainThread());
     243           0 :   MSE_DEBUG("");
     244             : 
     245             :   // Spec states:
     246             :   // 1. If the append state equals PARSING_MEDIA_SEGMENT and the input buffer contains some complete coded frames, then run the coded frame processing algorithm until all of these complete coded frames have been processed.
     247             :   // However, we will wait until all coded frames have been processed regardless
     248             :   // of the value of append state.
     249           0 :   QueueTask(new ResetTask());
     250             : 
     251             :   // ResetParserState has some synchronous steps that much be performed now.
     252             :   // The remaining steps will be performed once the ResetTask gets executed.
     253             : 
     254             :   // 6. If the mode attribute equals "sequence", then set the group start timestamp to the group end timestamp
     255           0 :   if (aAttributes.GetAppendMode() == SourceBufferAppendMode::Sequence) {
     256           0 :     aAttributes.SetGroupStartTimestamp(aAttributes.GetGroupEndTimestamp());
     257             :   }
     258             :   // 8. Set append state to WAITING_FOR_SEGMENT.
     259           0 :   aAttributes.SetAppendState(AppendState::WAITING_FOR_SEGMENT);
     260           0 : }
     261             : 
     262             : RefPtr<TrackBuffersManager::RangeRemovalPromise>
     263           0 : TrackBuffersManager::RangeRemoval(TimeUnit aStart, TimeUnit aEnd)
     264             : {
     265           0 :   MOZ_ASSERT(NS_IsMainThread());
     266           0 :   MSE_DEBUG("From %.2f to %.2f", aStart.ToSeconds(), aEnd.ToSeconds());
     267             : 
     268           0 :   mEnded = false;
     269             : 
     270           0 :   return InvokeAsync(GetTaskQueue(), this, __func__,
     271             :                      &TrackBuffersManager::CodedFrameRemovalWithPromise,
     272           0 :                      TimeInterval(aStart, aEnd));
     273             : }
     274             : 
     275             : TrackBuffersManager::EvictDataResult
     276           0 : TrackBuffersManager::EvictData(const TimeUnit& aPlaybackTime, int64_t aSize)
     277             : {
     278           0 :   MOZ_ASSERT(NS_IsMainThread());
     279             : 
     280           0 :   if (aSize > EvictionThreshold()) {
     281             :     // We're adding more data than we can hold.
     282           0 :     return EvictDataResult::BUFFER_FULL;
     283             :   }
     284           0 :   const int64_t toEvict = GetSize() + aSize - EvictionThreshold();
     285             : 
     286             :   const uint32_t canEvict =
     287           0 :     Evictable(HasVideo() ? TrackInfo::kVideoTrack : TrackInfo::kAudioTrack);
     288             : 
     289           0 :   MSE_DEBUG("currentTime=%" PRId64 " buffered=%" PRId64 "kB, eviction threshold=%" PRId64 "kB, "
     290             :             "evict=%" PRId64 "kB canevict=%" PRIu32 "kB",
     291             :             aPlaybackTime.ToMicroseconds(), GetSize() / 1024,
     292             :             EvictionThreshold() / 1024, toEvict / 1024, canEvict / 1024);
     293             : 
     294           0 :   if (toEvict <= 0) {
     295           0 :     mEvictionState = EvictionState::NO_EVICTION_NEEDED;
     296           0 :     return EvictDataResult::NO_DATA_EVICTED;
     297             :   }
     298             : 
     299             :   EvictDataResult result;
     300             : 
     301           0 :   if (mBufferFull && mEvictionState == EvictionState::EVICTION_COMPLETED &&
     302           0 :       canEvict < uint32_t(toEvict)) {
     303             :     // Our buffer is currently full. We will make another eviction attempt.
     304             :     // However, the current appendBuffer will fail as we can't know ahead of
     305             :     // time if the eviction will later succeed.
     306           0 :     result = EvictDataResult::BUFFER_FULL;
     307             :   } else {
     308           0 :     mEvictionState = EvictionState::EVICTION_NEEDED;
     309           0 :     result = EvictDataResult::NO_DATA_EVICTED;
     310             :   }
     311           0 :   MSE_DEBUG(
     312             :     "Reached our size limit, schedule eviction of %" PRId64 " bytes (%s)", toEvict,
     313             :     result == EvictDataResult::BUFFER_FULL ? "buffer full" : "no data evicted");
     314           0 :   QueueTask(new EvictDataTask(aPlaybackTime, toEvict));
     315             : 
     316           0 :   return result;
     317             : }
     318             : 
     319             : TimeIntervals
     320           0 : TrackBuffersManager::Buffered() const
     321             : {
     322           0 :   MSE_DEBUG("");
     323             : 
     324             :   // http://w3c.github.io/media-source/index.html#widl-SourceBuffer-buffered
     325             : 
     326           0 :   MonitorAutoLock mon(mMonitor);
     327           0 :   nsTArray<const TimeIntervals*> tracks;
     328           0 :   if (HasVideo()) {
     329           0 :     tracks.AppendElement(&mVideoBufferedRanges);
     330             :   }
     331           0 :   if (HasAudio()) {
     332           0 :     tracks.AppendElement(&mAudioBufferedRanges);
     333             :   }
     334             : 
     335             :   // 2. Let highest end time be the largest track buffer ranges end time across all the track buffers managed by this SourceBuffer object.
     336           0 :   TimeUnit highestEndTime = HighestEndTime(tracks);
     337             : 
     338             :   // 3. Let intersection ranges equal a TimeRange object containing a single range from 0 to highest end time.
     339           0 :   TimeIntervals intersection{TimeInterval(TimeUnit::FromSeconds(0), highestEndTime)};
     340             : 
     341             :   // 4. For each track buffer managed by this SourceBuffer, run the following steps:
     342             :   //   1. Let track ranges equal the track buffer ranges for the current track buffer.
     343           0 :   for (const TimeIntervals* trackRanges : tracks) {
     344             :     // 2. If readyState is "ended", then set the end time on the last range in track ranges to highest end time.
     345             :     // 3. Let new intersection ranges equal the intersection between the intersection ranges and the track ranges.
     346           0 :     if (mEnded) {
     347           0 :       TimeIntervals tR = *trackRanges;
     348           0 :       tR.Add(TimeInterval(tR.GetEnd(), highestEndTime));
     349           0 :       intersection.Intersection(tR);
     350             :     } else {
     351           0 :       intersection.Intersection(*trackRanges);
     352             :     }
     353             :   }
     354           0 :   return intersection;
     355             : }
     356             : 
     357             : int64_t
     358           0 : TrackBuffersManager::GetSize() const
     359             : {
     360           0 :   return mSizeSourceBuffer;
     361             : }
     362             : 
     363             : void
     364           0 : TrackBuffersManager::Ended()
     365             : {
     366           0 :   mEnded = true;
     367           0 : }
     368             : 
     369             : void
     370           0 : TrackBuffersManager::Detach()
     371             : {
     372           0 :   MOZ_ASSERT(NS_IsMainThread());
     373           0 :   MSE_DEBUG("");
     374           0 :   QueueTask(new DetachTask());
     375           0 : }
     376             : 
     377             : void
     378           0 : TrackBuffersManager::CompleteResetParserState()
     379             : {
     380           0 :   MOZ_ASSERT(OnTaskQueue());
     381           0 :   MSE_DEBUG("");
     382             : 
     383             :   // We shouldn't change mInputDemuxer while a demuxer init/reset request is
     384             :   // being processed. See bug 1239983.
     385           0 :   MOZ_DIAGNOSTIC_ASSERT(!mDemuxerInitRequest.Exists(), "Previous AppendBuffer didn't complete");
     386             : 
     387           0 :   for (auto& track : GetTracksList()) {
     388             :     // 2. Unset the last decode timestamp on all track buffers.
     389             :     // 3. Unset the last frame duration on all track buffers.
     390             :     // 4. Unset the highest end timestamp on all track buffers.
     391             :     // 5. Set the need random access point flag on all track buffers to true.
     392           0 :     track->ResetAppendState();
     393             : 
     394             :     // if we have been aborted, we may have pending frames that we are going
     395             :     // to discard now.
     396           0 :     track->mQueuedSamples.Clear();
     397             :   }
     398             : 
     399             :   // 7. Remove all bytes from the input buffer.
     400           0 :   mInputBuffer = nullptr;
     401           0 :   if (mCurrentInputBuffer) {
     402           0 :     mCurrentInputBuffer->EvictAll();
     403             :     // The demuxer will be recreated during the next run of SegmentParserLoop.
     404             :     // As such we don't need to notify it that data has been removed.
     405           0 :     mCurrentInputBuffer = new SourceBufferResource();
     406             :   }
     407             : 
     408             :   // We could be left with a demuxer in an unusable state. It needs to be
     409             :   // recreated. We store in the InputBuffer an init segment which will be parsed
     410             :   // during the next Segment Parser Loop and a new demuxer will be created and
     411             :   // initialized.
     412           0 :   if (mFirstInitializationSegmentReceived) {
     413           0 :     MOZ_ASSERT(mInitData && mInitData->Length(), "we must have an init segment");
     414             :     // The aim here is really to destroy our current demuxer.
     415           0 :     CreateDemuxerforMIMEType();
     416             :     // Recreate our input buffer. We can't directly assign the initData buffer
     417             :     // to mInputBuffer as it will get modified in the Segment Parser Loop.
     418           0 :     mInputBuffer = new MediaByteBuffer;
     419           0 :     mInputBuffer->AppendElements(*mInitData);
     420             :   }
     421           0 :   RecreateParser(true);
     422           0 : }
     423             : 
     424             : int64_t
     425           0 : TrackBuffersManager::EvictionThreshold() const
     426             : {
     427           0 :   if (HasVideo()) {
     428           0 :     return mVideoEvictionThreshold;
     429             :   }
     430           0 :   return mAudioEvictionThreshold;
     431             : }
     432             : 
     433             : void
     434           0 : TrackBuffersManager::DoEvictData(const TimeUnit& aPlaybackTime,
     435             :                                  int64_t aSizeToEvict)
     436             : {
     437           0 :   MOZ_ASSERT(OnTaskQueue());
     438             : 
     439           0 :   mEvictionState = EvictionState::EVICTION_COMPLETED;
     440             : 
     441             :   // Video is what takes the most space, only evict there if we have video.
     442           0 :   auto& track = HasVideo() ? mVideoTracks : mAudioTracks;
     443           0 :   const auto& buffer = track.GetTrackBuffer();
     444             :   // Remove any data we've already played, or before the next sample to be
     445             :   // demuxed whichever is lowest.
     446           0 :   TimeUnit lowerLimit = std::min(track.mNextSampleTime, aPlaybackTime);
     447           0 :   uint32_t lastKeyFrameIndex = 0;
     448           0 :   int64_t toEvict = aSizeToEvict;
     449           0 :   int64_t partialEvict = 0;
     450           0 :   for (uint32_t i = 0; i < buffer.Length(); i++) {
     451           0 :     const auto& frame = buffer[i];
     452           0 :     if (frame->mKeyframe) {
     453           0 :       lastKeyFrameIndex = i;
     454           0 :       toEvict -= partialEvict;
     455           0 :       if (toEvict < 0) {
     456           0 :         break;
     457             :       }
     458           0 :       partialEvict = 0;
     459             :     }
     460           0 :     if (frame->GetEndTime() >= lowerLimit) {
     461           0 :       break;
     462             :     }
     463           0 :     partialEvict += frame->ComputedSizeOfIncludingThis();
     464             :   }
     465             : 
     466           0 :   const int64_t finalSize = mSizeSourceBuffer - aSizeToEvict;
     467             : 
     468           0 :   if (lastKeyFrameIndex > 0) {
     469           0 :     MSE_DEBUG("Step1. Evicting %" PRId64 " bytes prior currentTime",
     470             :               aSizeToEvict - toEvict);
     471             :     CodedFrameRemoval(
     472           0 :       TimeInterval(TimeUnit::Zero(),
     473           0 :                    buffer[lastKeyFrameIndex]->mTime - TimeUnit::FromMicroseconds(1)));
     474             :   }
     475             : 
     476           0 :   if (mSizeSourceBuffer <= finalSize) {
     477           0 :     return;
     478             :   }
     479             : 
     480           0 :   toEvict = mSizeSourceBuffer - finalSize;
     481             : 
     482             :   // See if we can evict data into the future.
     483             :   // We do not evict data from the currently used buffered interval.
     484             : 
     485           0 :   TimeUnit currentPosition = std::max(aPlaybackTime, track.mNextSampleTime);
     486           0 :   TimeIntervals futureBuffered(TimeInterval(currentPosition, TimeUnit::FromInfinity()));
     487           0 :   futureBuffered.Intersection(track.mBufferedRanges);
     488           0 :   futureBuffered.SetFuzz(MediaSourceDemuxer::EOS_FUZZ / 2);
     489           0 :   if (futureBuffered.Length() <= 1) {
     490             :     // We have one continuous segment ahead of us:
     491             :     // nothing further can be evicted.
     492           0 :     return;
     493             :   }
     494             : 
     495             :   // Don't evict before the end of the current segment
     496           0 :   TimeUnit upperLimit = futureBuffered[0].mEnd;
     497           0 :   uint32_t evictedFramesStartIndex = buffer.Length();
     498           0 :   for (int32_t i = buffer.Length() - 1; i >= 0; i--) {
     499           0 :     const auto& frame = buffer[i];
     500           0 :     if (frame->mTime <= upperLimit || toEvict < 0) {
     501             :       // We've reached a frame that shouldn't be evicted -> Evict after it -> i+1.
     502             :       // Or the previous loop reached the eviction threshold -> Evict from it -> i+1.
     503           0 :       evictedFramesStartIndex = i + 1;
     504           0 :       break;
     505             :     }
     506           0 :     toEvict -= frame->ComputedSizeOfIncludingThis();
     507             :   }
     508           0 :   if (evictedFramesStartIndex < buffer.Length()) {
     509           0 :     MSE_DEBUG("Step2. Evicting %" PRId64 " bytes from trailing data",
     510             :               mSizeSourceBuffer - finalSize - toEvict);
     511             :     CodedFrameRemoval(
     512           0 :       TimeInterval(buffer[evictedFramesStartIndex]->mTime,
     513           0 :                    TimeUnit::FromInfinity()));
     514             :   }
     515             : }
     516             : 
     517             : RefPtr<TrackBuffersManager::RangeRemovalPromise>
     518           0 : TrackBuffersManager::CodedFrameRemovalWithPromise(TimeInterval aInterval)
     519             : {
     520           0 :   MOZ_ASSERT(OnTaskQueue());
     521             : 
     522           0 :   RefPtr<RangeRemovalTask> task = new RangeRemovalTask(aInterval);
     523           0 :   RefPtr<RangeRemovalPromise> p = task->mPromise.Ensure(__func__);
     524           0 :   QueueTask(task);
     525             : 
     526           0 :   return p;
     527             : }
     528             : 
     529             : bool
     530           0 : TrackBuffersManager::CodedFrameRemoval(TimeInterval aInterval)
     531             : {
     532           0 :   MOZ_ASSERT(OnTaskQueue());
     533           0 :   MSE_DEBUG("From %.2fs to %.2f",
     534             :             aInterval.mStart.ToSeconds(), aInterval.mEnd.ToSeconds());
     535             : 
     536             : #if DEBUG
     537           0 :   if (HasVideo()) {
     538           0 :     MSE_DEBUG("before video ranges=%s",
     539             :               DumpTimeRanges(mVideoTracks.mBufferedRanges).get());
     540             :   }
     541           0 :   if (HasAudio()) {
     542           0 :     MSE_DEBUG("before audio ranges=%s",
     543             :               DumpTimeRanges(mAudioTracks.mBufferedRanges).get());
     544             :   }
     545             : #endif
     546             : 
     547             :   // 1. Let start be the starting presentation timestamp for the removal range.
     548           0 :   TimeUnit start = aInterval.mStart;
     549             :   // 2. Let end be the end presentation timestamp for the removal range.
     550           0 :   TimeUnit end = aInterval.mEnd;
     551             : 
     552           0 :   bool dataRemoved = false;
     553             : 
     554             :   // 3. For each track buffer in this source buffer, run the following steps:
     555           0 :   for (auto track : GetTracksList()) {
     556           0 :     MSE_DEBUGV("Processing %s track", track->mInfo->mMimeType.get());
     557             :     // 1. Let remove end timestamp be the current value of duration
     558             :     // See bug: https://www.w3.org/Bugs/Public/show_bug.cgi?id=28727
     559             :     // At worse we will remove all frames until the end, unless a key frame is
     560             :     // found between the current interval's end and the trackbuffer's end.
     561           0 :     TimeUnit removeEndTimestamp = track->mBufferedRanges.GetEnd();
     562             : 
     563           0 :     if (start > removeEndTimestamp) {
     564             :       // Nothing to remove.
     565           0 :       continue;
     566             :     }
     567             : 
     568             :     // 2. If this track buffer has a random access point timestamp that is greater than or equal to end,
     569             :     // then update remove end timestamp to that random access point timestamp.
     570           0 :     if (end < track->mBufferedRanges.GetEnd()) {
     571           0 :       for (auto& frame : track->GetTrackBuffer()) {
     572           0 :         if (frame->mKeyframe && frame->mTime >= end) {
     573           0 :           removeEndTimestamp = frame->mTime;
     574           0 :           break;
     575             :         }
     576             :       }
     577             :     }
     578             : 
     579             :     // 3. Remove all media data, from this track buffer, that contain starting
     580             :     // timestamps greater than or equal to start and less than the remove end timestamp.
     581             :     // 4. Remove decoding dependencies of the coded frames removed in the previous step:
     582             :     // Remove all coded frames between the coded frames removed in the previous step and the next random access point after those removed frames.
     583           0 :     TimeIntervals removedInterval{TimeInterval(start, removeEndTimestamp)};
     584           0 :     RemoveFrames(removedInterval, *track, 0);
     585             : 
     586             :     // 5. If this object is in activeSourceBuffers, the current playback position
     587             :     // is greater than or equal to start and less than the remove end timestamp,
     588             :     // and HTMLMediaElement.readyState is greater than HAVE_METADATA, then set the
     589             :     // HTMLMediaElement.readyState attribute to HAVE_METADATA and stall playback.
     590             :     // This will be done by the MDSM during playback.
     591             :     // TODO properly, so it works even if paused.
     592             :   }
     593             : 
     594           0 :   UpdateBufferedRanges();
     595             : 
     596             :   // Update our reported total size.
     597           0 :   mSizeSourceBuffer = mVideoTracks.mSizeBuffer + mAudioTracks.mSizeBuffer;
     598             : 
     599             :   // 4. If buffer full flag equals true and this object is ready to accept more bytes, then set the buffer full flag to false.
     600           0 :   if (mBufferFull && mSizeSourceBuffer < EvictionThreshold()) {
     601           0 :     mBufferFull = false;
     602             :   }
     603             : 
     604           0 :   return dataRemoved;
     605             : }
     606             : 
     607             : void
     608           0 : TrackBuffersManager::UpdateBufferedRanges()
     609             : {
     610           0 :   MonitorAutoLock mon(mMonitor);
     611             : 
     612           0 :   mVideoBufferedRanges = mVideoTracks.mSanitizedBufferedRanges;
     613           0 :   mAudioBufferedRanges = mAudioTracks.mSanitizedBufferedRanges;
     614             : 
     615             : #if DEBUG
     616           0 :   if (HasVideo()) {
     617           0 :     MSE_DEBUG("after video ranges=%s",
     618             :               DumpTimeRanges(mVideoTracks.mBufferedRanges).get());
     619             :   }
     620           0 :   if (HasAudio()) {
     621           0 :     MSE_DEBUG("after audio ranges=%s",
     622             :               DumpTimeRanges(mAudioTracks.mBufferedRanges).get());
     623             :   }
     624             : #endif
     625           0 : }
     626             : 
     627             : void
     628           0 : TrackBuffersManager::SegmentParserLoop()
     629             : {
     630           0 :   MOZ_ASSERT(OnTaskQueue());
     631             : 
     632             :   while (true) {
     633             :     // 1. If the input buffer is empty, then jump to the need more data step below.
     634           0 :     if (!mInputBuffer || mInputBuffer->IsEmpty()) {
     635           0 :       NeedMoreData();
     636           0 :       return;
     637             :     }
     638             :     // 2. If the input buffer contains bytes that violate the SourceBuffer
     639             :     // byte stream format specification, then run the append error algorithm with
     640             :     // the decode error parameter set to true and abort this algorithm.
     641             :     // TODO
     642             : 
     643             :     // 3. Remove any bytes that the byte stream format specifications say must be
     644             :     // ignored from the start of the input buffer.
     645             :     // We do not remove bytes from our input buffer. Instead we enforce that
     646             :     // our ContainerParser is able to skip over all data that is supposed to be
     647             :     // ignored.
     648             : 
     649             :     // 4. If the append state equals WAITING_FOR_SEGMENT, then run the following
     650             :     // steps:
     651           0 :     if (mSourceBufferAttributes->GetAppendState() == AppendState::WAITING_FOR_SEGMENT) {
     652           0 :       MediaResult haveInitSegment = mParser->IsInitSegmentPresent(mInputBuffer);
     653           0 :       if (NS_SUCCEEDED(haveInitSegment)) {
     654           0 :         SetAppendState(AppendState::PARSING_INIT_SEGMENT);
     655           0 :         if (mFirstInitializationSegmentReceived) {
     656             :           // This is a new initialization segment. Obsolete the old one.
     657           0 :           RecreateParser(false);
     658             :         }
     659           0 :         continue;
     660             :       }
     661             :       MediaResult haveMediaSegment =
     662           0 :         mParser->IsMediaSegmentPresent(mInputBuffer);
     663           0 :       if (NS_SUCCEEDED(haveMediaSegment)) {
     664           0 :         SetAppendState(AppendState::PARSING_MEDIA_SEGMENT);
     665           0 :         mNewMediaSegmentStarted = true;
     666           0 :         continue;
     667             :       }
     668             :       // We have neither an init segment nor a media segment.
     669             :       // Check if it was invalid data.
     670           0 :       if (haveInitSegment != NS_ERROR_NOT_AVAILABLE) {
     671           0 :         MSE_DEBUG("Found invalid data.");
     672           0 :         RejectAppend(haveInitSegment, __func__);
     673           0 :         return;
     674             :       }
     675           0 :       if (haveMediaSegment != NS_ERROR_NOT_AVAILABLE) {
     676           0 :         MSE_DEBUG("Found invalid data.");
     677           0 :         RejectAppend(haveMediaSegment, __func__);
     678           0 :         return;
     679             :       }
     680           0 :       MSE_DEBUG("Found incomplete data.");
     681           0 :       NeedMoreData();
     682           0 :       return;
     683             :     }
     684             : 
     685             :     int64_t start, end;
     686             :     MediaResult newData =
     687           0 :       mParser->ParseStartAndEndTimestamps(mInputBuffer, start, end);
     688           0 :     if (!NS_SUCCEEDED(newData) && newData.Code() != NS_ERROR_NOT_AVAILABLE) {
     689           0 :       RejectAppend(newData, __func__);
     690           0 :       return;
     691             :     }
     692           0 :     mProcessedInput += mInputBuffer->Length();
     693             : 
     694             :     // 5. If the append state equals PARSING_INIT_SEGMENT, then run the
     695             :     // following steps:
     696           0 :     if (mSourceBufferAttributes->GetAppendState() == AppendState::PARSING_INIT_SEGMENT) {
     697           0 :       if (mParser->InitSegmentRange().IsEmpty()) {
     698           0 :         mInputBuffer = nullptr;
     699           0 :         NeedMoreData();
     700           0 :         return;
     701             :       }
     702           0 :       InitializationSegmentReceived();
     703           0 :       return;
     704             :     }
     705           0 :     if (mSourceBufferAttributes->GetAppendState() == AppendState::PARSING_MEDIA_SEGMENT) {
     706             :       // 1. If the first initialization segment received flag is false, then run the append error algorithm with the decode error parameter set to true and abort this algorithm.
     707           0 :       if (!mFirstInitializationSegmentReceived) {
     708           0 :         RejectAppend(NS_ERROR_FAILURE, __func__);
     709           0 :         return;
     710             :       }
     711             : 
     712             :       // We can't feed some demuxers (WebMDemuxer) with data that do not have
     713             :       // monotonizally increasing timestamps. So we check if we have a
     714             :       // discontinuity from the previous segment parsed.
     715             :       // If so, recreate a new demuxer to ensure that the demuxer is only fed
     716             :       // monotonically increasing data.
     717           0 :       if (mNewMediaSegmentStarted) {
     718           0 :         if (NS_SUCCEEDED(newData) && mLastParsedEndTime.isSome() &&
     719           0 :             start < mLastParsedEndTime.ref().ToMicroseconds()) {
     720           0 :           MSE_DEBUG("Re-creating demuxer");
     721           0 :           ResetDemuxingState();
     722           0 :           return;
     723             :         }
     724           0 :         if (NS_SUCCEEDED(newData) || !mParser->MediaSegmentRange().IsEmpty()) {
     725           0 :           if (mPendingInputBuffer) {
     726             :             // We now have a complete media segment header. We can resume parsing
     727             :             // the data.
     728           0 :             AppendDataToCurrentInputBuffer(mPendingInputBuffer);
     729           0 :             mPendingInputBuffer = nullptr;
     730             :           }
     731           0 :           mNewMediaSegmentStarted = false;
     732             :         } else {
     733             :           // We don't have any data to demux yet, stash aside the data.
     734             :           // This also handles the case:
     735             :           // 2. If the input buffer does not contain a complete media segment header yet, then jump to the need more data step below.
     736           0 :           if (!mPendingInputBuffer) {
     737           0 :             mPendingInputBuffer = mInputBuffer;
     738             :           } else {
     739           0 :             mPendingInputBuffer->AppendElements(*mInputBuffer);
     740             :           }
     741           0 :           mInputBuffer = nullptr;
     742           0 :           NeedMoreData();
     743           0 :           return;
     744             :         }
     745             :       }
     746             : 
     747             :       // 3. If the input buffer contains one or more complete coded frames, then run the coded frame processing algorithm.
     748           0 :       RefPtr<TrackBuffersManager> self = this;
     749           0 :       CodedFrameProcessing()
     750           0 :         ->Then(GetTaskQueue(), __func__,
     751           0 :                [self] (bool aNeedMoreData) {
     752           0 :                  self->mProcessingRequest.Complete();
     753           0 :                  if (aNeedMoreData) {
     754           0 :                    self->NeedMoreData();
     755             :                  } else {
     756           0 :                    self->ScheduleSegmentParserLoop();
     757             :                  }
     758           0 :                },
     759           0 :                [self] (const MediaResult& aRejectValue) {
     760           0 :                  self->mProcessingRequest.Complete();
     761           0 :                  self->RejectAppend(aRejectValue, __func__);
     762           0 :                })
     763           0 :         ->Track(mProcessingRequest);
     764           0 :       return;
     765             :     }
     766           0 :   }
     767             : }
     768             : 
     769             : void
     770           0 : TrackBuffersManager::NeedMoreData()
     771             : {
     772           0 :   MSE_DEBUG("");
     773           0 :   MOZ_DIAGNOSTIC_ASSERT(mCurrentTask && mCurrentTask->GetType() == SourceBufferTask::Type::AppendBuffer);
     774           0 :   MOZ_DIAGNOSTIC_ASSERT(mSourceBufferAttributes);
     775             : 
     776           0 :   mCurrentTask->As<AppendBufferTask>()->mPromise.Resolve(
     777           0 :     SourceBufferTask::AppendBufferResult(mActiveTrack,
     778             :                                          *mSourceBufferAttributes),
     779           0 :                                          __func__);
     780           0 :   mSourceBufferAttributes = nullptr;
     781           0 :   mCurrentTask = nullptr;
     782           0 :   ProcessTasks();
     783           0 : }
     784             : 
     785             : void
     786           0 : TrackBuffersManager::RejectAppend(const MediaResult& aRejectValue, const char* aName)
     787             : {
     788           0 :   MSE_DEBUG("rv=%" PRIu32, static_cast<uint32_t>(aRejectValue.Code()));
     789           0 :   MOZ_DIAGNOSTIC_ASSERT(mCurrentTask && mCurrentTask->GetType() == SourceBufferTask::Type::AppendBuffer);
     790             : 
     791           0 :   mCurrentTask->As<AppendBufferTask>()->mPromise.Reject(aRejectValue, __func__);
     792           0 :   mSourceBufferAttributes = nullptr;
     793           0 :   mCurrentTask = nullptr;
     794           0 :   ProcessTasks();
     795           0 : }
     796             : 
     797             : void
     798           0 : TrackBuffersManager::ScheduleSegmentParserLoop()
     799             : {
     800           0 :   GetTaskQueue()->Dispatch(
     801           0 :     NewRunnableMethod("TrackBuffersManager::SegmentParserLoop",
     802             :                       this,
     803           0 :                       &TrackBuffersManager::SegmentParserLoop));
     804           0 : }
     805             : 
     806             : void
     807           0 : TrackBuffersManager::ShutdownDemuxers()
     808             : {
     809           0 :   if (mVideoTracks.mDemuxer) {
     810           0 :     mVideoTracks.mDemuxer->BreakCycles();
     811           0 :     mVideoTracks.mDemuxer = nullptr;
     812             :   }
     813           0 :   if (mAudioTracks.mDemuxer) {
     814           0 :     mAudioTracks.mDemuxer->BreakCycles();
     815           0 :     mAudioTracks.mDemuxer = nullptr;
     816             :   }
     817             :   // We shouldn't change mInputDemuxer while a demuxer init/reset request is
     818             :   // being processed. See bug 1239983.
     819           0 :   MOZ_DIAGNOSTIC_ASSERT(!mDemuxerInitRequest.Exists());
     820           0 :   mInputDemuxer = nullptr;
     821           0 :   mLastParsedEndTime.reset();
     822           0 : }
     823             : 
     824             : void
     825           0 : TrackBuffersManager::CreateDemuxerforMIMEType()
     826             : {
     827           0 :   ShutdownDemuxers();
     828             : 
     829           0 :   if (mType.Type() == MEDIAMIMETYPE("video/webm") ||
     830           0 :       mType.Type() == MEDIAMIMETYPE("audio/webm")) {
     831           0 :     mInputDemuxer = new WebMDemuxer(mCurrentInputBuffer, true /* IsMediaSource*/ );
     832           0 :     return;
     833             :   }
     834             : 
     835             : #ifdef MOZ_FMP4
     836           0 :   if (mType.Type() == MEDIAMIMETYPE("video/mp4")
     837           0 :       || mType.Type() == MEDIAMIMETYPE("audio/mp4")) {
     838           0 :     mInputDemuxer = new MP4Demuxer(mCurrentInputBuffer);
     839           0 :     return;
     840             :   }
     841             : #endif
     842           0 :   NS_WARNING("Not supported (yet)");
     843           0 :   return;
     844             : }
     845             : 
     846             : // We reset the demuxer by creating a new one and initializing it.
     847             : void
     848           0 : TrackBuffersManager::ResetDemuxingState()
     849             : {
     850           0 :   MOZ_ASSERT(mParser && mParser->HasInitData());
     851           0 :   RecreateParser(true);
     852           0 :   mCurrentInputBuffer = new SourceBufferResource();
     853             :   // The demuxer isn't initialized yet ; we don't want to notify it
     854             :   // that data has been appended yet ; so we simply append the init segment
     855             :   // to the resource.
     856           0 :   mCurrentInputBuffer->AppendData(mParser->InitData());
     857           0 :   CreateDemuxerforMIMEType();
     858           0 :   if (!mInputDemuxer) {
     859           0 :     RejectAppend(NS_ERROR_FAILURE, __func__);
     860           0 :     return;
     861             :   }
     862           0 :   mInputDemuxer->Init()
     863           0 :     ->Then(GetTaskQueue(), __func__,
     864             :            this,
     865             :            &TrackBuffersManager::OnDemuxerResetDone,
     866             :            &TrackBuffersManager::OnDemuxerInitFailed)
     867           0 :     ->Track(mDemuxerInitRequest);
     868             : }
     869             : 
     870             : void
     871           0 : TrackBuffersManager::OnDemuxerResetDone(const MediaResult& aResult)
     872             : {
     873           0 :   MOZ_ASSERT(OnTaskQueue());
     874           0 :   mDemuxerInitRequest.Complete();
     875             : 
     876           0 :   if (NS_FAILED(aResult) && MediaPrefs::MediaWarningsAsErrors()) {
     877           0 :     RejectAppend(aResult, __func__);
     878           0 :     return;
     879             :   }
     880             : 
     881             :   // mInputDemuxer shouldn't have been destroyed while a demuxer init/reset
     882             :   // request was being processed. See bug 1239983.
     883           0 :   MOZ_DIAGNOSTIC_ASSERT(mInputDemuxer);
     884             : 
     885           0 :   if (aResult != NS_OK && mParentDecoder) {
     886           0 :     RefPtr<TrackBuffersManager> self = this;
     887           0 :     mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
     888           0 :       "TrackBuffersManager::OnDemuxerResetDone", [self, aResult]() {
     889           0 :         if (self->mParentDecoder && self->mParentDecoder->GetOwner()) {
     890           0 :           self->mParentDecoder->GetOwner()->DecodeWarning(aResult);
     891             :         }
     892           0 :       }));
     893             :   }
     894             : 
     895             :   // Recreate track demuxers.
     896           0 :   uint32_t numVideos = mInputDemuxer->GetNumberTracks(TrackInfo::kVideoTrack);
     897           0 :   if (numVideos) {
     898             :     // We currently only handle the first video track.
     899             :     mVideoTracks.mDemuxer =
     900           0 :       mInputDemuxer->GetTrackDemuxer(TrackInfo::kVideoTrack, 0);
     901           0 :     MOZ_ASSERT(mVideoTracks.mDemuxer);
     902             :   }
     903             : 
     904           0 :   uint32_t numAudios = mInputDemuxer->GetNumberTracks(TrackInfo::kAudioTrack);
     905           0 :   if (numAudios) {
     906             :     // We currently only handle the first audio track.
     907             :     mAudioTracks.mDemuxer =
     908           0 :       mInputDemuxer->GetTrackDemuxer(TrackInfo::kAudioTrack, 0);
     909           0 :     MOZ_ASSERT(mAudioTracks.mDemuxer);
     910             :   }
     911             : 
     912           0 :   if (mPendingInputBuffer) {
     913             :     // We had a partial media segment header stashed aside.
     914             :     // Reparse its content so we can continue parsing the current input buffer.
     915             :     int64_t start, end;
     916           0 :     mParser->ParseStartAndEndTimestamps(mPendingInputBuffer, start, end);
     917           0 :     mProcessedInput += mPendingInputBuffer->Length();
     918             :   }
     919             : 
     920           0 :   SegmentParserLoop();
     921             : }
     922             : 
     923             : void
     924           0 : TrackBuffersManager::AppendDataToCurrentInputBuffer(MediaByteBuffer* aData)
     925             : {
     926           0 :   MOZ_ASSERT(mCurrentInputBuffer);
     927           0 :   mCurrentInputBuffer->AppendData(aData);
     928           0 :   mInputDemuxer->NotifyDataArrived();
     929           0 : }
     930             : 
     931             : void
     932           0 : TrackBuffersManager::InitializationSegmentReceived()
     933             : {
     934           0 :   MOZ_ASSERT(mParser->HasCompleteInitData());
     935             : 
     936           0 :   int64_t endInit = mParser->InitSegmentRange().mEnd;
     937           0 :   if (mInputBuffer->Length() > mProcessedInput ||
     938           0 :       int64_t(mProcessedInput - mInputBuffer->Length()) > endInit) {
     939             :     // Something is not quite right with the data appended. Refuse it.
     940           0 :     RejectAppend(MediaResult(NS_ERROR_FAILURE,
     941             :                              "Invalid state following initialization segment"),
     942           0 :                  __func__);
     943           0 :     return;
     944             :   }
     945             : 
     946           0 :   mCurrentInputBuffer = new SourceBufferResource();
     947             :   // The demuxer isn't initialized yet ; we don't want to notify it
     948             :   // that data has been appended yet ; so we simply append the init segment
     949             :   // to the resource.
     950           0 :   mCurrentInputBuffer->AppendData(mParser->InitData());
     951           0 :   uint32_t length = endInit - (mProcessedInput - mInputBuffer->Length());
     952           0 :   if (mInputBuffer->Length() == length) {
     953           0 :     mInputBuffer = nullptr;
     954             :   } else {
     955           0 :     MOZ_RELEASE_ASSERT(length <= mInputBuffer->Length());
     956           0 :     mInputBuffer->RemoveElementsAt(0, length);
     957             :   }
     958           0 :   CreateDemuxerforMIMEType();
     959           0 :   if (!mInputDemuxer) {
     960           0 :     NS_WARNING("TODO type not supported");
     961           0 :     RejectAppend(NS_ERROR_DOM_NOT_SUPPORTED_ERR, __func__);
     962           0 :     return;
     963             :   }
     964           0 :   mInputDemuxer->Init()
     965           0 :     ->Then(GetTaskQueue(), __func__,
     966             :            this,
     967             :            &TrackBuffersManager::OnDemuxerInitDone,
     968             :            &TrackBuffersManager::OnDemuxerInitFailed)
     969           0 :     ->Track(mDemuxerInitRequest);
     970             : }
     971             : 
     972             : void
     973           0 : TrackBuffersManager::OnDemuxerInitDone(const MediaResult& aResult)
     974             : {
     975           0 :   MOZ_ASSERT(OnTaskQueue());
     976           0 :   MOZ_DIAGNOSTIC_ASSERT(mInputDemuxer, "mInputDemuxer has been destroyed");
     977             : 
     978           0 :   mDemuxerInitRequest.Complete();
     979             : 
     980           0 :   if (NS_FAILED(aResult) && MediaPrefs::MediaWarningsAsErrors()) {
     981           0 :     RejectAppend(aResult, __func__);
     982           0 :     return;
     983             :   }
     984             : 
     985           0 :   MediaInfo info;
     986             : 
     987           0 :   uint32_t numVideos = mInputDemuxer->GetNumberTracks(TrackInfo::kVideoTrack);
     988           0 :   if (numVideos) {
     989             :     // We currently only handle the first video track.
     990             :     mVideoTracks.mDemuxer =
     991           0 :       mInputDemuxer->GetTrackDemuxer(TrackInfo::kVideoTrack, 0);
     992           0 :     MOZ_ASSERT(mVideoTracks.mDemuxer);
     993           0 :     info.mVideo = *mVideoTracks.mDemuxer->GetInfo()->GetAsVideoInfo();
     994           0 :     info.mVideo.mTrackId = 2;
     995             :   }
     996             : 
     997           0 :   uint32_t numAudios = mInputDemuxer->GetNumberTracks(TrackInfo::kAudioTrack);
     998           0 :   if (numAudios) {
     999             :     // We currently only handle the first audio track.
    1000             :     mAudioTracks.mDemuxer =
    1001           0 :       mInputDemuxer->GetTrackDemuxer(TrackInfo::kAudioTrack, 0);
    1002           0 :     MOZ_ASSERT(mAudioTracks.mDemuxer);
    1003           0 :     info.mAudio = *mAudioTracks.mDemuxer->GetInfo()->GetAsAudioInfo();
    1004           0 :     info.mAudio.mTrackId = 1;
    1005             :   }
    1006             : 
    1007           0 :   int64_t videoDuration = numVideos ? info.mVideo.mDuration.ToMicroseconds() : 0;
    1008           0 :   int64_t audioDuration = numAudios ? info.mAudio.mDuration.ToMicroseconds() : 0;
    1009             : 
    1010           0 :   int64_t duration = std::max(videoDuration, audioDuration);
    1011             :   // 1. Update the duration attribute if it currently equals NaN.
    1012             :   // Those steps are performed by the MediaSourceDecoder::SetInitialDuration
    1013           0 :   mAbstractMainThread->Dispatch(
    1014           0 :     NewRunnableMethod<int64_t>("MediaSourceDecoder::SetInitialDuration",
    1015           0 :                                mParentDecoder.get(),
    1016             :                                &MediaSourceDecoder::SetInitialDuration,
    1017           0 :                                duration ? duration : -1));
    1018             : 
    1019             :   // 2. If the initialization segment has no audio, video, or text tracks, then
    1020             :   // run the append error algorithm with the decode error parameter set to true
    1021             :   // and abort these steps.
    1022           0 :   if (!numVideos && !numAudios) {
    1023           0 :     RejectAppend(NS_ERROR_FAILURE, __func__);
    1024           0 :     return;
    1025             :   }
    1026             : 
    1027             :   // 3. If the first initialization segment received flag is true, then run the following steps:
    1028           0 :   if (mFirstInitializationSegmentReceived) {
    1029           0 :     if (numVideos != mVideoTracks.mNumTracks ||
    1030           0 :         numAudios != mAudioTracks.mNumTracks ||
    1031           0 :         (numVideos && info.mVideo.mMimeType != mVideoTracks.mInfo->mMimeType) ||
    1032           0 :         (numAudios && info.mAudio.mMimeType != mAudioTracks.mInfo->mMimeType)) {
    1033           0 :       RejectAppend(NS_ERROR_FAILURE, __func__);
    1034           0 :       return;
    1035             :     }
    1036             :     // 1. If more than one track for a single type are present (ie 2 audio tracks),
    1037             :     // then the Track IDs match the ones in the first initialization segment.
    1038             :     // TODO
    1039             :     // 2. Add the appropriate track descriptions from this initialization
    1040             :     // segment to each of the track buffers.
    1041             :     // TODO
    1042             :     // 3. Set the need random access point flag on all track buffers to true.
    1043           0 :     mVideoTracks.mNeedRandomAccessPoint = true;
    1044           0 :     mAudioTracks.mNeedRandomAccessPoint = true;
    1045             :   }
    1046             : 
    1047             :   // 4. Let active track flag equal false.
    1048           0 :   bool activeTrack = false;
    1049             : 
    1050             :   // Increase our stream id.
    1051           0 :   uint32_t streamID = sStreamSourceID++;
    1052             : 
    1053             :   // 5. If the first initialization segment received flag is false, then run the following steps:
    1054           0 :   if (!mFirstInitializationSegmentReceived) {
    1055           0 :     mAudioTracks.mNumTracks = numAudios;
    1056             :     // TODO:
    1057             :     // 1. If the initialization segment contains tracks with codecs the user agent
    1058             :     // does not support, then run the append error algorithm with the decode
    1059             :     // error parameter set to true and abort these steps.
    1060             : 
    1061             :     // 2. For each audio track in the initialization segment, run following steps:
    1062             :     // for (uint32_t i = 0; i < numAudios; i++) {
    1063           0 :     if (numAudios) {
    1064             :       // 1. Let audio byte stream track ID be the Track ID for the current track being processed.
    1065             :       // 2. Let audio language be a BCP 47 language tag for the language specified in the initialization segment for this track or an empty string if no language info is present.
    1066             :       // 3. If audio language equals an empty string or the 'und' BCP 47 value, then run the default track language algorithm with byteStreamTrackID set to audio byte stream track ID and type set to "audio" and assign the value returned by the algorithm to audio language.
    1067             :       // 4. Let audio label be a label specified in the initialization segment for this track or an empty string if no label info is present.
    1068             :       // 5. If audio label equals an empty string, then run the default track label algorithm with byteStreamTrackID set to audio byte stream track ID and type set to "audio" and assign the value returned by the algorithm to audio label.
    1069             :       // 6. Let audio kinds be an array of kind strings specified in the initialization segment for this track or an empty array if no kind information is provided.
    1070             :       // 7. If audio kinds equals an empty array, then run the default track kinds algorithm with byteStreamTrackID set to audio byte stream track ID and type set to "audio" and assign the value returned by the algorithm to audio kinds.
    1071             :       // 8. For each value in audio kinds, run the following steps:
    1072             :       //   1. Let current audio kind equal the value from audio kinds for this iteration of the loop.
    1073             :       //   2. Let new audio track be a new AudioTrack object.
    1074             :       //   3. Generate a unique ID and assign it to the id property on new audio track.
    1075             :       //   4. Assign audio language to the language property on new audio track.
    1076             :       //   5. Assign audio label to the label property on new audio track.
    1077             :       //   6. Assign current audio kind to the kind property on new audio track.
    1078             :       //   7. If audioTracks.length equals 0, then run the following steps:
    1079             :       //     1. Set the enabled property on new audio track to true.
    1080             :       //     2. Set active track flag to true.
    1081           0 :       activeTrack = true;
    1082             :       //   8. Add new audio track to the audioTracks attribute on this SourceBuffer object.
    1083             :       //   9. Queue a task to fire a trusted event named addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, at the AudioTrackList object referenced by the audioTracks attribute on this SourceBuffer object.
    1084             :       //   10. Add new audio track to the audioTracks attribute on the HTMLMediaElement.
    1085             :       //   11. Queue a task to fire a trusted event named addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, at the AudioTrackList object referenced by the audioTracks attribute on the HTMLMediaElement.
    1086           0 :       mAudioTracks.mBuffers.AppendElement(TrackBuffer());
    1087             :       // 10. Add the track description for this track to the track buffer.
    1088           0 :       mAudioTracks.mInfo = new TrackInfoSharedPtr(info.mAudio, streamID);
    1089           0 :       mAudioTracks.mLastInfo = mAudioTracks.mInfo;
    1090             :     }
    1091             : 
    1092           0 :     mVideoTracks.mNumTracks = numVideos;
    1093             :     // 3. For each video track in the initialization segment, run following steps:
    1094             :     // for (uint32_t i = 0; i < numVideos; i++) {
    1095           0 :     if (numVideos) {
    1096             :       // 1. Let video byte stream track ID be the Track ID for the current track being processed.
    1097             :       // 2. Let video language be a BCP 47 language tag for the language specified in the initialization segment for this track or an empty string if no language info is present.
    1098             :       // 3. If video language equals an empty string or the 'und' BCP 47 value, then run the default track language algorithm with byteStreamTrackID set to video byte stream track ID and type set to "video" and assign the value returned by the algorithm to video language.
    1099             :       // 4. Let video label be a label specified in the initialization segment for this track or an empty string if no label info is present.
    1100             :       // 5. If video label equals an empty string, then run the default track label algorithm with byteStreamTrackID set to video byte stream track ID and type set to "video" and assign the value returned by the algorithm to video label.
    1101             :       // 6. Let video kinds be an array of kind strings specified in the initialization segment for this track or an empty array if no kind information is provided.
    1102             :       // 7. If video kinds equals an empty array, then run the default track kinds algorithm with byteStreamTrackID set to video byte stream track ID and type set to "video" and assign the value returned by the algorithm to video kinds.
    1103             :       // 8. For each value in video kinds, run the following steps:
    1104             :       //   1. Let current video kind equal the value from video kinds for this iteration of the loop.
    1105             :       //   2. Let new video track be a new VideoTrack object.
    1106             :       //   3. Generate a unique ID and assign it to the id property on new video track.
    1107             :       //   4. Assign video language to the language property on new video track.
    1108             :       //   5. Assign video label to the label property on new video track.
    1109             :       //   6. Assign current video kind to the kind property on new video track.
    1110             :       //   7. If videoTracks.length equals 0, then run the following steps:
    1111             :       //     1. Set the selected property on new video track to true.
    1112             :       //     2. Set active track flag to true.
    1113           0 :       activeTrack = true;
    1114             :       //   8. Add new video track to the videoTracks attribute on this SourceBuffer object.
    1115             :       //   9. Queue a task to fire a trusted event named addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, at the VideoTrackList object referenced by the videoTracks attribute on this SourceBuffer object.
    1116             :       //   10. Add new video track to the videoTracks attribute on the HTMLMediaElement.
    1117             :       //   11. Queue a task to fire a trusted event named addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, at the VideoTrackList object referenced by the videoTracks attribute on the HTMLMediaElement.
    1118           0 :       mVideoTracks.mBuffers.AppendElement(TrackBuffer());
    1119             :       // 10. Add the track description for this track to the track buffer.
    1120           0 :       mVideoTracks.mInfo = new TrackInfoSharedPtr(info.mVideo, streamID);
    1121           0 :       mVideoTracks.mLastInfo = mVideoTracks.mInfo;
    1122             :     }
    1123             :     // 4. For each text track in the initialization segment, run following steps:
    1124             :     // 5. If active track flag equals true, then run the following steps:
    1125             :     // This is handled by SourceBuffer once the promise is resolved.
    1126           0 :     if (activeTrack) {
    1127           0 :       mActiveTrack = true;
    1128             :     }
    1129             : 
    1130             :     // 6. Set first initialization segment received flag to true.
    1131           0 :     mFirstInitializationSegmentReceived = true;
    1132             :   } else {
    1133           0 :     mAudioTracks.mLastInfo = new TrackInfoSharedPtr(info.mAudio, streamID);
    1134           0 :     mVideoTracks.mLastInfo = new TrackInfoSharedPtr(info.mVideo, streamID);
    1135             :   }
    1136             : 
    1137           0 :   UniquePtr<EncryptionInfo> crypto = mInputDemuxer->GetCrypto();
    1138           0 :   if (crypto && crypto->IsEncrypted()) {
    1139             :     // Try and dispatch 'encrypted'. Won't go if ready state still HAVE_NOTHING.
    1140           0 :     for (uint32_t i = 0; i < crypto->mInitDatas.Length(); i++) {
    1141             :       nsCOMPtr<nsIRunnable> r =
    1142           0 :         new DispatchKeyNeededEvent(mParentDecoder, crypto->mInitDatas[i].mInitData,
    1143           0 :                                    crypto->mInitDatas[i].mType);
    1144           0 :       mAbstractMainThread->Dispatch(r.forget());
    1145             :     }
    1146           0 :     info.mCrypto = *crypto;
    1147             :     // We clear our crypto init data array, so the MediaFormatReader will
    1148             :     // not emit an encrypted event for the same init data again.
    1149           0 :     info.mCrypto.mInitDatas.Clear();
    1150             :   }
    1151             : 
    1152             :   {
    1153           0 :     MonitorAutoLock mon(mMonitor);
    1154           0 :     mInfo = info;
    1155             :   }
    1156             : 
    1157             :   // We now have a valid init data ; we can store it for later use.
    1158           0 :   mInitData = mParser->InitData();
    1159             : 
    1160             :   // 3. Remove the initialization segment bytes from the beginning of the input buffer.
    1161             :   // This step has already been done in InitializationSegmentReceived when we
    1162             :   // transferred the content into mCurrentInputBuffer.
    1163           0 :   mCurrentInputBuffer->EvictAll();
    1164           0 :   mInputDemuxer->NotifyDataRemoved();
    1165           0 :   RecreateParser(true);
    1166             : 
    1167             :   // 4. Set append state to WAITING_FOR_SEGMENT.
    1168           0 :   SetAppendState(AppendState::WAITING_FOR_SEGMENT);
    1169             :   // 5. Jump to the loop top step above.
    1170           0 :   ScheduleSegmentParserLoop();
    1171             : 
    1172           0 :   if (aResult != NS_OK && mParentDecoder) {
    1173           0 :     RefPtr<TrackBuffersManager> self = this;
    1174           0 :     mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
    1175           0 :       "TrackBuffersManager::OnDemuxerInitDone", [self, aResult]() {
    1176           0 :         if (self->mParentDecoder && self->mParentDecoder->GetOwner()) {
    1177           0 :           self->mParentDecoder->GetOwner()->DecodeWarning(aResult);
    1178             :         }
    1179           0 :       }));
    1180             :   }
    1181             : }
    1182             : 
    1183             : void
    1184           0 : TrackBuffersManager::OnDemuxerInitFailed(const MediaResult& aError)
    1185             : {
    1186           0 :   MOZ_ASSERT(aError != NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
    1187           0 :   mDemuxerInitRequest.Complete();
    1188             : 
    1189           0 :   RejectAppend(aError, __func__);
    1190           0 : }
    1191             : 
    1192             : RefPtr<TrackBuffersManager::CodedFrameProcessingPromise>
    1193           0 : TrackBuffersManager::CodedFrameProcessing()
    1194             : {
    1195           0 :   MOZ_ASSERT(OnTaskQueue());
    1196           0 :   MOZ_ASSERT(mProcessingPromise.IsEmpty());
    1197             : 
    1198           0 :   MediaByteRange mediaRange = mParser->MediaSegmentRange();
    1199           0 :   if (mediaRange.IsEmpty()) {
    1200           0 :     AppendDataToCurrentInputBuffer(mInputBuffer);
    1201           0 :     mInputBuffer = nullptr;
    1202             :   } else {
    1203           0 :     MOZ_ASSERT(mProcessedInput >= mInputBuffer->Length());
    1204           0 :     if (int64_t(mProcessedInput - mInputBuffer->Length()) > mediaRange.mEnd) {
    1205             :       // Something is not quite right with the data appended. Refuse it.
    1206             :       // This would typically happen if the previous media segment was partial
    1207             :       // yet a new complete media segment was added.
    1208           0 :       return CodedFrameProcessingPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
    1209             :     }
    1210             :     // The mediaRange is offset by the init segment position previously added.
    1211             :     uint32_t length =
    1212           0 :       mediaRange.mEnd - (mProcessedInput - mInputBuffer->Length());
    1213           0 :     if (!length) {
    1214             :       // We've completed our earlier media segment and no new data is to be
    1215             :       // processed. This happens with some containers that can't detect that a
    1216             :       // media segment is ending until a new one starts.
    1217           0 :       RefPtr<CodedFrameProcessingPromise> p = mProcessingPromise.Ensure(__func__);
    1218           0 :       CompleteCodedFrameProcessing();
    1219           0 :       return p;
    1220             :     }
    1221           0 :     RefPtr<MediaByteBuffer> segment = new MediaByteBuffer;
    1222           0 :     if (!segment->AppendElements(mInputBuffer->Elements(), length, fallible)) {
    1223           0 :       return CodedFrameProcessingPromise::CreateAndReject(NS_ERROR_OUT_OF_MEMORY, __func__);
    1224             :     }
    1225           0 :     AppendDataToCurrentInputBuffer(segment);
    1226           0 :     mInputBuffer->RemoveElementsAt(0, length);
    1227             :   }
    1228             : 
    1229           0 :   RefPtr<CodedFrameProcessingPromise> p = mProcessingPromise.Ensure(__func__);
    1230             : 
    1231           0 :   DoDemuxVideo();
    1232             : 
    1233           0 :   return p;
    1234             : }
    1235             : 
    1236             : void
    1237           0 : TrackBuffersManager::OnDemuxFailed(TrackType aTrack,
    1238             :                                    const MediaResult& aError)
    1239             : {
    1240           0 :   MOZ_ASSERT(OnTaskQueue());
    1241           0 :   MSE_DEBUG("Failed to demux %s, failure:%" PRIu32,
    1242             :             aTrack == TrackType::kVideoTrack ? "video" : "audio",
    1243             :             static_cast<uint32_t>(aError.Code()));
    1244           0 :   switch (aError.Code()) {
    1245             :     case NS_ERROR_DOM_MEDIA_END_OF_STREAM:
    1246             :     case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
    1247           0 :       if (aTrack == TrackType::kVideoTrack) {
    1248           0 :         DoDemuxAudio();
    1249             :       } else {
    1250           0 :         CompleteCodedFrameProcessing();
    1251             :       }
    1252           0 :       break;
    1253             :     default:
    1254           0 :       RejectProcessing(aError, __func__);
    1255           0 :       break;
    1256             :   }
    1257           0 : }
    1258             : 
    1259             : void
    1260           0 : TrackBuffersManager::DoDemuxVideo()
    1261             : {
    1262           0 :   MOZ_ASSERT(OnTaskQueue());
    1263           0 :   if (!HasVideo()) {
    1264           0 :     DoDemuxAudio();
    1265           0 :     return;
    1266             :   }
    1267           0 :   mVideoTracks.mDemuxer->GetSamples(-1)
    1268           0 :     ->Then(GetTaskQueue(), __func__, this,
    1269             :            &TrackBuffersManager::OnVideoDemuxCompleted,
    1270             :            &TrackBuffersManager::OnVideoDemuxFailed)
    1271           0 :     ->Track(mVideoTracks.mDemuxRequest);
    1272             : }
    1273             : 
    1274             : void
    1275           0 : TrackBuffersManager::OnVideoDemuxCompleted(RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
    1276             : {
    1277           0 :   MOZ_ASSERT(OnTaskQueue());
    1278           0 :   MSE_DEBUG("%" PRIuSIZE " video samples demuxed", aSamples->mSamples.Length());
    1279           0 :   mVideoTracks.mDemuxRequest.Complete();
    1280           0 :   mVideoTracks.mQueuedSamples.AppendElements(aSamples->mSamples);
    1281           0 :   DoDemuxAudio();
    1282           0 : }
    1283             : 
    1284             : void
    1285           0 : TrackBuffersManager::DoDemuxAudio()
    1286             : {
    1287           0 :   MOZ_ASSERT(OnTaskQueue());
    1288           0 :   if (!HasAudio()) {
    1289           0 :     CompleteCodedFrameProcessing();
    1290           0 :     return;
    1291             :   }
    1292           0 :   mAudioTracks.mDemuxer->GetSamples(-1)
    1293           0 :     ->Then(GetTaskQueue(), __func__, this,
    1294             :            &TrackBuffersManager::OnAudioDemuxCompleted,
    1295             :            &TrackBuffersManager::OnAudioDemuxFailed)
    1296           0 :     ->Track(mAudioTracks.mDemuxRequest);
    1297             : }
    1298             : 
    1299             : void
    1300           0 : TrackBuffersManager::OnAudioDemuxCompleted(RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
    1301             : {
    1302           0 :   MOZ_ASSERT(OnTaskQueue());
    1303           0 :   MSE_DEBUG("%" PRIuSIZE " audio samples demuxed", aSamples->mSamples.Length());
    1304           0 :   mAudioTracks.mDemuxRequest.Complete();
    1305           0 :   mAudioTracks.mQueuedSamples.AppendElements(aSamples->mSamples);
    1306           0 :   CompleteCodedFrameProcessing();
    1307           0 : }
    1308             : 
    1309             : void
    1310           0 : TrackBuffersManager::CompleteCodedFrameProcessing()
    1311             : {
    1312           0 :   MOZ_ASSERT(OnTaskQueue());
    1313             : 
    1314             :   // 1. For each coded frame in the media segment run the following steps:
    1315             :   // Coded Frame Processing steps 1.1 to 1.21.
    1316             : 
    1317           0 :   if (mSourceBufferAttributes->GetAppendMode() == SourceBufferAppendMode::Sequence &&
    1318           0 :       mVideoTracks.mQueuedSamples.Length() && mAudioTracks.mQueuedSamples.Length()) {
    1319             :     // When we are in sequence mode, the order in which we process the frames is
    1320             :     // important as it determines the future value of timestampOffset.
    1321             :     // So we process the earliest sample first. See bug 1293576.
    1322             :     TimeInterval videoInterval =
    1323           0 :       PresentationInterval(mVideoTracks.mQueuedSamples);
    1324             :     TimeInterval audioInterval =
    1325           0 :       PresentationInterval(mAudioTracks.mQueuedSamples);
    1326           0 :     if (audioInterval.mStart < videoInterval.mStart) {
    1327           0 :       ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
    1328           0 :       ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
    1329             :     } else {
    1330           0 :       ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
    1331           0 :       ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
    1332             :     }
    1333             :   } else {
    1334           0 :     ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
    1335           0 :     ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
    1336             :   }
    1337             : 
    1338             : #if defined(DEBUG)
    1339           0 :   if (HasVideo()) {
    1340           0 :     const auto& track = mVideoTracks.GetTrackBuffer();
    1341           0 :     MOZ_ASSERT(track.IsEmpty() || track[0]->mKeyframe);
    1342           0 :     for (uint32_t i = 1; i < track.Length(); i++) {
    1343           0 :       MOZ_ASSERT((track[i-1]->mTrackInfo->GetID() == track[i]->mTrackInfo->GetID() && track[i-1]->mTimecode <= track[i]->mTimecode) ||
    1344             :                  track[i]->mKeyframe);
    1345             :     }
    1346             :   }
    1347           0 :   if (HasAudio()) {
    1348           0 :     const auto& track = mAudioTracks.GetTrackBuffer();
    1349           0 :     MOZ_ASSERT(track.IsEmpty() || track[0]->mKeyframe);
    1350           0 :     for (uint32_t i = 1; i < track.Length(); i++) {
    1351           0 :       MOZ_ASSERT((track[i-1]->mTrackInfo->GetID() == track[i]->mTrackInfo->GetID() && track[i-1]->mTimecode <= track[i]->mTimecode) ||
    1352             :                  track[i]->mKeyframe);
    1353             :     }
    1354             :   }
    1355             : #endif
    1356             : 
    1357           0 :   mVideoTracks.mQueuedSamples.Clear();
    1358           0 :   mAudioTracks.mQueuedSamples.Clear();
    1359             : 
    1360           0 :   UpdateBufferedRanges();
    1361             : 
    1362             :   // Update our reported total size.
    1363           0 :   mSizeSourceBuffer = mVideoTracks.mSizeBuffer + mAudioTracks.mSizeBuffer;
    1364             : 
    1365             :   // Return to step 6.4 of Segment Parser Loop algorithm
    1366             :   // 4. If this SourceBuffer is full and cannot accept more media data, then set the buffer full flag to true.
    1367           0 :   if (mSizeSourceBuffer >= EvictionThreshold()) {
    1368           0 :     mBufferFull = true;
    1369             :   }
    1370             : 
    1371             :   // 5. If the input buffer does not contain a complete media segment, then jump to the need more data step below.
    1372           0 :   if (mParser->MediaSegmentRange().IsEmpty()) {
    1373           0 :     ResolveProcessing(true, __func__);
    1374           0 :     return;
    1375             :   }
    1376             : 
    1377           0 :   mLastParsedEndTime = Some(std::max(mAudioTracks.mLastParsedEndTime,
    1378           0 :                                      mVideoTracks.mLastParsedEndTime));
    1379             : 
    1380             :   // 6. Remove the media segment bytes from the beginning of the input buffer.
    1381             :   // Clear our demuxer from any already processed data.
    1382           0 :   int64_t safeToEvict = std::min(HasVideo()
    1383           0 :                                  ? mVideoTracks.mDemuxer->GetEvictionOffset(
    1384           0 :                                      mVideoTracks.mLastParsedEndTime)
    1385             :                                  : INT64_MAX,
    1386           0 :                                  HasAudio()
    1387           0 :                                  ? mAudioTracks.mDemuxer->GetEvictionOffset(
    1388           0 :                                      mAudioTracks.mLastParsedEndTime)
    1389           0 :                                  : INT64_MAX);
    1390           0 :   ErrorResult rv;
    1391           0 :   mCurrentInputBuffer->EvictBefore(safeToEvict, rv);
    1392           0 :   if (rv.Failed()) {
    1393           0 :     rv.SuppressException();
    1394           0 :     RejectProcessing(NS_ERROR_OUT_OF_MEMORY, __func__);
    1395           0 :     return;
    1396             :   }
    1397             : 
    1398           0 :   mInputDemuxer->NotifyDataRemoved();
    1399           0 :   RecreateParser(true);
    1400             : 
    1401             :   // 7. Set append state to WAITING_FOR_SEGMENT.
    1402           0 :   SetAppendState(AppendState::WAITING_FOR_SEGMENT);
    1403             : 
    1404             :   // 8. Jump to the loop top step above.
    1405           0 :   ResolveProcessing(false, __func__);
    1406             : }
    1407             : 
    1408             : void
    1409           0 : TrackBuffersManager::RejectProcessing(const MediaResult& aRejectValue, const char* aName)
    1410             : {
    1411           0 :   mProcessingPromise.RejectIfExists(aRejectValue, __func__);
    1412           0 : }
    1413             : 
    1414             : void
    1415           0 : TrackBuffersManager::ResolveProcessing(bool aResolveValue, const char* aName)
    1416             : {
    1417           0 :   mProcessingPromise.ResolveIfExists(aResolveValue, __func__);
    1418           0 : }
    1419             : 
    1420             : void
    1421           0 : TrackBuffersManager::CheckSequenceDiscontinuity(const TimeUnit& aPresentationTime)
    1422             : {
    1423           0 :   if (mSourceBufferAttributes->GetAppendMode() == SourceBufferAppendMode::Sequence &&
    1424           0 :       mSourceBufferAttributes->HaveGroupStartTimestamp()) {
    1425           0 :     mSourceBufferAttributes->SetTimestampOffset(
    1426           0 :       mSourceBufferAttributes->GetGroupStartTimestamp() - aPresentationTime);
    1427           0 :     mSourceBufferAttributes->SetGroupEndTimestamp(
    1428           0 :       mSourceBufferAttributes->GetGroupStartTimestamp());
    1429           0 :     mVideoTracks.mNeedRandomAccessPoint = true;
    1430           0 :     mAudioTracks.mNeedRandomAccessPoint = true;
    1431           0 :     mSourceBufferAttributes->ResetGroupStartTimestamp();
    1432             :   }
    1433           0 : }
    1434             : 
    1435             : TimeInterval
    1436           0 : TrackBuffersManager::PresentationInterval(const TrackBuffer& aSamples) const
    1437             : {
    1438             :   TimeInterval presentationInterval =
    1439           0 :     TimeInterval(aSamples[0]->mTime, aSamples[0]->GetEndTime());
    1440             : 
    1441           0 :   for (uint32_t i = 1; i < aSamples.Length(); i++) {
    1442           0 :     auto& sample = aSamples[i];
    1443           0 :     presentationInterval = presentationInterval.Span(
    1444           0 :       TimeInterval(sample->mTime, sample->GetEndTime()));
    1445             :   }
    1446           0 :   return presentationInterval;
    1447             : }
    1448             : 
    1449             : void
    1450           0 : TrackBuffersManager::ProcessFrames(TrackBuffer& aSamples, TrackData& aTrackData)
    1451             : {
    1452           0 :   if (!aSamples.Length()) {
    1453           0 :     return;
    1454             :   }
    1455             : 
    1456             :   // 1. If generate timestamps flag equals true
    1457             :   // Let presentation timestamp equal 0.
    1458             :   // Otherwise
    1459             :   // Let presentation timestamp be a double precision floating point representation of the coded frame's presentation timestamp in seconds.
    1460             :   TimeUnit presentationTimestamp =
    1461           0 :     mSourceBufferAttributes->mGenerateTimestamps
    1462             :     ? TimeUnit::Zero()
    1463           0 :     : aSamples[0]->mTime;
    1464             : 
    1465             :   // 3. If mode equals "sequence" and group start timestamp is set, then run the following steps:
    1466           0 :   CheckSequenceDiscontinuity(presentationTimestamp);
    1467             : 
    1468             :   // 5. Let track buffer equal the track buffer that the coded frame will be added to.
    1469           0 :   auto& trackBuffer = aTrackData;
    1470             : 
    1471             :   // Some videos do not exactly start at 0, but instead a small negative value.
    1472             :   // To avoid evicting the starting frame of those videos, we allow a leeway
    1473             :   // of +- mLongestFrameDuration on the append window start.
    1474             :   // We only apply the leeway with the default append window start of 0
    1475             :   // otherwise do as per spec.
    1476             :   TimeInterval targetWindow =
    1477           0 :     mAppendWindow.mStart != TimeUnit::FromSeconds(0)
    1478             :     ? mAppendWindow
    1479             :     : TimeInterval(mAppendWindow.mStart, mAppendWindow.mEnd,
    1480           0 :                    trackBuffer.mLastFrameDuration.isSome()
    1481             :                    ? trackBuffer.mLongestFrameDuration
    1482           0 :                    : aSamples[0]->mDuration);
    1483             : 
    1484           0 :   TimeIntervals samplesRange;
    1485           0 :   uint32_t sizeNewSamples = 0;
    1486           0 :   TrackBuffer samples; // array that will contain the frames to be added
    1487             :                        // to our track buffer.
    1488             : 
    1489             :   // We assume that no frames are contiguous within a media segment and as such
    1490             :   // don't need to check for discontinuity except for the first frame and should
    1491             :   // a frame be ignored due to the target window.
    1492           0 :   bool needDiscontinuityCheck = true;
    1493             : 
    1494             :   // Highest presentation time seen in samples block.
    1495           0 :   TimeUnit highestSampleTime;
    1496             : 
    1497           0 :   if (aSamples.Length()) {
    1498           0 :     aTrackData.mLastParsedEndTime = TimeUnit();
    1499             :   }
    1500             : 
    1501           0 :   for (auto& sample : aSamples) {
    1502           0 :     SAMPLE_DEBUG("Processing %s frame(pts:%" PRId64 " end:%" PRId64 ", dts:%" PRId64 ", duration:%" PRId64 ", "
    1503             :                "kf:%d)",
    1504             :                aTrackData.mInfo->mMimeType.get(),
    1505             :                sample->mTime.ToMicroseconds(),
    1506             :                sample->GetEndTime().ToMicroseconds(),
    1507             :                sample->mTimecode.ToMicroseconds(),
    1508             :                sample->mDuration.ToMicroseconds(),
    1509             :                sample->mKeyframe);
    1510             : 
    1511           0 :     const TimeUnit sampleEndTime = sample->GetEndTime();
    1512           0 :     if (sampleEndTime > aTrackData.mLastParsedEndTime) {
    1513           0 :       aTrackData.mLastParsedEndTime = sampleEndTime;
    1514             :     }
    1515             : 
    1516             :     // We perform step 10 right away as we can't do anything should a keyframe
    1517             :     // be needed until we have one.
    1518             : 
    1519             :     // 10. If the need random access point flag on track buffer equals true, then run the following steps:
    1520           0 :     if (trackBuffer.mNeedRandomAccessPoint) {
    1521             :       // 1. If the coded frame is not a random access point, then drop the coded frame and jump to the top of the loop to start processing the next coded frame.
    1522           0 :       if (!sample->mKeyframe) {
    1523           0 :         continue;
    1524             :       }
    1525             :       // 2. Set the need random access point flag on track buffer to false.
    1526           0 :       trackBuffer.mNeedRandomAccessPoint = false;
    1527             :     }
    1528             : 
    1529             :     // We perform step 1,2 and 4 at once:
    1530             :     // 1. If generate timestamps flag equals true:
    1531             :     //   Let presentation timestamp equal 0.
    1532             :     //   Let decode timestamp equal 0.
    1533             :     // Otherwise:
    1534             :     //   Let presentation timestamp be a double precision floating point representation of the coded frame's presentation timestamp in seconds.
    1535             :     //   Let decode timestamp be a double precision floating point representation of the coded frame's decode timestamp in seconds.
    1536             : 
    1537             :     // 2. Let frame duration be a double precision floating point representation of the coded frame's duration in seconds.
    1538             :     // Step 3 is performed earlier or when a discontinuity has been detected.
    1539             :     // 4. If timestampOffset is not 0, then run the following steps:
    1540             : 
    1541           0 :     TimeUnit sampleTime = sample->mTime;
    1542           0 :     TimeUnit sampleTimecode = sample->mTimecode;
    1543           0 :     TimeUnit sampleDuration = sample->mDuration;
    1544           0 :     TimeUnit timestampOffset = mSourceBufferAttributes->GetTimestampOffset();
    1545             : 
    1546             :     TimeInterval sampleInterval =
    1547           0 :       mSourceBufferAttributes->mGenerateTimestamps
    1548           0 :       ? TimeInterval(timestampOffset, timestampOffset + sampleDuration)
    1549           0 :       : TimeInterval(timestampOffset + sampleTime,
    1550           0 :                      timestampOffset + sampleTime + sampleDuration);
    1551           0 :     TimeUnit decodeTimestamp = mSourceBufferAttributes->mGenerateTimestamps
    1552             :                                ? timestampOffset
    1553           0 :                                : timestampOffset + sampleTimecode;
    1554             : 
    1555             :     // 6. If last decode timestamp for track buffer is set and decode timestamp is less than last decode timestamp:
    1556             :     // OR
    1557             :     // If last decode timestamp for track buffer is set and the difference between decode timestamp and last decode timestamp is greater than 2 times last frame duration:
    1558             : 
    1559           0 :     if (needDiscontinuityCheck && trackBuffer.mLastDecodeTimestamp.isSome() &&
    1560           0 :         (decodeTimestamp < trackBuffer.mLastDecodeTimestamp.ref() ||
    1561           0 :          (decodeTimestamp - trackBuffer.mLastDecodeTimestamp.ref()
    1562           0 :           > trackBuffer.mLongestFrameDuration * 2))) {
    1563           0 :       MSE_DEBUG("Discontinuity detected.");
    1564           0 :       SourceBufferAppendMode appendMode = mSourceBufferAttributes->GetAppendMode();
    1565             : 
    1566             :       // 1a. If mode equals "segments":
    1567           0 :       if (appendMode == SourceBufferAppendMode::Segments) {
    1568             :         // Set group end timestamp to presentation timestamp.
    1569           0 :         mSourceBufferAttributes->SetGroupEndTimestamp(sampleInterval.mStart);
    1570             :       }
    1571             :       // 1b. If mode equals "sequence":
    1572           0 :       if (appendMode == SourceBufferAppendMode::Sequence) {
    1573             :         // Set group start timestamp equal to the group end timestamp.
    1574           0 :         mSourceBufferAttributes->SetGroupStartTimestamp(
    1575           0 :           mSourceBufferAttributes->GetGroupEndTimestamp());
    1576             :       }
    1577           0 :       for (auto& track : GetTracksList()) {
    1578             :         // 2. Unset the last decode timestamp on all track buffers.
    1579             :         // 3. Unset the last frame duration on all track buffers.
    1580             :         // 4. Unset the highest end timestamp on all track buffers.
    1581             :         // 5. Set the need random access point flag on all track buffers to true.
    1582           0 :         track->ResetAppendState();
    1583             :       }
    1584             :       // 6. Jump to the Loop Top step above to restart processing of the current coded frame.
    1585             :       // Rather that restarting the process for the frame, we run the first
    1586             :       // steps again instead.
    1587             :       // 3. If mode equals "sequence" and group start timestamp is set, then run the following steps:
    1588             :       TimeUnit presentationTimestamp =
    1589           0 :         mSourceBufferAttributes->mGenerateTimestamps ? TimeUnit() : sampleTime;
    1590           0 :       CheckSequenceDiscontinuity(presentationTimestamp);
    1591             : 
    1592           0 :       if (!sample->mKeyframe) {
    1593           0 :         continue;
    1594             :       }
    1595           0 :       if (appendMode == SourceBufferAppendMode::Sequence) {
    1596             :         // mSourceBufferAttributes->GetTimestampOffset() was modified during CheckSequenceDiscontinuity.
    1597             :         // We need to update our variables.
    1598           0 :         timestampOffset = mSourceBufferAttributes->GetTimestampOffset();
    1599             :         sampleInterval =
    1600           0 :           mSourceBufferAttributes->mGenerateTimestamps
    1601           0 :           ? TimeInterval(timestampOffset, timestampOffset + sampleDuration)
    1602           0 :           : TimeInterval(timestampOffset + sampleTime,
    1603           0 :                          timestampOffset + sampleTime + sampleDuration);
    1604           0 :         decodeTimestamp = mSourceBufferAttributes->mGenerateTimestamps
    1605             :                           ? timestampOffset
    1606           0 :                           : timestampOffset + sampleTimecode;
    1607             :       }
    1608           0 :       trackBuffer.mNeedRandomAccessPoint = false;
    1609           0 :       needDiscontinuityCheck = false;
    1610             :     }
    1611             : 
    1612             :     // 7. Let frame end timestamp equal the sum of presentation timestamp and frame duration.
    1613             :     // This is sampleInterval.mEnd
    1614             : 
    1615             :     // 8. If presentation timestamp is less than appendWindowStart, then set the need random access point flag to true, drop the coded frame, and jump to the top of the loop to start processing the next coded frame.
    1616             :     // 9. If frame end timestamp is greater than appendWindowEnd, then set the need random access point flag to true, drop the coded frame, and jump to the top of the loop to start processing the next coded frame.
    1617           0 :     if (!targetWindow.ContainsWithStrictEnd(sampleInterval)) {
    1618           0 :       if (samples.Length()) {
    1619             :         // We are creating a discontinuity in the samples.
    1620             :         // Insert the samples processed so far.
    1621           0 :         InsertFrames(samples, samplesRange, trackBuffer);
    1622           0 :         samples.Clear();
    1623           0 :         samplesRange = TimeIntervals();
    1624           0 :         trackBuffer.mSizeBuffer += sizeNewSamples;
    1625           0 :         sizeNewSamples = 0;
    1626           0 :         UpdateHighestTimestamp(trackBuffer, highestSampleTime);
    1627             :       }
    1628           0 :       trackBuffer.mNeedRandomAccessPoint = true;
    1629           0 :       needDiscontinuityCheck = true;
    1630           0 :       continue;
    1631             :     }
    1632             : 
    1633           0 :     samplesRange += sampleInterval;
    1634           0 :     sizeNewSamples += sample->ComputedSizeOfIncludingThis();
    1635           0 :     sample->mTime = sampleInterval.mStart;
    1636           0 :     sample->mTimecode = decodeTimestamp;
    1637           0 :     sample->mTrackInfo = trackBuffer.mLastInfo;
    1638           0 :     samples.AppendElement(sample);
    1639             : 
    1640             :     // Steps 11,12,13,14, 15 and 16 will be done in one block in InsertFrames.
    1641             : 
    1642           0 :     trackBuffer.mLongestFrameDuration =
    1643           0 :       trackBuffer.mLastFrameDuration.isSome()
    1644           0 :       ? sample->mKeyframe
    1645             :         ? sampleDuration
    1646           0 :         : std::max(sampleDuration, trackBuffer.mLongestFrameDuration)
    1647             :       : sampleDuration;
    1648             : 
    1649             :     // 17. Set last decode timestamp for track buffer to decode timestamp.
    1650           0 :     trackBuffer.mLastDecodeTimestamp = Some(decodeTimestamp);
    1651             :     // 18. Set last frame duration for track buffer to frame duration.
    1652           0 :     trackBuffer.mLastFrameDuration = Some(sampleDuration);
    1653             : 
    1654             :     // 19. If highest end timestamp for track buffer is unset or frame end timestamp is greater than highest end timestamp, then set highest end timestamp for track buffer to frame end timestamp.
    1655           0 :     if (trackBuffer.mHighestEndTimestamp.isNothing() ||
    1656           0 :         sampleInterval.mEnd > trackBuffer.mHighestEndTimestamp.ref()) {
    1657           0 :       trackBuffer.mHighestEndTimestamp = Some(sampleInterval.mEnd);
    1658             :     }
    1659           0 :     if (sampleInterval.mStart > highestSampleTime) {
    1660           0 :       highestSampleTime = sampleInterval.mStart;
    1661             :     }
    1662             :     // 20. If frame end timestamp is greater than group end timestamp, then set group end timestamp equal to frame end timestamp.
    1663           0 :     if (sampleInterval.mEnd > mSourceBufferAttributes->GetGroupEndTimestamp()) {
    1664           0 :       mSourceBufferAttributes->SetGroupEndTimestamp(sampleInterval.mEnd);
    1665             :     }
    1666             :     // 21. If generate timestamps flag equals true, then set timestampOffset equal to frame end timestamp.
    1667           0 :     if (mSourceBufferAttributes->mGenerateTimestamps) {
    1668           0 :       mSourceBufferAttributes->SetTimestampOffset(sampleInterval.mEnd);
    1669             :     }
    1670             :   }
    1671             : 
    1672           0 :   if (samples.Length()) {
    1673           0 :     InsertFrames(samples, samplesRange, trackBuffer);
    1674           0 :     trackBuffer.mSizeBuffer += sizeNewSamples;
    1675           0 :     UpdateHighestTimestamp(trackBuffer, highestSampleTime);
    1676             :   }
    1677             : }
    1678             : 
    1679             : bool
    1680           0 : TrackBuffersManager::CheckNextInsertionIndex(TrackData& aTrackData,
    1681             :                                              const TimeUnit& aSampleTime)
    1682             : {
    1683           0 :   if (aTrackData.mNextInsertionIndex.isSome()) {
    1684           0 :     return true;
    1685             :   }
    1686             : 
    1687           0 :   const TrackBuffer& data = aTrackData.GetTrackBuffer();
    1688             : 
    1689           0 :   if (data.IsEmpty() || aSampleTime < aTrackData.mBufferedRanges.GetStart()) {
    1690           0 :     aTrackData.mNextInsertionIndex = Some(0u);
    1691           0 :     return true;
    1692             :   }
    1693             : 
    1694             :   // Find which discontinuity we should insert the frame before.
    1695           0 :   TimeInterval target;
    1696           0 :   for (const auto& interval : aTrackData.mBufferedRanges) {
    1697           0 :     if (aSampleTime < interval.mStart) {
    1698           0 :       target = interval;
    1699           0 :       break;
    1700             :     }
    1701             :   }
    1702           0 :   if (target.IsEmpty()) {
    1703             :     // No target found, it will be added at the end of the track buffer.
    1704           0 :     aTrackData.mNextInsertionIndex = Some(uint32_t(data.Length()));
    1705           0 :     return true;
    1706             :   }
    1707             :   // We now need to find the first frame of the searched interval.
    1708             :   // We will insert our new frames right before.
    1709           0 :   for (uint32_t i = 0; i < data.Length(); i++) {
    1710           0 :     const RefPtr<MediaRawData>& sample = data[i];
    1711           0 :     if (sample->mTime >= target.mStart ||
    1712           0 :         sample->GetEndTime() > target.mStart) {
    1713           0 :       aTrackData.mNextInsertionIndex = Some(i);
    1714           0 :       return true;
    1715             :     }
    1716             :   }
    1717           0 :   NS_ASSERTION(false, "Insertion Index Not Found");
    1718           0 :   return false;
    1719             : }
    1720             : 
    1721             : void
    1722           0 : TrackBuffersManager::InsertFrames(TrackBuffer& aSamples,
    1723             :                                   const TimeIntervals& aIntervals,
    1724             :                                   TrackData& aTrackData)
    1725             : {
    1726             :   // 5. Let track buffer equal the track buffer that the coded frame will be added to.
    1727           0 :   auto& trackBuffer = aTrackData;
    1728             : 
    1729           0 :   MSE_DEBUGV("Processing %" PRIuSIZE " %s frames(start:%" PRId64 " end:%" PRId64 ")",
    1730             :              aSamples.Length(),
    1731             :              aTrackData.mInfo->mMimeType.get(),
    1732             :              aIntervals.GetStart().ToMicroseconds(),
    1733             :              aIntervals.GetEnd().ToMicroseconds());
    1734             : 
    1735             :   // TODO: Handle splicing of audio (and text) frames.
    1736             :   // 11. Let spliced audio frame be an unset variable for holding audio splice information
    1737             :   // 12. Let spliced timed text frame be an unset variable for holding timed text splice information
    1738             : 
    1739             :   // 13. If last decode timestamp for track buffer is unset and presentation timestamp falls within the presentation interval of a coded frame in track buffer,then run the following steps:
    1740             :   // For now we only handle replacing existing frames with the new ones. So we
    1741             :   // skip this step.
    1742             : 
    1743             :   // 14. Remove existing coded frames in track buffer:
    1744             :   //   a) If highest end timestamp for track buffer is not set:
    1745             :   //      Remove all coded frames from track buffer that have a presentation timestamp greater than or equal to presentation timestamp and less than frame end timestamp.
    1746             :   //   b) If highest end timestamp for track buffer is set and less than or equal to presentation timestamp:
    1747             :   //      Remove all coded frames from track buffer that have a presentation timestamp greater than or equal to highest end timestamp and less than frame end timestamp
    1748             : 
    1749             :   // There is an ambiguity on how to remove frames, which was lodged with:
    1750             :   // https://www.w3.org/Bugs/Public/show_bug.cgi?id=28710, implementing as per
    1751             :   // bug description.
    1752             : 
    1753             :   // 15. Remove decoding dependencies of the coded frames removed in the previous step:
    1754             :   // Remove all coded frames between the coded frames removed in the previous step and the next random access point after those removed frames.
    1755             : 
    1756           0 :   TimeIntervals intersection = trackBuffer.mBufferedRanges;
    1757           0 :   intersection.Intersection(aIntervals);
    1758             : 
    1759           0 :   if (intersection.Length()) {
    1760           0 :     if (aSamples[0]->mKeyframe &&
    1761           0 :         (mType.Type() == MEDIAMIMETYPE("video/webm")
    1762           0 :          || mType.Type() == MEDIAMIMETYPE("audio/webm"))) {
    1763             :       // We are starting a new GOP, we do not have to worry about breaking an
    1764             :       // existing current coded frame group. Reset the next insertion index
    1765             :       // so the search for when to start our frames removal can be exhaustive.
    1766             :       // This is a workaround for bug 1276184 and only until either bug 1277733
    1767             :       // or bug 1209386 is fixed.
    1768             :       // With the webm container, we can't always properly determine the
    1769             :       // duration of the last frame, which may cause the last frame of a cluster
    1770             :       // to overlap the following frame.
    1771           0 :       trackBuffer.mNextInsertionIndex.reset();
    1772             :     }
    1773             :     uint32_t index =
    1774           0 :       RemoveFrames(aIntervals, trackBuffer, trackBuffer.mNextInsertionIndex.refOr(0));
    1775           0 :     if (index) {
    1776           0 :       trackBuffer.mNextInsertionIndex = Some(index);
    1777             :     }
    1778             :   }
    1779             : 
    1780             :   // 16. Add the coded frame with the presentation timestamp, decode timestamp, and frame duration to the track buffer.
    1781           0 :   if (!CheckNextInsertionIndex(aTrackData, aSamples[0]->mTime)) {
    1782           0 :     RejectProcessing(NS_ERROR_FAILURE, __func__);
    1783           0 :     return;
    1784             :   }
    1785             : 
    1786             :   // Adjust our demuxing index if necessary.
    1787           0 :   if (trackBuffer.mNextGetSampleIndex.isSome()) {
    1788           0 :     if (trackBuffer.mNextInsertionIndex.ref() == trackBuffer.mNextGetSampleIndex.ref() &&
    1789           0 :         aIntervals.GetEnd() >= trackBuffer.mNextSampleTime) {
    1790           0 :       MSE_DEBUG("Next sample to be played got overwritten");
    1791           0 :       trackBuffer.mNextGetSampleIndex.reset();
    1792           0 :       ResetEvictionIndex(trackBuffer);
    1793           0 :     } else if (trackBuffer.mNextInsertionIndex.ref() <= trackBuffer.mNextGetSampleIndex.ref()) {
    1794           0 :       trackBuffer.mNextGetSampleIndex.ref() += aSamples.Length();
    1795             :       // We could adjust the eviction index so that the new data gets added to
    1796             :       // the evictable amount (as it is prior currentTime). However, considering
    1797             :       // new data is being added prior the current playback, it's likely that
    1798             :       // this data will be played next, and as such we probably don't want to
    1799             :       // have it evicted too early. So instead reset the eviction index instead.
    1800           0 :       ResetEvictionIndex(trackBuffer);
    1801             :     }
    1802             :   }
    1803             : 
    1804           0 :   TrackBuffer& data = trackBuffer.GetTrackBuffer();
    1805           0 :   data.InsertElementsAt(trackBuffer.mNextInsertionIndex.ref(), aSamples);
    1806           0 :   trackBuffer.mNextInsertionIndex.ref() += aSamples.Length();
    1807             : 
    1808             :   // Update our buffered range with new sample interval.
    1809           0 :   trackBuffer.mBufferedRanges += aIntervals;
    1810             :   // We allow a fuzz factor in our interval of half a frame length,
    1811             :   // as fuzz is +/- value, giving an effective leeway of a full frame
    1812             :   // length.
    1813           0 :   if (aIntervals.Length()) {
    1814           0 :     TimeIntervals range(aIntervals);
    1815           0 :     range.SetFuzz(trackBuffer.mLongestFrameDuration / 2);
    1816           0 :     trackBuffer.mSanitizedBufferedRanges += range;
    1817             :   }
    1818             : }
    1819             : 
    1820             : void
    1821           0 : TrackBuffersManager::UpdateHighestTimestamp(TrackData& aTrackData,
    1822             :                                             const media::TimeUnit& aHighestTime)
    1823             : {
    1824           0 :   if (aHighestTime > aTrackData.mHighestStartTimestamp) {
    1825           0 :     MonitorAutoLock mon(mMonitor);
    1826           0 :     aTrackData.mHighestStartTimestamp = aHighestTime;
    1827             :   }
    1828           0 : }
    1829             : 
    1830             : uint32_t
    1831           0 : TrackBuffersManager::RemoveFrames(const TimeIntervals& aIntervals,
    1832             :                                   TrackData& aTrackData,
    1833             :                                   uint32_t aStartIndex)
    1834             : {
    1835           0 :   TrackBuffer& data = aTrackData.GetTrackBuffer();
    1836           0 :   Maybe<uint32_t> firstRemovedIndex;
    1837           0 :   uint32_t lastRemovedIndex = 0;
    1838             : 
    1839             :   // We loop from aStartIndex to avoid removing frames that we inserted earlier
    1840             :   // and part of the current coded frame group. This is allows to handle step
    1841             :   // 14 of the coded frame processing algorithm without having to check the value
    1842             :   // of highest end timestamp:
    1843             :   // "Remove existing coded frames in track buffer:
    1844             :   //  If highest end timestamp for track buffer is not set:
    1845             :   //   Remove all coded frames from track buffer that have a presentation timestamp greater than or equal to presentation timestamp and less than frame end timestamp.
    1846             :   //  If highest end timestamp for track buffer is set and less than or equal to presentation timestamp:
    1847             :   //   Remove all coded frames from track buffer that have a presentation timestamp greater than or equal to highest end timestamp and less than frame end timestamp"
    1848           0 :   TimeUnit intervalsEnd = aIntervals.GetEnd();
    1849           0 :   bool mayBreakLoop = false;
    1850           0 :   for (uint32_t i = aStartIndex; i < data.Length(); i++) {
    1851           0 :     const RefPtr<MediaRawData> sample = data[i];
    1852             :     TimeInterval sampleInterval =
    1853           0 :       TimeInterval(sample->mTime, sample->GetEndTime());
    1854           0 :     if (aIntervals.Contains(sampleInterval)) {
    1855           0 :       if (firstRemovedIndex.isNothing()) {
    1856           0 :         firstRemovedIndex = Some(i);
    1857             :       }
    1858           0 :       lastRemovedIndex = i;
    1859           0 :       mayBreakLoop = false;
    1860           0 :       continue;
    1861             :     }
    1862           0 :     if (sample->mKeyframe && mayBreakLoop) {
    1863           0 :       break;
    1864             :     }
    1865           0 :     if (sampleInterval.mStart > intervalsEnd) {
    1866           0 :       mayBreakLoop = true;
    1867             :     }
    1868             :   }
    1869             : 
    1870           0 :   if (firstRemovedIndex.isNothing()) {
    1871           0 :     return 0;
    1872             :   }
    1873             : 
    1874             :   // Remove decoding dependencies of the coded frames removed in the previous step:
    1875             :   // Remove all coded frames between the coded frames removed in the previous step and the next random access point after those removed frames.
    1876           0 :   for (uint32_t i = lastRemovedIndex + 1; i < data.Length(); i++) {
    1877           0 :     const RefPtr<MediaRawData>& sample = data[i];
    1878           0 :     if (sample->mKeyframe) {
    1879           0 :       break;
    1880             :     }
    1881           0 :     lastRemovedIndex = i;
    1882             :   }
    1883             : 
    1884           0 :   TimeUnit maxSampleDuration;
    1885           0 :   uint32_t sizeRemoved = 0;
    1886           0 :   TimeIntervals removedIntervals;
    1887           0 :   for (uint32_t i = firstRemovedIndex.ref(); i <= lastRemovedIndex; i++) {
    1888           0 :     const RefPtr<MediaRawData> sample = data[i];
    1889             :     TimeInterval sampleInterval =
    1890           0 :       TimeInterval(sample->mTime, sample->GetEndTime());
    1891           0 :     removedIntervals += sampleInterval;
    1892           0 :     if (sample->mDuration > maxSampleDuration) {
    1893           0 :       maxSampleDuration = sample->mDuration;
    1894             :     }
    1895           0 :     sizeRemoved += sample->ComputedSizeOfIncludingThis();
    1896             :   }
    1897           0 :   aTrackData.mSizeBuffer -= sizeRemoved;
    1898             : 
    1899           0 :   MSE_DEBUG("Removing frames from:%u (frames:%u) ([%f, %f))",
    1900             :             firstRemovedIndex.ref(),
    1901             :             lastRemovedIndex - firstRemovedIndex.ref() + 1,
    1902             :             removedIntervals.GetStart().ToSeconds(),
    1903             :             removedIntervals.GetEnd().ToSeconds());
    1904             : 
    1905           0 :   if (aTrackData.mNextGetSampleIndex.isSome()) {
    1906           0 :     if (aTrackData.mNextGetSampleIndex.ref() >= firstRemovedIndex.ref() &&
    1907           0 :         aTrackData.mNextGetSampleIndex.ref() <= lastRemovedIndex) {
    1908           0 :       MSE_DEBUG("Next sample to be played got evicted");
    1909           0 :       aTrackData.mNextGetSampleIndex.reset();
    1910           0 :       ResetEvictionIndex(aTrackData);
    1911           0 :     } else if (aTrackData.mNextGetSampleIndex.ref() > lastRemovedIndex) {
    1912           0 :       uint32_t samplesRemoved = lastRemovedIndex - firstRemovedIndex.ref() + 1;
    1913           0 :       aTrackData.mNextGetSampleIndex.ref() -= samplesRemoved;
    1914           0 :       if (aTrackData.mEvictionIndex.mLastIndex > lastRemovedIndex) {
    1915           0 :         MOZ_DIAGNOSTIC_ASSERT(
    1916             :           aTrackData.mEvictionIndex.mLastIndex >= samplesRemoved &&
    1917             :           aTrackData.mEvictionIndex.mEvictable >= sizeRemoved,
    1918             :           "Invalid eviction index");
    1919           0 :         MonitorAutoLock mon(mMonitor);
    1920           0 :         aTrackData.mEvictionIndex.mLastIndex -= samplesRemoved;
    1921           0 :         aTrackData.mEvictionIndex.mEvictable -= sizeRemoved;
    1922             :       } else {
    1923           0 :         ResetEvictionIndex(aTrackData);
    1924             :       }
    1925             :     }
    1926             :   }
    1927             : 
    1928           0 :   if (aTrackData.mNextInsertionIndex.isSome()) {
    1929           0 :     if (aTrackData.mNextInsertionIndex.ref() > firstRemovedIndex.ref() &&
    1930           0 :         aTrackData.mNextInsertionIndex.ref() <= lastRemovedIndex + 1) {
    1931           0 :       aTrackData.ResetAppendState();
    1932           0 :       MSE_DEBUG("NextInsertionIndex got reset.");
    1933           0 :     } else if (aTrackData.mNextInsertionIndex.ref() > lastRemovedIndex + 1) {
    1934           0 :       aTrackData.mNextInsertionIndex.ref() -=
    1935           0 :         lastRemovedIndex - firstRemovedIndex.ref() + 1;
    1936             :     }
    1937             :   }
    1938             : 
    1939             :   // Update our buffered range to exclude the range just removed.
    1940           0 :   aTrackData.mBufferedRanges -= removedIntervals;
    1941             : 
    1942             :   // Recalculate sanitized buffered ranges.
    1943           0 :   aTrackData.mSanitizedBufferedRanges = aTrackData.mBufferedRanges;
    1944           0 :   aTrackData.mSanitizedBufferedRanges.SetFuzz(maxSampleDuration/2);
    1945             : 
    1946           0 :   data.RemoveElementsAt(firstRemovedIndex.ref(),
    1947           0 :                         lastRemovedIndex - firstRemovedIndex.ref() + 1);
    1948             : 
    1949           0 :   if (aIntervals.GetEnd() >= aTrackData.mHighestStartTimestamp) {
    1950             :     // The sample with the highest presentation time got removed.
    1951             :     // Rescan the trackbuffer to determine the new one.
    1952           0 :     TimeUnit highestStartTime;
    1953           0 :     for (const auto& sample : data) {
    1954           0 :       if (sample->mTime > highestStartTime) {
    1955           0 :         highestStartTime = sample->mTime;
    1956             :       }
    1957             :     }
    1958           0 :     MonitorAutoLock mon(mMonitor);
    1959           0 :     aTrackData.mHighestStartTimestamp = highestStartTime;
    1960             :   }
    1961             : 
    1962           0 :   return firstRemovedIndex.ref();
    1963             : }
    1964             : 
    1965             : void
    1966           0 : TrackBuffersManager::RecreateParser(bool aReuseInitData)
    1967             : {
    1968           0 :   MOZ_ASSERT(OnTaskQueue());
    1969             :   // Recreate our parser for only the data remaining. This is required
    1970             :   // as it has parsed the entire InputBuffer provided.
    1971             :   // Once the old TrackBuffer/MediaSource implementation is removed
    1972             :   // we can optimize this part. TODO
    1973           0 :   mParser = ContainerParser::CreateForMIMEType(mType);
    1974           0 :   if (aReuseInitData && mInitData) {
    1975             :     int64_t start, end;
    1976           0 :     mParser->ParseStartAndEndTimestamps(mInitData, start, end);
    1977           0 :     mProcessedInput = mInitData->Length();
    1978             :   } else {
    1979           0 :     mProcessedInput = 0;
    1980             :   }
    1981           0 : }
    1982             : 
    1983             : nsTArray<TrackBuffersManager::TrackData*>
    1984           0 : TrackBuffersManager::GetTracksList()
    1985             : {
    1986           0 :   nsTArray<TrackData*> tracks;
    1987           0 :   if (HasVideo()) {
    1988           0 :     tracks.AppendElement(&mVideoTracks);
    1989             :   }
    1990           0 :   if (HasAudio()) {
    1991           0 :     tracks.AppendElement(&mAudioTracks);
    1992             :   }
    1993           0 :   return tracks;
    1994             : }
    1995             : 
    1996             : nsTArray<const TrackBuffersManager::TrackData*>
    1997           0 : TrackBuffersManager::GetTracksList() const
    1998             : {
    1999           0 :   nsTArray<const TrackData*> tracks;
    2000           0 :   if (HasVideo()) {
    2001           0 :     tracks.AppendElement(&mVideoTracks);
    2002             :   }
    2003           0 :   if (HasAudio()) {
    2004           0 :     tracks.AppendElement(&mAudioTracks);
    2005             :   }
    2006           0 :   return tracks;
    2007             : }
    2008             : 
    2009             : void
    2010           0 : TrackBuffersManager::SetAppendState(SourceBufferAttributes::AppendState aAppendState)
    2011             : {
    2012           0 :   MSE_DEBUG("AppendState changed from %s to %s",
    2013             :             AppendStateToStr(mSourceBufferAttributes->GetAppendState()), AppendStateToStr(aAppendState));
    2014           0 :   mSourceBufferAttributes->SetAppendState(aAppendState);
    2015           0 : }
    2016             : 
    2017             : MediaInfo
    2018           0 : TrackBuffersManager::GetMetadata() const
    2019             : {
    2020           0 :   MonitorAutoLock mon(mMonitor);
    2021           0 :   return mInfo;
    2022             : }
    2023             : 
    2024             : const TimeIntervals&
    2025           0 : TrackBuffersManager::Buffered(TrackInfo::TrackType aTrack) const
    2026             : {
    2027           0 :   MOZ_ASSERT(OnTaskQueue());
    2028           0 :   return GetTracksData(aTrack).mBufferedRanges;
    2029             : }
    2030             : 
    2031             : const media::TimeUnit&
    2032           0 : TrackBuffersManager::HighestStartTime(TrackInfo::TrackType aTrack) const
    2033             : {
    2034           0 :   MOZ_ASSERT(OnTaskQueue());
    2035           0 :   return GetTracksData(aTrack).mHighestStartTimestamp;
    2036             : }
    2037             : 
    2038             : TimeIntervals
    2039           0 : TrackBuffersManager::SafeBuffered(TrackInfo::TrackType aTrack) const
    2040             : {
    2041           0 :   MonitorAutoLock mon(mMonitor);
    2042             :   return aTrack == TrackInfo::kVideoTrack
    2043             :     ? mVideoBufferedRanges
    2044           0 :     : mAudioBufferedRanges;
    2045             : }
    2046             : 
    2047             : TimeUnit
    2048           0 : TrackBuffersManager::HighestStartTime() const
    2049             : {
    2050           0 :   MonitorAutoLock mon(mMonitor);
    2051           0 :   TimeUnit highestStartTime;
    2052           0 :   for (auto& track : GetTracksList()) {
    2053           0 :     highestStartTime =
    2054           0 :       std::max(track->mHighestStartTimestamp, highestStartTime);
    2055             :   }
    2056           0 :   return highestStartTime;
    2057             : }
    2058             : 
    2059             : TimeUnit
    2060           0 : TrackBuffersManager::HighestEndTime() const
    2061             : {
    2062           0 :   MonitorAutoLock mon(mMonitor);
    2063             : 
    2064           0 :   nsTArray<const TimeIntervals*> tracks;
    2065           0 :   if (HasVideo()) {
    2066           0 :     tracks.AppendElement(&mVideoBufferedRanges);
    2067             :   }
    2068           0 :   if (HasAudio()) {
    2069           0 :     tracks.AppendElement(&mAudioBufferedRanges);
    2070             :   }
    2071           0 :   return HighestEndTime(tracks);
    2072             : }
    2073             : 
    2074             : TimeUnit
    2075           0 : TrackBuffersManager::HighestEndTime(
    2076             :   nsTArray<const TimeIntervals*>& aTracks) const
    2077             : {
    2078           0 :   mMonitor.AssertCurrentThreadOwns();
    2079             : 
    2080           0 :   TimeUnit highestEndTime;
    2081             : 
    2082           0 :   for (const auto& trackRanges : aTracks) {
    2083           0 :     highestEndTime = std::max(trackRanges->GetEnd(), highestEndTime);
    2084             :   }
    2085           0 :   return highestEndTime;
    2086             : }
    2087             : 
    2088             : void
    2089           0 : TrackBuffersManager::ResetEvictionIndex(TrackData& aTrackData)
    2090             : {
    2091           0 :   MonitorAutoLock mon(mMonitor);
    2092           0 :   aTrackData.mEvictionIndex.Reset();
    2093           0 : }
    2094             : 
    2095             : void
    2096           0 : TrackBuffersManager::UpdateEvictionIndex(TrackData& aTrackData,
    2097             :                                          uint32_t currentIndex)
    2098             : {
    2099           0 :   uint32_t evictable = 0;
    2100           0 :   TrackBuffer& data = aTrackData.GetTrackBuffer();
    2101           0 :   MOZ_DIAGNOSTIC_ASSERT(currentIndex >= aTrackData.mEvictionIndex.mLastIndex,
    2102             :                         "Invalid call");
    2103           0 :   MOZ_DIAGNOSTIC_ASSERT(currentIndex == data.Length() ||
    2104             :                         data[currentIndex]->mKeyframe,"Must stop at keyframe");
    2105             : 
    2106           0 :   for (uint32_t i = aTrackData.mEvictionIndex.mLastIndex; i < currentIndex;
    2107             :        i++) {
    2108           0 :     evictable += data[i]->ComputedSizeOfIncludingThis();
    2109             :   }
    2110           0 :   aTrackData.mEvictionIndex.mLastIndex = currentIndex;
    2111           0 :   MonitorAutoLock mon(mMonitor);
    2112           0 :   aTrackData.mEvictionIndex.mEvictable += evictable;
    2113           0 : }
    2114             : 
    2115             : const TrackBuffersManager::TrackBuffer&
    2116           0 : TrackBuffersManager::GetTrackBuffer(TrackInfo::TrackType aTrack) const
    2117             : {
    2118           0 :   MOZ_ASSERT(OnTaskQueue());
    2119           0 :   return GetTracksData(aTrack).GetTrackBuffer();
    2120             : }
    2121             : 
    2122           0 : uint32_t TrackBuffersManager::FindSampleIndex(const TrackBuffer& aTrackBuffer,
    2123             :                                               const TimeInterval& aInterval)
    2124             : {
    2125           0 :   TimeUnit target = aInterval.mStart - aInterval.mFuzz;
    2126             : 
    2127           0 :   for (uint32_t i = 0; i < aTrackBuffer.Length(); i++) {
    2128           0 :     const RefPtr<MediaRawData>& sample = aTrackBuffer[i];
    2129           0 :     if (sample->mTime >= target ||
    2130           0 :         sample->GetEndTime() > target) {
    2131           0 :       return i;
    2132             :     }
    2133             :   }
    2134           0 :   NS_ASSERTION(false, "FindSampleIndex called with invalid arguments");
    2135             : 
    2136           0 :   return 0;
    2137             : }
    2138             : 
    2139             : TimeUnit
    2140           0 : TrackBuffersManager::Seek(TrackInfo::TrackType aTrack,
    2141             :                           const TimeUnit& aTime,
    2142             :                           const TimeUnit& aFuzz)
    2143             : {
    2144           0 :   MOZ_ASSERT(OnTaskQueue());
    2145           0 :   auto& trackBuffer = GetTracksData(aTrack);
    2146           0 :   const TrackBuffersManager::TrackBuffer& track = GetTrackBuffer(aTrack);
    2147             : 
    2148           0 :   if (!track.Length()) {
    2149             :     // This a reset. It will be followed by another valid seek.
    2150           0 :     trackBuffer.mNextGetSampleIndex = Some(uint32_t(0));
    2151           0 :     trackBuffer.mNextSampleTimecode = TimeUnit();
    2152           0 :     trackBuffer.mNextSampleTime = TimeUnit();
    2153           0 :     ResetEvictionIndex(trackBuffer);
    2154           0 :     return TimeUnit();
    2155             :   }
    2156             : 
    2157           0 :   uint32_t i = 0;
    2158             : 
    2159           0 :   if (aTime != TimeUnit()) {
    2160             :     // Determine the interval of samples we're attempting to seek to.
    2161           0 :     TimeIntervals buffered = trackBuffer.mBufferedRanges;
    2162             :     // Fuzz factor is +/- aFuzz; as we want to only eliminate gaps
    2163             :     // that are less than aFuzz wide, we set a fuzz factor aFuzz/2.
    2164           0 :     buffered.SetFuzz(aFuzz / 2);
    2165           0 :     TimeIntervals::IndexType index = buffered.Find(aTime);
    2166           0 :     MOZ_ASSERT(index != TimeIntervals::NoIndex,
    2167             :                "We shouldn't be called if aTime isn't buffered");
    2168           0 :     TimeInterval target = buffered[index];
    2169           0 :     target.mFuzz = aFuzz;
    2170           0 :     i = FindSampleIndex(track, target);
    2171             :   }
    2172             : 
    2173           0 :   Maybe<TimeUnit> lastKeyFrameTime;
    2174           0 :   TimeUnit lastKeyFrameTimecode;
    2175           0 :   uint32_t lastKeyFrameIndex = 0;
    2176           0 :   for (; i < track.Length(); i++) {
    2177           0 :     const RefPtr<MediaRawData>& sample = track[i];
    2178           0 :     TimeUnit sampleTime = sample->mTime;
    2179           0 :     if (sampleTime > aTime && lastKeyFrameTime.isSome()) {
    2180           0 :       break;
    2181             :     }
    2182           0 :     if (sample->mKeyframe) {
    2183           0 :       lastKeyFrameTimecode = sample->mTimecode;
    2184           0 :       lastKeyFrameTime = Some(sampleTime);
    2185           0 :       lastKeyFrameIndex = i;
    2186             :     }
    2187           0 :     if (sampleTime == aTime ||
    2188           0 :         (sampleTime > aTime && lastKeyFrameTime.isSome())) {
    2189           0 :       break;
    2190             :     }
    2191             :   }
    2192           0 :   MSE_DEBUG("Keyframe %s found at %" PRId64 " @ %u",
    2193             :             lastKeyFrameTime.isSome() ? "" : "not",
    2194             :             lastKeyFrameTime.refOr(TimeUnit()).ToMicroseconds(),
    2195             :             lastKeyFrameIndex);
    2196             : 
    2197           0 :   trackBuffer.mNextGetSampleIndex = Some(lastKeyFrameIndex);
    2198           0 :   trackBuffer.mNextSampleTimecode = lastKeyFrameTimecode;
    2199           0 :   trackBuffer.mNextSampleTime = lastKeyFrameTime.refOr(TimeUnit());
    2200           0 :   ResetEvictionIndex(trackBuffer);
    2201           0 :   UpdateEvictionIndex(trackBuffer, lastKeyFrameIndex);
    2202             : 
    2203           0 :   return lastKeyFrameTime.refOr(TimeUnit());
    2204             : }
    2205             : 
    2206             : uint32_t
    2207           0 : TrackBuffersManager::SkipToNextRandomAccessPoint(TrackInfo::TrackType aTrack,
    2208             :                                                  const TimeUnit& aTimeThreadshold,
    2209             :                                                  const media::TimeUnit& aFuzz,
    2210             :                                                  bool& aFound)
    2211             : {
    2212           0 :   MOZ_ASSERT(OnTaskQueue());
    2213           0 :   uint32_t parsed = 0;
    2214           0 :   auto& trackData = GetTracksData(aTrack);
    2215           0 :   const TrackBuffer& track = GetTrackBuffer(aTrack);
    2216           0 :   aFound = false;
    2217             : 
    2218             :   // SkipToNextRandomAccessPoint can only be called if aTimeThreadshold is known
    2219             :   // to be buffered.
    2220             : 
    2221             :   // So first determine the current position in the track buffer if necessary.
    2222           0 :   if (trackData.mNextGetSampleIndex.isNothing()) {
    2223           0 :     if (trackData.mNextSampleTimecode == TimeUnit()) {
    2224             :       // First demux, get first sample.
    2225           0 :       trackData.mNextGetSampleIndex = Some(0u);
    2226             :     } else {
    2227           0 :       int32_t pos = FindCurrentPosition(aTrack, aFuzz);
    2228           0 :       if (pos < 0) {
    2229           0 :         return 0;
    2230             :       }
    2231           0 :       trackData.mNextGetSampleIndex = Some(uint32_t(pos));
    2232             :     }
    2233             :   }
    2234             : 
    2235           0 :   TimeUnit nextSampleTimecode = trackData.mNextSampleTimecode;
    2236           0 :   TimeUnit nextSampleTime = trackData.mNextSampleTime;
    2237           0 :   uint32_t i = trackData.mNextGetSampleIndex.ref();
    2238           0 :   int32_t originalPos = i;
    2239             : 
    2240           0 :   for (; i < track.Length(); i++) {
    2241             :     const MediaRawData* sample =
    2242           0 :       GetSample(aTrack,
    2243             :                 i,
    2244             :                 nextSampleTimecode,
    2245             :                 nextSampleTime,
    2246           0 :                 aFuzz);
    2247           0 :     if (!sample) {
    2248           0 :       break;
    2249             :     }
    2250           0 :     if (sample->mKeyframe &&
    2251           0 :         sample->mTime >= aTimeThreadshold) {
    2252           0 :       aFound = true;
    2253           0 :       break;
    2254             :     }
    2255           0 :     nextSampleTimecode = sample->mTimecode + sample->mDuration;
    2256           0 :     nextSampleTime = sample->GetEndTime();
    2257           0 :     parsed++;
    2258             :   }
    2259             : 
    2260             :   // Adjust the next demux time and index so that the next call to
    2261             :   // SkipToNextRandomAccessPoint will not count again the parsed sample as
    2262             :   // skipped.
    2263           0 :   if (aFound) {
    2264           0 :     trackData.mNextSampleTimecode = track[i]->mTimecode;
    2265           0 :     trackData.mNextSampleTime = track[i]->mTime;
    2266           0 :     trackData.mNextGetSampleIndex = Some(i);
    2267           0 :   } else if (i > 0) {
    2268             :     // Go back to the previous keyframe or the original position so the next
    2269             :     // demux can succeed and be decoded.
    2270           0 :     for (int j = i - 1; j >= originalPos; j--) {
    2271           0 :       const RefPtr<MediaRawData>& sample = track[j];
    2272           0 :       if (sample->mKeyframe) {
    2273           0 :         trackData.mNextSampleTimecode = sample->mTimecode;
    2274           0 :         trackData.mNextSampleTime = sample->mTime;
    2275           0 :         trackData.mNextGetSampleIndex = Some(uint32_t(j));
    2276             :         // We are unable to skip to a keyframe past aTimeThreshold, however
    2277             :         // we are speeding up decoding by dropping the unplayable frames.
    2278             :         // So we can mark aFound as true.
    2279           0 :         aFound = true;
    2280           0 :         break;
    2281             :       }
    2282           0 :       parsed--;
    2283             :     }
    2284             :   }
    2285             : 
    2286           0 :   if (aFound) {
    2287           0 :     UpdateEvictionIndex(trackData, trackData.mNextGetSampleIndex.ref());
    2288             :   }
    2289             : 
    2290           0 :   return parsed;
    2291             : }
    2292             : 
    2293             : const MediaRawData*
    2294           0 : TrackBuffersManager::GetSample(TrackInfo::TrackType aTrack,
    2295             :                                uint32_t aIndex,
    2296             :                                const TimeUnit& aExpectedDts,
    2297             :                                const TimeUnit& aExpectedPts,
    2298             :                                const TimeUnit& aFuzz)
    2299             : {
    2300           0 :   MOZ_ASSERT(OnTaskQueue());
    2301           0 :   const TrackBuffer& track = GetTrackBuffer(aTrack);
    2302             : 
    2303           0 :   if (aIndex >= track.Length()) {
    2304             :     // reached the end.
    2305           0 :     return nullptr;
    2306             :   }
    2307             : 
    2308           0 :   const RefPtr<MediaRawData>& sample = track[aIndex];
    2309           0 :   if (!aIndex || sample->mTimecode <= aExpectedDts + aFuzz ||
    2310           0 :       sample->mTime <= aExpectedPts + aFuzz) {
    2311           0 :     return sample;
    2312             :   }
    2313             : 
    2314             :   // Gap is too big. End of Stream or Waiting for Data.
    2315             :   // TODO, check that we have continuous data based on the sanitized buffered
    2316             :   // range instead.
    2317           0 :   return nullptr;
    2318             : }
    2319             : 
    2320             : already_AddRefed<MediaRawData>
    2321           0 : TrackBuffersManager::GetSample(TrackInfo::TrackType aTrack,
    2322             :                                const TimeUnit& aFuzz,
    2323             :                                MediaResult& aResult)
    2324             : {
    2325           0 :   MOZ_ASSERT(OnTaskQueue());
    2326           0 :   auto& trackData = GetTracksData(aTrack);
    2327           0 :   const TrackBuffer& track = GetTrackBuffer(aTrack);
    2328             : 
    2329           0 :   aResult = NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA;
    2330             : 
    2331           0 :   if (!track.Length()) {
    2332           0 :     aResult = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
    2333           0 :     return nullptr;
    2334             :   }
    2335             : 
    2336           0 :   if (trackData.mNextGetSampleIndex.isNothing() &&
    2337           0 :       trackData.mNextSampleTimecode == TimeUnit()) {
    2338             :     // First demux, get first sample.
    2339           0 :     trackData.mNextGetSampleIndex = Some(0u);
    2340             :   }
    2341             : 
    2342           0 :   if (trackData.mNextGetSampleIndex.isSome()) {
    2343           0 :     if (trackData.mNextGetSampleIndex.ref() >= track.Length()) {
    2344           0 :       aResult = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
    2345           0 :       return nullptr;
    2346             :     }
    2347             :     const MediaRawData* sample =
    2348           0 :       GetSample(aTrack,
    2349           0 :                 trackData.mNextGetSampleIndex.ref(),
    2350             :                 trackData.mNextSampleTimecode,
    2351             :                 trackData.mNextSampleTime,
    2352           0 :                 aFuzz);
    2353           0 :     if (!sample) {
    2354           0 :       return nullptr;
    2355             :     }
    2356             : 
    2357           0 :     RefPtr<MediaRawData> p = sample->Clone();
    2358           0 :     if (!p) {
    2359           0 :       aResult = MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__);
    2360           0 :       return nullptr;
    2361             :     }
    2362           0 :     if (p->mKeyframe) {
    2363           0 :       UpdateEvictionIndex(trackData, trackData.mNextGetSampleIndex.ref());
    2364             :     }
    2365           0 :     trackData.mNextGetSampleIndex.ref()++;
    2366             :     // Estimate decode timestamp and timestamp of the next sample.
    2367           0 :     TimeUnit nextSampleTimecode = sample->mTimecode + sample->mDuration;
    2368           0 :     TimeUnit nextSampleTime = sample->GetEndTime();
    2369             :     const MediaRawData* nextSample =
    2370           0 :       GetSample(aTrack,
    2371           0 :                 trackData.mNextGetSampleIndex.ref(),
    2372             :                 nextSampleTimecode,
    2373             :                 nextSampleTime,
    2374           0 :                 aFuzz);
    2375           0 :     if (nextSample) {
    2376             :       // We have a valid next sample, can use exact values.
    2377           0 :       trackData.mNextSampleTimecode = nextSample->mTimecode;
    2378           0 :       trackData.mNextSampleTime = nextSample->mTime;
    2379             :     } else {
    2380             :       // Next sample isn't available yet. Use estimates.
    2381           0 :       trackData.mNextSampleTimecode = nextSampleTimecode;
    2382           0 :       trackData.mNextSampleTime = nextSampleTime;
    2383             :     }
    2384           0 :     aResult = NS_OK;
    2385           0 :     return p.forget();
    2386             :   }
    2387             : 
    2388           0 :   if (trackData.mNextSampleTimecode >
    2389           0 :       track.LastElement()->mTimecode + track.LastElement()->mDuration) {
    2390             :     // The next element is past our last sample. We're done.
    2391           0 :     trackData.mNextGetSampleIndex = Some(uint32_t(track.Length()));
    2392           0 :     aResult = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
    2393           0 :     return nullptr;
    2394             :   }
    2395             : 
    2396             :   // Our previous index has been overwritten, attempt to find the new one.
    2397           0 :   int32_t pos = FindCurrentPosition(aTrack, aFuzz);
    2398           0 :   if (pos < 0) {
    2399           0 :     MSE_DEBUG("Couldn't find sample (pts:%" PRId64 " dts:%" PRId64 ")",
    2400             :               trackData.mNextSampleTime.ToMicroseconds(),
    2401             :               trackData.mNextSampleTimecode.ToMicroseconds());
    2402           0 :     return nullptr;
    2403             :   }
    2404             : 
    2405           0 :   const RefPtr<MediaRawData>& sample = track[pos];
    2406           0 :   RefPtr<MediaRawData> p = sample->Clone();
    2407           0 :   if (!p) {
    2408             :     // OOM
    2409           0 :     aResult = MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__);
    2410           0 :     return nullptr;
    2411             :   }
    2412             : 
    2413             :   // Find the previous keyframe to calculate the evictable amount.
    2414           0 :   int32_t i = pos;
    2415           0 :   for (; !track[i]->mKeyframe; i--) {
    2416             :   }
    2417           0 :   UpdateEvictionIndex(trackData, i);
    2418             : 
    2419           0 :   trackData.mNextGetSampleIndex = Some(uint32_t(pos)+1);
    2420           0 :   trackData.mNextSampleTimecode = sample->mTimecode + sample->mDuration;
    2421           0 :   trackData.mNextSampleTime = sample->GetEndTime();
    2422           0 :   aResult = NS_OK;
    2423           0 :   return p.forget();
    2424             : }
    2425             : 
    2426             : int32_t
    2427           0 : TrackBuffersManager::FindCurrentPosition(TrackInfo::TrackType aTrack,
    2428             :                                          const TimeUnit& aFuzz) const
    2429             : {
    2430           0 :   MOZ_ASSERT(OnTaskQueue());
    2431           0 :   auto& trackData = GetTracksData(aTrack);
    2432           0 :   const TrackBuffer& track = GetTrackBuffer(aTrack);
    2433             : 
    2434             :   // Perform an exact search first.
    2435           0 :   for (uint32_t i = 0; i < track.Length(); i++) {
    2436           0 :     const RefPtr<MediaRawData>& sample = track[i];
    2437             :     TimeInterval sampleInterval{
    2438           0 :       sample->mTimecode,
    2439           0 :       sample->mTimecode + sample->mDuration};
    2440             : 
    2441           0 :     if (sampleInterval.ContainsStrict(trackData.mNextSampleTimecode)) {
    2442           0 :       return i;
    2443             :     }
    2444           0 :     if (sampleInterval.mStart > trackData.mNextSampleTimecode) {
    2445             :       // Samples are ordered by timecode. There's no need to search
    2446             :       // any further.
    2447           0 :       break;
    2448             :     }
    2449             :   }
    2450             : 
    2451           0 :   for (uint32_t i = 0; i < track.Length(); i++) {
    2452           0 :     const RefPtr<MediaRawData>& sample = track[i];
    2453             :     TimeInterval sampleInterval{
    2454           0 :       sample->mTimecode,
    2455           0 :       sample->mTimecode + sample->mDuration,
    2456           0 :       aFuzz};
    2457             : 
    2458           0 :     if (sampleInterval.ContainsWithStrictEnd(trackData.mNextSampleTimecode)) {
    2459           0 :       return i;
    2460             :     }
    2461           0 :     if (sampleInterval.mStart - aFuzz > trackData.mNextSampleTimecode) {
    2462             :       // Samples are ordered by timecode. There's no need to search
    2463             :       // any further.
    2464           0 :       break;
    2465             :     }
    2466             :   }
    2467             : 
    2468             :   // We couldn't find our sample by decode timestamp. Attempt to find it using
    2469             :   // presentation timestamp. There will likely be small jerkiness.
    2470           0 :   for (uint32_t i = 0; i < track.Length(); i++) {
    2471           0 :     const RefPtr<MediaRawData>& sample = track[i];
    2472             :     TimeInterval sampleInterval{
    2473           0 :       sample->mTime,
    2474           0 :       sample->GetEndTime(),
    2475           0 :       aFuzz};
    2476             : 
    2477           0 :     if (sampleInterval.ContainsWithStrictEnd(trackData.mNextSampleTimecode)) {
    2478           0 :       return i;
    2479             :     }
    2480             :   }
    2481             : 
    2482             :   // Still not found.
    2483           0 :   return -1;
    2484             : }
    2485             : 
    2486             : uint32_t
    2487           0 : TrackBuffersManager::Evictable(TrackInfo::TrackType aTrack) const
    2488             : {
    2489           0 :   MonitorAutoLock mon(mMonitor);
    2490           0 :   return GetTracksData(aTrack).mEvictionIndex.mEvictable;
    2491             : }
    2492             : 
    2493             : TimeUnit
    2494           0 : TrackBuffersManager::GetNextRandomAccessPoint(TrackInfo::TrackType aTrack,
    2495             :                                               const TimeUnit& aFuzz)
    2496             : {
    2497           0 :   MOZ_ASSERT(OnTaskQueue());
    2498           0 :   auto& trackData = GetTracksData(aTrack);
    2499           0 :   MOZ_ASSERT(trackData.mNextGetSampleIndex.isSome());
    2500           0 :   const TrackBuffersManager::TrackBuffer& track = GetTrackBuffer(aTrack);
    2501             : 
    2502           0 :   uint32_t i = trackData.mNextGetSampleIndex.ref();
    2503           0 :   TimeUnit nextSampleTimecode = trackData.mNextSampleTimecode;
    2504           0 :   TimeUnit nextSampleTime = trackData.mNextSampleTime;
    2505             : 
    2506           0 :   for (; i < track.Length(); i++) {
    2507             :     const MediaRawData* sample =
    2508           0 :       GetSample(aTrack, i, nextSampleTimecode, nextSampleTime, aFuzz);
    2509           0 :     if (!sample) {
    2510           0 :       break;
    2511             :     }
    2512           0 :     if (sample->mKeyframe) {
    2513           0 :       return sample->mTime;
    2514             :     }
    2515           0 :     nextSampleTimecode = sample->mTimecode + sample->mDuration;
    2516           0 :     nextSampleTime = sample->GetEndTime();
    2517             :   }
    2518           0 :   return TimeUnit::FromInfinity();
    2519             : }
    2520             : 
    2521             : void
    2522           0 : TrackBuffersManager::TrackData::AddSizeOfResources(MediaSourceDecoder::ResourceSizes* aSizes) const
    2523             : {
    2524           0 :   for (const TrackBuffer& buffer : mBuffers) {
    2525           0 :     for (const MediaRawData* data : buffer) {
    2526           0 :       aSizes->mByteSize += data->SizeOfIncludingThis(aSizes->mMallocSizeOf);
    2527             :     }
    2528             :   }
    2529           0 : }
    2530             : 
    2531             : void
    2532           0 : TrackBuffersManager::AddSizeOfResources(MediaSourceDecoder::ResourceSizes* aSizes) const
    2533             : {
    2534           0 :   MOZ_ASSERT(OnTaskQueue());
    2535           0 :   mVideoTracks.AddSizeOfResources(aSizes);
    2536           0 :   mAudioTracks.AddSizeOfResources(aSizes);
    2537           0 : }
    2538             : 
    2539             : } // namespace mozilla
    2540             : #undef MSE_DEBUG
    2541             : #undef MSE_DEBUGV
    2542             : #undef SAMPLE_DEBUG

Generated by: LCOV version 1.13