DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

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

#include "HLSDemuxer.h"

#include <algorithm>
#include <limits>
#include <stdint.h>

#include "HLSUtils.h"
#include "MediaCodec.h"
#include "mozilla/Unused.h"
#include "nsPrintfCString.h"

using namespace mozilla::java;

namespace mozilla {

static Atomic<uint32_t> sStreamSourceID(0u);

typedef TrackInfo::TrackType TrackType;
using media::TimeInterval;
using media::TimeIntervals;
using media::TimeUnit;

static VideoInfo::Rotation getVideoInfoRotation(int aRotation) {
  switch (aRotation) {
    case 0:
      return VideoInfo::Rotation::kDegree_0;
    case 90:
      return VideoInfo::Rotation::kDegree_90;
    case 180:
      return VideoInfo::Rotation::kDegree_180;
    case 270:
      return VideoInfo::Rotation::kDegree_270;
    default:
      return VideoInfo::Rotation::kDegree_0;
  }
}

static mozilla::StereoMode getStereoMode(int aMode) {
  switch (aMode) {
    case 0:
      return mozilla::StereoMode::MONO;
    case 1:
      return mozilla::StereoMode::TOP_BOTTOM;
    case 2:
      return mozilla::StereoMode::LEFT_RIGHT;
    default:
      return mozilla::StereoMode::MONO;
  }
}

// HLSDemuxerCallbacksSupport is a native implemented callback class for
// Callbacks in GeckoHLSDemuxerWrapper.java.
// The callback functions will be invoked by JAVA-side thread.
// Should dispatch the task to the demuxer's task queue.
// We ensure the callback will never be invoked after
// HLSDemuxerCallbacksSupport::DisposeNative has been called in ~HLSDemuxer.
class HLSDemuxer::HLSDemuxerCallbacksSupport
    : public GeckoHLSDemuxerWrapper::Callbacks::Natives<
          HLSDemuxerCallbacksSupport> {
  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(HLSDemuxerCallbacksSupport)
 public:
  typedef GeckoHLSDemuxerWrapper::Callbacks::Natives<HLSDemuxerCallbacksSupport>
      NativeCallbacks;
  using NativeCallbacks::AttachNative;
  using NativeCallbacks::DisposeNative;

  explicit HLSDemuxerCallbacksSupport(HLSDemuxer* aDemuxer)
      : mMutex("HLSDemuxerCallbacksSupport"), mDemuxer(aDemuxer) {
    MOZ_ASSERT(mDemuxer);
  }

  void OnInitialized(bool aHasAudio, bool aHasVideo) {
    HLS_DEBUG("HLSDemuxerCallbacksSupport", "OnInitialized");
    MutexAutoLock lock(mMutex);
    if (!mDemuxer) {
      return;
    }
    RefPtr<HLSDemuxerCallbacksSupport> self = this;
    nsresult rv = mDemuxer->GetTaskQueue()->Dispatch(NS_NewRunnableFunction(
        "HLSDemuxer::HLSDemuxerCallbacksSupport::OnInitialized", [=]() {
          MutexAutoLock lock(self->mMutex);
          if (self->mDemuxer) {
            self->mDemuxer->OnInitialized(aHasAudio, aHasVideo);
          }
        }));
    MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
    Unused << rv;
  }

  void OnError(int aErrorCode) {
    HLS_DEBUG("HLSDemuxerCallbacksSupport", "Got error(%d) from java side",
              aErrorCode);
    MutexAutoLock lock(mMutex);
    if (!mDemuxer) {
      return;
    }
    RefPtr<HLSDemuxerCallbacksSupport> self = this;
    nsresult rv = mDemuxer->GetTaskQueue()->Dispatch(NS_NewRunnableFunction(
        "HLSDemuxer::HLSDemuxerCallbacksSupport::OnError", [=]() {
          MutexAutoLock lock(self->mMutex);
          if (self->mDemuxer) {
            self->mDemuxer->OnError(aErrorCode);
          }
        }));
    MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
    Unused << rv;
  }

  void Detach() {
    MutexAutoLock lock(mMutex);
    mDemuxer = nullptr;
  }

  Mutex mMutex;

 private:
  ~HLSDemuxerCallbacksSupport() {}
  HLSDemuxer* mDemuxer;
};

HLSDemuxer::HLSDemuxer(int aPlayerId)
    : mTaskQueue(new TaskQueue(GetMediaThreadPool(MediaThreadType::PLAYBACK),
                               /* aSupportsTailDispatch = */ false)) {
  MOZ_ASSERT(NS_IsMainThread());
  HLSDemuxerCallbacksSupport::Init();
  mJavaCallbacks = GeckoHLSDemuxerWrapper::Callbacks::New();
  MOZ_ASSERT(mJavaCallbacks);

  mCallbackSupport = new HLSDemuxerCallbacksSupport(this);
  HLSDemuxerCallbacksSupport::AttachNative(mJavaCallbacks, mCallbackSupport);

  mHLSDemuxerWrapper =
      GeckoHLSDemuxerWrapper::Create(aPlayerId, mJavaCallbacks);
  MOZ_ASSERT(mHLSDemuxerWrapper);
}

void HLSDemuxer::OnInitialized(bool aHasAudio, bool aHasVideo) {
  MOZ_ASSERT(OnTaskQueue());

  if (aHasAudio) {
    mAudioDemuxer = new HLSTrackDemuxer(this, TrackInfo::TrackType::kAudioTrack,
                                        MakeUnique<AudioInfo>());
  }
  if (aHasVideo) {
    mVideoDemuxer = new HLSTrackDemuxer(this, TrackInfo::TrackType::kVideoTrack,
                                        MakeUnique<VideoInfo>());
  }

  mInitPromise.ResolveIfExists(NS_OK, __func__);
}

void HLSDemuxer::OnError(int aErrorCode) {
  MOZ_ASSERT(OnTaskQueue());
  mInitPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
}

RefPtr<HLSDemuxer::InitPromise> HLSDemuxer::Init() {
  RefPtr<HLSDemuxer> self = this;
  return InvokeAsync(GetTaskQueue(), __func__, [self]() {
    RefPtr<InitPromise> p = self->mInitPromise.Ensure(__func__);
    return p;
  });
}

void HLSDemuxer::NotifyDataArrived() {
  HLS_DEBUG("HLSDemuxer", "NotifyDataArrived");
}

uint32_t HLSDemuxer::GetNumberTracks(TrackType aType) const {
  switch (aType) {
    case TrackType::kAudioTrack:
      return mHLSDemuxerWrapper->GetNumberOfTracks(TrackType::kAudioTrack);
    case TrackType::kVideoTrack:
      return mHLSDemuxerWrapper->GetNumberOfTracks(TrackType::kVideoTrack);
    default:
      return 0;
  }
}

already_AddRefed<MediaTrackDemuxer> HLSDemuxer::GetTrackDemuxer(
    TrackType aType, uint32_t aTrackNumber) {
  RefPtr<HLSTrackDemuxer> e = nullptr;
  if (aType == TrackInfo::TrackType::kAudioTrack) {
    e = mAudioDemuxer;
  } else {
    e = mVideoDemuxer;
  }
  return e.forget();
}

bool HLSDemuxer::IsSeekable() const {
  return !mHLSDemuxerWrapper->IsLiveStream();
}

UniquePtr<EncryptionInfo> HLSDemuxer::GetCrypto() {
  // TODO: Currently, our HLS implementation doesn't support encrypted content.
  // Return null at this stage.
  return nullptr;
}

TimeUnit HLSDemuxer::GetNextKeyFrameTime() {
  MOZ_ASSERT(mHLSDemuxerWrapper);
  return TimeUnit::FromMicroseconds(mHLSDemuxerWrapper->GetNextKeyFrameTime());
}

bool HLSDemuxer::OnTaskQueue() const { return mTaskQueue->IsCurrentThreadIn(); }

HLSDemuxer::~HLSDemuxer() {
  HLS_DEBUG("HLSDemuxer", "~HLSDemuxer()");
  mCallbackSupport->Detach();
  if (mHLSDemuxerWrapper) {
    mHLSDemuxerWrapper->Destroy();
    mHLSDemuxerWrapper = nullptr;
  }
  if (mJavaCallbacks) {
    HLSDemuxerCallbacksSupport::DisposeNative(mJavaCallbacks);
    mJavaCallbacks = nullptr;
  }
  mInitPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
}

HLSTrackDemuxer::HLSTrackDemuxer(HLSDemuxer* aParent,
                                 TrackInfo::TrackType aType,
                                 UniquePtr<TrackInfo> aTrackInfo)
    : mParent(aParent),
      mType(aType),
      mMutex("HLSTrackDemuxer"),
      mTrackInfo(std::move(aTrackInfo)) {
  // Only support audio and video track currently.
  MOZ_ASSERT(mType == TrackInfo::kVideoTrack ||
             mType == TrackInfo::kAudioTrack);
  UpdateMediaInfo(0);
}

UniquePtr<TrackInfo> HLSTrackDemuxer::GetInfo() const {
  MutexAutoLock lock(mMutex);
  return mTrackInfo->Clone();
}

RefPtr<HLSTrackDemuxer::SeekPromise> HLSTrackDemuxer::Seek(
    const TimeUnit& aTime) {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  return InvokeAsync<TimeUnit&&>(mParent->GetTaskQueue(), this, __func__,
                                 &HLSTrackDemuxer::DoSeek, aTime);
}

RefPtr<HLSTrackDemuxer::SeekPromise> HLSTrackDemuxer::DoSeek(
    const TimeUnit& aTime) {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  MOZ_ASSERT(mParent->OnTaskQueue());
  mQueuedSample = nullptr;
  int64_t seekTimeUs = aTime.ToMicroseconds();
  bool result = mParent->mHLSDemuxerWrapper->Seek(seekTimeUs);
  if (!result) {
    return SeekPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA,
                                        __func__);
  }
  TimeUnit seekTime = TimeUnit::FromMicroseconds(seekTimeUs);
  return SeekPromise::CreateAndResolve(seekTime, __func__);
}

