7 #include "packager/media/formats/mp4/mp4_muxer.h"
9 #include "packager/base/time/clock.h"
10 #include "packager/base/time/time.h"
11 #include "packager/media/base/aes_encryptor.h"
12 #include "packager/media/base/audio_stream_info.h"
13 #include "packager/media/base/fourccs.h"
14 #include "packager/media/base/key_source.h"
15 #include "packager/media/base/media_sample.h"
16 #include "packager/media/base/video_stream_info.h"
17 #include "packager/media/codecs/es_descriptor.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/file/file.h"
20 #include "packager/media/formats/mp4/box_definitions.h"
21 #include "packager/media/formats/mp4/multi_segment_segmenter.h"
22 #include "packager/media/formats/mp4/single_segment_segmenter.h"
32 void SetStartAndEndFromOffsetAndSize(
size_t offset,
37 *start =
static_cast<uint32_t
>(offset);
39 *end = *start +
static_cast<uint32_t
>(size) - 1;
42 FourCC CodecToFourCC(Codec codec) {
82 MP4Muxer::~MP4Muxer() {}
84 Status MP4Muxer::InitializeMuxer() {
85 DCHECK(!streams().empty());
87 std::unique_ptr<FileType> ftyp(
new FileType);
88 std::unique_ptr<Movie> moov(
new Movie);
90 ftyp->major_brand = FOURCC_dash;
91 ftyp->compatible_brands.push_back(FOURCC_iso6);
92 ftyp->compatible_brands.push_back(FOURCC_mp41);
93 if (streams().size() == 1 && streams()[0]->stream_type() == kStreamVideo) {
94 const FourCC codec_fourcc = CodecToFourCC(
95 static_cast<VideoStreamInfo*>(streams()[0].
get())->codec());
96 if (codec_fourcc != FOURCC_NULL)
97 ftyp->compatible_brands.push_back(codec_fourcc);
100 moov->header.creation_time = IsoTimeNow();
101 moov->header.modification_time = IsoTimeNow();
102 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
104 moov->tracks.resize(streams().size());
105 moov->extends.tracks.resize(streams().size());
108 for (uint32_t i = 0; i < streams().size(); ++i) {
109 Track& trak = moov->tracks[i];
110 trak.header.track_id = i + 1;
112 TrackExtends& trex = moov->extends.tracks[i];
113 trex.track_id = trak.header.track_id;
114 trex.default_sample_description_index = 1;
116 switch (streams()[i]->stream_type()) {
118 GenerateVideoTrak(static_cast<VideoStreamInfo*>(streams()[i].
get()),
122 GenerateAudioTrak(static_cast<AudioStreamInfo*>(streams()[i].
get()),
126 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
127 << streams()[i]->stream_type();
131 if (options().segment_template.empty()) {
132 segmenter_.reset(
new SingleSegmentSegmenter(options(), std::move(ftyp),
136 new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
139 const Status segmenter_initialized = segmenter_->Initialize(
140 streams(), muxer_listener(), progress_listener(), encryption_key_source(),
141 max_sd_pixels(), max_hd_pixels(), max_uhd1_pixels(),
142 clear_lead_in_seconds(), crypto_period_duration_in_seconds(),
143 protection_scheme());
145 if (!segmenter_initialized.ok())
146 return segmenter_initialized;
148 FireOnMediaStartEvent();
152 Status MP4Muxer::Finalize() {
154 Status segmenter_finalized = segmenter_->Finalize();
156 if (!segmenter_finalized.ok())
157 return segmenter_finalized;
159 FireOnMediaEndEvent();
164 Status MP4Muxer::DoAddSample(std::shared_ptr<MediaSample> sample) {
166 return segmenter_->AddSample(*streams()[0], sample);
169 void MP4Muxer::InitializeTrak(
const StreamInfo* info, Track* trak) {
170 int64_t now = IsoTimeNow();
171 trak->header.creation_time = now;
172 trak->header.modification_time = now;
173 trak->header.duration = 0;
174 trak->media.header.creation_time = now;
175 trak->media.header.modification_time = now;
176 trak->media.header.timescale = info->time_scale();
177 trak->media.header.duration = 0;
178 if (!info->language().empty()) {
180 std::string main_language = info->language();
181 size_t dash = main_language.find(
'-');
182 if (dash != std::string::npos) {
183 main_language.erase(dash);
187 if (main_language.size() != 3) {
188 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 "
189 <<
"language code, ignoring.";
191 trak->media.header.language.code = main_language;
196 void MP4Muxer::GenerateVideoTrak(
const VideoStreamInfo* video_info,
199 InitializeTrak(video_info, trak);
203 uint32_t pixel_width = video_info->pixel_width();
204 uint32_t pixel_height = video_info->pixel_height();
205 if (pixel_width == 0 || pixel_height == 0) {
206 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
210 const double sample_aspect_ratio =
211 static_cast<double>(pixel_width) / pixel_height;
212 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
213 trak->header.height = video_info->height() * 0x10000;
215 VideoSampleEntry video;
216 video.format = CodecToFourCC(video_info->codec());
217 video.width = video_info->width();
218 video.height = video_info->height();
219 video.codec_configuration.data = video_info->codec_config();
220 if (pixel_width != 1 || pixel_height != 1) {
221 video.pixel_aspect.h_spacing = pixel_width;
222 video.pixel_aspect.v_spacing = pixel_height;
225 SampleDescription& sample_description =
226 trak->media.information.sample_table.description;
227 sample_description.type = kVideo;
228 sample_description.video_entries.push_back(video);
231 void MP4Muxer::GenerateAudioTrak(
const AudioStreamInfo* audio_info,
234 InitializeTrak(audio_info, trak);
236 trak->header.volume = 0x100;
238 AudioSampleEntry audio;
239 audio.format = CodecToFourCC(audio_info->codec());
240 switch(audio_info->codec()){
242 audio.esds.es_descriptor.set_object_type(kISO_14496_3);
243 audio.esds.es_descriptor.set_esid(track_id);
244 audio.esds.es_descriptor.set_decoder_specific_info(
245 audio_info->codec_config());
246 audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
247 audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
254 audio.ddts.extra_data = audio_info->codec_config();
255 audio.ddts.max_bitrate = audio_info->max_bitrate();
256 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
257 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
258 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
261 audio.dac3.data = audio_info->codec_config();
264 audio.dec3.data = audio_info->codec_config();
267 audio.dops.opus_identification_header = audio_info->codec_config();
274 audio.channelcount = audio_info->num_channels();
275 audio.samplesize = audio_info->sample_bits();
276 audio.samplerate = audio_info->sampling_frequency();
277 SampleTable& sample_table = trak->media.information.sample_table;
278 SampleDescription& sample_description = sample_table.description;
279 sample_description.type = kAudio;
280 sample_description.audio_entries.push_back(audio);
284 if (audio_info->codec() == kCodecOpus) {
285 sample_table.sample_group_descriptions.resize(1);
286 SampleGroupDescription& sample_group_description =
287 sample_table.sample_group_descriptions.back();
288 sample_group_description.grouping_type = FOURCC_roll;
289 sample_group_description.audio_roll_recovery_entries.resize(1);
292 const uint64_t kNanosecondsPerSecond = 1000000000ull;
293 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
294 (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
295 kNanosecondsPerSecond / 2)) /
296 kNanosecondsPerSecond;
298 sample_table.sample_to_groups.resize(1);
299 SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
300 sample_to_group.grouping_type = FOURCC_roll;
302 sample_to_group.entries.resize(1);
303 SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
305 sample_to_group_entry.sample_count = 0;
306 sample_to_group_entry.group_description_index =
307 SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
308 }
else if (audio_info->seek_preroll_ns() != 0) {
309 LOG(WARNING) <<
"Unexpected seek preroll for codec " << audio_info->codec();
314 bool MP4Muxer::GetInitRangeStartAndEnd(uint32_t* start, uint32_t* end) {
315 DCHECK(start && end);
316 size_t range_offset = 0;
317 size_t range_size = 0;
318 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
323 SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
327 bool MP4Muxer::GetIndexRangeStartAndEnd(uint32_t* start, uint32_t* end) {
328 DCHECK(start && end);
329 size_t range_offset = 0;
330 size_t range_size = 0;
331 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
336 SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
340 void MP4Muxer::FireOnMediaStartEvent() {
341 if (!muxer_listener())
344 if (streams().size() > 1) {
345 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
348 DCHECK(!streams().empty()) <<
"Media started without a stream.";
350 const uint32_t timescale = segmenter_->GetReferenceTimeScale();
351 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
352 MuxerListener::kContainerMp4);
355 void MP4Muxer::FireOnMediaEndEvent() {
356 if (!muxer_listener())
359 uint32_t init_range_start = 0;
360 uint32_t init_range_end = 0;
361 const bool has_init_range =
362 GetInitRangeStartAndEnd(&init_range_start, &init_range_end);
364 uint32_t index_range_start = 0;
365 uint32_t index_range_end = 0;
366 const bool has_index_range =
367 GetIndexRangeStartAndEnd(&index_range_start, &index_range_end);
369 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
371 const int64_t file_size =
373 if (file_size <= 0) {
374 LOG(ERROR) <<
"Invalid file size: " << file_size;
388 uint64_t MP4Muxer::IsoTimeNow() {
390 const uint64_t kIsomTimeOffset = 2082844800l;
391 return kIsomTimeOffset +
392 (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();