forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MediaCache.cpp
2346 lines (2067 loc) · 78 KB
/
MediaCache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ReentrantMonitor.h"
#include "mozilla/XPCOM.h"
#include "MediaCache.h"
#include "nsNetUtil.h"
#include "prio.h"
#include "nsContentUtils.h"
#include "nsThreadUtils.h"
#include "MediaResource.h"
#include "nsMathUtils.h"
#include "prlog.h"
#include "mozilla/Preferences.h"
#include "FileBlockCache.h"
#include "mozilla/Attributes.h"
#include "nsAnonymousTemporaryFile.h"
namespace mozilla {
#ifdef PR_LOGGING
PRLogModuleInfo* gMediaCacheLog;
#define LOG(type, msg) PR_LOG(gMediaCacheLog, type, msg)
#else
#define LOG(type, msg)
#endif
// Readahead blocks for non-seekable streams will be limited to this
// fraction of the cache space. We don't normally evict such blocks
// because replacing them requires a seek, but we need to make sure
// they don't monopolize the cache.
static const double NONSEEKABLE_READAHEAD_MAX = 0.5;
// Assume that any replaying or backward seeking will happen
// this far in the future (in seconds). This is a random guess/estimate
// penalty to account for the possibility that we might not replay at
// all.
static const uint32_t REPLAY_DELAY = 30;
// When looking for a reusable block, scan forward this many blocks
// from the desired "best" block location to look for free blocks,
// before we resort to scanning the whole cache. The idea is to try to
// store runs of stream blocks close-to-consecutively in the cache if we
// can.
static const uint32_t FREE_BLOCK_SCAN_LIMIT = 16;
#ifdef DEBUG
// Turn this on to do very expensive cache state validation
// #define DEBUG_VERIFY_CACHE
#endif
// There is at most one media cache (although that could quite easily be
// relaxed if we wanted to manage multiple caches with independent
// size limits).
static MediaCache* gMediaCache;
class MediaCacheFlusher MOZ_FINAL : public nsIObserver,
public nsSupportsWeakReference {
MediaCacheFlusher() {}
~MediaCacheFlusher();
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
static void Init();
};
static MediaCacheFlusher* gMediaCacheFlusher;
NS_IMPL_ISUPPORTS2(MediaCacheFlusher, nsIObserver, nsISupportsWeakReference)
MediaCacheFlusher::~MediaCacheFlusher()
{
gMediaCacheFlusher = nullptr;
}
void MediaCacheFlusher::Init()
{
if (gMediaCacheFlusher) {
return;
}
gMediaCacheFlusher = new MediaCacheFlusher();
NS_ADDREF(gMediaCacheFlusher);
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->AddObserver(gMediaCacheFlusher, "last-pb-context-exited", true);
}
}
class MediaCache {
public:
friend class MediaCacheStream::BlockList;
typedef MediaCacheStream::BlockList BlockList;
enum {
BLOCK_SIZE = MediaCacheStream::BLOCK_SIZE
};
MediaCache() : mNextResourceID(1),
mReentrantMonitor("MediaCache.mReentrantMonitor"),
mUpdateQueued(false)
#ifdef DEBUG
, mInUpdate(false)
#endif
{
MOZ_COUNT_CTOR(MediaCache);
}
~MediaCache() {
NS_ASSERTION(mStreams.IsEmpty(), "Stream(s) still open!");
Truncate();
NS_ASSERTION(mIndex.Length() == 0, "Blocks leaked?");
if (mFileCache) {
mFileCache->Close();
mFileCache = nullptr;
}
MOZ_COUNT_DTOR(MediaCache);
}
// Main thread only. Creates the backing cache file. If this fails,
// then the cache is still in a semi-valid state; mFD will be null,
// so all I/O on the cache file will fail.
nsresult Init();
// Shut down the global cache if it's no longer needed. We shut down
// the cache as soon as there are no streams. This means that during
// normal operation we are likely to start up the cache and shut it down
// many times, but that's OK since starting it up is cheap and
// shutting it down cleans things up and releases disk space.
static void MaybeShutdown();
// Brutally flush the cache contents. Main thread only.
static void Flush();
void FlushInternal();
// Cache-file access methods. These are the lowest-level cache methods.
// mReentrantMonitor must be held; these can be called on any thread.
// This can return partial reads.
nsresult ReadCacheFile(int64_t aOffset, void* aData, int32_t aLength,
int32_t* aBytes);
// This will fail if all aLength bytes are not read
nsresult ReadCacheFileAllBytes(int64_t aOffset, void* aData, int32_t aLength);
int64_t AllocateResourceID()
{
mReentrantMonitor.AssertCurrentThreadIn();
return mNextResourceID++;
}
// mReentrantMonitor must be held, called on main thread.
// These methods are used by the stream to set up and tear down streams,
// and to handle reads and writes.
// Add aStream to the list of streams.
void OpenStream(MediaCacheStream* aStream);
// Remove aStream from the list of streams.
void ReleaseStream(MediaCacheStream* aStream);
// Free all blocks belonging to aStream.
void ReleaseStreamBlocks(MediaCacheStream* aStream);
// Find a cache entry for this data, and write the data into it
void AllocateAndWriteBlock(MediaCacheStream* aStream, const void* aData,
MediaCacheStream::ReadMode aMode);
// mReentrantMonitor must be held; can be called on any thread
// Notify the cache that a seek has been requested. Some blocks may
// need to change their class between PLAYED_BLOCK and READAHEAD_BLOCK.
// This does not trigger channel seeks directly, the next Update()
// will do that if necessary. The caller will call QueueUpdate().
void NoteSeek(MediaCacheStream* aStream, int64_t aOldOffset);
// Notify the cache that a block has been read from. This is used
// to update last-use times. The block may not actually have a
// cache entry yet since Read can read data from a stream's
// in-memory mPartialBlockBuffer while the block is only partly full,
// and thus hasn't yet been committed to the cache. The caller will
// call QueueUpdate().
void NoteBlockUsage(MediaCacheStream* aStream, int32_t aBlockIndex,
MediaCacheStream::ReadMode aMode, TimeStamp aNow);
// Mark aStream as having the block, adding it as an owner.
void AddBlockOwnerAsReadahead(int32_t aBlockIndex, MediaCacheStream* aStream,
int32_t aStreamBlockIndex);
// This queues a call to Update() on the main thread.
void QueueUpdate();
// Updates the cache state asynchronously on the main thread:
// -- try to trim the cache back to its desired size, if necessary
// -- suspend channels that are going to read data that's lower priority
// than anything currently cached
// -- resume channels that are going to read data that's higher priority
// than something currently cached
// -- seek channels that need to seek to a new location
void Update();
#ifdef DEBUG_VERIFY_CACHE
// Verify invariants, especially block list invariants
void Verify();
#else
void Verify() {}
#endif
ReentrantMonitor& GetReentrantMonitor() { return mReentrantMonitor; }
/**
* An iterator that makes it easy to iterate through all streams that
* have a given resource ID and are not closed.
* Can be used on the main thread or while holding the media cache lock.
*/
class ResourceStreamIterator {
public:
ResourceStreamIterator(int64_t aResourceID) :
mResourceID(aResourceID), mNext(0) {}
MediaCacheStream* Next()
{
while (mNext < gMediaCache->mStreams.Length()) {
MediaCacheStream* stream = gMediaCache->mStreams[mNext];
++mNext;
if (stream->GetResourceID() == mResourceID && !stream->IsClosed())
return stream;
}
return nullptr;
}
private:
int64_t mResourceID;
uint32_t mNext;
};
protected:
// Find a free or reusable block and return its index. If there are no
// free blocks and no reusable blocks, add a new block to the cache
// and return it. Can return -1 on OOM.
int32_t FindBlockForIncomingData(TimeStamp aNow, MediaCacheStream* aStream);
// Find a reusable block --- a free block, if there is one, otherwise
// the reusable block with the latest predicted-next-use, or -1 if
// there aren't any freeable blocks. Only block indices less than
// aMaxSearchBlockIndex are considered. If aForStream is non-null,
// then aForStream and aForStreamBlock indicate what media data will
// be placed; FindReusableBlock will favour returning free blocks
// near other blocks for that point in the stream.
int32_t FindReusableBlock(TimeStamp aNow,
MediaCacheStream* aForStream,
int32_t aForStreamBlock,
int32_t aMaxSearchBlockIndex);
bool BlockIsReusable(int32_t aBlockIndex);
// Given a list of blocks sorted with the most reusable blocks at the
// end, find the last block whose stream is not pinned (if any)
// and whose cache entry index is less than aBlockIndexLimit
// and append it to aResult.
void AppendMostReusableBlock(BlockList* aBlockList,
nsTArray<uint32_t>* aResult,
int32_t aBlockIndexLimit);
enum BlockClass {
// block belongs to mMetadataBlockList because data has been consumed
// from it in "metadata mode" --- in particular blocks read during
// Ogg seeks go into this class. These blocks may have played data
// in them too.
METADATA_BLOCK,
// block belongs to mPlayedBlockList because its offset is
// less than the stream's current reader position
PLAYED_BLOCK,
// block belongs to the stream's mReadaheadBlockList because its
// offset is greater than or equal to the stream's current
// reader position
READAHEAD_BLOCK
};
struct BlockOwner {
BlockOwner() : mStream(nullptr), mClass(READAHEAD_BLOCK) {}
// The stream that owns this block, or null if the block is free.
MediaCacheStream* mStream;
// The block index in the stream. Valid only if mStream is non-null.
uint32_t mStreamBlock;
// Time at which this block was last used. Valid only if
// mClass is METADATA_BLOCK or PLAYED_BLOCK.
TimeStamp mLastUseTime;
BlockClass mClass;
};
struct Block {
// Free blocks have an empty mOwners array
nsTArray<BlockOwner> mOwners;
};
// Get the BlockList that the block should belong to given its
// current owner
BlockList* GetListForBlock(BlockOwner* aBlock);
// Get the BlockOwner for the given block index and owning stream
// (returns null if the stream does not own the block)
BlockOwner* GetBlockOwner(int32_t aBlockIndex, MediaCacheStream* aStream);
// Returns true iff the block is free
bool IsBlockFree(int32_t aBlockIndex)
{ return mIndex[aBlockIndex].mOwners.IsEmpty(); }
// Add the block to the free list and mark its streams as not having
// the block in cache
void FreeBlock(int32_t aBlock);
// Mark aStream as not having the block, removing it as an owner. If
// the block has no more owners it's added to the free list.
void RemoveBlockOwner(int32_t aBlockIndex, MediaCacheStream* aStream);
// Swap all metadata associated with the two blocks. The caller
// is responsible for swapping up any cache file state.
void SwapBlocks(int32_t aBlockIndex1, int32_t aBlockIndex2);
// Insert the block into the readahead block list for the stream
// at the right point in the list.
void InsertReadaheadBlock(BlockOwner* aBlockOwner, int32_t aBlockIndex);
// Guess the duration until block aBlock will be next used
TimeDuration PredictNextUse(TimeStamp aNow, int32_t aBlock);
// Guess the duration until the next incoming data on aStream will be used
TimeDuration PredictNextUseForIncomingData(MediaCacheStream* aStream);
// Truncate the file and index array if there are free blocks at the
// end
void Truncate();
// This member is main-thread only. It's used to allocate unique
// resource IDs to streams.
int64_t mNextResourceID;
// The monitor protects all the data members here. Also, off-main-thread
// readers that need to block will Wait() on this monitor. When new
// data becomes available in the cache, we NotifyAll() on this monitor.
ReentrantMonitor mReentrantMonitor;
// This is only written while on the main thread and the monitor is held.
// Thus, it can be safely read from the main thread or while holding the monitor.
nsTArray<MediaCacheStream*> mStreams;
// The Blocks describing the cache entries.
nsTArray<Block> mIndex;
// Writer which performs IO, asynchronously writing cache blocks.
nsRefPtr<FileBlockCache> mFileCache;
// The list of free blocks; they are not ordered.
BlockList mFreeBlocks;
// True if an event to run Update() has been queued but not processed
bool mUpdateQueued;
#ifdef DEBUG
bool mInUpdate;
#endif
};
NS_IMETHODIMP
MediaCacheFlusher::Observe(nsISupports *aSubject, char const *aTopic, PRUnichar const *aData)
{
if (strcmp(aTopic, "last-pb-context-exited") == 0) {
MediaCache::Flush();
}
return NS_OK;
}
void MediaCacheStream::BlockList::AddFirstBlock(int32_t aBlock)
{
NS_ASSERTION(!mEntries.GetEntry(aBlock), "Block already in list");
Entry* entry = mEntries.PutEntry(aBlock);
if (mFirstBlock < 0) {
entry->mNextBlock = entry->mPrevBlock = aBlock;
} else {
entry->mNextBlock = mFirstBlock;
entry->mPrevBlock = mEntries.GetEntry(mFirstBlock)->mPrevBlock;
mEntries.GetEntry(entry->mNextBlock)->mPrevBlock = aBlock;
mEntries.GetEntry(entry->mPrevBlock)->mNextBlock = aBlock;
}
mFirstBlock = aBlock;
++mCount;
}
void MediaCacheStream::BlockList::AddAfter(int32_t aBlock, int32_t aBefore)
{
NS_ASSERTION(!mEntries.GetEntry(aBlock), "Block already in list");
Entry* entry = mEntries.PutEntry(aBlock);
Entry* addAfter = mEntries.GetEntry(aBefore);
NS_ASSERTION(addAfter, "aBefore not in list");
entry->mNextBlock = addAfter->mNextBlock;
entry->mPrevBlock = aBefore;
mEntries.GetEntry(entry->mNextBlock)->mPrevBlock = aBlock;
mEntries.GetEntry(entry->mPrevBlock)->mNextBlock = aBlock;
++mCount;
}
void MediaCacheStream::BlockList::RemoveBlock(int32_t aBlock)
{
Entry* entry = mEntries.GetEntry(aBlock);
NS_ASSERTION(entry, "Block not in list");
if (entry->mNextBlock == aBlock) {
NS_ASSERTION(entry->mPrevBlock == aBlock, "Linked list inconsistency");
NS_ASSERTION(mFirstBlock == aBlock, "Linked list inconsistency");
mFirstBlock = -1;
} else {
if (mFirstBlock == aBlock) {
mFirstBlock = entry->mNextBlock;
}
mEntries.GetEntry(entry->mNextBlock)->mPrevBlock = entry->mPrevBlock;
mEntries.GetEntry(entry->mPrevBlock)->mNextBlock = entry->mNextBlock;
}
mEntries.RemoveEntry(aBlock);
--mCount;
}
int32_t MediaCacheStream::BlockList::GetLastBlock() const
{
if (mFirstBlock < 0)
return -1;
return mEntries.GetEntry(mFirstBlock)->mPrevBlock;
}
int32_t MediaCacheStream::BlockList::GetNextBlock(int32_t aBlock) const
{
int32_t block = mEntries.GetEntry(aBlock)->mNextBlock;
if (block == mFirstBlock)
return -1;
return block;
}
int32_t MediaCacheStream::BlockList::GetPrevBlock(int32_t aBlock) const
{
if (aBlock == mFirstBlock)
return -1;
return mEntries.GetEntry(aBlock)->mPrevBlock;
}
#ifdef DEBUG
void MediaCacheStream::BlockList::Verify()
{
int32_t count = 0;
if (mFirstBlock >= 0) {
int32_t block = mFirstBlock;
do {
Entry* entry = mEntries.GetEntry(block);
NS_ASSERTION(mEntries.GetEntry(entry->mNextBlock)->mPrevBlock == block,
"Bad prev link");
NS_ASSERTION(mEntries.GetEntry(entry->mPrevBlock)->mNextBlock == block,
"Bad next link");
block = entry->mNextBlock;
++count;
} while (block != mFirstBlock);
}
NS_ASSERTION(count == mCount, "Bad count");
}
#endif
static void UpdateSwappedBlockIndex(int32_t* aBlockIndex,
int32_t aBlock1Index, int32_t aBlock2Index)
{
int32_t index = *aBlockIndex;
if (index == aBlock1Index) {
*aBlockIndex = aBlock2Index;
} else if (index == aBlock2Index) {
*aBlockIndex = aBlock1Index;
}
}
void
MediaCacheStream::BlockList::NotifyBlockSwapped(int32_t aBlockIndex1,
int32_t aBlockIndex2)
{
Entry* e1 = mEntries.GetEntry(aBlockIndex1);
Entry* e2 = mEntries.GetEntry(aBlockIndex2);
int32_t e1Prev = -1, e1Next = -1, e2Prev = -1, e2Next = -1;
// Fix mFirstBlock
UpdateSwappedBlockIndex(&mFirstBlock, aBlockIndex1, aBlockIndex2);
// Fix mNextBlock/mPrevBlock links. First capture previous/next links
// so we don't get confused due to aliasing.
if (e1) {
e1Prev = e1->mPrevBlock;
e1Next = e1->mNextBlock;
}
if (e2) {
e2Prev = e2->mPrevBlock;
e2Next = e2->mNextBlock;
}
// Update the entries.
if (e1) {
mEntries.GetEntry(e1Prev)->mNextBlock = aBlockIndex2;
mEntries.GetEntry(e1Next)->mPrevBlock = aBlockIndex2;
}
if (e2) {
mEntries.GetEntry(e2Prev)->mNextBlock = aBlockIndex1;
mEntries.GetEntry(e2Next)->mPrevBlock = aBlockIndex1;
}
// Fix hashtable keys. First remove stale entries.
if (e1) {
e1Prev = e1->mPrevBlock;
e1Next = e1->mNextBlock;
mEntries.RemoveEntry(aBlockIndex1);
// Refresh pointer after hashtable mutation.
e2 = mEntries.GetEntry(aBlockIndex2);
}
if (e2) {
e2Prev = e2->mPrevBlock;
e2Next = e2->mNextBlock;
mEntries.RemoveEntry(aBlockIndex2);
}
// Put new entries back.
if (e1) {
e1 = mEntries.PutEntry(aBlockIndex2);
e1->mNextBlock = e1Next;
e1->mPrevBlock = e1Prev;
}
if (e2) {
e2 = mEntries.PutEntry(aBlockIndex1);
e2->mNextBlock = e2Next;
e2->mPrevBlock = e2Prev;
}
}
nsresult
MediaCache::Init()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
NS_ASSERTION(!mFileCache, "Cache file already open?");
PRFileDesc* fileDesc = nullptr;
nsresult rv = NS_OpenAnonymousTemporaryFile(&fileDesc);
NS_ENSURE_SUCCESS(rv,rv);
mFileCache = new FileBlockCache();
rv = mFileCache->Open(fileDesc);
NS_ENSURE_SUCCESS(rv,rv);
#ifdef PR_LOGGING
if (!gMediaCacheLog) {
gMediaCacheLog = PR_NewLogModule("MediaCache");
}
#endif
MediaCacheFlusher::Init();
return NS_OK;
}
void
MediaCache::Flush()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
if (!gMediaCache)
return;
gMediaCache->FlushInternal();
}
void
MediaCache::FlushInternal()
{
ReentrantMonitorAutoEnter mon(mReentrantMonitor);
for (uint32_t blockIndex = 0; blockIndex < mIndex.Length(); ++blockIndex) {
FreeBlock(blockIndex);
}
// Truncate file, close it, and reopen
Truncate();
NS_ASSERTION(mIndex.Length() == 0, "Blocks leaked?");
if (mFileCache) {
mFileCache->Close();
mFileCache = nullptr;
}
Init();
}
void
MediaCache::MaybeShutdown()
{
NS_ASSERTION(NS_IsMainThread(),
"MediaCache::MaybeShutdown called on non-main thread");
if (!gMediaCache->mStreams.IsEmpty()) {
// Don't shut down yet, streams are still alive
return;
}
// Since we're on the main thread, no-one is going to add a new stream
// while we shut down.
// This function is static so we don't have to delete 'this'.
delete gMediaCache;
gMediaCache = nullptr;
NS_IF_RELEASE(gMediaCacheFlusher);
}
static void
InitMediaCache()
{
if (gMediaCache)
return;
gMediaCache = new MediaCache();
if (!gMediaCache)
return;
nsresult rv = gMediaCache->Init();
if (NS_FAILED(rv)) {
delete gMediaCache;
gMediaCache = nullptr;
}
}
nsresult
MediaCache::ReadCacheFile(int64_t aOffset, void* aData, int32_t aLength,
int32_t* aBytes)
{
mReentrantMonitor.AssertCurrentThreadIn();
if (!mFileCache)
return NS_ERROR_FAILURE;
return mFileCache->Read(aOffset, reinterpret_cast<uint8_t*>(aData), aLength, aBytes);
}
nsresult
MediaCache::ReadCacheFileAllBytes(int64_t aOffset, void* aData, int32_t aLength)
{
mReentrantMonitor.AssertCurrentThreadIn();
int64_t offset = aOffset;
int32_t count = aLength;
// Cast to char* so we can do byte-wise pointer arithmetic
char* data = static_cast<char*>(aData);
while (count > 0) {
int32_t bytes;
nsresult rv = ReadCacheFile(offset, data, count, &bytes);
if (NS_FAILED(rv))
return rv;
if (bytes == 0)
return NS_ERROR_FAILURE;
count -= bytes;
data += bytes;
offset += bytes;
}
return NS_OK;
}
static int32_t GetMaxBlocks()
{
// We look up the cache size every time. This means dynamic changes
// to the pref are applied.
// Cache size is in KB
int32_t cacheSize = Preferences::GetInt("media.cache_size", 500*1024);
int64_t maxBlocks = static_cast<int64_t>(cacheSize)*1024/MediaCache::BLOCK_SIZE;
maxBlocks = NS_MAX<int64_t>(maxBlocks, 1);
return int32_t(NS_MIN<int64_t>(maxBlocks, INT32_MAX));
}
int32_t
MediaCache::FindBlockForIncomingData(TimeStamp aNow,
MediaCacheStream* aStream)
{
mReentrantMonitor.AssertCurrentThreadIn();
int32_t blockIndex = FindReusableBlock(aNow, aStream,
aStream->mChannelOffset/BLOCK_SIZE, INT32_MAX);
if (blockIndex < 0 || !IsBlockFree(blockIndex)) {
// The block returned is already allocated.
// Don't reuse it if a) there's room to expand the cache or
// b) the data we're going to store in the free block is not higher
// priority than the data already stored in the free block.
// The latter can lead us to go over the cache limit a bit.
if ((mIndex.Length() < uint32_t(GetMaxBlocks()) || blockIndex < 0 ||
PredictNextUseForIncomingData(aStream) >= PredictNextUse(aNow, blockIndex))) {
blockIndex = mIndex.Length();
if (!mIndex.AppendElement())
return -1;
mFreeBlocks.AddFirstBlock(blockIndex);
return blockIndex;
}
}
return blockIndex;
}
bool
MediaCache::BlockIsReusable(int32_t aBlockIndex)
{
Block* block = &mIndex[aBlockIndex];
for (uint32_t i = 0; i < block->mOwners.Length(); ++i) {
MediaCacheStream* stream = block->mOwners[i].mStream;
if (stream->mPinCount > 0 ||
stream->mStreamOffset/BLOCK_SIZE == block->mOwners[i].mStreamBlock) {
return false;
}
}
return true;
}
void
MediaCache::AppendMostReusableBlock(BlockList* aBlockList,
nsTArray<uint32_t>* aResult,
int32_t aBlockIndexLimit)
{
mReentrantMonitor.AssertCurrentThreadIn();
int32_t blockIndex = aBlockList->GetLastBlock();
if (blockIndex < 0)
return;
do {
// Don't consider blocks for pinned streams, or blocks that are
// beyond the specified limit, or a block that contains a stream's
// current read position (such a block contains both played data
// and readahead data)
if (blockIndex < aBlockIndexLimit && BlockIsReusable(blockIndex)) {
aResult->AppendElement(blockIndex);
return;
}
blockIndex = aBlockList->GetPrevBlock(blockIndex);
} while (blockIndex >= 0);
}
int32_t
MediaCache::FindReusableBlock(TimeStamp aNow,
MediaCacheStream* aForStream,
int32_t aForStreamBlock,
int32_t aMaxSearchBlockIndex)
{
mReentrantMonitor.AssertCurrentThreadIn();
uint32_t length = NS_MIN(uint32_t(aMaxSearchBlockIndex), mIndex.Length());
if (aForStream && aForStreamBlock > 0 &&
uint32_t(aForStreamBlock) <= aForStream->mBlocks.Length()) {
int32_t prevCacheBlock = aForStream->mBlocks[aForStreamBlock - 1];
if (prevCacheBlock >= 0) {
uint32_t freeBlockScanEnd =
NS_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
for (uint32_t i = prevCacheBlock; i < freeBlockScanEnd; ++i) {
if (IsBlockFree(i))
return i;
}
}
}
if (!mFreeBlocks.IsEmpty()) {
int32_t blockIndex = mFreeBlocks.GetFirstBlock();
do {
if (blockIndex < aMaxSearchBlockIndex)
return blockIndex;
blockIndex = mFreeBlocks.GetNextBlock(blockIndex);
} while (blockIndex >= 0);
}
// Build a list of the blocks we should consider for the "latest
// predicted time of next use". We can exploit the fact that the block
// linked lists are ordered by increasing time of next use. This is
// actually the whole point of having the linked lists.
nsAutoTArray<uint32_t,8> candidates;
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
MediaCacheStream* stream = mStreams[i];
if (stream->mPinCount > 0) {
// No point in even looking at this stream's blocks
continue;
}
AppendMostReusableBlock(&stream->mMetadataBlocks, &candidates, length);
AppendMostReusableBlock(&stream->mPlayedBlocks, &candidates, length);
// Don't consider readahead blocks in non-seekable streams. If we
// remove the block we won't be able to seek back to read it later.
if (stream->mIsTransportSeekable) {
AppendMostReusableBlock(&stream->mReadaheadBlocks, &candidates, length);
}
}
TimeDuration latestUse;
int32_t latestUseBlock = -1;
for (uint32_t i = 0; i < candidates.Length(); ++i) {
TimeDuration nextUse = PredictNextUse(aNow, candidates[i]);
if (nextUse > latestUse) {
latestUse = nextUse;
latestUseBlock = candidates[i];
}
}
return latestUseBlock;
}
MediaCache::BlockList*
MediaCache::GetListForBlock(BlockOwner* aBlock)
{
switch (aBlock->mClass) {
case METADATA_BLOCK:
NS_ASSERTION(aBlock->mStream, "Metadata block has no stream?");
return &aBlock->mStream->mMetadataBlocks;
case PLAYED_BLOCK:
NS_ASSERTION(aBlock->mStream, "Metadata block has no stream?");
return &aBlock->mStream->mPlayedBlocks;
case READAHEAD_BLOCK:
NS_ASSERTION(aBlock->mStream, "Readahead block has no stream?");
return &aBlock->mStream->mReadaheadBlocks;
default:
NS_ERROR("Invalid block class");
return nullptr;
}
}
MediaCache::BlockOwner*
MediaCache::GetBlockOwner(int32_t aBlockIndex, MediaCacheStream* aStream)
{
Block* block = &mIndex[aBlockIndex];
for (uint32_t i = 0; i < block->mOwners.Length(); ++i) {
if (block->mOwners[i].mStream == aStream)
return &block->mOwners[i];
}
return nullptr;
}
void
MediaCache::SwapBlocks(int32_t aBlockIndex1, int32_t aBlockIndex2)
{
mReentrantMonitor.AssertCurrentThreadIn();
Block* block1 = &mIndex[aBlockIndex1];
Block* block2 = &mIndex[aBlockIndex2];
block1->mOwners.SwapElements(block2->mOwners);
// Now all references to block1 have to be replaced with block2 and
// vice versa.
// First update stream references to blocks via mBlocks.
const Block* blocks[] = { block1, block2 };
int32_t blockIndices[] = { aBlockIndex1, aBlockIndex2 };
for (int32_t i = 0; i < 2; ++i) {
for (uint32_t j = 0; j < blocks[i]->mOwners.Length(); ++j) {
const BlockOwner* b = &blocks[i]->mOwners[j];
b->mStream->mBlocks[b->mStreamBlock] = blockIndices[i];
}
}
// Now update references to blocks in block lists.
mFreeBlocks.NotifyBlockSwapped(aBlockIndex1, aBlockIndex2);
nsTHashtable<nsPtrHashKey<MediaCacheStream> > visitedStreams;
visitedStreams.Init();
for (int32_t i = 0; i < 2; ++i) {
for (uint32_t j = 0; j < blocks[i]->mOwners.Length(); ++j) {
MediaCacheStream* stream = blocks[i]->mOwners[j].mStream;
// Make sure that we don't update the same stream twice --- that
// would result in swapping the block references back again!
if (visitedStreams.GetEntry(stream))
continue;
visitedStreams.PutEntry(stream);
stream->mReadaheadBlocks.NotifyBlockSwapped(aBlockIndex1, aBlockIndex2);
stream->mPlayedBlocks.NotifyBlockSwapped(aBlockIndex1, aBlockIndex2);
stream->mMetadataBlocks.NotifyBlockSwapped(aBlockIndex1, aBlockIndex2);
}
}
Verify();
}
void
MediaCache::RemoveBlockOwner(int32_t aBlockIndex, MediaCacheStream* aStream)
{
Block* block = &mIndex[aBlockIndex];
for (uint32_t i = 0; i < block->mOwners.Length(); ++i) {
BlockOwner* bo = &block->mOwners[i];
if (bo->mStream == aStream) {
GetListForBlock(bo)->RemoveBlock(aBlockIndex);
bo->mStream->mBlocks[bo->mStreamBlock] = -1;
block->mOwners.RemoveElementAt(i);
if (block->mOwners.IsEmpty()) {
mFreeBlocks.AddFirstBlock(aBlockIndex);
}
return;
}
}
}
void
MediaCache::AddBlockOwnerAsReadahead(int32_t aBlockIndex,
MediaCacheStream* aStream,
int32_t aStreamBlockIndex)
{
Block* block = &mIndex[aBlockIndex];
if (block->mOwners.IsEmpty()) {
mFreeBlocks.RemoveBlock(aBlockIndex);
}
BlockOwner* bo = block->mOwners.AppendElement();
bo->mStream = aStream;
bo->mStreamBlock = aStreamBlockIndex;
aStream->mBlocks[aStreamBlockIndex] = aBlockIndex;
bo->mClass = READAHEAD_BLOCK;
InsertReadaheadBlock(bo, aBlockIndex);
}
void
MediaCache::FreeBlock(int32_t aBlock)
{
mReentrantMonitor.AssertCurrentThreadIn();
Block* block = &mIndex[aBlock];
if (block->mOwners.IsEmpty()) {
// already free
return;
}
LOG(PR_LOG_DEBUG, ("Released block %d", aBlock));
for (uint32_t i = 0; i < block->mOwners.Length(); ++i) {
BlockOwner* bo = &block->mOwners[i];
GetListForBlock(bo)->RemoveBlock(aBlock);
bo->mStream->mBlocks[bo->mStreamBlock] = -1;
}
block->mOwners.Clear();
mFreeBlocks.AddFirstBlock(aBlock);
Verify();
}
TimeDuration
MediaCache::PredictNextUse(TimeStamp aNow, int32_t aBlock)
{
mReentrantMonitor.AssertCurrentThreadIn();
NS_ASSERTION(!IsBlockFree(aBlock), "aBlock is free");
Block* block = &mIndex[aBlock];
// Blocks can be belong to multiple streams. The predicted next use
// time is the earliest time predicted by any of the streams.
TimeDuration result;
for (uint32_t i = 0; i < block->mOwners.Length(); ++i) {
BlockOwner* bo = &block->mOwners[i];
TimeDuration prediction;
switch (bo->mClass) {
case METADATA_BLOCK:
// This block should be managed in LRU mode. For metadata we predict
// that the time until the next use is the time since the last use.
prediction = aNow - bo->mLastUseTime;
break;
case PLAYED_BLOCK:
// This block should be managed in LRU mode, and we should impose
// a "replay delay" to reflect the likelihood of replay happening
NS_ASSERTION(static_cast<int64_t>(bo->mStreamBlock)*BLOCK_SIZE <
bo->mStream->mStreamOffset,
"Played block after the current stream position?");
prediction = aNow - bo->mLastUseTime +
TimeDuration::FromSeconds(REPLAY_DELAY);
break;
case READAHEAD_BLOCK: {
int64_t bytesAhead =
static_cast<int64_t>(bo->mStreamBlock)*BLOCK_SIZE - bo->mStream->mStreamOffset;
NS_ASSERTION(bytesAhead >= 0,
"Readahead block before the current stream position?");
int64_t millisecondsAhead =
bytesAhead*1000/bo->mStream->mPlaybackBytesPerSecond;
prediction = TimeDuration::FromMilliseconds(
NS_MIN<int64_t>(millisecondsAhead, INT32_MAX));
break;
}
default:
NS_ERROR("Invalid class for predicting next use");
return TimeDuration(0);
}
if (i == 0 || prediction < result) {
result = prediction;
}
}
return result;
}
TimeDuration
MediaCache::PredictNextUseForIncomingData(MediaCacheStream* aStream)
{
mReentrantMonitor.AssertCurrentThreadIn();
int64_t bytesAhead = aStream->mChannelOffset - aStream->mStreamOffset;
if (bytesAhead <= -BLOCK_SIZE) {
// Hmm, no idea when data behind us will be used. Guess 24 hours.
return TimeDuration::FromSeconds(24*60*60);
}
if (bytesAhead <= 0)
return TimeDuration(0);
int64_t millisecondsAhead = bytesAhead*1000/aStream->mPlaybackBytesPerSecond;
return TimeDuration::FromMilliseconds(
NS_MIN<int64_t>(millisecondsAhead, INT32_MAX));
}
enum StreamAction { NONE, SEEK, SEEK_AND_RESUME, RESUME, SUSPEND };
void
MediaCache::Update()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
// The action to use for each stream. We store these so we can make
// decisions while holding the cache lock but implement those decisions
// without holding the cache lock, since we need to call out to
// stream, decoder and element code.
nsAutoTArray<StreamAction,10> actions;
{
ReentrantMonitorAutoEnter mon(mReentrantMonitor);
mUpdateQueued = false;
#ifdef DEBUG
mInUpdate = true;
#endif