RefPtr<HLSTrackDemuxer::SamplesPromise> HLSTrackDemuxer::GetSamples(
    int32_t aNumSamples) {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  return InvokeAsync(mParent->GetTaskQueue(), this, __func__,
                     &HLSTrackDemuxer::DoGetSamples, aNumSamples);
}

RefPtr<HLSTrackDemuxer::SamplesPromise> HLSTrackDemuxer::DoGetSamples(
    int32_t aNumSamples) {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  MOZ_ASSERT(mParent->OnTaskQueue());
  if (!aNumSamples) {
    return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_DEMUXER_ERR,
                                           __func__);
  }
  RefPtr<SamplesHolder> samples = new SamplesHolder;
  if (mQueuedSample) {
    if (mQueuedSample->mEOS) {
      return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_END_OF_STREAM,
                                             __func__);
    }
    MOZ_ASSERT(mQueuedSample->mKeyframe, "mQueuedSample must be a keyframe");
    samples->AppendSample(mQueuedSample);
    mQueuedSample = nullptr;
    aNumSamples--;
  }
  if (aNumSamples == 0) {
    // Return the queued sample.
    return SamplesPromise::CreateAndResolve(samples, __func__);
  }
  mozilla::jni::ObjectArray::LocalRef demuxedSamples =
      (mType == TrackInfo::kAudioTrack)
          ? mParent->mHLSDemuxerWrapper->GetSamples(TrackInfo::kAudioTrack,
                                                    aNumSamples)
          : mParent->mHLSDemuxerWrapper->GetSamples(TrackInfo::kVideoTrack,
                                                    aNumSamples);
  nsTArray<jni::Object::LocalRef> sampleObjectArray(
      demuxedSamples->GetElements());

  if (sampleObjectArray.IsEmpty()) {
    return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA,
                                           __func__);
  }

  for (auto&& demuxedSample : sampleObjectArray) {
    java::GeckoHLSSample::LocalRef sample(std::move(demuxedSample));
    if (sample->IsEOS()) {
      HLS_DEBUG("HLSTrackDemuxer", "Met BUFFER_FLAG_END_OF_STREAM.");
      if (samples->GetSamples().IsEmpty()) {
        return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_END_OF_STREAM,
                                               __func__);
      }
      mQueuedSample = new MediaRawData();
      mQueuedSample->mEOS = true;
      break;
    }
    RefPtr<MediaRawData> mrd = ConvertToMediaRawData(sample);
    if (!mrd) {
      return SamplesPromise::CreateAndReject(NS_ERROR_OUT_OF_MEMORY, __func__);
    }
    if (!mrd->HasValidTime()) {
      return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_DEMUXER_ERR,
                                             __func__);
    }
    samples->AppendSample(mrd);
  }
  if (mType == TrackInfo::kVideoTrack &&
      (mNextKeyframeTime.isNothing() ||
       samples->GetSamples().LastElement()->mTime >=
           mNextKeyframeTime.value())) {
    // Only need to find NextKeyFrame for Video
    UpdateNextKeyFrameTime();
  }

  return SamplesPromise::CreateAndResolve(samples, __func__);
}

