forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsOggReader.cpp
1812 lines (1629 loc) · 66.9 KB
/
nsOggReader.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: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla code.
*
* The Initial Developer of the Original Code is the Mozilla Corporation.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Double <chris.double@double.co.nz>
* Chris Pearce <chris@pearce.org.nz>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsError.h"
#include "nsBuiltinDecoderStateMachine.h"
#include "nsBuiltinDecoder.h"
#include "nsOggReader.h"
#include "VideoUtils.h"
#include "theora/theoradec.h"
#include "nsTimeRanges.h"
#include "mozilla/TimeStamp.h"
using namespace mozilla;
// Un-comment to enable logging of seek bisections.
//#define SEEK_LOGGING
#ifdef PR_LOGGING
extern PRLogModuleInfo* gBuiltinDecoderLog;
#define LOG(type, msg) PR_LOG(gBuiltinDecoderLog, type, msg)
#ifdef SEEK_LOGGING
#define SEEK_LOG(type, msg) PR_LOG(gBuiltinDecoderLog, type, msg)
#else
#define SEEK_LOG(type, msg)
#endif
#else
#define LOG(type, msg)
#define SEEK_LOG(type, msg)
#endif
// If we don't have a Theora video stream, then during seeking, if a seek
// target is less than SEEK_DECODE_MARGIN ahead of the current playback
// position, we'll just decode forwards rather than performing a bisection
// search. If we have Theora video we use the maximum keyframe interval as
// this value, rather than SEEK_DECODE_MARGIN. This makes small seeks faster.
#define SEEK_DECODE_MARGIN 2000
// The number of milliseconds of "fuzz" we use in a bisection search over
// HTTP. When we're seeking with fuzz, we'll stop the search if a bisection
// lands between the seek target and SEEK_FUZZ_MS milliseconds before the
// seek target. This is becaue it's usually quicker to just keep downloading
// from an exisiting connection than to do another bisection inside that
// small range, which would open a new HTTP connetion.
#define SEEK_FUZZ_MS 500
enum PageSyncResult {
PAGE_SYNC_ERROR = 1,
PAGE_SYNC_END_OF_RANGE= 2,
PAGE_SYNC_OK = 3
};
// Reads a page from the media stream.
static PageSyncResult
PageSync(nsMediaStream* aStream,
ogg_sync_state* aState,
PRBool aCachedDataOnly,
PRInt64 aOffset,
PRInt64 aEndOffset,
ogg_page* aPage,
int& aSkippedBytes);
// Chunk size to read when reading Ogg files. Average Ogg page length
// is about 4300 bytes, so we read the file in chunks larger than that.
static const int PAGE_STEP = 8192;
nsOggReader::nsOggReader(nsBuiltinDecoder* aDecoder)
: nsBuiltinDecoderReader(aDecoder),
mTheoraState(nsnull),
mVorbisState(nsnull),
mSkeletonState(nsnull),
mVorbisSerial(0),
mTheoraSerial(0),
mPageOffset(0),
mTheoraGranulepos(-1),
mVorbisGranulepos(-1)
{
MOZ_COUNT_CTOR(nsOggReader);
}
nsOggReader::~nsOggReader()
{
ogg_sync_clear(&mOggState);
MOZ_COUNT_DTOR(nsOggReader);
}
nsresult nsOggReader::Init(nsBuiltinDecoderReader* aCloneDonor) {
PRBool init = mCodecStates.Init();
NS_ASSERTION(init, "Failed to initialize mCodecStates");
if (!init) {
return NS_ERROR_FAILURE;
}
int ret = ogg_sync_init(&mOggState);
NS_ENSURE_TRUE(ret == 0, NS_ERROR_FAILURE);
return NS_OK;
}
nsresult nsOggReader::ResetDecode()
{
nsresult res = NS_OK;
// Clear the Theora/Vorbis granulepos capture status, so that the next
// decode calls recaptures the granulepos.
mTheoraGranulepos = -1;
mVorbisGranulepos = -1;
if (NS_FAILED(nsBuiltinDecoderReader::ResetDecode())) {
res = NS_ERROR_FAILURE;
}
{
MonitorAutoEnter mon(mMonitor);
// Discard any previously buffered packets/pages.
ogg_sync_reset(&mOggState);
if (mVorbisState && NS_FAILED(mVorbisState->Reset())) {
res = NS_ERROR_FAILURE;
}
if (mTheoraState && NS_FAILED(mTheoraState->Reset())) {
res = NS_ERROR_FAILURE;
}
}
return res;
}
// Returns PR_TRUE when all bitstreams in aBitstreams array have finished
// reading their headers.
static PRBool DoneReadingHeaders(nsTArray<nsOggCodecState*>& aBitstreams) {
for (PRUint32 i = 0; i < aBitstreams .Length(); i++) {
if (!aBitstreams [i]->DoneReadingHeaders()) {
return PR_FALSE;
}
}
return PR_TRUE;
}
nsresult nsOggReader::ReadMetadata(nsVideoInfo* aInfo)
{
NS_ASSERTION(mDecoder->OnStateMachineThread(), "Should be on play state machine thread.");
MonitorAutoEnter mon(mMonitor);
// We read packets until all bitstreams have read all their header packets.
// We record the offset of the first non-header page so that we know
// what page to seek to when seeking to the media start.
ogg_page page;
PRInt64 pageOffset;
nsAutoTArray<nsOggCodecState*,4> bitstreams;
PRBool readAllBOS = PR_FALSE;
mDataOffset = 0;
while (PR_TRUE) {
if (readAllBOS && DoneReadingHeaders(bitstreams)) {
if (mDataOffset == 0) {
// We've previously found the start of the first non-header packet.
mDataOffset = mPageOffset;
}
break;
}
pageOffset = ReadOggPage(&page);
if (pageOffset == -1) {
// Some kind of error...
break;
}
int ret = 0;
int serial = ogg_page_serialno(&page);
nsOggCodecState* codecState = 0;
if (ogg_page_bos(&page)) {
NS_ASSERTION(!readAllBOS, "We shouldn't encounter another BOS page");
codecState = nsOggCodecState::Create(&page);
#ifdef DEBUG
PRBool r =
#endif
mCodecStates.Put(serial, codecState);
NS_ASSERTION(r, "Failed to insert into mCodecStates");
bitstreams.AppendElement(codecState);
mKnownStreams.AppendElement(serial);
if (codecState &&
codecState->GetType() == nsOggCodecState::TYPE_VORBIS &&
!mVorbisState)
{
// First Vorbis bitstream, we'll play this one. Subsequent Vorbis
// bitstreams will be ignored.
mVorbisState = static_cast<nsVorbisState*>(codecState);
}
if (codecState &&
codecState->GetType() == nsOggCodecState::TYPE_THEORA &&
!mTheoraState)
{
// First Theora bitstream, we'll play this one. Subsequent Theora
// bitstreams will be ignored.
mTheoraState = static_cast<nsTheoraState*>(codecState);
}
if (codecState &&
codecState->GetType() == nsOggCodecState::TYPE_SKELETON &&
!mSkeletonState)
{
mSkeletonState = static_cast<nsSkeletonState*>(codecState);
}
} else {
// We've encountered the a non Beginning Of Stream page. No more
// BOS pages can follow in this Ogg segment, so there will be no other
// bitstreams in the Ogg (unless it's invalid).
readAllBOS = PR_TRUE;
}
mCodecStates.Get(serial, &codecState);
NS_ENSURE_TRUE(codecState, NS_ERROR_FAILURE);
// Add a complete page to the bitstream
ret = ogg_stream_pagein(&codecState->mState, &page);
NS_ENSURE_TRUE(ret == 0, NS_ERROR_FAILURE);
// Process all available header packets in the stream.
ogg_packet packet;
if (codecState->DoneReadingHeaders() && mDataOffset == 0)
{
// Stream has read all header packets, but now there's more data in
// (presumably) a non-header page, we must have finished header packets.
// This can happen in incorrectly chopped streams.
mDataOffset = pageOffset;
continue;
}
while (!codecState->DoneReadingHeaders() &&
(ret = ogg_stream_packetout(&codecState->mState, &packet)) != 0)
{
if (ret == -1) {
// Sync lost, we've probably encountered the continuation of a packet
// in a chopped video.
continue;
}
// A packet is available. If it is not a header packet we'll break.
// If it is a header packet, process it as normal.
codecState->DecodeHeader(&packet);
}
if (ogg_stream_packetpeek(&codecState->mState, &packet) != 0 &&
mDataOffset == 0)
{
// We're finished reading headers for this bitstream, but there's still
// packets in the bitstream to read. The bitstream is probably poorly
// muxed, and includes the last header packet on a page with non-header
// packets. We need to ensure that this is the media start page offset.
mDataOffset = pageOffset;
}
}
// Deactivate any non-primary bitstreams.
for (PRUint32 i = 0; i < bitstreams.Length(); i++) {
nsOggCodecState* s = bitstreams[i];
if (s != mVorbisState && s != mTheoraState && s != mSkeletonState) {
s->Deactivate();
}
}
// Initialize the first Theora and Vorbis bitstreams. According to the
// Theora spec these can be considered the 'primary' bitstreams for playback.
// Extract the metadata needed from these streams.
// Set a default callback period for if we have no video data
if (mTheoraState && mTheoraState->Init()) {
gfxIntSize sz(mTheoraState->mInfo.pic_width,
mTheoraState->mInfo.pic_height);
mDecoder->SetVideoData(sz, mTheoraState->mPixelAspectRatio, nsnull, TimeStamp::Now());
}
if (mVorbisState) {
mVorbisState->Init();
}
if (!HasAudio() && !HasVideo() && mSkeletonState) {
// We have a skeleton track, but no audio or video, may as well disable
// the skeleton, we can't do anything useful with this media.
mSkeletonState->Deactivate();
}
mInfo.mHasAudio = HasAudio();
mInfo.mHasVideo = HasVideo();
if (HasAudio()) {
mInfo.mAudioRate = mVorbisState->mInfo.rate;
mInfo.mAudioChannels = mVorbisState->mInfo.channels;
}
if (HasVideo()) {
mInfo.mPixelAspectRatio = mTheoraState->mPixelAspectRatio;
mInfo.mPicture = nsIntRect(mTheoraState->mInfo.pic_x,
mTheoraState->mInfo.pic_y,
mTheoraState->mInfo.pic_width,
mTheoraState->mInfo.pic_height);
mInfo.mFrame = nsIntSize(mTheoraState->mInfo.frame_width,
mTheoraState->mInfo.frame_height);
mInfo.mDisplay = nsIntSize(mInfo.mPicture.width,
mInfo.mPicture.height);
}
mInfo.mDataOffset = mDataOffset;
if (mSkeletonState && mSkeletonState->HasIndex()) {
// Extract the duration info out of the index, so we don't need to seek to
// the end of stream to get it.
nsAutoTArray<PRUint32, 2> tracks;
if (HasVideo()) {
tracks.AppendElement(mTheoraState->mSerial);
}
if (HasAudio()) {
tracks.AppendElement(mVorbisState->mSerial);
}
PRInt64 duration = 0;
if (NS_SUCCEEDED(mSkeletonState->GetDuration(tracks, duration))) {
MonitorAutoExit exitReaderMon(mMonitor);
MonitorAutoEnter decoderMon(mDecoder->GetMonitor());
mDecoder->GetStateMachine()->SetDuration(duration);
LOG(PR_LOG_DEBUG, ("Got duration from Skeleton index %lld", duration));
}
}
// Copy Vorbis and Theora info data for time computations on other threads.
if (mVorbisState) {
memcpy(&mVorbisInfo, &mVorbisState->mInfo, sizeof(mVorbisInfo));
mVorbisInfo.codec_setup = NULL;
mVorbisSerial = mVorbisState->mSerial;
}
if (mTheoraState) {
memcpy(&mTheoraInfo, &mTheoraState->mInfo, sizeof(mTheoraInfo));
mTheoraSerial = mTheoraState->mSerial;
}
*aInfo = mInfo;
LOG(PR_LOG_DEBUG, ("Done loading headers, data offset %lld", mDataOffset));
return NS_OK;
}
nsresult nsOggReader::DecodeVorbis(nsTArray<nsAutoPtr<SoundData> >& aChunks,
ogg_packet* aPacket)
{
// Successfully read a packet.
if (vorbis_synthesis(&mVorbisState->mBlock, aPacket) != 0) {
return NS_ERROR_FAILURE;
}
if (vorbis_synthesis_blockin(&mVorbisState->mDsp,
&mVorbisState->mBlock) != 0)
{
return NS_ERROR_FAILURE;
}
VorbisPCMValue** pcm = 0;
PRInt32 samples = 0;
PRUint32 channels = mVorbisState->mInfo.channels;
while ((samples = vorbis_synthesis_pcmout(&mVorbisState->mDsp, &pcm)) > 0) {
SoundDataValue* buffer = new SoundDataValue[samples * channels];
for (PRUint32 j = 0; j < channels; ++j) {
VorbisPCMValue* channel = pcm[j];
for (PRUint32 i = 0; i < PRUint32(samples); ++i) {
buffer[i*channels + j] = MOZ_CONVERT_VORBIS_SAMPLE(channel[i]);
}
}
PRInt64 duration = mVorbisState->Time((PRInt64)samples);
PRInt64 startTime = (mVorbisGranulepos != -1) ?
mVorbisState->Time(mVorbisGranulepos) : -1;
SoundData* s = new SoundData(mPageOffset,
startTime,
duration,
samples,
buffer,
channels);
if (mVorbisGranulepos != -1) {
mVorbisGranulepos += samples;
}
if (!aChunks.AppendElement(s)) {
delete s;
}
if (vorbis_synthesis_read(&mVorbisState->mDsp, samples) != 0) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
PRBool nsOggReader::DecodeAudioData()
{
MonitorAutoEnter mon(mMonitor);
NS_ASSERTION(mDecoder->OnStateMachineThread() || mDecoder->OnDecodeThread(),
"Should be on playback or decode thread.");
NS_ASSERTION(mVorbisState!=0, "Need Vorbis state to decode audio");
ogg_packet packet;
packet.granulepos = -1;
PRBool endOfStream = PR_FALSE;
nsAutoTArray<nsAutoPtr<SoundData>, 64> chunks;
if (mVorbisGranulepos == -1) {
// Not captured Vorbis granulepos, read up until we get a granulepos, and
// back propagate the granulepos.
// We buffer the packets' pcm samples until we reach a packet with a granulepos.
// This will be the last packet in a page. Then using that granulepos to
// calculate the packet's end time, we calculate all the packets' start times by
// subtracting their durations.
// Ensure we've got Vorbis packets; read one more Vorbis page if necessary.
while (packet.granulepos <= 0 && !endOfStream) {
if (!ReadOggPacket(mVorbisState, &packet)) {
endOfStream = PR_TRUE;
break;
}
if (packet.e_o_s != 0) {
// This packet marks the logical end of the Vorbis bitstream. It may
// still contain sound samples, so we must still decode it.
endOfStream = PR_TRUE;
}
if (NS_FAILED(DecodeVorbis(chunks, &packet))) {
NS_WARNING("Failed to decode Vorbis packet");
}
}
if (packet.granulepos > 0) {
// Successfully read up to a non -1 granulepos.
// Calculate the timestamps of the sound samples.
PRInt64 granulepos = packet.granulepos; // Represents end time of last sample.
mVorbisGranulepos = packet.granulepos;
for (int i = chunks.Length() - 1; i >= 0; --i) {
SoundData* s = chunks[i];
PRInt64 startGranule = granulepos - s->mSamples;
s->mTime = mVorbisState->Time(startGranule);
granulepos = startGranule;
}
}
} else {
// We have already captured the granulepos. The next packet's granulepos
// is its number of samples, plus the previous granulepos.
if (!ReadOggPacket(mVorbisState, &packet)) {
endOfStream = PR_TRUE;
} else {
// Successfully read a packet from the file. Decode it.
endOfStream = packet.e_o_s != 0;
// Try to decode any packet we've read.
if (NS_FAILED(DecodeVorbis(chunks, &packet))) {
NS_WARNING("Failed to decode Vorbis packet");
}
if (packet.granulepos != -1 && packet.granulepos != mVorbisGranulepos) {
// If the packet's granulepos doesn't match our running sample total,
// it's likely the bitstream has been damaged somehow, or perhaps
// oggz-chopped. Just assume the packet's granulepos is correct...
mVorbisGranulepos = packet.granulepos;
}
}
}
// We've successfully decoded some sound chunks. Push them onto the audio
// queue.
for (PRUint32 i = 0; i < chunks.Length(); ++i) {
mAudioQueue.Push(chunks[i].forget());
}
if (endOfStream) {
// We've encountered an end of bitstream packet, or we've hit the end of
// file while trying to decode, so inform the audio queue that there'll
// be no more samples.
mAudioQueue.Finish();
return PR_FALSE;
}
return PR_TRUE;
}
// Returns 1 if the Theora info struct is decoding a media of Theora
// verion (maj,min,sub) or later, otherwise returns 0.
static int
TheoraVersion(th_info* info,
unsigned char maj,
unsigned char min,
unsigned char sub)
{
ogg_uint32_t ver = (maj << 16) + (min << 8) + sub;
ogg_uint32_t th_ver = (info->version_major << 16) +
(info->version_minor << 8) +
info->version_subminor;
return (th_ver >= ver) ? 1 : 0;
}
#ifdef DEBUG
// Ensures that all the VideoData in aFrames array are stored in increasing
// order by timestamp. Used in assertions in debug builds.
static PRBool
AllFrameTimesIncrease(nsTArray<nsAutoPtr<VideoData> >& aFrames)
{
PRInt64 prevTime = -1;
PRInt64 prevGranulepos = -1;
for (PRUint32 i = 0; i < aFrames.Length(); i++) {
VideoData* f = aFrames[i];
if (f->mTime < prevTime) {
return PR_FALSE;
}
prevTime = f->mTime;
prevGranulepos = f->mTimecode;
}
return PR_TRUE;
}
#endif
nsresult nsOggReader::DecodeTheora(nsTArray<nsAutoPtr<VideoData> >& aFrames,
ogg_packet* aPacket)
{
int ret = th_decode_packetin(mTheoraState->mCtx, aPacket, 0);
if (ret != 0 && ret != TH_DUPFRAME) {
return NS_ERROR_FAILURE;
}
PRInt64 time = (aPacket->granulepos != -1)
? mTheoraState->StartTime(aPacket->granulepos) : -1;
PRInt64 endTime = time != -1 ? time + mTheoraState->mFrameDuration : -1;
if (ret == TH_DUPFRAME) {
VideoData* v = VideoData::CreateDuplicate(mPageOffset,
time,
endTime,
aPacket->granulepos);
if (!aFrames.AppendElement(v)) {
delete v;
}
} else if (ret == 0) {
th_ycbcr_buffer buffer;
ret = th_decode_ycbcr_out(mTheoraState->mCtx, buffer);
NS_ASSERTION(ret == 0, "th_decode_ycbcr_out failed");
PRBool isKeyframe = th_packet_iskeyframe(aPacket) == 1;
VideoData::YCbCrBuffer b;
for (PRUint32 i=0; i < 3; ++i) {
b.mPlanes[i].mData = buffer[i].data;
b.mPlanes[i].mHeight = buffer[i].height;
b.mPlanes[i].mWidth = buffer[i].width;
b.mPlanes[i].mStride = buffer[i].stride;
}
// Need the monitor to be held to be able to use mInfo. This
// is held by our caller.
mMonitor.AssertCurrentThreadIn();
VideoData *v = VideoData::Create(mInfo,
mDecoder->GetImageContainer(),
mPageOffset,
time,
endTime,
b,
isKeyframe,
aPacket->granulepos);
if (!v) {
// There may be other reasons for this error, but for
// simplicity just assume the worst case: out of memory.
NS_WARNING("Failed to allocate memory for video frame");
return NS_ERROR_OUT_OF_MEMORY;
}
if (!aFrames.AppendElement(v)) {
delete v;
}
}
return NS_OK;
}
PRBool nsOggReader::DecodeVideoFrame(PRBool &aKeyframeSkip,
PRInt64 aTimeThreshold)
{
MonitorAutoEnter mon(mMonitor);
NS_ASSERTION(mDecoder->OnStateMachineThread() || mDecoder->OnDecodeThread(),
"Should be on state machine or AV thread.");
// Record number of frames decoded and parsed. Automatically update the
// stats counters using the AutoNotifyDecoded stack-based class.
PRUint32 parsed = 0, decoded = 0;
nsMediaDecoder::AutoNotifyDecoded autoNotify(mDecoder, parsed, decoded);
// We chose to keep track of the Theora granulepos ourselves, rather than
// rely on th_decode_packetin() to do it for us. This is because
// th_decode_packetin() simply works by incrementing a counter every time
// it's called, so if we drop frames and don't call it, subsequent granulepos
// will be wrong. Whenever we read a packet which has a granulepos, we use
// its granulepos, otherwise we increment the previous packet's granulepos.
nsAutoTArray<nsAutoPtr<VideoData>, 8> frames;
ogg_packet packet;
PRBool endOfStream = PR_FALSE;
if (mTheoraGranulepos == -1) {
// We've not read a Theora packet with a granulepos, so we don't know what
// timestamp to assign to Theora frames we decode. This will only happen
// the first time we read, or after a seek. We must read and buffer up to
// the first Theora packet with a granulepos, and back-propagate its
// granulepos to calculate the buffered frames' granulepos.
do {
if (!ReadOggPacket(mTheoraState, &packet)) {
// Failed to read another page, must be the end of file. We can't have
// already encountered an end of bitstream packet, else we wouldn't be
// here, so this bitstream must be missing its end of stream packet, or
// is otherwise corrupt (oggz-chop can output files like this). Inform
// the queue that there will be no more frames.
mVideoQueue.Finish();
return PR_FALSE;
}
parsed++;
if (packet.granulepos > 0) {
// We've found a packet with a granulepos, we can now determine the
// buffered packet's timestamps, as well as the timestamps for any
// packets we read subsequently.
mTheoraGranulepos = packet.granulepos;
}
if (DecodeTheora(frames, &packet) == NS_ERROR_OUT_OF_MEMORY) {
NS_WARNING("Theora decode memory allocation failure!");
return PR_FALSE;
}
} while (packet.granulepos <= 0 && !endOfStream);
if (packet.granulepos > 0) {
// Reconstruct the granulepos (and thus timestamps) of the decoded
// frames. Granulepos are stored as ((keyframe<<shift)+offset). We
// know the granulepos of the last frame in the list, so we can infer
// the granulepos of the intermediate frames using their frame numbers.
ogg_int64_t shift = mTheoraState->mInfo.keyframe_granule_shift;
ogg_int64_t version_3_2_1 = TheoraVersion(&mTheoraState->mInfo,3,2,1);
ogg_int64_t lastFrame = th_granule_frame(mTheoraState->mCtx,
packet.granulepos) + version_3_2_1;
ogg_int64_t firstFrame = lastFrame - frames.Length() + 1;
// Until we encounter a keyframe, we'll assume that the "keyframe"
// segment of the granulepos is the first frame, or if that causes
// the "offset" segment to overflow, we assume the required
// keyframe is maximumally offset. Until we encounter a keyframe
// the granulepos will probably be wrong, but we can't decode the
// frame anyway (since we don't have its keyframe) so it doesn't really
// matter.
ogg_int64_t keyframe = packet.granulepos >> shift;
// The lastFrame, firstFrame, keyframe variables, as well as the frame
// variable in the loop below, store the frame number for Theora
// version >= 3.2.1 streams, and store the frame index for Theora
// version < 3.2.1 streams.
for (PRUint32 i = 0; i < frames.Length() - 1; ++i) {
ogg_int64_t frame = firstFrame + i;
ogg_int64_t granulepos;
if (frames[i]->mKeyframe) {
granulepos = frame << shift;
keyframe = frame;
} else if (frame >= keyframe &&
frame - keyframe < ((ogg_int64_t)1 << shift))
{
// (frame - keyframe) won't overflow the "offset" segment of the
// granulepos, so it's safe to calculate the granulepos.
granulepos = (keyframe << shift) + (frame - keyframe);
} else {
// (frame - keyframeno) will overflow the "offset" segment of the
// granulepos, so we take "keyframe" to be the max possible offset
// frame instead.
ogg_int64_t k = NS_MAX(frame - (((ogg_int64_t)1 << shift) - 1), version_3_2_1);
granulepos = (k << shift) + (frame - k);
}
// Theora 3.2.1+ granulepos store frame number [1..N], so granulepos
// should be > 0.
// Theora 3.2.0 granulepos store the frame index [0..(N-1)], so
// granulepos should be >= 0.
NS_ASSERTION(granulepos >= version_3_2_1,
"Invalid granulepos for Theora version");
// Check that the frame's granule number is one more than the
// previous frame's.
NS_ASSERTION(i == 0 ||
th_granule_frame(mTheoraState->mCtx, granulepos) ==
th_granule_frame(mTheoraState->mCtx, frames[i-1]->mTimecode) + 1,
"Granulepos calculation is incorrect!");
frames[i]->mTime = mTheoraState->StartTime(granulepos);
frames[i]->mEndTime = frames[i]->mTime + mTheoraState->mFrameDuration;
NS_ASSERTION(frames[i]->mEndTime >= frames[i]->mTime, "Frame must start before it ends.");
frames[i]->mTimecode = granulepos;
}
NS_ASSERTION(AllFrameTimesIncrease(frames), "All frames must have granulepos");
// Check that the second to last frame's granule number is one less than
// the last frame's (the known granule number). If not our granulepos
// recovery missed a beat.
NS_ASSERTION(frames.Length() < 2 ||
th_granule_frame(mTheoraState->mCtx, frames[frames.Length()-2]->mTimecode) + 1 ==
th_granule_frame(mTheoraState->mCtx, packet.granulepos),
"Granulepos recovery should catch up with packet.granulepos!");
}
} else {
NS_ASSERTION(mTheoraGranulepos > 0, "We must Theora granulepos!");
if (!ReadOggPacket(mTheoraState, &packet)) {
// Failed to read from file, so EOF or other premature failure.
// Inform the queue that there will be no more frames.
mVideoQueue.Finish();
return PR_FALSE;
}
parsed++;
endOfStream = packet.e_o_s != 0;
// Maintain the Theora granulepos. We must do this even if we drop frames,
// otherwise our clock will be wrong after we've skipped frames.
if (packet.granulepos != -1) {
// Incoming packet has a granulepos, use that as it's granulepos.
mTheoraGranulepos = packet.granulepos;
} else {
// Increment the previous Theora granulepos.
PRInt64 granulepos = 0;
int shift = mTheoraState->mInfo.keyframe_granule_shift;
// Theora 3.2.1+ bitstreams granulepos store frame number; [1..N]
// Theora 3.2.0 bitstreams store the frame index; [0..(N-1)]
if (!th_packet_iskeyframe(&packet)) {
granulepos = mTheoraGranulepos + 1;
} else {
ogg_int64_t frameindex = th_granule_frame(mTheoraState->mCtx,
mTheoraGranulepos);
ogg_int64_t granule = frameindex +
TheoraVersion(&mTheoraState->mInfo,3,2,1) + 1;
NS_ASSERTION(granule > 0, "Must have positive granulepos");
granulepos = granule << shift;
}
NS_ASSERTION(th_granule_frame(mTheoraState->mCtx, mTheoraGranulepos) + 1 ==
th_granule_frame(mTheoraState->mCtx, granulepos),
"Frame number must increment by 1");
packet.granulepos = mTheoraGranulepos = granulepos;
}
PRInt64 time = mTheoraState->StartTime(mTheoraGranulepos);
NS_ASSERTION(packet.granulepos != -1, "Must know packet granulepos");
if (!aKeyframeSkip ||
(th_packet_iskeyframe(&packet) == 1 && time >= aTimeThreshold))
{
if (DecodeTheora(frames, &packet) == NS_ERROR_OUT_OF_MEMORY) {
NS_WARNING("Theora decode memory allocation failure");
return PR_FALSE;
}
}
}
// Push decoded data into the video frame queue.
for (PRUint32 i = 0; i < frames.Length(); i++) {
nsAutoPtr<VideoData> data(frames[i].forget());
// Don't use the frame if it's outside the bounds of the presentation
// start time in the skeleton track.
if (!mSkeletonState || mSkeletonState->IsPresentable(data->mTime)) {
if (aKeyframeSkip && data->mKeyframe) {
aKeyframeSkip = PR_FALSE;
}
if (!aKeyframeSkip && data->mEndTime >= aTimeThreshold) {
mVideoQueue.Push(data.forget());
decoded++;
}
}
}
if (endOfStream) {
// We've encountered an end of bitstream packet. Inform the queue that
// there will be no more frames.
mVideoQueue.Finish();
}
return !endOfStream;
}
PRInt64 nsOggReader::ReadOggPage(ogg_page* aPage)
{
NS_ASSERTION(mDecoder->OnStateMachineThread() || mDecoder->OnDecodeThread(),
"Should be on play state machine or decode thread.");
mMonitor.AssertCurrentThreadIn();
int ret = 0;
while((ret = ogg_sync_pageseek(&mOggState, aPage)) <= 0) {
if (ret < 0) {
// Lost page sync, have to skip up to next page.
mPageOffset += -ret;
continue;
}
// Returns a buffer that can be written too
// with the given size. This buffer is stored
// in the ogg synchronisation structure.
char* buffer = ogg_sync_buffer(&mOggState, 4096);
NS_ASSERTION(buffer, "ogg_sync_buffer failed");
// Read from the stream into the buffer
PRUint32 bytesRead = 0;
nsresult rv = mDecoder->GetCurrentStream()->Read(buffer, 4096, &bytesRead);
if (NS_FAILED(rv) || (bytesRead == 0 && ret == 0)) {
// End of file.
return -1;
}
mDecoder->NotifyBytesConsumed(bytesRead);
// Update the synchronisation layer with the number
// of bytes written to the buffer
ret = ogg_sync_wrote(&mOggState, bytesRead);
NS_ENSURE_TRUE(ret == 0, -1);
}
PRInt64 offset = mPageOffset;
mPageOffset += aPage->header_len + aPage->body_len;
return offset;
}
PRBool nsOggReader::ReadOggPacket(nsOggCodecState* aCodecState,
ogg_packet* aPacket)
{
NS_ASSERTION(mDecoder->OnStateMachineThread() || mDecoder->OnDecodeThread(),
"Should be on play state machine or decode thread.");
mMonitor.AssertCurrentThreadIn();
if (!aCodecState || !aCodecState->mActive) {
return PR_FALSE;
}
int ret = 0;
while ((ret = ogg_stream_packetout(&aCodecState->mState, aPacket)) != 1) {
ogg_page page;
if (aCodecState->PageInFromBuffer()) {
// The codec state has inserted a previously buffered page into its
// ogg_stream_state, no need to read a page from the channel.
continue;
}
// The codec state does not have any buffered pages, so try to read another
// page from the channel.
if (ReadOggPage(&page) == -1) {
return PR_FALSE;
}
PRUint32 serial = ogg_page_serialno(&page);
nsOggCodecState* codecState = nsnull;
mCodecStates.Get(serial, &codecState);
if (serial == aCodecState->mSerial) {
// This page is from our target bitstream, insert it into the
// codec state's ogg_stream_state so we can read a packet.
ret = ogg_stream_pagein(&codecState->mState, &page);
NS_ENSURE_TRUE(ret == 0, PR_FALSE);
} else if (codecState && codecState->mActive) {
// Page is for another active bitstream, add the page to its codec
// state's buffer for later consumption when that stream next tries
// to read a packet.
codecState->AddToBuffer(&page);
}
}
return PR_TRUE;
}
// Returns an ogg page's checksum.
static ogg_uint32_t
GetChecksum(ogg_page* page)
{
if (page == 0 || page->header == 0 || page->header_len < 25) {
return 0;
}
const unsigned char* p = page->header + 22;
PRUint32 c = p[0] +
(p[1] << 8) +
(p[2] << 16) +
(p[3] << 24);
return c;
}
VideoData* nsOggReader::FindStartTime(PRInt64 aOffset,
PRInt64& aOutStartTime)
{
NS_ASSERTION(mDecoder->OnStateMachineThread(),
"Should be on state machine thread.");
nsMediaStream* stream = mDecoder->GetCurrentStream();
NS_ENSURE_TRUE(stream != nsnull, nsnull);
nsresult res = stream->Seek(nsISeekableStream::NS_SEEK_SET, aOffset);
NS_ENSURE_SUCCESS(res, nsnull);
return nsBuiltinDecoderReader::FindStartTime(aOffset, aOutStartTime);
}
PRInt64 nsOggReader::FindEndTime(PRInt64 aEndOffset)
{
MonitorAutoEnter mon(mMonitor);
NS_ASSERTION(mDecoder->OnStateMachineThread(),
"Should be on state machine thread.");
NS_ASSERTION(mDataOffset > 0,
"Should have offset of first non-header page");
PRInt64 endTime = FindEndTime(mDataOffset, aEndOffset, PR_FALSE, &mOggState);
// Reset read head to start of media data.
nsMediaStream* stream = mDecoder->GetCurrentStream();
NS_ENSURE_TRUE(stream != nsnull, -1);
nsresult res = stream->Seek(nsISeekableStream::NS_SEEK_SET, mDataOffset);
NS_ENSURE_SUCCESS(res, -1);
return endTime;
}
PRInt64 nsOggReader::FindEndTime(PRInt64 aStartOffset,
PRInt64 aEndOffset,
PRBool aCachedDataOnly,
ogg_sync_state* aState)
{
nsMediaStream* stream = mDecoder->GetCurrentStream();
ogg_sync_reset(aState);
// We need to find the last page which ends before aEndOffset that
// has a granulepos that we can convert to a timestamp. We do this by
// backing off from aEndOffset until we encounter a page on which we can
// interpret the granulepos. If while backing off we encounter a page which
// we've previously encountered before, we'll either backoff again if we
// haven't found an end time yet, or return the last end time found.
const int step = 5000;
PRInt64 readStartOffset = aEndOffset;
PRInt64 readHead = aEndOffset;
PRInt64 endTime = -1;
PRUint32 checksumAfterSeek = 0;
PRUint32 prevChecksumAfterSeek = 0;
PRBool mustBackOff = PR_FALSE;
while (PR_TRUE) {
ogg_page page;
int ret = ogg_sync_pageseek(aState, &page);
if (ret == 0) {
// We need more data if we've not encountered a page we've seen before,
// or we've read to the end of file.
if (mustBackOff || readHead == aEndOffset || readHead == aStartOffset) {
if (endTime != -1 || readStartOffset == 0) {
// We have encountered a page before, or we're at the end of file.
break;
}
mustBackOff = PR_FALSE;
prevChecksumAfterSeek = checksumAfterSeek;
checksumAfterSeek = 0;
ogg_sync_reset(aState);
readStartOffset = NS_MAX(static_cast<PRInt64>(0), readStartOffset - step);
readHead = NS_MAX(aStartOffset, readStartOffset);
}
PRInt64 limit = NS_MIN(static_cast<PRInt64>(PR_UINT32_MAX),
aEndOffset - readHead);
limit = NS_MAX(static_cast<PRInt64>(0), limit);
limit = NS_MIN(limit, static_cast<PRInt64>(step));
PRUint32 bytesToRead = static_cast<PRUint32>(limit);
PRUint32 bytesRead = 0;
char* buffer = ogg_sync_buffer(aState, bytesToRead);
NS_ASSERTION(buffer, "Must have buffer");
nsresult res;
if (aCachedDataOnly) {
res = stream->ReadFromCache(buffer, readHead, bytesToRead);
NS_ENSURE_SUCCESS(res, -1);
bytesRead = bytesToRead;
} else {
NS_ASSERTION(readHead < aEndOffset,
"Stream pos must be before range end");
res = stream->Seek(nsISeekableStream::NS_SEEK_SET, readHead);
NS_ENSURE_SUCCESS(res, -1);
res = stream->Read(buffer, bytesToRead, &bytesRead);
NS_ENSURE_SUCCESS(res, -1);
}
readHead += bytesRead;
// Update the synchronisation layer with the number
// of bytes written to the buffer
ret = ogg_sync_wrote(aState, bytesRead);
if (ret != 0) {
endTime = -1;
break;