Coverage Report

Created: 2018-09-25 14:53

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