void HLSTrackDemuxer::UpdateMediaInfo(int index) {
  MOZ_ASSERT(mParent->OnTaskQueue());
  MOZ_ASSERT(mParent->mHLSDemuxerWrapper);
  MutexAutoLock lock(mMutex);
  jni::Object::LocalRef infoObj = nullptr;
  if (mType == TrackType::kAudioTrack) {
    infoObj = mParent->mHLSDemuxerWrapper->GetAudioInfo(index);
    auto* audioInfo = mTrackInfo->GetAsAudioInfo();
    if (infoObj && audioInfo) {
      HLS_DEBUG("HLSTrackDemuxer", "Update audio info (%d)", index);
      java::GeckoAudioInfo::LocalRef audioInfoObj(std::move(infoObj));
      audioInfo->mRate = audioInfoObj->Rate();
      audioInfo->mChannels = audioInfoObj->Channels();
      audioInfo->mProfile = audioInfoObj->Profile();
      audioInfo->mBitDepth = audioInfoObj->BitDepth();
      audioInfo->mMimeType =
          NS_ConvertUTF16toUTF8(audioInfoObj->MimeType()->ToString());
      audioInfo->mDuration =
          TimeUnit::FromMicroseconds(audioInfoObj->Duration());
      jni::ByteArray::LocalRef csdBytes = audioInfoObj->CodecSpecificData();
      if (csdBytes) {
        auto&& csd = csdBytes->GetElements();
        audioInfo->mCodecSpecificConfig->Clear();
        audioInfo->mCodecSpecificConfig->AppendElements(
            reinterpret_cast<uint8_t*>(&csd[0]), csd.Length());
      }
    }
  } else {
    infoObj = mParent->mHLSDemuxerWrapper->GetVideoInfo(index);
    auto* videoInfo = mTrackInfo->GetAsVideoInfo();
    if (infoObj && videoInfo) {
      java::GeckoVideoInfo::LocalRef videoInfoObj(std::move(infoObj));
      videoInfo->mStereoMode = getStereoMode(videoInfoObj->StereoMode());
      videoInfo->mRotation = getVideoInfoRotation(videoInfoObj->Rotation());
      videoInfo->mImage.width = videoInfoObj->DisplayWidth();
      videoInfo->mImage.height = videoInfoObj->DisplayHeight();
      videoInfo->mDisplay.width = videoInfoObj->PictureWidth();
      videoInfo->mDisplay.height = videoInfoObj->PictureHeight();
      videoInfo->mMimeType =
          NS_ConvertUTF16toUTF8(videoInfoObj->MimeType()->ToString());
      videoInfo->mDuration =
          TimeUnit::FromMicroseconds(videoInfoObj->Duration());
      HLS_DEBUG("HLSTrackDemuxer",
                "Update video info (%d) / I(%dx%d) / D(%dx%d)", index,
                videoInfo->mImage.width, videoInfo->mImage.height,
                videoInfo->mDisplay.width, videoInfo->mDisplay.height);
    }
  }
}

