forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MediaResource.cpp
1694 lines (1462 loc) · 52.4 KB
/
MediaResource.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/DebugOnly.h"
#include "MediaResource.h"
#include "RtspMediaResource.h"
#include "mozilla/Mutex.h"
#include "nsDebug.h"
#include "MediaDecoder.h"
#include "nsNetUtil.h"
#include "nsThreadUtils.h"
#include "nsIFile.h"
#include "nsIFileChannel.h"
#include "nsIHttpChannel.h"
#include "nsISeekableStream.h"
#include "nsIInputStream.h"
#include "nsIRequestObserver.h"
#include "nsIStreamListener.h"
#include "nsIScriptSecurityManager.h"
#include "nsCORSListenerProxy.h"
#include "mozilla/dom/HTMLMediaElement.h"
#include "nsError.h"
#include "nsICachingChannel.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsContentUtils.h"
#include "nsHostObjectProtocolHandler.h"
#include <algorithm>
#include "nsProxyRelease.h"
#include "nsIContentPolicy.h"
#ifdef PR_LOGGING
PRLogModuleInfo* gMediaResourceLog;
#define RESOURCE_LOG(msg, ...) PR_LOG(gMediaResourceLog, PR_LOG_DEBUG, \
(msg, ##__VA_ARGS__))
// Debug logging macro with object pointer and class name.
#define CMLOG(msg, ...) \
RESOURCE_LOG("%p [ChannelMediaResource]: " msg, this, ##__VA_ARGS__)
#else
#define RESOURCE_LOG(msg, ...)
#define CMLOG(msg, ...)
#endif
static const uint32_t HTTP_OK_CODE = 200;
static const uint32_t HTTP_PARTIAL_RESPONSE_CODE = 206;
namespace mozilla {
void
MediaResource::Destroy()
{
// If we're being destroyed on a non-main thread, we AddRef again and
// use a proxy to release the MediaResource on the main thread, where
// the MediaResource is deleted. This ensures we only delete the
// MediaResource on the main thread.
if (!NS_IsMainThread()) {
nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
NS_ENSURE_TRUE_VOID(mainThread);
nsRefPtr<MediaResource> doomed(this);
if (NS_FAILED(NS_ProxyRelease(mainThread, doomed, true))) {
NS_WARNING("Failed to proxy release to main thread!");
}
} else {
delete this;
}
}
NS_IMPL_ADDREF(MediaResource)
NS_IMPL_RELEASE_WITH_DESTROY(MediaResource, Destroy())
NS_IMPL_QUERY_INTERFACE0(MediaResource)
ChannelMediaResource::ChannelMediaResource(MediaDecoder* aDecoder,
nsIChannel* aChannel,
nsIURI* aURI,
const nsACString& aContentType)
: BaseMediaResource(aDecoder, aChannel, aURI, aContentType),
mOffset(0), mSuspendCount(0),
mReopenOnError(false), mIgnoreClose(false),
mCacheStream(this),
mLock("ChannelMediaResource.mLock"),
mIgnoreResume(false),
mIsTransportSeekable(true)
{
#ifdef PR_LOGGING
if (!gMediaResourceLog) {
gMediaResourceLog = PR_NewLogModule("MediaResource");
}
#endif
}
ChannelMediaResource::~ChannelMediaResource()
{
if (mListener) {
// Kill its reference to us since we're going away
mListener->Revoke();
}
}
// ChannelMediaResource::Listener just observes the channel and
// forwards notifications to the ChannelMediaResource. We use multiple
// listener objects so that when we open a new stream for a seek we can
// disconnect the old listener from the ChannelMediaResource and hook up
// a new listener, so notifications from the old channel are discarded
// and don't confuse us.
NS_IMPL_ISUPPORTS(ChannelMediaResource::Listener,
nsIRequestObserver, nsIStreamListener, nsIChannelEventSink,
nsIInterfaceRequestor)
nsresult
ChannelMediaResource::Listener::OnStartRequest(nsIRequest* aRequest,
nsISupports* aContext)
{
if (!mResource)
return NS_OK;
return mResource->OnStartRequest(aRequest);
}
nsresult
ChannelMediaResource::Listener::OnStopRequest(nsIRequest* aRequest,
nsISupports* aContext,
nsresult aStatus)
{
if (!mResource)
return NS_OK;
return mResource->OnStopRequest(aRequest, aStatus);
}
nsresult
ChannelMediaResource::Listener::OnDataAvailable(nsIRequest* aRequest,
nsISupports* aContext,
nsIInputStream* aStream,
uint64_t aOffset,
uint32_t aCount)
{
if (!mResource)
return NS_OK;
return mResource->OnDataAvailable(aRequest, aStream, aCount);
}
nsresult
ChannelMediaResource::Listener::AsyncOnChannelRedirect(nsIChannel* aOldChannel,
nsIChannel* aNewChannel,
uint32_t aFlags,
nsIAsyncVerifyRedirectCallback* cb)
{
nsresult rv = NS_OK;
if (mResource)
rv = mResource->OnChannelRedirect(aOldChannel, aNewChannel, aFlags);
if (NS_FAILED(rv))
return rv;
cb->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
nsresult
ChannelMediaResource::Listener::GetInterface(const nsIID & aIID, void **aResult)
{
return QueryInterface(aIID, aResult);
}
nsresult
ChannelMediaResource::OnStartRequest(nsIRequest* aRequest)
{
NS_ASSERTION(mChannel.get() == aRequest, "Wrong channel!");
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
NS_ENSURE_TRUE(owner, NS_ERROR_FAILURE);
dom::HTMLMediaElement* element = owner->GetMediaElement();
NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
nsresult status;
nsresult rv = aRequest->GetStatus(&status);
NS_ENSURE_SUCCESS(rv, rv);
if (status == NS_BINDING_ABORTED) {
// Request was aborted before we had a chance to receive any data, or
// even an OnStartRequest(). Close the channel. This is important, as
// we don't want to mess up our state, as if we're cloned that would
// cause the clone to copy incorrect metadata (like whether we're
// infinite for example).
CloseChannel();
return status;
}
if (element->ShouldCheckAllowOrigin()) {
// If the request was cancelled by nsCORSListenerProxy due to failing
// the CORS security check, send an error through to the media element.
if (status == NS_ERROR_DOM_BAD_URI) {
mDecoder->NetworkError();
return NS_ERROR_DOM_BAD_URI;
}
}
nsCOMPtr<nsIHttpChannel> hc = do_QueryInterface(aRequest);
bool seekable = false;
if (hc) {
uint32_t responseStatus = 0;
hc->GetResponseStatus(&responseStatus);
bool succeeded = false;
hc->GetRequestSucceeded(&succeeded);
if (!succeeded && NS_SUCCEEDED(status)) {
// HTTP-level error (e.g. 4xx); treat this as a fatal network-level error.
// We might get this on a seek.
// (Note that lower-level errors indicated by NS_FAILED(status) are
// handled in OnStopRequest.)
// A 416 error should treated as EOF here... it's possible
// that we don't get Content-Length, we read N bytes, then we
// suspend and resume, the resume reopens the channel and we seek to
// offset N, but there are no more bytes, so we get a 416
// "Requested Range Not Satisfiable".
if (responseStatus == HTTP_REQUESTED_RANGE_NOT_SATISFIABLE_CODE) {
// OnStopRequest will not be fired, so we need to do some of its
// work here.
mCacheStream.NotifyDataEnded(status);
} else {
mDecoder->NetworkError();
}
// This disconnects our listener so we don't get any more data. We
// certainly don't want an error page to end up in our cache!
CloseChannel();
return NS_OK;
}
nsAutoCString ranges;
hc->GetResponseHeader(NS_LITERAL_CSTRING("Accept-Ranges"),
ranges);
bool acceptsRanges = ranges.EqualsLiteral("bytes");
// True if this channel will not return an unbounded amount of data
bool dataIsBounded = false;
int64_t contentLength = -1;
hc->GetContentLength(&contentLength);
if (contentLength >= 0 && responseStatus == HTTP_OK_CODE) {
// "OK" status means Content-Length is for the whole resource.
// Since that's bounded, we know we have a finite-length resource.
dataIsBounded = true;
}
if (mOffset == 0) {
// Look for duration headers from known Ogg content systems.
// In the case of multiple options for obtaining the duration
// the order of precedence is:
// 1) The Media resource metadata if possible (done by the decoder itself).
// 2) Content-Duration message header.
// 3) X-AMZ-Meta-Content-Duration.
// 4) X-Content-Duration.
// 5) Perform a seek in the decoder to find the value.
nsAutoCString durationText;
nsresult ec = NS_OK;
rv = hc->GetResponseHeader(NS_LITERAL_CSTRING("Content-Duration"), durationText);
if (NS_FAILED(rv)) {
rv = hc->GetResponseHeader(NS_LITERAL_CSTRING("X-AMZ-Meta-Content-Duration"), durationText);
}
if (NS_FAILED(rv)) {
rv = hc->GetResponseHeader(NS_LITERAL_CSTRING("X-Content-Duration"), durationText);
}
// If there is a Content-Duration header with a valid value, record
// the duration.
if (NS_SUCCEEDED(rv)) {
double duration = durationText.ToDouble(&ec);
if (ec == NS_OK && duration >= 0) {
mDecoder->SetDuration(duration);
// We know the resource must be bounded.
dataIsBounded = true;
}
}
}
// Assume Range requests have a bounded upper limit unless the
// Content-Range header tells us otherwise.
bool boundedSeekLimit = true;
// Check response code for byte-range requests (seeking, chunk requests).
if (!mByteRange.IsNull() && (responseStatus == HTTP_PARTIAL_RESPONSE_CODE)) {
// Parse Content-Range header.
int64_t rangeStart = 0;
int64_t rangeEnd = 0;
int64_t rangeTotal = 0;
rv = ParseContentRangeHeader(hc, rangeStart, rangeEnd, rangeTotal);
if (NS_FAILED(rv)) {
// Content-Range header text should be parse-able.
CMLOG("Error processing \'Content-Range' for "
"HTTP_PARTIAL_RESPONSE_CODE: rv[%x] channel[%p] decoder[%p]",
rv, hc.get(), mDecoder);
mDecoder->NetworkError();
CloseChannel();
return NS_OK;
}
// Give some warnings if the ranges are unexpected.
// XXX These could be error conditions.
NS_WARN_IF_FALSE(mByteRange.mStart == rangeStart,
"response range start does not match request");
NS_WARN_IF_FALSE(mOffset == rangeStart,
"response range start does not match current offset");
NS_WARN_IF_FALSE(mByteRange.mEnd == rangeEnd,
"response range end does not match request");
// Notify media cache about the length and start offset of data received.
// Note: If aRangeTotal == -1, then the total bytes is unknown at this stage.
// For now, tell the decoder that the stream is infinite.
if (rangeTotal == -1) {
boundedSeekLimit = false;
} else {
mCacheStream.NotifyDataLength(rangeTotal);
}
mCacheStream.NotifyDataStarted(rangeStart);
mOffset = rangeStart;
// We received 'Content-Range', so the server accepts range requests.
acceptsRanges = true;
} else if (((mOffset > 0) || !mByteRange.IsNull())
&& (responseStatus == HTTP_OK_CODE)) {
// If we get an OK response but we were seeking, or requesting a byte
// range, then we have to assume that seeking doesn't work. We also need
// to tell the cache that it's getting data for the start of the stream.
mCacheStream.NotifyDataStarted(0);
mOffset = 0;
// The server claimed it supported range requests. It lied.
acceptsRanges = false;
} else if (mOffset == 0 &&
(responseStatus == HTTP_OK_CODE ||
responseStatus == HTTP_PARTIAL_RESPONSE_CODE)) {
if (contentLength >= 0) {
mCacheStream.NotifyDataLength(contentLength);
}
}
// XXX we probably should examine the Content-Range header in case
// the server gave us a range which is not quite what we asked for
// If we get an HTTP_OK_CODE response to our byte range request,
// and the server isn't sending Accept-Ranges:bytes then we don't
// support seeking.
seekable =
responseStatus == HTTP_PARTIAL_RESPONSE_CODE || acceptsRanges;
if (seekable && boundedSeekLimit) {
// If range requests are supported, and we did not see an unbounded
// upper range limit, we assume the resource is bounded.
dataIsBounded = true;
}
mDecoder->SetInfinite(!dataIsBounded);
}
mCacheStream.SetTransportSeekable(seekable);
{
MutexAutoLock lock(mLock);
mIsTransportSeekable = seekable;
mChannelStatistics->Start();
}
mReopenOnError = false;
mIgnoreClose = false;
if (mSuspendCount > 0) {
// Re-suspend the channel if it needs to be suspended
// No need to call PossiblySuspend here since the channel is
// definitely in the right state for us in OnStartRequest.
mChannel->Suspend();
mIgnoreResume = false;
}
// Fires an initial progress event.
owner->DownloadProgressed();
return NS_OK;
}
bool
ChannelMediaResource::IsTransportSeekable()
{
MutexAutoLock lock(mLock);
return mIsTransportSeekable;
}
nsresult
ChannelMediaResource::ParseContentRangeHeader(nsIHttpChannel * aHttpChan,
int64_t& aRangeStart,
int64_t& aRangeEnd,
int64_t& aRangeTotal)
{
NS_ENSURE_ARG(aHttpChan);
nsAutoCString rangeStr;
nsresult rv = aHttpChan->GetResponseHeader(NS_LITERAL_CSTRING("Content-Range"),
rangeStr);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_FALSE(rangeStr.IsEmpty(), NS_ERROR_ILLEGAL_VALUE);
// Parse the range header: e.g. Content-Range: bytes 7000-7999/8000.
int32_t spacePos = rangeStr.Find(NS_LITERAL_CSTRING(" "));
int32_t dashPos = rangeStr.Find(NS_LITERAL_CSTRING("-"), true, spacePos);
int32_t slashPos = rangeStr.Find(NS_LITERAL_CSTRING("/"), true, dashPos);
nsAutoCString aRangeStartText;
rangeStr.Mid(aRangeStartText, spacePos+1, dashPos-(spacePos+1));
aRangeStart = aRangeStartText.ToInteger64(&rv);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(0 <= aRangeStart, NS_ERROR_ILLEGAL_VALUE);
nsAutoCString aRangeEndText;
rangeStr.Mid(aRangeEndText, dashPos+1, slashPos-(dashPos+1));
aRangeEnd = aRangeEndText.ToInteger64(&rv);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(aRangeStart < aRangeEnd, NS_ERROR_ILLEGAL_VALUE);
nsAutoCString aRangeTotalText;
rangeStr.Right(aRangeTotalText, rangeStr.Length()-(slashPos+1));
if (aRangeTotalText[0] == '*') {
aRangeTotal = -1;
} else {
aRangeTotal = aRangeTotalText.ToInteger64(&rv);
NS_ENSURE_TRUE(aRangeEnd < aRangeTotal, NS_ERROR_ILLEGAL_VALUE);
NS_ENSURE_SUCCESS(rv, rv);
}
CMLOG("Received bytes [%lld] to [%lld] of [%lld] for decoder[%p]",
aRangeStart, aRangeEnd, aRangeTotal, mDecoder);
return NS_OK;
}
nsresult
ChannelMediaResource::OnStopRequest(nsIRequest* aRequest, nsresult aStatus)
{
NS_ASSERTION(mChannel.get() == aRequest, "Wrong channel!");
NS_ASSERTION(mSuspendCount == 0,
"How can OnStopRequest fire while we're suspended?");
{
MutexAutoLock lock(mLock);
mChannelStatistics->Stop();
}
// Note that aStatus might have succeeded --- this might be a normal close
// --- even in situations where the server cut us off because we were
// suspended. So we need to "reopen on error" in that case too. The only
// cases where we don't need to reopen are when *we* closed the stream.
// But don't reopen if we need to seek and we don't think we can... that would
// cause us to just re-read the stream, which would be really bad.
if (mReopenOnError &&
aStatus != NS_ERROR_PARSED_DATA_CACHED && aStatus != NS_BINDING_ABORTED &&
(mOffset == 0 || mCacheStream.IsTransportSeekable())) {
// If the stream did close normally, then if the server is seekable we'll
// just seek to the end of the resource and get an HTTP 416 error because
// there's nothing there, so this isn't bad.
nsresult rv = CacheClientSeek(mOffset, false);
if (NS_SUCCEEDED(rv))
return rv;
// If the reopen/reseek fails, just fall through and treat this
// error as fatal.
}
if (!mIgnoreClose) {
mCacheStream.NotifyDataEnded(aStatus);
// Move this request back into the foreground. This is necessary for
// requests owned by video documents to ensure the load group fires
// OnStopRequest when restoring from session history.
nsLoadFlags loadFlags;
DebugOnly<nsresult> rv = mChannel->GetLoadFlags(&loadFlags);
NS_ASSERTION(NS_SUCCEEDED(rv), "GetLoadFlags() failed!");
if (loadFlags & nsIRequest::LOAD_BACKGROUND) {
ModifyLoadFlags(loadFlags & ~nsIRequest::LOAD_BACKGROUND);
}
}
return NS_OK;
}
nsresult
ChannelMediaResource::OnChannelRedirect(nsIChannel* aOld, nsIChannel* aNew,
uint32_t aFlags)
{
mChannel = aNew;
return SetupChannelHeaders();
}
struct CopySegmentClosure {
nsCOMPtr<nsIPrincipal> mPrincipal;
ChannelMediaResource* mResource;
};
NS_METHOD
ChannelMediaResource::CopySegmentToCache(nsIInputStream *aInStream,
void *aClosure,
const char *aFromSegment,
uint32_t aToOffset,
uint32_t aCount,
uint32_t *aWriteCount)
{
CopySegmentClosure* closure = static_cast<CopySegmentClosure*>(aClosure);
closure->mResource->mDecoder->NotifyDataArrived(aFromSegment, aCount, closure->mResource->mOffset);
// Keep track of where we're up to.
RESOURCE_LOG("%p [ChannelMediaResource]: CopySegmentToCache at mOffset [%lld] add "
"[%d] bytes for decoder[%p]",
closure->mResource, closure->mResource->mOffset, aCount,
closure->mResource->mDecoder);
closure->mResource->mOffset += aCount;
closure->mResource->mCacheStream.NotifyDataReceived(aCount, aFromSegment,
closure->mPrincipal);
*aWriteCount = aCount;
return NS_OK;
}
nsresult
ChannelMediaResource::OnDataAvailable(nsIRequest* aRequest,
nsIInputStream* aStream,
uint32_t aCount)
{
NS_ASSERTION(mChannel.get() == aRequest, "Wrong channel!");
{
MutexAutoLock lock(mLock);
mChannelStatistics->AddBytes(aCount);
}
CopySegmentClosure closure;
nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
if (secMan && mChannel) {
secMan->GetChannelResultPrincipal(mChannel, getter_AddRefs(closure.mPrincipal));
}
closure.mResource = this;
uint32_t count = aCount;
while (count > 0) {
uint32_t read;
nsresult rv = aStream->ReadSegments(CopySegmentToCache, &closure, count,
&read);
if (NS_FAILED(rv))
return rv;
NS_ASSERTION(read > 0, "Read 0 bytes while data was available?");
count -= read;
}
return NS_OK;
}
nsresult ChannelMediaResource::Open(nsIStreamListener **aStreamListener)
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
if (!mChannelStatistics) {
mChannelStatistics = new MediaChannelStatistics();
}
nsresult rv = mCacheStream.Init();
if (NS_FAILED(rv))
return rv;
NS_ASSERTION(mOffset == 0, "Who set mOffset already?");
if (!mChannel) {
// When we're a clone, the decoder might ask us to Open even though
// we haven't established an mChannel (because we might not need one)
NS_ASSERTION(!aStreamListener,
"Should have already been given a channel if we're to return a stream listener");
return NS_OK;
}
return OpenChannel(aStreamListener);
}
nsresult ChannelMediaResource::OpenChannel(nsIStreamListener** aStreamListener)
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
NS_ENSURE_TRUE(mChannel, NS_ERROR_NULL_POINTER);
NS_ASSERTION(!mListener, "Listener should have been removed by now");
if (aStreamListener) {
*aStreamListener = nullptr;
}
if (mByteRange.IsNull()) {
// We're not making a byte range request, so set the content length,
// if it's available as an HTTP header. This ensures that MediaResource
// wrapping objects for platform libraries that expect to know
// the length of a resource can get it before OnStartRequest() fires.
nsCOMPtr<nsIHttpChannel> hc = do_QueryInterface(mChannel);
if (hc) {
int64_t cl = -1;
if (NS_SUCCEEDED(hc->GetContentLength(&cl)) && cl != -1) {
mCacheStream.NotifyDataLength(cl);
}
}
}
mListener = new Listener(this);
NS_ENSURE_TRUE(mListener, NS_ERROR_OUT_OF_MEMORY);
if (aStreamListener) {
*aStreamListener = mListener;
NS_ADDREF(*aStreamListener);
} else {
nsresult rv = mChannel->SetNotificationCallbacks(mListener.get());
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIStreamListener> listener = mListener.get();
// Ensure that if we're loading cross domain, that the server is sending
// an authorizing Access-Control header.
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
NS_ENSURE_TRUE(owner, NS_ERROR_FAILURE);
dom::HTMLMediaElement* element = owner->GetMediaElement();
NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
if (element->ShouldCheckAllowOrigin()) {
nsRefPtr<nsCORSListenerProxy> crossSiteListener =
new nsCORSListenerProxy(mListener,
element->NodePrincipal(),
false);
NS_ENSURE_TRUE(crossSiteListener, NS_ERROR_OUT_OF_MEMORY);
rv = crossSiteListener->Init(mChannel);
NS_ENSURE_SUCCESS(rv, rv);
listener = crossSiteListener;
} else {
rv = nsContentUtils::GetSecurityManager()->
CheckLoadURIWithPrincipal(element->NodePrincipal(),
mURI,
nsIScriptSecurityManager::STANDARD);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = SetupChannelHeaders();
NS_ENSURE_SUCCESS(rv, rv);
rv = mChannel->AsyncOpen(listener, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
// Tell the media element that we are fetching data from a channel.
element->DownloadResumed(true);
}
return NS_OK;
}
nsresult ChannelMediaResource::SetupChannelHeaders()
{
// Always use a byte range request even if we're reading from the start
// of the resource.
// This enables us to detect if the stream supports byte range
// requests, and therefore seeking, early.
nsCOMPtr<nsIHttpChannel> hc = do_QueryInterface(mChannel);
if (hc) {
// Use |mByteRange| for a specific chunk, or |mOffset| if seeking in a
// complete file download.
nsAutoCString rangeString("bytes=");
if (!mByteRange.IsNull()) {
rangeString.AppendInt(mByteRange.mStart);
mOffset = mByteRange.mStart;
} else {
rangeString.AppendInt(mOffset);
}
rangeString.Append('-');
if (!mByteRange.IsNull()) {
rangeString.AppendInt(mByteRange.mEnd);
}
nsresult rv = hc->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false);
NS_ENSURE_SUCCESS(rv, rv);
// Send Accept header for video and audio types only (Bug 489071)
NS_ASSERTION(NS_IsMainThread(), "Don't call on non-main thread");
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
NS_ENSURE_TRUE(owner, NS_ERROR_FAILURE);
dom::HTMLMediaElement* element = owner->GetMediaElement();
NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
element->SetRequestHeaders(hc);
} else {
NS_ASSERTION(mOffset == 0, "Don't know how to seek on this channel type");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult ChannelMediaResource::Close()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
mCacheStream.Close();
CloseChannel();
return NS_OK;
}
already_AddRefed<nsIPrincipal> ChannelMediaResource::GetCurrentPrincipal()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
nsCOMPtr<nsIPrincipal> principal = mCacheStream.GetCurrentPrincipal();
return principal.forget();
}
bool ChannelMediaResource::CanClone()
{
return mCacheStream.IsAvailableForSharing();
}
already_AddRefed<MediaResource> ChannelMediaResource::CloneData(MediaDecoder* aDecoder)
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
NS_ASSERTION(mCacheStream.IsAvailableForSharing(), "Stream can't be cloned");
nsRefPtr<ChannelMediaResource> resource =
new ChannelMediaResource(aDecoder,
nullptr,
mURI,
GetContentType());
if (resource) {
// Initially the clone is treated as suspended by the cache, because
// we don't have a channel. If the cache needs to read data from the clone
// it will call CacheClientResume (or CacheClientSeek with aResume true)
// which will recreate the channel. This way, if all of the media data
// is already in the cache we don't create an unnecessary HTTP channel
// and perform a useless HTTP transaction.
resource->mSuspendCount = 1;
resource->mCacheStream.InitAsClone(&mCacheStream);
resource->mChannelStatistics = new MediaChannelStatistics(mChannelStatistics);
resource->mChannelStatistics->Stop();
}
return resource.forget();
}
void ChannelMediaResource::CloseChannel()
{
NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
{
MutexAutoLock lock(mLock);
mChannelStatistics->Stop();
}
if (mListener) {
mListener->Revoke();
mListener = nullptr;
}
if (mChannel) {
if (mSuspendCount > 0) {
// Resume the channel before we cancel it
PossiblyResume();
}
// The status we use here won't be passed to the decoder, since
// we've already revoked the listener. It can however be passed
// to nsDocumentViewer::LoadComplete if our channel is the one
// that kicked off creation of a video document. We don't want that
// document load to think there was an error.
// NS_ERROR_PARSED_DATA_CACHED is the best thing we have for that
// at the moment.
mChannel->Cancel(NS_ERROR_PARSED_DATA_CACHED);
mChannel = nullptr;
}
}
nsresult ChannelMediaResource::ReadFromCache(char* aBuffer,
int64_t aOffset,
uint32_t aCount)
{
return mCacheStream.ReadFromCache(aBuffer, aOffset, aCount);
}
nsresult ChannelMediaResource::Read(char* aBuffer,
uint32_t aCount,
uint32_t* aBytes)
{
NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread");
int64_t offset = mCacheStream.Tell();
nsresult rv = mCacheStream.Read(aBuffer, aCount, aBytes);
if (NS_SUCCEEDED(rv)) {
DispatchBytesConsumed(*aBytes, offset);
}
return rv;
}
nsresult ChannelMediaResource::ReadAt(int64_t aOffset,
char* aBuffer,
uint32_t aCount,
uint32_t* aBytes)
{
NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread");
nsresult rv = mCacheStream.ReadAt(aOffset, aBuffer, aCount, aBytes);
if (NS_SUCCEEDED(rv)) {
DispatchBytesConsumed(*aBytes, aOffset);
}
return rv;
}
nsresult ChannelMediaResource::Seek(int32_t aWhence, int64_t aOffset)
{
NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread");
CMLOG("Seek requested for aOffset [%lld] for decoder [%p]",
aOffset, mDecoder);
return mCacheStream.Seek(aWhence, aOffset);
}
int64_t ChannelMediaResource::Tell()
{
NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread");
return mCacheStream.Tell();
}
nsresult ChannelMediaResource::GetCachedRanges(nsTArray<MediaByteRange>& aRanges)
{
return mCacheStream.GetCachedRanges(aRanges);
}
void ChannelMediaResource::Suspend(bool aCloseImmediately)
{
NS_ASSERTION(NS_IsMainThread(), "Don't call on non-main thread");
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
if (!owner) {
// Shutting down; do nothing.
return;
}
dom::HTMLMediaElement* element = owner->GetMediaElement();
if (!element) {
// Shutting down; do nothing.
return;
}
if (mChannel) {
if (aCloseImmediately && mCacheStream.IsTransportSeekable()) {
// Kill off our channel right now, but don't tell anyone about it.
mIgnoreClose = true;
CloseChannel();
element->DownloadSuspended();
} else if (mSuspendCount == 0) {
{
MutexAutoLock lock(mLock);
mChannelStatistics->Stop();
}
PossiblySuspend();
element->DownloadSuspended();
}
}
++mSuspendCount;
}
void ChannelMediaResource::Resume()
{
NS_ASSERTION(NS_IsMainThread(), "Don't call on non-main thread");
NS_ASSERTION(mSuspendCount > 0, "Too many resumes!");
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
if (!owner) {
// Shutting down; do nothing.
return;
}
dom::HTMLMediaElement* element = owner->GetMediaElement();
if (!element) {
// Shutting down; do nothing.
return;
}
NS_ASSERTION(mSuspendCount > 0, "Resume without previous Suspend!");
--mSuspendCount;
if (mSuspendCount == 0) {
if (mChannel) {
// Just wake up our existing channel
{
MutexAutoLock lock(mLock);
mChannelStatistics->Start();
}
// if an error occurs after Resume, assume it's because the server
// timed out the connection and we should reopen it.
mReopenOnError = true;
PossiblyResume();
element->DownloadResumed();
} else {
int64_t totalLength = mCacheStream.GetLength();
// If mOffset is at the end of the stream, then we shouldn't try to
// seek to it. The seek will fail and be wasted anyway. We can leave
// the channel dead; if the media cache wants to read some other data
// in the future, it will call CacheClientSeek itself which will reopen the
// channel.
if (totalLength < 0 || mOffset < totalLength) {
// There is (or may be) data to read at mOffset, so start reading it.
// Need to recreate the channel.
CacheClientSeek(mOffset, false);
element->DownloadResumed();
} else {
// The channel remains dead. Do not notify DownloadResumed() which
// will leave the media element in NETWORK_LOADING state.
}
}
}
}
nsresult
ChannelMediaResource::RecreateChannel()
{
nsLoadFlags loadFlags =
nsICachingChannel::LOAD_BYPASS_LOCAL_CACHE_IF_BUSY |
(mLoadInBackground ? nsIRequest::LOAD_BACKGROUND : 0);
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
if (!owner) {
// The decoder is being shut down, so don't bother opening a new channel
return NS_OK;
}
dom::HTMLMediaElement* element = owner->GetMediaElement();
if (!element) {
// The decoder is being shut down, so don't bother opening a new channel
return NS_OK;
}
nsCOMPtr<nsILoadGroup> loadGroup = element->GetDocumentLoadGroup();
NS_ENSURE_TRUE(loadGroup, NS_ERROR_NULL_POINTER);
nsresult rv = NS_NewChannel(getter_AddRefs(mChannel),
mURI,
element,
nsILoadInfo::SEC_NORMAL,
nsIContentPolicy::TYPE_MEDIA,
loadGroup,
nullptr, // aCallbacks
loadFlags);
NS_ENSURE_SUCCESS(rv, rv);
// We have cached the Content-Type, which should not change. Give a hint to
// the channel to avoid a sniffing failure, which would be expected because we
// are probably seeking in the middle of the bitstream, and sniffing relies
// on the presence of a magic number at the beginning of the stream.
NS_ASSERTION(!GetContentType().IsEmpty(),
"When recreating a channel, we should know the Content-Type.");
mChannel->SetContentType(GetContentType());
// Tell the cache to reset the download status when the channel is reopened.
mCacheStream.NotifyChannelRecreated();
return rv;
}
void
ChannelMediaResource::DoNotifyDataReceived()
{
mDataReceivedEvent.Revoke();
mDecoder->NotifyBytesDownloaded();
}
void
ChannelMediaResource::CacheClientNotifyDataReceived()
{
NS_ASSERTION(NS_IsMainThread(), "Don't call on non-main thread");
// NOTE: this can be called with the media cache lock held, so don't
// block or do anything which might try to acquire a lock!
if (mDataReceivedEvent.IsPending())
return;
mDataReceivedEvent =
NS_NewNonOwningRunnableMethod(this, &ChannelMediaResource::DoNotifyDataReceived);
NS_DispatchToMainThread(mDataReceivedEvent.get());
}
class DataEnded : public nsRunnable {
public:
DataEnded(MediaDecoder* aDecoder, nsresult aStatus) :
mDecoder(aDecoder), mStatus(aStatus) {}
NS_IMETHOD Run() {
mDecoder->NotifyDownloadEnded(mStatus);
if (NS_SUCCEEDED(mStatus)) {
MediaDecoderOwner* owner = mDecoder->GetMediaOwner();
if (owner) {
dom::HTMLMediaElement* element = owner->GetMediaElement();
if (element) {
element->DownloadSuspended();
}
}
// NotifySuspendedStatusChanged will tell the element that download
// has been suspended "by the cache", which is true since we never download
// anything. The element can then transition to HAVE_ENOUGH_DATA.
mDecoder->NotifySuspendedStatusChanged();
}
return NS_OK;
}
private:
nsRefPtr<MediaDecoder> mDecoder;
nsresult mStatus;
};
void
ChannelMediaResource::CacheClientNotifyDataEnded(nsresult aStatus)
{
MOZ_ASSERT(NS_IsMainThread());
// NOTE: this can be called with the media cache lock held, so don't
// block or do anything which might try to acquire a lock!
nsCOMPtr<nsIRunnable> event = new DataEnded(mDecoder, aStatus);