This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
MPEG4Writer.cpp
3115 lines (2670 loc) · 98.5 KB
/
MPEG4Writer.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
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "MPEG4Writer"
#include <arpa/inet.h>
#include <fcntl.h>
#include <inttypes.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utils/Log.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MPEG4Writer.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/Utils.h>
#include <media/mediarecorder.h>
#include <cutils/properties.h>
#include "include/ESDS.h"
#define WARN_UNLESS(condition, message, ...) \
( (CONDITION(condition)) ? false : ({ \
ALOGW("Condition %s failed " message, #condition, ##__VA_ARGS__); \
true; \
}))
namespace android {
static const int64_t kMinStreamableFileSizeInBytes = 5 * 1024 * 1024;
static const int64_t kMax32BitFileSize = 0x00ffffffffLL; // 2^32-1 : max FAT32
// filesystem file size
// used by most SD cards
static const uint8_t kNalUnitTypeSeqParamSet = 0x07;
static const uint8_t kNalUnitTypePicParamSet = 0x08;
static const int64_t kInitialDelayTimeUs = 700000LL;
class MPEG4Writer::Track {
public:
Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
~Track();
status_t start(MetaData *params);
status_t stop();
status_t pause();
bool reachedEOS();
int64_t getDurationUs() const;
int64_t getEstimatedTrackSizeBytes() const;
void writeTrackHeader(bool use32BitOffset = true);
void bufferChunk(int64_t timestampUs);
bool isAvc() const { return mIsAvc; }
bool isAudio() const { return mIsAudio; }
bool isMPEG4() const { return mIsMPEG4; }
void addChunkOffset(off64_t offset);
int32_t getTrackId() const { return mTrackId; }
status_t dump(int fd, const Vector<String16>& args) const;
private:
enum {
kMaxCttsOffsetTimeUs = 1000000LL, // 1 second
kSampleArraySize = 1000,
};
// A helper class to handle faster write box with table entries
template<class TYPE>
struct ListTableEntries {
ListTableEntries(uint32_t elementCapacity, uint32_t entryCapacity)
: mElementCapacity(elementCapacity),
mEntryCapacity(entryCapacity),
mTotalNumTableEntries(0),
mNumValuesInCurrEntry(0),
mCurrTableEntriesElement(NULL) {
CHECK_GT(mElementCapacity, 0);
CHECK_GT(mEntryCapacity, 0);
}
// Free the allocated memory.
~ListTableEntries() {
while (!mTableEntryList.empty()) {
typename List<TYPE *>::iterator it = mTableEntryList.begin();
delete[] (*it);
mTableEntryList.erase(it);
}
}
// Replace the value at the given position by the given value.
// There must be an existing value at the given position.
// @arg value must be in network byte order
// @arg pos location the value must be in.
void set(const TYPE& value, uint32_t pos) {
CHECK_LT(pos, mTotalNumTableEntries * mEntryCapacity);
typename List<TYPE *>::iterator it = mTableEntryList.begin();
uint32_t iterations = (pos / (mElementCapacity * mEntryCapacity));
while (it != mTableEntryList.end() && iterations > 0) {
++it;
--iterations;
}
CHECK(it != mTableEntryList.end());
CHECK_EQ(iterations, 0);
(*it)[(pos % (mElementCapacity * mEntryCapacity))] = value;
}
// Get the value at the given position by the given value.
// @arg value the retrieved value at the position in network byte order.
// @arg pos location the value must be in.
// @return true if a value is found.
bool get(TYPE& value, uint32_t pos) const {
if (pos >= mTotalNumTableEntries * mEntryCapacity) {
return false;
}
typename List<TYPE *>::iterator it = mTableEntryList.begin();
uint32_t iterations = (pos / (mElementCapacity * mEntryCapacity));
while (it != mTableEntryList.end() && iterations > 0) {
++it;
--iterations;
}
CHECK(it != mTableEntryList.end());
CHECK_EQ(iterations, 0);
value = (*it)[(pos % (mElementCapacity * mEntryCapacity))];
return true;
}
// Store a single value.
// @arg value must be in network byte order.
void add(const TYPE& value) {
CHECK_LT(mNumValuesInCurrEntry, mElementCapacity);
uint32_t nEntries = mTotalNumTableEntries % mElementCapacity;
uint32_t nValues = mNumValuesInCurrEntry % mEntryCapacity;
if (nEntries == 0 && nValues == 0) {
mCurrTableEntriesElement = new TYPE[mEntryCapacity * mElementCapacity];
CHECK(mCurrTableEntriesElement != NULL);
mTableEntryList.push_back(mCurrTableEntriesElement);
}
uint32_t pos = nEntries * mEntryCapacity + nValues;
mCurrTableEntriesElement[pos] = value;
++mNumValuesInCurrEntry;
if ((mNumValuesInCurrEntry % mEntryCapacity) == 0) {
++mTotalNumTableEntries;
mNumValuesInCurrEntry = 0;
}
}
// Write out the table entries:
// 1. the number of entries goes first
// 2. followed by the values in the table enties in order
// @arg writer the writer to actual write to the storage
void write(MPEG4Writer *writer) const {
CHECK_EQ(mNumValuesInCurrEntry % mEntryCapacity, 0);
uint32_t nEntries = mTotalNumTableEntries;
writer->writeInt32(nEntries);
for (typename List<TYPE *>::iterator it = mTableEntryList.begin();
it != mTableEntryList.end(); ++it) {
CHECK_GT(nEntries, 0);
if (nEntries >= mElementCapacity) {
writer->write(*it, sizeof(TYPE) * mEntryCapacity, mElementCapacity);
nEntries -= mElementCapacity;
} else {
writer->write(*it, sizeof(TYPE) * mEntryCapacity, nEntries);
break;
}
}
}
// Return the number of entries in the table.
uint32_t count() const { return mTotalNumTableEntries; }
private:
uint32_t mElementCapacity; // # entries in an element
uint32_t mEntryCapacity; // # of values in each entry
uint32_t mTotalNumTableEntries;
uint32_t mNumValuesInCurrEntry; // up to mEntryCapacity
TYPE *mCurrTableEntriesElement;
mutable List<TYPE *> mTableEntryList;
DISALLOW_EVIL_CONSTRUCTORS(ListTableEntries);
};
MPEG4Writer *mOwner;
sp<MetaData> mMeta;
sp<MediaSource> mSource;
volatile bool mDone;
volatile bool mPaused;
volatile bool mResumed;
volatile bool mStarted;
bool mIsAvc;
bool mIsAudio;
bool mIsMPEG4;
int32_t mTrackId;
int64_t mTrackDurationUs;
int64_t mMaxChunkDurationUs;
int64_t mEstimatedTrackSizeBytes;
int64_t mMdatSizeBytes;
int32_t mTimeScale;
pthread_t mThread;
List<MediaBuffer *> mChunkSamples;
bool mSamplesHaveSameSize;
ListTableEntries<uint32_t> *mStszTableEntries;
ListTableEntries<uint32_t> *mStcoTableEntries;
ListTableEntries<off64_t> *mCo64TableEntries;
ListTableEntries<uint32_t> *mStscTableEntries;
ListTableEntries<uint32_t> *mStssTableEntries;
ListTableEntries<uint32_t> *mSttsTableEntries;
ListTableEntries<uint32_t> *mCttsTableEntries;
int64_t mMinCttsOffsetTimeUs;
int64_t mMaxCttsOffsetTimeUs;
// Sequence parameter set or picture parameter set
struct AVCParamSet {
AVCParamSet(uint16_t length, const uint8_t *data)
: mLength(length), mData(data) {}
uint16_t mLength;
const uint8_t *mData;
};
List<AVCParamSet> mSeqParamSets;
List<AVCParamSet> mPicParamSets;
uint8_t mProfileIdc;
uint8_t mProfileCompatible;
uint8_t mLevelIdc;
void *mCodecSpecificData;
size_t mCodecSpecificDataSize;
bool mGotAllCodecSpecificData;
bool mTrackingProgressStatus;
bool mReachedEOS;
int64_t mStartTimestampUs;
int64_t mStartTimeRealUs;
int64_t mFirstSampleTimeRealUs;
int64_t mPreviousTrackTimeUs;
int64_t mTrackEveryTimeDurationUs;
// Update the audio track's drift information.
void updateDriftTime(const sp<MetaData>& meta);
int32_t getStartTimeOffsetScaledTime() const;
static void *ThreadWrapper(void *me);
status_t threadEntry();
const uint8_t *parseParamSet(
const uint8_t *data, size_t length, int type, size_t *paramSetLen);
status_t makeAVCCodecSpecificData(const uint8_t *data, size_t size);
status_t copyAVCCodecSpecificData(const uint8_t *data, size_t size);
status_t parseAVCCodecSpecificData(const uint8_t *data, size_t size);
// Track authoring progress status
void trackProgressStatus(int64_t timeUs, status_t err = OK);
void initTrackingProgressStatus(MetaData *params);
void getCodecSpecificDataFromInputFormatIfPossible();
// Determine the track time scale
// If it is an audio track, try to use the sampling rate as
// the time scale; however, if user chooses the overwrite
// value, the user-supplied time scale will be used.
void setTimeScale();
// Simple validation on the codec specific data
status_t checkCodecSpecificData() const;
int32_t mRotation;
void updateTrackSizeEstimate();
void addOneStscTableEntry(size_t chunkId, size_t sampleId);
void addOneStssTableEntry(size_t sampleId);
// Duration is time scale based
void addOneSttsTableEntry(size_t sampleCount, int32_t timescaledDur);
void addOneCttsTableEntry(size_t sampleCount, int32_t timescaledDur);
bool isTrackMalFormed() const;
void sendTrackSummary(bool hasMultipleTracks);
// Write the boxes
void writeStcoBox(bool use32BitOffset);
void writeStscBox();
void writeStszBox();
void writeStssBox();
void writeSttsBox();
void writeCttsBox();
void writeD263Box();
void writePaspBox();
void writeAvccBox();
void writeUrlBox();
void writeDrefBox();
void writeDinfBox();
void writeDamrBox();
void writeMdhdBox(uint32_t now);
void writeSmhdBox();
void writeVmhdBox();
void writeHdlrBox();
void writeTkhdBox(uint32_t now);
void writeMp4aEsdsBox();
void writeMp4vEsdsBox();
void writeAudioFourCCBox();
void writeVideoFourCCBox();
void writeStblBox(bool use32BitOffset);
Track(const Track &);
Track &operator=(const Track &);
};
MPEG4Writer::MPEG4Writer(const char *filename)
: mFd(-1),
mInitCheck(NO_INIT),
mIsRealTimeRecording(true),
mUse4ByteNalLength(true),
mUse32BitOffset(true),
mIsFileSizeLimitExplicitlyRequested(false),
mPaused(false),
mStarted(false),
mWriterThreadStarted(false),
mOffset(0),
mMdatOffset(0),
mEstimatedMoovBoxSize(0),
mInterleaveDurationUs(1000000),
mLatitudex10000(0),
mLongitudex10000(0),
mAreGeoTagsAvailable(false),
mStartTimeOffsetMs(-1) {
mFd = open(filename, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
if (mFd >= 0) {
mInitCheck = OK;
}
}
MPEG4Writer::MPEG4Writer(int fd)
: mFd(dup(fd)),
mInitCheck(mFd < 0? NO_INIT: OK),
mIsRealTimeRecording(true),
mUse4ByteNalLength(true),
mUse32BitOffset(true),
mIsFileSizeLimitExplicitlyRequested(false),
mPaused(false),
mStarted(false),
mWriterThreadStarted(false),
mOffset(0),
mMdatOffset(0),
mEstimatedMoovBoxSize(0),
mInterleaveDurationUs(1000000),
mLatitudex10000(0),
mLongitudex10000(0),
mAreGeoTagsAvailable(false),
mStartTimeOffsetMs(-1) {
}
MPEG4Writer::~MPEG4Writer() {
reset();
while (!mTracks.empty()) {
List<Track *>::iterator it = mTracks.begin();
delete *it;
(*it) = NULL;
mTracks.erase(it);
}
mTracks.clear();
}
status_t MPEG4Writer::dump(
int fd, const Vector<String16>& args) {
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, " MPEG4Writer %p\n", this);
result.append(buffer);
snprintf(buffer, SIZE, " mStarted: %s\n", mStarted? "true": "false");
result.append(buffer);
::write(fd, result.string(), result.size());
for (List<Track *>::iterator it = mTracks.begin();
it != mTracks.end(); ++it) {
(*it)->dump(fd, args);
}
return OK;
}
status_t MPEG4Writer::Track::dump(
int fd, const Vector<String16>& /* args */) const {
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, " %s track\n", mIsAudio? "Audio": "Video");
result.append(buffer);
snprintf(buffer, SIZE, " reached EOS: %s\n",
mReachedEOS? "true": "false");
result.append(buffer);
snprintf(buffer, SIZE, " frames encoded : %d\n", mStszTableEntries->count());
result.append(buffer);
snprintf(buffer, SIZE, " duration encoded : %" PRId64 " us\n", mTrackDurationUs);
result.append(buffer);
::write(fd, result.string(), result.size());
return OK;
}
status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
Mutex::Autolock l(mLock);
if (mStarted) {
ALOGE("Attempt to add source AFTER recording is started");
return UNKNOWN_ERROR;
}
// At most 2 tracks can be supported.
if (mTracks.size() >= 2) {
ALOGE("Too many tracks (%zu) to add", mTracks.size());
return ERROR_UNSUPPORTED;
}
CHECK(source.get() != NULL);
// A track of type other than video or audio is not supported.
const char *mime;
source->getFormat()->findCString(kKeyMIMEType, &mime);
bool isAudio = !strncasecmp(mime, "audio/", 6);
bool isVideo = !strncasecmp(mime, "video/", 6);
if (!isAudio && !isVideo) {
ALOGE("Track (%s) other than video or audio is not supported",
mime);
return ERROR_UNSUPPORTED;
}
// At this point, we know the track to be added is either
// video or audio. Thus, we only need to check whether it
// is an audio track or not (if it is not, then it must be
// a video track).
// No more than one video or one audio track is supported.
for (List<Track*>::iterator it = mTracks.begin();
it != mTracks.end(); ++it) {
if ((*it)->isAudio() == isAudio) {
ALOGE("%s track already exists", isAudio? "Audio": "Video");
return ERROR_UNSUPPORTED;
}
}
// This is the first track of either audio or video.
// Go ahead to add the track.
Track *track = new Track(this, source, 1 + mTracks.size());
mTracks.push_back(track);
return OK;
}
status_t MPEG4Writer::startTracks(MetaData *params) {
if (mTracks.empty()) {
ALOGE("No source added");
return INVALID_OPERATION;
}
for (List<Track *>::iterator it = mTracks.begin();
it != mTracks.end(); ++it) {
status_t err = (*it)->start(params);
if (err != OK) {
for (List<Track *>::iterator it2 = mTracks.begin();
it2 != it; ++it2) {
(*it2)->stop();
}
return err;
}
}
return OK;
}
int64_t MPEG4Writer::estimateMoovBoxSize(int32_t bitRate) {
// This implementation is highly experimental/heurisitic.
//
// Statistical analysis shows that metadata usually accounts
// for a small portion of the total file size, usually < 0.6%.
// The default MIN_MOOV_BOX_SIZE is set to 0.6% x 1MB / 2,
// where 1MB is the common file size limit for MMS application.
// The default MAX _MOOV_BOX_SIZE value is based on about 3
// minute video recording with a bit rate about 3 Mbps, because
// statistics also show that most of the video captured are going
// to be less than 3 minutes.
// If the estimation is wrong, we will pay the price of wasting
// some reserved space. This should not happen so often statistically.
static const int32_t factor = mUse32BitOffset? 1: 2;
static const int64_t MIN_MOOV_BOX_SIZE = 3 * 1024; // 3 KB
static const int64_t MAX_MOOV_BOX_SIZE = (180 * 3000000 * 6LL / 8000);
int64_t size = MIN_MOOV_BOX_SIZE;
// Max file size limit is set
if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
size = mMaxFileSizeLimitBytes * 6 / 1000;
}
// Max file duration limit is set
if (mMaxFileDurationLimitUs != 0) {
if (bitRate > 0) {
int64_t size2 =
((mMaxFileDurationLimitUs * bitRate * 6) / 1000 / 8000000);
if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
// When both file size and duration limits are set,
// we use the smaller limit of the two.
if (size > size2) {
size = size2;
}
} else {
// Only max file duration limit is set
size = size2;
}
}
}
if (size < MIN_MOOV_BOX_SIZE) {
size = MIN_MOOV_BOX_SIZE;
}
// Any long duration recording will be probably end up with
// non-streamable mp4 file.
if (size > MAX_MOOV_BOX_SIZE) {
size = MAX_MOOV_BOX_SIZE;
}
ALOGI("limits: %" PRId64 "/%" PRId64 " bytes/us, bit rate: %d bps and the"
" estimated moov size %" PRId64 " bytes",
mMaxFileSizeLimitBytes, mMaxFileDurationLimitUs, bitRate, size);
return factor * size;
}
status_t MPEG4Writer::start(MetaData *param) {
if (mInitCheck != OK) {
return UNKNOWN_ERROR;
}
/*
* Check mMaxFileSizeLimitBytes at the beginning
* since mMaxFileSizeLimitBytes may be implicitly
* changed later for 32-bit file offset even if
* user does not ask to set it explicitly.
*/
if (mMaxFileSizeLimitBytes != 0) {
mIsFileSizeLimitExplicitlyRequested = true;
}
int32_t use64BitOffset;
if (param &&
param->findInt32(kKey64BitFileOffset, &use64BitOffset) &&
use64BitOffset) {
mUse32BitOffset = false;
}
if (mUse32BitOffset) {
// Implicit 32 bit file size limit
if (mMaxFileSizeLimitBytes == 0) {
mMaxFileSizeLimitBytes = kMax32BitFileSize;
}
// If file size is set to be larger than the 32 bit file
// size limit, treat it as an error.
if (mMaxFileSizeLimitBytes > kMax32BitFileSize) {
ALOGW("32-bit file size limit (%" PRId64 " bytes) too big. "
"It is changed to %" PRId64 " bytes",
mMaxFileSizeLimitBytes, kMax32BitFileSize);
mMaxFileSizeLimitBytes = kMax32BitFileSize;
}
}
int32_t use2ByteNalLength;
if (param &&
param->findInt32(kKey2ByteNalLength, &use2ByteNalLength) &&
use2ByteNalLength) {
mUse4ByteNalLength = false;
}
int32_t isRealTimeRecording;
if (param && param->findInt32(kKeyRealTimeRecording, &isRealTimeRecording)) {
mIsRealTimeRecording = isRealTimeRecording;
}
mStartTimestampUs = -1;
if (mStarted) {
if (mPaused) {
mPaused = false;
return startTracks(param);
}
return OK;
}
if (!param ||
!param->findInt32(kKeyTimeScale, &mTimeScale)) {
mTimeScale = 1000;
}
CHECK_GT(mTimeScale, 0);
ALOGV("movie time scale: %d", mTimeScale);
/*
* When the requested file size limit is small, the priority
* is to meet the file size limit requirement, rather than
* to make the file streamable. mStreamableFile does not tell
* whether the actual recorded file is streamable or not.
*/
mStreamableFile =
(mMaxFileSizeLimitBytes != 0 &&
mMaxFileSizeLimitBytes >= kMinStreamableFileSizeInBytes);
/*
* mWriteMoovBoxToMemory is true if the amount of data in moov box is
* smaller than the reserved free space at the beginning of a file, AND
* when the content of moov box is constructed. Note that video/audio
* frame data is always written to the file but not in the memory.
*
* Before stop()/reset() is called, mWriteMoovBoxToMemory is always
* false. When reset() is called at the end of a recording session,
* Moov box needs to be constructed.
*
* 1) Right before a moov box is constructed, mWriteMoovBoxToMemory
* to set to mStreamableFile so that if
* the file is intended to be streamable, it is set to true;
* otherwise, it is set to false. When the value is set to false,
* all the content of the moov box is written immediately to
* the end of the file. When the value is set to true, all the
* content of the moov box is written to an in-memory cache,
* mMoovBoxBuffer, util the following condition happens. Note
* that the size of the in-memory cache is the same as the
* reserved free space at the beginning of the file.
*
* 2) While the data of the moov box is written to an in-memory
* cache, the data size is checked against the reserved space.
* If the data size surpasses the reserved space, subsequent moov
* data could no longer be hold in the in-memory cache. This also
* indicates that the reserved space was too small. At this point,
* _all_ moov data must be written to the end of the file.
* mWriteMoovBoxToMemory must be set to false to direct the write
* to the file.
*
* 3) If the data size in moov box is smaller than the reserved
* space after moov box is completely constructed, the in-memory
* cache copy of the moov box is written to the reserved free
* space. Thus, immediately after the moov is completedly
* constructed, mWriteMoovBoxToMemory is always set to false.
*/
mWriteMoovBoxToMemory = false;
mMoovBoxBuffer = NULL;
mMoovBoxBufferOffset = 0;
writeFtypBox(param);
mFreeBoxOffset = mOffset;
if (mEstimatedMoovBoxSize == 0) {
int32_t bitRate = -1;
if (param) {
param->findInt32(kKeyBitRate, &bitRate);
}
mEstimatedMoovBoxSize = estimateMoovBoxSize(bitRate);
}
CHECK_GE(mEstimatedMoovBoxSize, 8);
if (mStreamableFile) {
// Reserve a 'free' box only for streamable file
lseek64(mFd, mFreeBoxOffset, SEEK_SET);
writeInt32(mEstimatedMoovBoxSize);
write("free", 4);
mMdatOffset = mFreeBoxOffset + mEstimatedMoovBoxSize;
} else {
mMdatOffset = mOffset;
}
mOffset = mMdatOffset;
lseek64(mFd, mMdatOffset, SEEK_SET);
if (mUse32BitOffset) {
write("????mdat", 8);
} else {
write("\x00\x00\x00\x01mdat????????", 16);
}
status_t err = startWriterThread();
if (err != OK) {
return err;
}
err = startTracks(param);
if (err != OK) {
return err;
}
mStarted = true;
return OK;
}
bool MPEG4Writer::use32BitFileOffset() const {
return mUse32BitOffset;
}
status_t MPEG4Writer::pause() {
if (mInitCheck != OK) {
return OK;
}
mPaused = true;
status_t err = OK;
for (List<Track *>::iterator it = mTracks.begin();
it != mTracks.end(); ++it) {
status_t status = (*it)->pause();
if (status != OK) {
err = status;
}
}
return err;
}
void MPEG4Writer::stopWriterThread() {
ALOGD("Stopping writer thread");
if (!mWriterThreadStarted) {
return;
}
{
Mutex::Autolock autolock(mLock);
mDone = true;
mChunkReadyCondition.signal();
}
void *dummy;
pthread_join(mThread, &dummy);
mWriterThreadStarted = false;
ALOGD("Writer thread stopped");
}
/*
* MP4 file standard defines a composition matrix:
* | a b u |
* | c d v |
* | x y w |
*
* the element in the matrix is stored in the following
* order: {a, b, u, c, d, v, x, y, w},
* where a, b, c, d, x, and y is in 16.16 format, while
* u, v and w is in 2.30 format.
*/
void MPEG4Writer::writeCompositionMatrix(int degrees) {
ALOGV("writeCompositionMatrix");
uint32_t a = 0x00010000;
uint32_t b = 0;
uint32_t c = 0;
uint32_t d = 0x00010000;
switch (degrees) {
case 0:
break;
case 90:
a = 0;
b = 0x00010000;
c = 0xFFFF0000;
d = 0;
break;
case 180:
a = 0xFFFF0000;
d = 0xFFFF0000;
break;
case 270:
a = 0;
b = 0xFFFF0000;
c = 0x00010000;
d = 0;
break;
default:
CHECK(!"Should never reach this unknown rotation");
break;
}
writeInt32(a); // a
writeInt32(b); // b
writeInt32(0); // u
writeInt32(c); // c
writeInt32(d); // d
writeInt32(0); // v
writeInt32(0); // x
writeInt32(0); // y
writeInt32(0x40000000); // w
}
void MPEG4Writer::release() {
close(mFd);
mFd = -1;
mInitCheck = NO_INIT;
mStarted = false;
}
status_t MPEG4Writer::reset() {
if (mInitCheck != OK) {
return OK;
} else {
if (!mWriterThreadStarted ||
!mStarted) {
if (mWriterThreadStarted) {
stopWriterThread();
}
release();
return OK;
}
}
status_t err = OK;
int64_t maxDurationUs = 0;
int64_t minDurationUs = 0x7fffffffffffffffLL;
for (List<Track *>::iterator it = mTracks.begin();
it != mTracks.end(); ++it) {
status_t status = (*it)->stop();
if (err == OK && status != OK) {
err = status;
}
int64_t durationUs = (*it)->getDurationUs();
if (durationUs > maxDurationUs) {
maxDurationUs = durationUs;
}
if (durationUs < minDurationUs) {
minDurationUs = durationUs;
}
}
if (mTracks.size() > 1) {
ALOGD("Duration from tracks range is [%" PRId64 ", %" PRId64 "] us",
minDurationUs, maxDurationUs);
}
stopWriterThread();
// Do not write out movie header on error.
if (err != OK) {
release();
return err;
}
// Fix up the size of the 'mdat' chunk.
if (mUse32BitOffset) {
lseek64(mFd, mMdatOffset, SEEK_SET);
uint32_t size = htonl(static_cast<uint32_t>(mOffset - mMdatOffset));
::write(mFd, &size, 4);
} else {
lseek64(mFd, mMdatOffset + 8, SEEK_SET);
uint64_t size = mOffset - mMdatOffset;
size = hton64(size);
::write(mFd, &size, 8);
}
lseek64(mFd, mOffset, SEEK_SET);
// Construct moov box now
mMoovBoxBufferOffset = 0;
mWriteMoovBoxToMemory = mStreamableFile;
if (mWriteMoovBoxToMemory) {
// There is no need to allocate in-memory cache
// for moov box if the file is not streamable.
mMoovBoxBuffer = (uint8_t *) malloc(mEstimatedMoovBoxSize);
CHECK(mMoovBoxBuffer != NULL);
}
writeMoovBox(maxDurationUs);
// mWriteMoovBoxToMemory could be set to false in
// MPEG4Writer::write() method
if (mWriteMoovBoxToMemory) {
mWriteMoovBoxToMemory = false;
// Content of the moov box is saved in the cache, and the in-memory
// moov box needs to be written to the file in a single shot.
CHECK_LE(mMoovBoxBufferOffset + 8, mEstimatedMoovBoxSize);
// Moov box
lseek64(mFd, mFreeBoxOffset, SEEK_SET);
mOffset = mFreeBoxOffset;
write(mMoovBoxBuffer, 1, mMoovBoxBufferOffset);
// Free box
lseek64(mFd, mOffset, SEEK_SET);
writeInt32(mEstimatedMoovBoxSize - mMoovBoxBufferOffset);
write("free", 4);
} else {
ALOGI("The mp4 file will not be streamable.");
}
// Free in-memory cache for moov box
if (mMoovBoxBuffer != NULL) {
free(mMoovBoxBuffer);
mMoovBoxBuffer = NULL;
mMoovBoxBufferOffset = 0;
}
CHECK(mBoxes.empty());
release();
return err;
}
uint32_t MPEG4Writer::getMpeg4Time() {
time_t now = time(NULL);
// MP4 file uses time counting seconds since midnight, Jan. 1, 1904
// while time function returns Unix epoch values which starts
// at 1970-01-01. Lets add the number of seconds between them
uint32_t mpeg4Time = now + (66 * 365 + 17) * (24 * 60 * 60);
return mpeg4Time;
}
void MPEG4Writer::writeMvhdBox(int64_t durationUs) {
uint32_t now = getMpeg4Time();
beginBox("mvhd");
writeInt32(0); // version=0, flags=0
writeInt32(now); // creation time
writeInt32(now); // modification time
writeInt32(mTimeScale); // mvhd timescale
int32_t duration = (durationUs * mTimeScale + 5E5) / 1E6;
writeInt32(duration);
writeInt32(0x10000); // rate: 1.0
writeInt16(0x100); // volume
writeInt16(0); // reserved
writeInt32(0); // reserved
writeInt32(0); // reserved
writeCompositionMatrix(0); // matrix
writeInt32(0); // predefined
writeInt32(0); // predefined
writeInt32(0); // predefined
writeInt32(0); // predefined
writeInt32(0); // predefined
writeInt32(0); // predefined
writeInt32(mTracks.size() + 1); // nextTrackID
endBox(); // mvhd
}
void MPEG4Writer::writeMoovBox(int64_t durationUs) {
beginBox("moov");
writeMvhdBox(durationUs);
if (mAreGeoTagsAvailable) {
writeUdtaBox();
}
int32_t id = 1;
for (List<Track *>::iterator it = mTracks.begin();
it != mTracks.end(); ++it, ++id) {
(*it)->writeTrackHeader(mUse32BitOffset);
}
endBox(); // moov
}
void MPEG4Writer::writeFtypBox(MetaData *param) {
beginBox("ftyp");
int32_t fileType;
if (param && param->findInt32(kKeyFileType, &fileType) &&
fileType != OUTPUT_FORMAT_MPEG_4) {
writeFourcc("3gp4");
writeInt32(0);
writeFourcc("isom");
writeFourcc("3gp4");
} else {
writeFourcc("mp42");
writeInt32(0);
writeFourcc("isom");
writeFourcc("mp42");
}
endBox();
}
static bool isTestModeEnabled() {
#if (PROPERTY_VALUE_MAX < 5)
#error "PROPERTY_VALUE_MAX must be at least 5"
#endif