CryptoSample HLSTrackDemuxer::ExtractCryptoSample(
    size_t aSampleSize, java::sdk::CryptoInfo::LocalRef aCryptoInfo) {
  if (!aCryptoInfo) {
    return CryptoSample{};
  }
  // Extract Crypto information
  CryptoSample crypto;
  char const* msg = "";
  do {
    HLS_DEBUG("HLSTrackDemuxer", "Sample has Crypto Info");

    int32_t mode = 0;
    if (NS_FAILED(aCryptoInfo->Mode(&mode))) {
      msg = "Error when extracting encryption mode.";
      break;
    }
    // We currently only handle ctr mode.
    if (mode != java::sdk::MediaCodec::CRYPTO_MODE_AES_CTR) {
      msg = "Error: unexpected encryption mode.";
      break;
    }

    crypto.mCryptoScheme = CryptoScheme::Cenc;

    mozilla::jni::ByteArray::LocalRef ivData;
    if (NS_FAILED(aCryptoInfo->Iv(&ivData))) {
      msg = "Error when extracting encryption IV.";
      break;
    }
    // Data in mIV is uint8_t and jbyte is signed char
    auto&& ivArr = ivData->GetElements();
    crypto.mIV.AppendElements(reinterpret_cast<uint8_t*>(&ivArr[0]),
                              ivArr.Length());
    crypto.mIVSize = ivArr.Length();
    mozilla::jni::ByteArray::LocalRef keyData;
    if (NS_FAILED(aCryptoInfo->Key(&keyData))) {
      msg = "Error when extracting encryption key.";
      break;
    }
    auto&& keyArr = keyData->GetElements();
    // Data in mKeyId is uint8_t and jbyte is signed char
    crypto.mKeyId.AppendElements(reinterpret_cast<uint8_t*>(&keyArr[0]),
                                 keyArr.Length());

    mozilla::jni::IntArray::LocalRef clearData;
    if (NS_FAILED(aCryptoInfo->NumBytesOfClearData(&clearData))) {
      msg = "Error when extracting clear data.";
      break;
    }
    // Data in mPlainSizes is uint16_t, NumBytesOfClearData is int32_t
    // , so need a for loop to copy
    for (const auto& b : clearData->GetElements()) {
      crypto.mPlainSizes.AppendElement(b);
    }

    mozilla::jni::IntArray::LocalRef encryptedData;
    if (NS_FAILED(aCryptoInfo->NumBytesOfEncryptedData(&encryptedData))) {
      msg = "Error when extracting encrypted data.";
      break;
    }
    auto&& encryptedArr = encryptedData->GetElements();
    // Data in mEncryptedSizes is uint32_t, NumBytesOfEncryptedData is int32_t
    crypto.mEncryptedSizes.AppendElements(
        reinterpret_cast<uint32_t*>(&encryptedArr[0]), encryptedArr.Length());
    int subSamplesNum = 0;
    if (NS_FAILED(aCryptoInfo->NumSubSamples(&subSamplesNum))) {
      msg = "Error when extracting subsamples.";
      break;
    }
    crypto.mPlainSizes[0] -= (aSampleSize - subSamplesNum);

    return crypto;
  } while (false);

  HLS_DEBUG("HLSTrackDemuxer", "%s", msg);
  return CryptoSample{};
}

