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"
39 #include "hlsplaylist.h"
42 #include "os_support.h"
46 typedef struct Segment {
49 int range_length, index_length;
55 typedef struct AdaptationSet {
57 enum AVMediaType media_type;
58 AVDictionary *metadata;
59 AVRational min_frame_rate, max_frame_rate;
60 int ambiguous_frame_rate;
63 typedef struct OutputStream {
65 int ctx_inited, as_idx;
70 int64_t init_start_pos, pos;
71 int init_range_length;
72 int nb_segments, segments_size, segment_index;
74 int64_t first_pts, start_pts, max_pts;
77 char bandwidth_str[64];
82 typedef struct DASHContext {
83 const AVClass *class; /* Class for private options. */
84 char *adaptation_sets;
88 int extra_window_size;
94 OutputStream *streams;
96 int64_t last_duration;
97 int64_t total_duration;
98 char availability_start_time[100];
100 const char *single_file_name;
101 const char *init_seg_name;
102 const char *media_seg_name;
103 const char *utc_timing_url;
104 const char *user_agent;
106 int master_playlist_created;
109 static struct codec_string {
113 { AV_CODEC_ID_VP8, "vp8" },
114 { AV_CODEC_ID_VP9, "vp9" },
115 { AV_CODEC_ID_VORBIS, "vorbis" },
116 { AV_CODEC_ID_OPUS, "opus" },
120 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
123 const AVCodecTag *tags[2] = { NULL, NULL };
127 // common Webm codecs are not part of RFC 6381
128 for (i = 0; codecs[i].id; i++)
129 if (codecs[i].id == par->codec_id) {
130 av_strlcpy(str, codecs[i].str, size);
134 // for codecs part of RFC 6381
135 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
136 tags[0] = ff_codec_movvideo_tags;
137 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
138 tags[0] = ff_codec_movaudio_tags;
142 tag = av_codec_get_tag(tags, par->codec_id);
150 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
152 tags[0] = ff_mp4_obj_type;
153 oti = av_codec_get_tag(tags, par->codec_id);
155 av_strlcatf(str, size, ".%02"PRIx32, oti);
159 if (tag == MKTAG('m', 'p', '4', 'a')) {
160 if (par->extradata_size >= 2) {
161 int aot = par->extradata[0] >> 3;
163 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
164 av_strlcatf(str, size, ".%d", aot);
166 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
167 // Unimplemented, should output ProfileLevelIndication as a decimal number
168 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
170 } else if (!strcmp(str, "avc1")) {
171 uint8_t *tmpbuf = NULL;
172 uint8_t *extradata = par->extradata;
173 int extradata_size = par->extradata_size;
176 if (extradata[0] != 1) {
178 if (avio_open_dyn_buf(&pb) < 0)
180 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
181 ffio_free_dyn_buf(&pb);
184 extradata_size = avio_close_dyn_buf(pb, &extradata);
188 if (extradata_size >= 4)
189 av_strlcatf(str, size, ".%02x%02x%02x",
190 extradata[1], extradata[2], extradata[3]);
195 static int flush_dynbuf(OutputStream *os, int *range_length)
200 return AVERROR(EINVAL);
204 av_write_frame(os->ctx, NULL);
205 avio_flush(os->ctx->pb);
208 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
210 avio_write(os->out, buffer, *range_length);
214 return avio_open_dyn_buf(&os->ctx->pb);
217 static void set_http_options(AVDictionary **options, DASHContext *c)
220 av_dict_set(options, "user_agent", c->user_agent, 0);
223 static void get_hls_playlist_name(char *playlist_name, int string_size,
224 const char *base_url, int id) {
226 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
228 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
231 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
233 DASHContext *c = s->priv_data;
234 int ret, range_length;
236 ret = flush_dynbuf(os, &range_length);
240 os->pos = os->init_range_length = range_length;
242 ff_format_io_close(s, &os->out);
246 static void dash_free(AVFormatContext *s)
248 DASHContext *c = s->priv_data;
252 for (i = 0; i < c->nb_as; i++)
253 av_dict_free(&c->as[i].metadata);
260 for (i = 0; i < s->nb_streams; i++) {
261 OutputStream *os = &c->streams[i];
262 if (os->ctx && os->ctx_inited)
263 av_write_trailer(os->ctx);
264 if (os->ctx && os->ctx->pb)
265 ffio_free_dyn_buf(&os->ctx->pb);
266 ff_format_io_close(s, &os->out);
268 avformat_free_context(os->ctx);
269 for (j = 0; j < os->nb_segments; j++)
270 av_free(os->segments[j]);
271 av_free(os->segments);
273 av_freep(&c->streams);
276 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c,
277 int representation_id, int final)
279 int i, start_index = 0, start_number = 1;
280 if (c->window_size) {
281 start_index = FFMAX(os->nb_segments - c->window_size, 0);
282 start_number = FFMAX(os->segment_index - c->window_size, 1);
285 if (c->use_template) {
286 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
287 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
288 if (!c->use_timeline)
289 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
290 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
291 if (c->use_timeline) {
292 int64_t cur_time = 0;
293 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
294 for (i = start_index; i < os->nb_segments; ) {
295 Segment *seg = os->segments[i];
297 avio_printf(out, "\t\t\t\t\t\t<S ");
298 if (i == start_index || seg->time != cur_time) {
299 cur_time = seg->time;
300 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
302 avio_printf(out, "d=\"%d\" ", seg->duration);
303 while (i + repeat + 1 < os->nb_segments &&
304 os->segments[i + repeat + 1]->duration == seg->duration &&
305 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
308 avio_printf(out, "r=\"%d\" ", repeat);
309 avio_printf(out, "/>\n");
311 cur_time += (1 + repeat) * seg->duration;
313 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
315 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
316 } else if (c->single_file) {
317 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
318 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
319 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);
320 for (i = start_index; i < os->nb_segments; i++) {
321 Segment *seg = os->segments[i];
322 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
323 if (seg->index_length)
324 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
325 avio_printf(out, "/>\n");
327 avio_printf(out, "\t\t\t\t</SegmentList>\n");
329 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
330 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
331 for (i = start_index; i < os->nb_segments; i++) {
332 Segment *seg = os->segments[i];
333 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
335 avio_printf(out, "\t\t\t\t</SegmentList>\n");
337 if (c->hls_playlist && start_index < os->nb_segments)
339 int timescale = os->ctx->streams[0]->time_base.den;
340 char temp_filename_hls[1024];
341 char filename_hls[1024];
342 AVIOContext *out_hls = NULL;
343 AVDictionary *http_opts = NULL;
344 int target_duration = 0;
346 const char *proto = avio_find_protocol_name(c->dirname);
347 int use_rename = proto && !strcmp(proto, "file");
349 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
350 c->dirname, representation_id);
352 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
354 set_http_options(&http_opts, c);
355 avio_open2(&out_hls, temp_filename_hls, AVIO_FLAG_WRITE, NULL, &http_opts);
356 av_dict_free(&http_opts);
357 for (i = start_index; i < os->nb_segments; i++) {
358 Segment *seg = os->segments[i];
359 double duration = (double) seg->duration / timescale;
360 if (target_duration <= duration)
361 target_duration = lrint(duration);
364 ff_hls_write_playlist_header(out_hls, 6, -1, target_duration,
365 start_number, PLAYLIST_TYPE_NONE);
367 ff_hls_write_init_file(out_hls, os->initfile, c->single_file,
368 os->init_range_length, os->init_start_pos);
370 for (i = start_index; i < os->nb_segments; i++) {
371 Segment *seg = os->segments[i];
372 ret = ff_hls_write_file_entry(out_hls, 0, c->single_file,
373 (double) seg->duration / timescale, 0,
374 seg->range_length, seg->start_pos, NULL,
375 c->single_file ? os->initfile : seg->file,
378 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
383 ff_hls_write_end_list(out_hls);
387 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
388 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
394 static char *xmlescape(const char *str) {
395 int outlen = strlen(str)*3/2 + 6;
396 char *out = av_realloc(NULL, outlen + 1);
400 for (; *str; str++) {
401 if (pos + 6 > outlen) {
403 outlen = 2 * outlen + 6;
404 tmp = av_realloc(out, outlen + 1);
412 memcpy(&out[pos], "&", 5);
414 } else if (*str == '<') {
415 memcpy(&out[pos], "<", 4);
417 } else if (*str == '>') {
418 memcpy(&out[pos], ">", 4);
420 } else if (*str == '\'') {
421 memcpy(&out[pos], "'", 6);
423 } else if (*str == '\"') {
424 memcpy(&out[pos], """, 6);
434 static void write_time(AVIOContext *out, int64_t time)
436 int seconds = time / AV_TIME_BASE;
437 int fractions = time % AV_TIME_BASE;
438 int minutes = seconds / 60;
439 int hours = minutes / 60;
442 avio_printf(out, "PT");
444 avio_printf(out, "%dH", hours);
445 if (hours || minutes)
446 avio_printf(out, "%dM", minutes);
447 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
450 static void format_date_now(char *buf, int size)
452 time_t t = time(NULL);
453 struct tm *ptm, tmbuf;
454 ptm = gmtime_r(&t, &tmbuf);
456 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
461 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
464 DASHContext *c = s->priv_data;
465 AdaptationSet *as = &c->as[as_index];
466 AVDictionaryEntry *lang, *role;
469 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
470 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
471 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)
472 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
473 lang = av_dict_get(as->metadata, "language", NULL, 0);
475 avio_printf(out, " lang=\"%s\"", lang->value);
476 avio_printf(out, ">\n");
478 role = av_dict_get(as->metadata, "role", NULL, 0);
480 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
482 for (i = 0; i < s->nb_streams; i++) {
483 OutputStream *os = &c->streams[i];
485 if (os->as_idx - 1 != as_index)
488 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
489 AVStream *st = s->streams[i];
490 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
491 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
492 if (st->avg_frame_rate.num)
493 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
494 avio_printf(out, ">\n");
496 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
497 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
498 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
499 s->streams[i]->codecpar->channels);
501 output_segment_list(os, out, c, i, final);
502 avio_printf(out, "\t\t\t</Representation>\n");
504 avio_printf(out, "\t\t</AdaptationSet>\n");
509 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
511 DASHContext *c = s->priv_data;
513 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
515 return AVERROR(ENOMEM);
519 *as = &c->as[c->nb_as - 1];
520 memset(*as, 0, sizeof(**as));
521 (*as)->media_type = type;
526 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
528 DASHContext *c = s->priv_data;
529 AdaptationSet *as = &c->as[as_idx - 1];
530 OutputStream *os = &c->streams[i];
532 if (as->media_type != s->streams[i]->codecpar->codec_type) {
533 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
534 return AVERROR(EINVAL);
535 } else if (os->as_idx) {
536 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
537 return AVERROR(EINVAL);
544 static int parse_adaptation_sets(AVFormatContext *s)
546 DASHContext *c = s->priv_data;
547 const char *p = c->adaptation_sets;
548 enum { new_set, parse_id, parsing_streams } state;
552 // default: one AdaptationSet for each stream
554 for (i = 0; i < s->nb_streams; i++) {
555 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
557 snprintf(as->id, sizeof(as->id), "%d", i);
559 c->streams[i].as_idx = c->nb_as;
564 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
570 } else if (state == new_set && av_strstart(p, "id=", &p)) {
572 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
576 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
582 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
583 state = parsing_streams;
584 } else if (state == parsing_streams) {
585 AdaptationSet *as = &c->as[c->nb_as - 1];
586 char idx_str[8], *end_str;
588 n = strcspn(p, " ,");
589 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
592 // if value is "a" or "v", map all streams of that type
593 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
594 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
595 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
597 for (i = 0; i < s->nb_streams; i++) {
598 if (s->streams[i]->codecpar->codec_type != type)
601 as->media_type = s->streams[i]->codecpar->codec_type;
603 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
606 } else { // select single stream
607 i = strtol(idx_str, &end_str, 10);
608 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
609 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
610 return AVERROR(EINVAL);
612 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
614 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
615 as->media_type = s->streams[i]->codecpar->codec_type;
618 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
627 return AVERROR(EINVAL);
632 // check for unassigned streams
633 for (i = 0; i < s->nb_streams; i++) {
634 OutputStream *os = &c->streams[i];
636 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
637 return AVERROR(EINVAL);
643 static int write_manifest(AVFormatContext *s, int final)
645 DASHContext *c = s->priv_data;
647 char temp_filename[1024];
649 const char *proto = avio_find_protocol_name(s->filename);
650 int use_rename = proto && !strcmp(proto, "file");
651 static unsigned int warned_non_file = 0;
652 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
653 AVDictionary *opts = NULL;
655 if (!use_rename && !warned_non_file++)
656 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
658 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
659 set_http_options(&opts, c);
660 ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &opts);
662 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
666 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
667 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
668 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
669 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
670 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
671 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
672 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
674 avio_printf(out, "\tmediaPresentationDuration=\"");
675 write_time(out, c->total_duration);
676 avio_printf(out, "\"\n");
678 int64_t update_period = c->last_duration / AV_TIME_BASE;
680 if (c->use_template && !c->use_timeline)
682 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
683 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
684 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
685 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
687 if (c->availability_start_time[0])
688 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
689 format_date_now(now_str, sizeof(now_str));
691 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
692 if (c->window_size && c->use_template) {
693 avio_printf(out, "\ttimeShiftBufferDepth=\"");
694 write_time(out, c->last_duration * c->window_size);
695 avio_printf(out, "\"\n");
698 avio_printf(out, "\tminBufferTime=\"");
699 write_time(out, c->last_duration * 2);
700 avio_printf(out, "\">\n");
701 avio_printf(out, "\t<ProgramInformation>\n");
703 char *escaped = xmlescape(title->value);
704 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
707 avio_printf(out, "\t</ProgramInformation>\n");
709 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
710 OutputStream *os = &c->streams[0];
711 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
712 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
713 avio_printf(out, "\t<Period id=\"0\" start=\"");
714 write_time(out, start_time);
715 avio_printf(out, "\">\n");
717 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
720 for (i = 0; i < c->nb_as; i++) {
721 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
724 avio_printf(out, "\t</Period>\n");
726 if (c->utc_timing_url)
727 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
729 avio_printf(out, "</MPD>\n");
731 ff_format_io_close(s, &out);
734 if ((ret = avpriv_io_move(temp_filename, s->filename)) < 0)
738 if (c->hls_playlist && !c->master_playlist_created) {
739 char filename_hls[1024];
742 snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
744 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
746 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
748 set_http_options(&opts, c);
749 ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
751 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
756 ff_hls_write_playlist_version(out, 6);
758 for (i = 0; i < s->nb_streams; i++) {
759 char playlist_file[64];
760 AVStream *st = s->streams[i];
761 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
762 ff_hls_write_stream_info(st, out, st->codecpar->bit_rate,
763 playlist_file, NULL);
767 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
769 c->master_playlist_created = 1;
775 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
777 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
779 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
783 static int dash_init(AVFormatContext *s)
785 DASHContext *c = s->priv_data;
790 if (c->single_file_name)
795 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
796 ptr = strrchr(c->dirname, '/');
798 av_strlcpy(basename, &ptr[1], sizeof(basename));
801 c->dirname[0] = '\0';
802 av_strlcpy(basename, s->filename, sizeof(basename));
805 ptr = strrchr(basename, '.');
809 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
811 return AVERROR(ENOMEM);
813 if ((ret = parse_adaptation_sets(s)) < 0)
816 for (i = 0; i < s->nb_streams; i++) {
817 OutputStream *os = &c->streams[i];
818 AdaptationSet *as = &c->as[os->as_idx - 1];
819 AVFormatContext *ctx;
821 AVDictionary *opts = NULL;
824 os->bit_rate = s->streams[i]->codecpar->bit_rate;
826 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
827 " bandwidth=\"%d\"", os->bit_rate);
829 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
830 AV_LOG_ERROR : AV_LOG_WARNING;
831 av_log(s, level, "No bit rate set for stream %d\n", i);
832 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
833 return AVERROR(EINVAL);
836 // copy AdaptationSet language and role from stream metadata
837 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
838 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
840 ctx = avformat_alloc_context();
842 return AVERROR(ENOMEM);
844 // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
845 // note: os->format_name is also used as part of the mimetype of the
846 // representation, e.g. video/<format_name>
847 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
848 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
849 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
850 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
851 snprintf(os->format_name, sizeof(os->format_name), "webm");
853 snprintf(os->format_name, sizeof(os->format_name), "mp4");
855 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
857 return AVERROR_MUXER_NOT_FOUND;
859 ctx->interrupt_callback = s->interrupt_callback;
860 ctx->opaque = s->opaque;
861 ctx->io_close = s->io_close;
862 ctx->io_open = s->io_open;
864 if (!(st = avformat_new_stream(ctx, NULL)))
865 return AVERROR(ENOMEM);
866 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
867 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
868 st->time_base = s->streams[i]->time_base;
869 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
870 ctx->avoid_negative_ts = s->avoid_negative_ts;
871 ctx->flags = s->flags;
873 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
876 if (c->single_file) {
877 if (c->single_file_name)
878 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
880 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
882 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
884 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
885 set_http_options(&opts, c);
886 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
890 os->init_start_pos = 0;
892 if (!strcmp(os->format_name, "mp4")) {
893 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
895 av_dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
896 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
897 av_dict_set_int(&opts, "dash", 1, 0);
898 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
899 av_dict_set_int(&opts, "live", 1, 0);
901 if ((ret = avformat_init_output(ctx, &opts)) < 0)
907 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
909 // Flush init segment
910 // except for mp4, since delay_moov is set and the init segment
911 // is then flushed after the first packets
912 if (strcmp(os->format_name, "mp4")) {
913 flush_init_segment(s, os);
916 s->streams[i]->time_base = st->time_base;
917 // If the muxer wants to shift timestamps, request to have them shifted
918 // already before being handed to this muxer, so we don't have mismatches
919 // between the MPD and the actual segments.
920 s->avoid_negative_ts = ctx->avoid_negative_ts;
921 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
922 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
923 if (avg_frame_rate.num > 0) {
924 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
925 as->min_frame_rate = avg_frame_rate;
926 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
927 as->max_frame_rate = avg_frame_rate;
929 as->ambiguous_frame_rate = 1;
934 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
935 os->first_pts = AV_NOPTS_VALUE;
936 os->max_pts = AV_NOPTS_VALUE;
937 os->last_dts = AV_NOPTS_VALUE;
938 os->segment_index = 1;
941 if (!c->has_video && c->min_seg_duration <= 0) {
942 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
943 return AVERROR(EINVAL);
948 static int dash_write_header(AVFormatContext *s)
950 DASHContext *c = s->priv_data;
952 for (i = 0; i < s->nb_streams; i++) {
953 OutputStream *os = &c->streams[i];
954 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
959 ret = write_manifest(s, 0);
961 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
965 static int add_segment(OutputStream *os, const char *file,
966 int64_t time, int duration,
967 int64_t start_pos, int64_t range_length,
968 int64_t index_length)
972 if (os->nb_segments >= os->segments_size) {
973 os->segments_size = (os->segments_size + 1) * 2;
974 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
975 os->segments_size)) < 0) {
976 os->segments_size = 0;
981 seg = av_mallocz(sizeof(*seg));
983 return AVERROR(ENOMEM);
984 av_strlcpy(seg->file, file, sizeof(seg->file));
986 seg->duration = duration;
987 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
988 seg->duration += seg->time;
991 seg->start_pos = start_pos;
992 seg->range_length = range_length;
993 seg->index_length = index_length;
994 os->segments[os->nb_segments++] = seg;
999 static void write_styp(AVIOContext *pb)
1002 ffio_wfourcc(pb, "styp");
1003 ffio_wfourcc(pb, "msdh");
1004 avio_wb32(pb, 0); /* minor */
1005 ffio_wfourcc(pb, "msdh");
1006 ffio_wfourcc(pb, "msix");
1009 static void find_index_range(AVFormatContext *s, const char *full_path,
1010 int64_t pos, int *index_length)
1016 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1019 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1020 ff_format_io_close(s, &pb);
1023 ret = avio_read(pb, buf, 8);
1024 ff_format_io_close(s, &pb);
1027 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1029 *index_length = AV_RB32(&buf[0]);
1032 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1033 AVCodecParameters *par)
1037 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1040 extradata = av_malloc(par->extradata_size);
1043 return AVERROR(ENOMEM);
1045 memcpy(extradata, par->extradata, par->extradata_size);
1047 os->ctx->streams[0]->codecpar->extradata = extradata;
1048 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1050 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
1055 static int dash_flush(AVFormatContext *s, int final, int stream)
1057 DASHContext *c = s->priv_data;
1060 const char *proto = avio_find_protocol_name(s->filename);
1061 int use_rename = proto && !strcmp(proto, "file");
1063 int cur_flush_segment_index = 0;
1065 cur_flush_segment_index = c->streams[stream].segment_index;
1067 for (i = 0; i < s->nb_streams; i++) {
1068 OutputStream *os = &c->streams[i];
1069 AVStream *st = s->streams[i];
1070 char filename[1024] = "", full_path[1024], temp_path[1024];
1071 int range_length, index_length = 0;
1073 if (!os->packets_written)
1076 // Flush the single stream that got a keyframe right now.
1077 // Flush all audio streams as well, in sync with video keyframes,
1078 // but not the other video streams.
1079 if (stream >= 0 && i != stream) {
1080 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1082 // Make sure we don't flush audio streams multiple times, when
1083 // all video streams are flushed one at a time.
1084 if (c->has_video && os->segment_index > cur_flush_segment_index)
1088 if (!os->init_range_length) {
1089 flush_init_segment(s, os);
1092 if (!c->single_file) {
1093 AVDictionary *opts = NULL;
1094 ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
1095 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
1096 snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
1097 set_http_options(&opts, c);
1098 ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, &opts);
1101 av_dict_free(&opts);
1102 if (!strcmp(os->format_name, "mp4"))
1103 write_styp(os->ctx->pb);
1105 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
1108 ret = flush_dynbuf(os, &range_length);
1111 os->packets_written = 0;
1113 if (c->single_file) {
1114 find_index_range(s, full_path, os->pos, &index_length);
1116 ff_format_io_close(s, &os->out);
1119 ret = avpriv_io_move(temp_path, full_path);
1125 if (!os->bit_rate) {
1126 // calculate average bitrate of first segment
1127 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1131 os->bit_rate = bitrate;
1132 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1133 " bandwidth=\"%d\"", os->bit_rate);
1136 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1137 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
1139 os->pos += range_length;
1142 if (c->window_size || (final && c->remove_at_exit)) {
1143 for (i = 0; i < s->nb_streams; i++) {
1144 OutputStream *os = &c->streams[i];
1146 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1147 if (final && c->remove_at_exit)
1148 remove = os->nb_segments;
1150 for (j = 0; j < remove; j++) {
1151 char filename[1024];
1152 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1154 av_free(os->segments[j]);
1156 os->nb_segments -= remove;
1157 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1163 ret = write_manifest(s, final);
1167 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1169 DASHContext *c = s->priv_data;
1170 AVStream *st = s->streams[pkt->stream_index];
1171 OutputStream *os = &c->streams[pkt->stream_index];
1174 ret = update_stream_extradata(s, os, st->codecpar);
1178 // Fill in a heuristic guess of the packet duration, if none is available.
1179 // The mp4 muxer will do something similar (for the last packet in a fragment)
1180 // if nothing is set (setting it for the other packets doesn't hurt).
1181 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1182 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1183 // so that we know the exact timestamps of fragments.
1184 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1185 pkt->duration = pkt->dts - os->last_dts;
1186 os->last_dts = pkt->dts;
1188 // If forcing the stream to start at 0, the mp4 muxer will set the start
1189 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1190 if (os->first_pts == AV_NOPTS_VALUE &&
1191 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1192 pkt->pts -= pkt->dts;
1196 if (os->first_pts == AV_NOPTS_VALUE)
1197 os->first_pts = pkt->pts;
1199 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1200 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1201 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
1202 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
1203 int64_t prev_duration = c->last_duration;
1205 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1208 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1212 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1213 if (c->last_duration < prev_duration*9/10 ||
1214 c->last_duration > prev_duration*11/10) {
1215 av_log(s, AV_LOG_WARNING,
1216 "Segment durations differ too much, enable use_timeline "
1217 "and use_template, or keep a stricter keyframe interval\n");
1221 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1225 if (!os->packets_written) {
1226 // If we wrote a previous segment, adjust the start time of the segment
1227 // to the end of the previous one (which is the same as the mp4 muxer
1228 // does). This avoids gaps in the timeline.
1229 if (os->max_pts != AV_NOPTS_VALUE)
1230 os->start_pts = os->max_pts;
1232 os->start_pts = pkt->pts;
1234 if (os->max_pts == AV_NOPTS_VALUE)
1235 os->max_pts = pkt->pts + pkt->duration;
1237 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1238 os->packets_written++;
1239 return ff_write_chained(os->ctx, 0, pkt, s, 0);
1242 static int dash_write_trailer(AVFormatContext *s)
1244 DASHContext *c = s->priv_data;
1246 if (s->nb_streams > 0) {
1247 OutputStream *os = &c->streams[0];
1248 // If no segments have been written so far, try to do a crude
1249 // guess of the segment duration
1250 if (!c->last_duration)
1251 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1252 s->streams[0]->time_base,
1254 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1255 s->streams[0]->time_base,
1258 dash_flush(s, 1, -1);
1260 if (c->remove_at_exit) {
1261 char filename[1024];
1263 for (i = 0; i < s->nb_streams; i++) {
1264 OutputStream *os = &c->streams[i];
1265 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1268 unlink(s->filename);
1274 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1276 DASHContext *c = s->priv_data;
1277 OutputStream *os = &c->streams[avpkt->stream_index];
1278 AVFormatContext *oc = os->ctx;
1279 if (oc->oformat->check_bitstream) {
1281 AVPacket pkt = *avpkt;
1282 pkt.stream_index = 0;
1283 ret = oc->oformat->check_bitstream(oc, &pkt);
1285 AVStream *st = s->streams[avpkt->stream_index];
1286 AVStream *ost = oc->streams[0];
1287 st->internal->bsfcs = ost->internal->bsfcs;
1288 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1289 ost->internal->bsfcs = NULL;
1290 ost->internal->nb_bsfcs = 0;
1297 #define OFFSET(x) offsetof(DASHContext, x)
1298 #define E AV_OPT_FLAG_ENCODING_PARAM
1299 static const AVOption options[] = {
1300 { "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 },
1301 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1302 { "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 },
1303 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1304 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1305 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1306 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1307 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1308 { "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 },
1309 { "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 },
1310 { "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 },
1311 { "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 },
1312 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1313 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1317 static const AVClass dash_class = {
1318 .class_name = "dash muxer",
1319 .item_name = av_default_item_name,
1321 .version = LIBAVUTIL_VERSION_INT,
1324 AVOutputFormat ff_dash_muxer = {
1326 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1327 .extensions = "mpd",
1328 .priv_data_size = sizeof(DASHContext),
1329 .audio_codec = AV_CODEC_ID_AAC,
1330 .video_codec = AV_CODEC_ID_H264,
1331 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1333 .write_header = dash_write_header,
1334 .write_packet = dash_write_packet,
1335 .write_trailer = dash_write_trailer,
1336 .deinit = dash_free,
1337 .check_bitstream = dash_check_bitstream,
1338 .priv_class = &dash_class,