2 * MPEG-DASH ISO BMFF segmenter
3 * Copyright (c) 2014 Martin Storsjo
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avassert.h"
28 #include "libavutil/avutil.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/rational.h"
34 #include "libavutil/time_internal.h"
38 #include "avio_internal.h"
41 #include "os_support.h"
45 typedef struct Segment {
48 int range_length, index_length;
54 typedef struct AdaptationSet {
56 enum AVMediaType media_type;
57 AVDictionary *metadata;
58 AVRational min_frame_rate, max_frame_rate;
59 int ambiguous_frame_rate;
62 typedef struct OutputStream {
64 int ctx_inited, as_idx;
69 int64_t init_start_pos, pos;
70 int init_range_length;
71 int nb_segments, segments_size, segment_index;
73 int64_t first_pts, start_pts, max_pts;
76 char bandwidth_str[64];
81 typedef struct DASHContext {
82 const AVClass *class; /* Class for private options. */
83 char *adaptation_sets;
87 int extra_window_size;
93 OutputStream *streams;
95 int64_t last_duration;
96 int64_t total_duration;
97 char availability_start_time[100];
99 const char *single_file_name;
100 const char *init_seg_name;
101 const char *media_seg_name;
102 const char *utc_timing_url;
105 static struct codec_string {
109 { AV_CODEC_ID_VP8, "vp8" },
110 { AV_CODEC_ID_VP9, "vp9" },
111 { AV_CODEC_ID_VORBIS, "vorbis" },
112 { AV_CODEC_ID_OPUS, "opus" },
116 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
119 const AVCodecTag *tags[2] = { NULL, NULL };
123 // common Webm codecs are not part of RFC 6381
124 for (i = 0; codecs[i].id; i++)
125 if (codecs[i].id == par->codec_id) {
126 av_strlcpy(str, codecs[i].str, size);
130 // for codecs part of RFC 6381
131 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
132 tags[0] = ff_codec_movvideo_tags;
133 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
134 tags[0] = ff_codec_movaudio_tags;
138 tag = av_codec_get_tag(tags, par->codec_id);
146 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
148 tags[0] = ff_mp4_obj_type;
149 oti = av_codec_get_tag(tags, par->codec_id);
151 av_strlcatf(str, size, ".%02"PRIx32, oti);
155 if (tag == MKTAG('m', 'p', '4', 'a')) {
156 if (par->extradata_size >= 2) {
157 int aot = par->extradata[0] >> 3;
159 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
160 av_strlcatf(str, size, ".%d", aot);
162 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
163 // Unimplemented, should output ProfileLevelIndication as a decimal number
164 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
166 } else if (!strcmp(str, "avc1")) {
167 uint8_t *tmpbuf = NULL;
168 uint8_t *extradata = par->extradata;
169 int extradata_size = par->extradata_size;
172 if (extradata[0] != 1) {
174 if (avio_open_dyn_buf(&pb) < 0)
176 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
177 ffio_free_dyn_buf(&pb);
180 extradata_size = avio_close_dyn_buf(pb, &extradata);
184 if (extradata_size >= 4)
185 av_strlcatf(str, size, ".%02x%02x%02x",
186 extradata[1], extradata[2], extradata[3]);
191 static int flush_dynbuf(OutputStream *os, int *range_length)
196 return AVERROR(EINVAL);
200 av_write_frame(os->ctx, NULL);
201 avio_flush(os->ctx->pb);
204 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
206 avio_write(os->out, buffer, *range_length);
210 return avio_open_dyn_buf(&os->ctx->pb);
213 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
215 DASHContext *c = s->priv_data;
216 int ret, range_length;
218 ret = flush_dynbuf(os, &range_length);
222 os->pos = os->init_range_length = range_length;
224 ff_format_io_close(s, &os->out);
228 static void dash_free(AVFormatContext *s)
230 DASHContext *c = s->priv_data;
234 for (i = 0; i < c->nb_as; i++)
235 av_dict_free(&c->as[i].metadata);
242 for (i = 0; i < s->nb_streams; i++) {
243 OutputStream *os = &c->streams[i];
244 if (os->ctx && os->ctx_inited)
245 av_write_trailer(os->ctx);
246 if (os->ctx && os->ctx->pb)
247 ffio_free_dyn_buf(&os->ctx->pb);
248 ff_format_io_close(s, &os->out);
250 avformat_free_context(os->ctx);
251 for (j = 0; j < os->nb_segments; j++)
252 av_free(os->segments[j]);
253 av_free(os->segments);
255 av_freep(&c->streams);
258 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
260 int i, start_index = 0, start_number = 1;
261 if (c->window_size) {
262 start_index = FFMAX(os->nb_segments - c->window_size, 0);
263 start_number = FFMAX(os->segment_index - c->window_size, 1);
266 if (c->use_template) {
267 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
268 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
269 if (!c->use_timeline)
270 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
271 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
272 if (c->use_timeline) {
273 int64_t cur_time = 0;
274 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
275 for (i = start_index; i < os->nb_segments; ) {
276 Segment *seg = os->segments[i];
278 avio_printf(out, "\t\t\t\t\t\t<S ");
279 if (i == start_index || seg->time != cur_time) {
280 cur_time = seg->time;
281 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
283 avio_printf(out, "d=\"%d\" ", seg->duration);
284 while (i + repeat + 1 < os->nb_segments &&
285 os->segments[i + repeat + 1]->duration == seg->duration &&
286 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
289 avio_printf(out, "r=\"%d\" ", repeat);
290 avio_printf(out, "/>\n");
292 cur_time += (1 + repeat) * seg->duration;
294 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
296 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
297 } else if (c->single_file) {
298 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
299 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
300 avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
301 for (i = start_index; i < os->nb_segments; i++) {
302 Segment *seg = os->segments[i];
303 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
304 if (seg->index_length)
305 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
306 avio_printf(out, "/>\n");
308 avio_printf(out, "\t\t\t\t</SegmentList>\n");
310 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
311 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
312 for (i = start_index; i < os->nb_segments; i++) {
313 Segment *seg = os->segments[i];
314 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
316 avio_printf(out, "\t\t\t\t</SegmentList>\n");
320 static char *xmlescape(const char *str) {
321 int outlen = strlen(str)*3/2 + 6;
322 char *out = av_realloc(NULL, outlen + 1);
326 for (; *str; str++) {
327 if (pos + 6 > outlen) {
329 outlen = 2 * outlen + 6;
330 tmp = av_realloc(out, outlen + 1);
338 memcpy(&out[pos], "&", 5);
340 } else if (*str == '<') {
341 memcpy(&out[pos], "<", 4);
343 } else if (*str == '>') {
344 memcpy(&out[pos], ">", 4);
346 } else if (*str == '\'') {
347 memcpy(&out[pos], "'", 6);
349 } else if (*str == '\"') {
350 memcpy(&out[pos], """, 6);
360 static void write_time(AVIOContext *out, int64_t time)
362 int seconds = time / AV_TIME_BASE;
363 int fractions = time % AV_TIME_BASE;
364 int minutes = seconds / 60;
365 int hours = minutes / 60;
368 avio_printf(out, "PT");
370 avio_printf(out, "%dH", hours);
371 if (hours || minutes)
372 avio_printf(out, "%dM", minutes);
373 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
376 static void format_date_now(char *buf, int size)
378 time_t t = time(NULL);
379 struct tm *ptm, tmbuf;
380 ptm = gmtime_r(&t, &tmbuf);
382 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
387 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
389 DASHContext *c = s->priv_data;
390 AdaptationSet *as = &c->as[as_index];
391 AVDictionaryEntry *lang, *role;
394 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
395 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
396 if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
397 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
398 lang = av_dict_get(as->metadata, "language", NULL, 0);
400 avio_printf(out, " lang=\"%s\"", lang->value);
401 avio_printf(out, ">\n");
403 role = av_dict_get(as->metadata, "role", NULL, 0);
405 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
407 for (i = 0; i < s->nb_streams; i++) {
408 OutputStream *os = &c->streams[i];
410 if (os->as_idx - 1 != as_index)
413 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
414 AVStream *st = s->streams[i];
415 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
416 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
417 if (st->avg_frame_rate.num)
418 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
419 avio_printf(out, ">\n");
421 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
422 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
423 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
424 s->streams[i]->codecpar->channels);
426 output_segment_list(os, out, c);
427 avio_printf(out, "\t\t\t</Representation>\n");
429 avio_printf(out, "\t\t</AdaptationSet>\n");
434 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
436 DASHContext *c = s->priv_data;
438 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
440 return AVERROR(ENOMEM);
444 *as = &c->as[c->nb_as - 1];
445 memset(*as, 0, sizeof(**as));
446 (*as)->media_type = type;
451 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
453 DASHContext *c = s->priv_data;
454 AdaptationSet *as = &c->as[as_idx - 1];
455 OutputStream *os = &c->streams[i];
457 if (as->media_type != s->streams[i]->codecpar->codec_type) {
458 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
459 return AVERROR(EINVAL);
460 } else if (os->as_idx) {
461 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
462 return AVERROR(EINVAL);
469 static int parse_adaptation_sets(AVFormatContext *s)
471 DASHContext *c = s->priv_data;
472 const char *p = c->adaptation_sets;
473 enum { new_set, parse_id, parsing_streams } state;
477 // default: one AdaptationSet for each stream
479 for (i = 0; i < s->nb_streams; i++) {
480 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
482 snprintf(as->id, sizeof(as->id), "%d", i);
484 c->streams[i].as_idx = c->nb_as;
489 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
495 } else if (state == new_set && av_strstart(p, "id=", &p)) {
497 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
501 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
507 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
508 state = parsing_streams;
509 } else if (state == parsing_streams) {
510 AdaptationSet *as = &c->as[c->nb_as - 1];
511 char idx_str[8], *end_str;
513 n = strcspn(p, " ,");
514 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
517 // if value is "a" or "v", map all streams of that type
518 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
519 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
520 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
522 for (i = 0; i < s->nb_streams; i++) {
523 if (s->streams[i]->codecpar->codec_type != type)
526 as->media_type = s->streams[i]->codecpar->codec_type;
528 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
531 } else { // select single stream
532 i = strtol(idx_str, &end_str, 10);
533 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
534 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
535 return AVERROR(EINVAL);
537 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
539 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
540 as->media_type = s->streams[i]->codecpar->codec_type;
543 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
552 return AVERROR(EINVAL);
557 // check for unassigned streams
558 for (i = 0; i < s->nb_streams; i++) {
559 OutputStream *os = &c->streams[i];
561 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
562 return AVERROR(EINVAL);
568 static int write_manifest(AVFormatContext *s, int final)
570 DASHContext *c = s->priv_data;
572 char temp_filename[1024];
574 const char *proto = avio_find_protocol_name(s->filename);
575 int use_rename = proto && !strcmp(proto, "file");
576 static unsigned int warned_non_file = 0;
577 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
579 if (!use_rename && !warned_non_file++)
580 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
582 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
583 ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
585 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
588 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
589 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
590 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
591 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
592 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
593 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
594 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
596 avio_printf(out, "\tmediaPresentationDuration=\"");
597 write_time(out, c->total_duration);
598 avio_printf(out, "\"\n");
600 int64_t update_period = c->last_duration / AV_TIME_BASE;
602 if (c->use_template && !c->use_timeline)
604 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
605 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
606 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
607 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
609 if (c->availability_start_time[0])
610 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
611 format_date_now(now_str, sizeof(now_str));
613 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
614 if (c->window_size && c->use_template) {
615 avio_printf(out, "\ttimeShiftBufferDepth=\"");
616 write_time(out, c->last_duration * c->window_size);
617 avio_printf(out, "\"\n");
620 avio_printf(out, "\tminBufferTime=\"");
621 write_time(out, c->last_duration * 2);
622 avio_printf(out, "\">\n");
623 avio_printf(out, "\t<ProgramInformation>\n");
625 char *escaped = xmlescape(title->value);
626 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
629 avio_printf(out, "\t</ProgramInformation>\n");
631 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
632 OutputStream *os = &c->streams[0];
633 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
634 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
635 avio_printf(out, "\t<Period id=\"0\" start=\"");
636 write_time(out, start_time);
637 avio_printf(out, "\">\n");
639 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
642 for (i = 0; i < c->nb_as; i++) {
643 if ((ret = write_adaptation_set(s, out, i)) < 0)
646 avio_printf(out, "\t</Period>\n");
648 if (c->utc_timing_url)
649 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
651 avio_printf(out, "</MPD>\n");
653 ff_format_io_close(s, &out);
656 return avpriv_io_move(temp_filename, s->filename);
661 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
663 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
665 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
669 static int dash_init(AVFormatContext *s)
671 DASHContext *c = s->priv_data;
676 if (c->single_file_name)
681 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
682 ptr = strrchr(c->dirname, '/');
684 av_strlcpy(basename, &ptr[1], sizeof(basename));
687 c->dirname[0] = '\0';
688 av_strlcpy(basename, s->filename, sizeof(basename));
691 ptr = strrchr(basename, '.');
695 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
697 return AVERROR(ENOMEM);
699 if ((ret = parse_adaptation_sets(s)) < 0)
702 for (i = 0; i < s->nb_streams; i++) {
703 OutputStream *os = &c->streams[i];
704 AdaptationSet *as = &c->as[os->as_idx - 1];
705 AVFormatContext *ctx;
707 AVDictionary *opts = NULL;
710 os->bit_rate = s->streams[i]->codecpar->bit_rate;
712 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
713 " bandwidth=\"%d\"", os->bit_rate);
715 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
716 AV_LOG_ERROR : AV_LOG_WARNING;
717 av_log(s, level, "No bit rate set for stream %d\n", i);
718 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
719 return AVERROR(EINVAL);
722 // copy AdaptationSet language and role from stream metadata
723 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
724 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
726 ctx = avformat_alloc_context();
728 return AVERROR(ENOMEM);
730 // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
731 // note: os->format_name is also used as part of the mimetype of the
732 // representation, e.g. video/<format_name>
733 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
734 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
735 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
736 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
737 snprintf(os->format_name, sizeof(os->format_name), "webm");
739 snprintf(os->format_name, sizeof(os->format_name), "mp4");
741 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
743 return AVERROR_MUXER_NOT_FOUND;
745 ctx->interrupt_callback = s->interrupt_callback;
746 ctx->opaque = s->opaque;
747 ctx->io_close = s->io_close;
748 ctx->io_open = s->io_open;
750 if (!(st = avformat_new_stream(ctx, NULL)))
751 return AVERROR(ENOMEM);
752 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
753 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
754 st->time_base = s->streams[i]->time_base;
755 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
756 ctx->avoid_negative_ts = s->avoid_negative_ts;
757 ctx->flags = s->flags;
759 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
762 if (c->single_file) {
763 if (c->single_file_name)
764 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
766 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
768 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
770 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
771 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
774 os->init_start_pos = 0;
776 if (!strcmp(os->format_name, "mp4")) {
777 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
779 av_dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
780 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
781 av_dict_set_int(&opts, "dash", 1, 0);
782 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
783 av_dict_set_int(&opts, "live", 1, 0);
785 if ((ret = avformat_init_output(ctx, &opts)) < 0)
791 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
793 // Flush init segment
794 // except for mp4, since delay_moov is set and the init segment
795 // is then flushed after the first packets
796 if (strcmp(os->format_name, "mp4")) {
797 flush_init_segment(s, os);
800 s->streams[i]->time_base = st->time_base;
801 // If the muxer wants to shift timestamps, request to have them shifted
802 // already before being handed to this muxer, so we don't have mismatches
803 // between the MPD and the actual segments.
804 s->avoid_negative_ts = ctx->avoid_negative_ts;
805 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
806 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
807 if (avg_frame_rate.num > 0) {
808 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
809 as->min_frame_rate = avg_frame_rate;
810 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
811 as->max_frame_rate = avg_frame_rate;
813 as->ambiguous_frame_rate = 1;
818 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
819 os->first_pts = AV_NOPTS_VALUE;
820 os->max_pts = AV_NOPTS_VALUE;
821 os->last_dts = AV_NOPTS_VALUE;
822 os->segment_index = 1;
825 if (!c->has_video && c->min_seg_duration <= 0) {
826 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
827 return AVERROR(EINVAL);
832 static int dash_write_header(AVFormatContext *s)
834 DASHContext *c = s->priv_data;
836 for (i = 0; i < s->nb_streams; i++) {
837 OutputStream *os = &c->streams[i];
838 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
843 ret = write_manifest(s, 0);
845 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
849 static int add_segment(OutputStream *os, const char *file,
850 int64_t time, int duration,
851 int64_t start_pos, int64_t range_length,
852 int64_t index_length)
856 if (os->nb_segments >= os->segments_size) {
857 os->segments_size = (os->segments_size + 1) * 2;
858 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
859 os->segments_size)) < 0) {
860 os->segments_size = 0;
865 seg = av_mallocz(sizeof(*seg));
867 return AVERROR(ENOMEM);
868 av_strlcpy(seg->file, file, sizeof(seg->file));
870 seg->duration = duration;
871 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
872 seg->duration += seg->time;
875 seg->start_pos = start_pos;
876 seg->range_length = range_length;
877 seg->index_length = index_length;
878 os->segments[os->nb_segments++] = seg;
883 static void write_styp(AVIOContext *pb)
886 ffio_wfourcc(pb, "styp");
887 ffio_wfourcc(pb, "msdh");
888 avio_wb32(pb, 0); /* minor */
889 ffio_wfourcc(pb, "msdh");
890 ffio_wfourcc(pb, "msix");
893 static void find_index_range(AVFormatContext *s, const char *full_path,
894 int64_t pos, int *index_length)
900 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
903 if (avio_seek(pb, pos, SEEK_SET) != pos) {
904 ff_format_io_close(s, &pb);
907 ret = avio_read(pb, buf, 8);
908 ff_format_io_close(s, &pb);
911 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
913 *index_length = AV_RB32(&buf[0]);
916 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
917 AVCodecParameters *par)
921 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
924 extradata = av_malloc(par->extradata_size);
927 return AVERROR(ENOMEM);
929 memcpy(extradata, par->extradata, par->extradata_size);
931 os->ctx->streams[0]->codecpar->extradata = extradata;
932 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
934 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
939 static int dash_flush(AVFormatContext *s, int final, int stream)
941 DASHContext *c = s->priv_data;
944 const char *proto = avio_find_protocol_name(s->filename);
945 int use_rename = proto && !strcmp(proto, "file");
947 int cur_flush_segment_index = 0;
949 cur_flush_segment_index = c->streams[stream].segment_index;
951 for (i = 0; i < s->nb_streams; i++) {
952 OutputStream *os = &c->streams[i];
953 AVStream *st = s->streams[i];
954 char filename[1024] = "", full_path[1024], temp_path[1024];
955 int range_length, index_length = 0;
957 if (!os->packets_written)
960 // Flush the single stream that got a keyframe right now.
961 // Flush all audio streams as well, in sync with video keyframes,
962 // but not the other video streams.
963 if (stream >= 0 && i != stream) {
964 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
966 // Make sure we don't flush audio streams multiple times, when
967 // all video streams are flushed one at a time.
968 if (c->has_video && os->segment_index > cur_flush_segment_index)
972 if (!os->init_range_length) {
973 flush_init_segment(s, os);
976 if (!c->single_file) {
977 ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
978 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
979 snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
980 ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
983 if (!strcmp(os->format_name, "mp4"))
984 write_styp(os->ctx->pb);
986 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
989 ret = flush_dynbuf(os, &range_length);
992 os->packets_written = 0;
994 if (c->single_file) {
995 find_index_range(s, full_path, os->pos, &index_length);
997 ff_format_io_close(s, &os->out);
1000 ret = avpriv_io_move(temp_path, full_path);
1006 if (!os->bit_rate) {
1007 // calculate average bitrate of first segment
1008 int64_t bitrate = (int64_t) range_length * 8 / ((os->max_pts - os->start_pts) * av_q2d(st->time_base));
1010 os->bit_rate = bitrate;
1011 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1012 " bandwidth=\"%d\"", os->bit_rate);
1015 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1016 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
1018 os->pos += range_length;
1021 if (c->window_size || (final && c->remove_at_exit)) {
1022 for (i = 0; i < s->nb_streams; i++) {
1023 OutputStream *os = &c->streams[i];
1025 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1026 if (final && c->remove_at_exit)
1027 remove = os->nb_segments;
1029 for (j = 0; j < remove; j++) {
1030 char filename[1024];
1031 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1033 av_free(os->segments[j]);
1035 os->nb_segments -= remove;
1036 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1042 ret = write_manifest(s, final);
1046 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1048 DASHContext *c = s->priv_data;
1049 AVStream *st = s->streams[pkt->stream_index];
1050 OutputStream *os = &c->streams[pkt->stream_index];
1053 ret = update_stream_extradata(s, os, st->codecpar);
1057 // Fill in a heuristic guess of the packet duration, if none is available.
1058 // The mp4 muxer will do something similar (for the last packet in a fragment)
1059 // if nothing is set (setting it for the other packets doesn't hurt).
1060 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1061 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1062 // so that we know the exact timestamps of fragments.
1063 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1064 pkt->duration = pkt->dts - os->last_dts;
1065 os->last_dts = pkt->dts;
1067 // If forcing the stream to start at 0, the mp4 muxer will set the start
1068 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1069 if (os->first_pts == AV_NOPTS_VALUE &&
1070 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1071 pkt->pts -= pkt->dts;
1075 if (os->first_pts == AV_NOPTS_VALUE)
1076 os->first_pts = pkt->pts;
1078 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1079 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1080 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
1081 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
1082 int64_t prev_duration = c->last_duration;
1084 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1087 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1091 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1092 if (c->last_duration < prev_duration*9/10 ||
1093 c->last_duration > prev_duration*11/10) {
1094 av_log(s, AV_LOG_WARNING,
1095 "Segment durations differ too much, enable use_timeline "
1096 "and use_template, or keep a stricter keyframe interval\n");
1100 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1104 if (!os->packets_written) {
1105 // If we wrote a previous segment, adjust the start time of the segment
1106 // to the end of the previous one (which is the same as the mp4 muxer
1107 // does). This avoids gaps in the timeline.
1108 if (os->max_pts != AV_NOPTS_VALUE)
1109 os->start_pts = os->max_pts;
1111 os->start_pts = pkt->pts;
1113 if (os->max_pts == AV_NOPTS_VALUE)
1114 os->max_pts = pkt->pts + pkt->duration;
1116 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1117 os->packets_written++;
1118 return ff_write_chained(os->ctx, 0, pkt, s, 0);
1121 static int dash_write_trailer(AVFormatContext *s)
1123 DASHContext *c = s->priv_data;
1125 if (s->nb_streams > 0) {
1126 OutputStream *os = &c->streams[0];
1127 // If no segments have been written so far, try to do a crude
1128 // guess of the segment duration
1129 if (!c->last_duration)
1130 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1131 s->streams[0]->time_base,
1133 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1134 s->streams[0]->time_base,
1137 dash_flush(s, 1, -1);
1139 if (c->remove_at_exit) {
1140 char filename[1024];
1142 for (i = 0; i < s->nb_streams; i++) {
1143 OutputStream *os = &c->streams[i];
1144 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1147 unlink(s->filename);
1153 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1155 DASHContext *c = s->priv_data;
1156 OutputStream *os = &c->streams[avpkt->stream_index];
1157 AVFormatContext *oc = os->ctx;
1158 if (oc->oformat->check_bitstream) {
1160 AVPacket pkt = *avpkt;
1161 pkt.stream_index = 0;
1162 ret = oc->oformat->check_bitstream(oc, &pkt);
1164 AVStream *st = s->streams[avpkt->stream_index];
1165 AVStream *ost = oc->streams[0];
1166 st->internal->bsfcs = ost->internal->bsfcs;
1167 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1168 ost->internal->bsfcs = NULL;
1169 ost->internal->nb_bsfcs = 0;
1176 #define OFFSET(x) offsetof(DASHContext, x)
1177 #define E AV_OPT_FLAG_ENCODING_PARAM
1178 static const AVOption options[] = {
1179 { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
1180 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1181 { "extra_window_size", "number of segments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
1182 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
1183 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1184 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1185 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1186 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1187 { "single_file_name", "DASH-templated name to be used for baseURL. Implies storing all segments in one file, accessed using byte ranges", OFFSET(single_file_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
1188 { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.m4s"}, 0, 0, E },
1189 { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.m4s"}, 0, 0, E },
1190 { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
1194 static const AVClass dash_class = {
1195 .class_name = "dash muxer",
1196 .item_name = av_default_item_name,
1198 .version = LIBAVUTIL_VERSION_INT,
1201 AVOutputFormat ff_dash_muxer = {
1203 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1204 .priv_data_size = sizeof(DASHContext),
1205 .audio_codec = AV_CODEC_ID_AAC,
1206 .video_codec = AV_CODEC_ID_H264,
1207 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1209 .write_header = dash_write_header,
1210 .write_packet = dash_write_packet,
1211 .write_trailer = dash_write_trailer,
1212 .deinit = dash_free,
1213 .check_bitstream = dash_check_bitstream,
1214 .priv_class = &dash_class,