RefPtr<MediaRawData> HLSTrackDemuxer::ConvertToMediaRawData(
    java::GeckoHLSSample::LocalRef aSample) {
  java::sdk::BufferInfo::LocalRef info = aSample->Info();
  // Currently extract PTS, Size and Data without Crypto information.
  // Transform java Sample into MediaRawData
  RefPtr<MediaRawData> mrd = new MediaRawData();
  int64_t presentationTimeUs = 0;
  bool ok = NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs));
  mrd->mTime = TimeUnit::FromMicroseconds(presentationTimeUs);
  mrd->mTimecode = TimeUnit::FromMicroseconds(presentationTimeUs);
  mrd->mKeyframe = aSample->IsKeyFrame();
  mrd->mDuration = (mType == TrackInfo::kVideoTrack)
                       ? TimeUnit::FromMicroseconds(aSample->Duration())
                       : TimeUnit::Zero();

  int32_t size = 0;
  ok &= NS_SUCCEEDED(info->Size(&size));
  if (!ok) {
    HLS_DEBUG("HLSTrackDemuxer",
              "Error occurred during extraction from Sample java object.");
    return nullptr;
  }

  // Update A/V stream souce ID & Audio/VideoInfo for MFR.
  auto sampleFormatIndex = aSample->FormatIndex();
  if (mLastFormatIndex != sampleFormatIndex) {
    mLastFormatIndex = sampleFormatIndex;
    UpdateMediaInfo(mLastFormatIndex);
    MutexAutoLock lock(mMutex);
    mrd->mTrackInfo = new TrackInfoSharedPtr(*mTrackInfo, ++sStreamSourceID);
  }

  // Write payload into MediaRawData
  UniquePtr<MediaRawDataWriter> writer(mrd->CreateWriter());
  if (!writer->SetSize(size)) {
    HLS_DEBUG("HLSTrackDemuxer", "Exit failed to allocate media buffer");
    return nullptr;
  }
  jni::ByteBuffer::LocalRef dest =
      jni::ByteBuffer::New(writer->Data(), writer->Size());
  aSample->WriteToByteBuffer(dest);

  writer->mCrypto = ExtractCryptoSample(writer->Size(), aSample->CryptoInfo());
  return mrd;
}

