TrackBuffersManager.cpp 94 KB

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