void HLSTrackDemuxer::Reset() {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  mQueuedSample = nullptr;
}

void HLSTrackDemuxer::UpdateNextKeyFrameTime() {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  TimeUnit nextKeyFrameTime = mParent->GetNextKeyFrameTime();
  if (nextKeyFrameTime != mNextKeyframeTime.refOr(TimeUnit::FromInfinity())) {
    HLS_DEBUG("HLSTrackDemuxer", "Update mNextKeyframeTime to %" PRId64,
              nextKeyFrameTime.ToMicroseconds());
    mNextKeyframeTime = Some(nextKeyFrameTime);
  }
}

nsresult HLSTrackDemuxer::GetNextRandomAccessPoint(TimeUnit* aTime) {
  if (mNextKeyframeTime.isNothing()) {
    // There's no next key frame.
    *aTime = TimeUnit::FromInfinity();
  } else {
    *aTime = mNextKeyframeTime.value();
  }
  return NS_OK;
}

RefPtr<HLSTrackDemuxer::SkipAccessPointPromise>
HLSTrackDemuxer::SkipToNextRandomAccessPoint(const TimeUnit& aTimeThreshold) {
  return InvokeAsync(mParent->GetTaskQueue(), this, __func__,
                     &HLSTrackDemuxer::DoSkipToNextRandomAccessPoint,
                     aTimeThreshold);
}

RefPtr<HLSTrackDemuxer::SkipAccessPointPromise>
HLSTrackDemuxer::DoSkipToNextRandomAccessPoint(const TimeUnit& aTimeThreshold) {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  MOZ_ASSERT(mParent->OnTaskQueue());
  mQueuedSample = nullptr;
  uint32_t parsed = 0;
  bool found = false;
  MediaResult result = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
  do {
    mozilla::jni::ObjectArray::LocalRef demuxedSamples =
        mParent->mHLSDemuxerWrapper->GetSamples(mType, 1);
    nsTArray<jni::Object::LocalRef> sampleObjectArray(
        demuxedSamples->GetElements());
    if (sampleObjectArray.IsEmpty()) {
      result = NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA;
      break;
    }
    parsed++;
    java::GeckoHLSSample::LocalRef sample(std::move(sampleObjectArray[0]));
    if (sample->IsEOS()) {
      result = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
      break;
    }
    if (sample->IsKeyFrame()) {
      java::sdk::BufferInfo::LocalRef info = sample->Info();
      int64_t presentationTimeUs = 0;
      if (NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs)) &&
          TimeUnit::FromMicroseconds(presentationTimeUs) >= aTimeThreshold) {
        RefPtr<MediaRawData> rawData = ConvertToMediaRawData(sample);
        if (!rawData) {
          result = NS_ERROR_OUT_OF_MEMORY;
          break;
        }
        if (!rawData->HasValidTime()) {
          result = NS_ERROR_DOM_MEDIA_DEMUXER_ERR;
          break;
        }
        found = true;
        mQueuedSample = rawData;
        break;
      }
    }
  } while (true);

  if (!found) {
    return SkipAccessPointPromise::CreateAndReject(
        SkipFailureHolder(result, parsed), __func__);
  }
  return SkipAccessPointPromise::CreateAndResolve(parsed, __func__);
}

TimeIntervals HLSTrackDemuxer::GetBuffered() {
  MOZ_ASSERT(mParent, "Called after BreackCycle()");
  int64_t bufferedTime = mParent->mHLSDemuxerWrapper->GetBuffered();  // us
  return TimeIntervals(
      TimeInterval(TimeUnit(), TimeUnit::FromMicroseconds(bufferedTime)));
}

void HLSTrackDemuxer::BreakCycles() {
  RefPtr<HLSTrackDemuxer> self = this;
  nsCOMPtr<nsIRunnable> task = NS_NewRunnableFunction(
      "HLSTrackDemuxer::BreakCycles", [self]() { self->mParent = nullptr; });
  nsresult rv = mParent->GetTaskQueue()->Dispatch(task.forget());
  MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
  Unused << rv;
}

HLSTrackDemuxer::~HLSTrackDemuxer() {}

}  // namespace mozilla