2 * WebM DASH Manifest XML muxer
3 * Copyright (c) 2014 Vignesh Venkatasubramanian
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
23 * WebM DASH Specification:
24 * https://sites.google.com/a/webmproject.org/wiki/adaptive-streaming/webm-dash-specification
25 * ISO DASH Specification:
26 * http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
34 #include "avio_internal.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/time_internal.h"
42 typedef struct AdaptationSet {
48 typedef struct WebMDashMuxContext {
50 char *adaptation_sets;
53 int representation_id;
55 int chunk_start_index;
58 double time_shift_buffer_depth;
62 static const char *get_codec_name(int codec_id)
69 case AV_CODEC_ID_VORBIS:
71 case AV_CODEC_ID_OPUS:
77 static double get_duration(AVFormatContext *s)
81 for (i = 0; i < s->nb_streams; i++) {
82 AVDictionaryEntry *duration = av_dict_get(s->streams[i]->metadata,
84 if (!duration || atof(duration->value) < 0) continue;
85 if (atof(duration->value) > max) max = atof(duration->value);
90 static void write_header(AVFormatContext *s)
92 WebMDashMuxContext *w = s->priv_data;
93 double min_buffer_time = 1.0;
94 avio_printf(s->pb, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
95 avio_printf(s->pb, "<MPD\n");
96 avio_printf(s->pb, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
97 avio_printf(s->pb, " xmlns=\"urn:mpeg:DASH:schema:MPD:2011\"\n");
98 avio_printf(s->pb, " xsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011\"\n");
99 avio_printf(s->pb, " type=\"%s\"\n", w->is_live ? "dynamic" : "static");
101 avio_printf(s->pb, " mediaPresentationDuration=\"PT%gS\"\n",
104 avio_printf(s->pb, " minBufferTime=\"PT%gS\"\n", min_buffer_time);
105 avio_printf(s->pb, " profiles=\"%s\"%s",
106 w->is_live ? "urn:mpeg:dash:profile:isoff-live:2011" : "urn:webm:dash:profile:webm-on-demand:2012",
107 w->is_live ? "\n" : ">\n");
109 time_t local_time = time(NULL);
110 struct tm gmt_buffer;
111 struct tm *gmt = gmtime_r(&local_time, &gmt_buffer);
112 char *gmt_iso = av_malloc(21);
113 strftime(gmt_iso, 21, "%Y-%m-%dT%H:%M:%SZ", gmt);
115 av_strlcpy(gmt_iso, "", 1);
117 avio_printf(s->pb, " availabilityStartTime=\"%s\"\n", gmt_iso);
118 avio_printf(s->pb, " timeShiftBufferDepth=\"PT%gS\"", w->time_shift_buffer_depth);
119 avio_printf(s->pb, ">\n");
120 avio_printf(s->pb, "<UTCTiming\n");
121 avio_printf(s->pb, " schemeIdUri=\"%s\"\n",
122 w->utc_timing_url ? "urn:mpeg:dash:utc:http-iso:2014" : "urn:mpeg:dash:utc:direct:2012");
123 avio_printf(s->pb, " value=\"%s\"/>\n",
124 w->utc_timing_url ? w->utc_timing_url : gmt_iso);
129 static void write_footer(AVFormatContext *s)
131 avio_printf(s->pb, "</MPD>\n");
134 static int subsegment_alignment(AVFormatContext *s, AdaptationSet *as) {
136 AVDictionaryEntry *gold = av_dict_get(s->streams[as->streams[0]]->metadata,
137 CUE_TIMESTAMPS, NULL, 0);
139 for (i = 1; i < as->nb_streams; i++) {
140 AVDictionaryEntry *ts = av_dict_get(s->streams[as->streams[i]]->metadata,
141 CUE_TIMESTAMPS, NULL, 0);
142 if (!ts || strncmp(gold->value, ts->value, strlen(gold->value))) return 0;
147 static int bitstream_switching(AVFormatContext *s, AdaptationSet *as) {
149 AVDictionaryEntry *gold_track_num = av_dict_get(s->streams[as->streams[0]]->metadata,
150 TRACK_NUMBER, NULL, 0);
151 AVCodecContext *gold_codec = s->streams[as->streams[0]]->codec;
152 if (!gold_track_num) return 0;
153 for (i = 1; i < as->nb_streams; i++) {
154 AVDictionaryEntry *track_num = av_dict_get(s->streams[as->streams[i]]->metadata,
155 TRACK_NUMBER, NULL, 0);
156 AVCodecContext *codec = s->streams[as->streams[i]]->codec;
158 strncmp(gold_track_num->value, track_num->value, strlen(gold_track_num->value)) ||
159 gold_codec->codec_id != codec->codec_id ||
160 gold_codec->extradata_size != codec->extradata_size ||
161 memcmp(gold_codec->extradata, codec->extradata, codec->extradata_size)) {
169 * Writes a Representation within an Adaptation Set. Returns 0 on success and
172 static int write_representation(AVFormatContext *s, AVStream *stream, char *id,
173 int output_width, int output_height,
174 int output_sample_rate) {
175 WebMDashMuxContext *w = s->priv_data;
176 AVDictionaryEntry *irange = av_dict_get(stream->metadata, INITIALIZATION_RANGE, NULL, 0);
177 AVDictionaryEntry *cues_start = av_dict_get(stream->metadata, CUES_START, NULL, 0);
178 AVDictionaryEntry *cues_end = av_dict_get(stream->metadata, CUES_END, NULL, 0);
179 AVDictionaryEntry *filename = av_dict_get(stream->metadata, FILENAME, NULL, 0);
180 AVDictionaryEntry *bandwidth = av_dict_get(stream->metadata, BANDWIDTH, NULL, 0);
181 if ((w->is_live && (!filename)) ||
182 (!w->is_live && (!irange || !cues_start || !cues_end || !filename || !bandwidth))) {
185 avio_printf(s->pb, "<Representation id=\"%s\"", id);
186 // FIXME: For live, This should be obtained from the input file or as an AVOption.
187 avio_printf(s->pb, " bandwidth=\"%s\"",
188 w->is_live ? (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO ? "128000" : "1000000") : bandwidth->value);
189 if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_width)
190 avio_printf(s->pb, " width=\"%d\"", stream->codec->width);
191 if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_height)
192 avio_printf(s->pb, " height=\"%d\"", stream->codec->height);
193 if (stream->codec->codec_type = AVMEDIA_TYPE_AUDIO && output_sample_rate)
194 avio_printf(s->pb, " audioSamplingRate=\"%d\"", stream->codec->sample_rate);
196 // For live streams, Codec and Mime Type always go in the Representation tag.
197 avio_printf(s->pb, " codecs=\"%s\"", get_codec_name(stream->codec->codec_id));
198 avio_printf(s->pb, " mimeType=\"%s/webm\"",
199 stream->codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
200 // For live streams, subsegments always start with key frames. So this
202 avio_printf(s->pb, " startsWithSAP=\"1\"");
203 avio_printf(s->pb, ">");
205 avio_printf(s->pb, ">\n");
206 avio_printf(s->pb, "<BaseURL>%s</BaseURL>\n", filename->value);
207 avio_printf(s->pb, "<SegmentBase\n");
208 avio_printf(s->pb, " indexRange=\"%s-%s\">\n", cues_start->value, cues_end->value);
209 avio_printf(s->pb, "<Initialization\n");
210 avio_printf(s->pb, " range=\"0-%s\" />\n", irange->value);
211 avio_printf(s->pb, "</SegmentBase>\n");
213 avio_printf(s->pb, "</Representation>\n");
218 * Checks if width of all streams are the same. Returns 1 if true, 0 otherwise.
220 static int check_matching_width(AVFormatContext *s, AdaptationSet *as) {
222 if (as->nb_streams < 2) return 1;
223 first_width = s->streams[as->streams[0]]->codec->width;
224 for (i = 1; i < as->nb_streams; i++)
225 if (first_width != s->streams[as->streams[i]]->codec->width)
231 * Checks if height of all streams are the same. Returns 1 if true, 0 otherwise.
233 static int check_matching_height(AVFormatContext *s, AdaptationSet *as) {
235 if (as->nb_streams < 2) return 1;
236 first_height = s->streams[as->streams[0]]->codec->height;
237 for (i = 1; i < as->nb_streams; i++)
238 if (first_height != s->streams[as->streams[i]]->codec->height)
244 * Checks if sample rate of all streams are the same. Returns 1 if true, 0 otherwise.
246 static int check_matching_sample_rate(AVFormatContext *s, AdaptationSet *as) {
247 int first_sample_rate, i;
248 if (as->nb_streams < 2) return 1;
249 first_sample_rate = s->streams[as->streams[0]]->codec->sample_rate;
250 for (i = 1; i < as->nb_streams; i++)
251 if (first_sample_rate != s->streams[as->streams[i]]->codec->sample_rate)
257 * Parses a live header filename and computes the representation id,
258 * initialization pattern and the media pattern. Pass NULL if you don't want to
259 * compute any of those 3. Returns 0 on success and non-zero on failure.
261 * Name of the header file should conform to the following pattern:
262 * <file_description>_<representation_id>.hdr where <file_description> can be
263 * anything. The chunks should be named according to the following pattern:
264 * <file_description>_<representation_id>_<chunk_number>.chk
266 static int parse_filename(char *filename, char **representation_id,
267 char **initialization_pattern, char **media_pattern) {
268 char *underscore_pos = NULL;
269 char *period_pos = NULL;
270 char *temp_pos = NULL;
271 char *filename_str = av_strdup(filename);
272 if (!filename_str) return AVERROR(ENOMEM);
273 temp_pos = av_stristr(filename_str, "_");
275 underscore_pos = temp_pos + 1;
276 temp_pos = av_stristr(temp_pos + 1, "_");
278 if (!underscore_pos) return -1;
279 period_pos = av_stristr(underscore_pos, ".");
280 if (!period_pos) return -1;
281 *(underscore_pos - 1) = 0;
282 if (representation_id) {
283 *representation_id = av_malloc(period_pos - underscore_pos + 1);
284 if (!(*representation_id)) return AVERROR(ENOMEM);
285 av_strlcpy(*representation_id, underscore_pos, period_pos - underscore_pos + 1);
287 if (initialization_pattern) {
288 *initialization_pattern = av_asprintf("%s_$RepresentationID$.hdr",
290 if (!(*initialization_pattern)) return AVERROR(ENOMEM);
293 *media_pattern = av_asprintf("%s_$RepresentationID$_$Number$.chk",
295 if (!(*media_pattern)) return AVERROR(ENOMEM);
297 av_free(filename_str);
302 * Writes an Adaptation Set. Returns 0 on success and < 0 on failure.
304 static int write_adaptation_set(AVFormatContext *s, int as_index)
306 WebMDashMuxContext *w = s->priv_data;
307 AdaptationSet *as = &w->as[as_index];
308 AVCodecContext *codec = s->streams[as->streams[0]]->codec;
309 AVDictionaryEntry *lang;
311 static const char boolean[2][6] = { "false", "true" };
312 int subsegmentStartsWithSAP = 1;
314 // Width, Height and Sample Rate will go in the AdaptationSet tag if they
315 // are the same for all contained Representations. otherwise, they will go
316 // on their respective Representation tag. For live streams, they always go
317 // in the Representation tag.
318 int width_in_as = 1, height_in_as = 1, sample_rate_in_as = 1;
319 if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
320 width_in_as = !w->is_live && check_matching_width(s, as);
321 height_in_as = !w->is_live && check_matching_height(s, as);
323 sample_rate_in_as = !w->is_live && check_matching_sample_rate(s, as);
326 avio_printf(s->pb, "<AdaptationSet id=\"%s\"", as->id);
327 avio_printf(s->pb, " mimeType=\"%s/webm\"",
328 codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
329 avio_printf(s->pb, " codecs=\"%s\"", get_codec_name(codec->codec_id));
331 lang = av_dict_get(s->streams[as->streams[0]]->metadata, "language", NULL, 0);
332 if (lang) avio_printf(s->pb, " lang=\"%s\"", lang->value);
334 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && width_in_as)
335 avio_printf(s->pb, " width=\"%d\"", codec->width);
336 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && height_in_as)
337 avio_printf(s->pb, " height=\"%d\"", codec->height);
338 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && sample_rate_in_as)
339 avio_printf(s->pb, " audioSamplingRate=\"%d\"", codec->sample_rate);
341 avio_printf(s->pb, " bitstreamSwitching=\"%s\"",
342 boolean[bitstream_switching(s, as)]);
343 avio_printf(s->pb, " subsegmentAlignment=\"%s\"",
344 boolean[w->is_live || subsegment_alignment(s, as)]);
346 for (i = 0; i < as->nb_streams; i++) {
347 AVDictionaryEntry *kf = av_dict_get(s->streams[as->streams[i]]->metadata,
348 CLUSTER_KEYFRAME, NULL, 0);
349 if (!w->is_live && (!kf || !strncmp(kf->value, "0", 1))) subsegmentStartsWithSAP = 0;
351 avio_printf(s->pb, " subsegmentStartsWithSAP=\"%d\"", subsegmentStartsWithSAP);
352 avio_printf(s->pb, ">\n");
355 AVDictionaryEntry *filename =
356 av_dict_get(s->streams[as->streams[0]]->metadata, FILENAME, NULL, 0);
357 char *initialization_pattern = NULL;
358 char *media_pattern = NULL;
359 int ret = parse_filename(filename->value, NULL, &initialization_pattern,
362 avio_printf(s->pb, "<ContentComponent id=\"1\" type=\"%s\"/>\n",
363 codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
364 avio_printf(s->pb, "<SegmentTemplate");
365 avio_printf(s->pb, " timescale=\"1000\"");
366 avio_printf(s->pb, " duration=\"%d\"", w->chunk_duration);
367 avio_printf(s->pb, " media=\"%s\"", media_pattern);
368 avio_printf(s->pb, " startNumber=\"%d\"", w->chunk_start_index);
369 avio_printf(s->pb, " initialization=\"%s\"", initialization_pattern);
370 avio_printf(s->pb, "/>\n");
371 av_free(initialization_pattern);
372 av_free(media_pattern);
375 for (i = 0; i < as->nb_streams; i++) {
376 char *representation_id = NULL;
378 AVDictionaryEntry *filename =
379 av_dict_get(s->streams[as->streams[i]]->metadata, FILENAME, NULL, 0);
381 parse_filename(filename->value, &representation_id, NULL, NULL)) {
385 representation_id = av_asprintf("%d", w->representation_id++);
386 if (!representation_id) return -1;
388 write_representation(s, s->streams[as->streams[i]], representation_id,
389 !width_in_as, !height_in_as, !sample_rate_in_as);
390 av_free(representation_id);
392 avio_printf(s->pb, "</AdaptationSet>\n");
396 static int to_integer(char *p, int len)
399 char *q = av_malloc(sizeof(char) * len);
401 return AVERROR(ENOMEM);
402 av_strlcpy(q, p, len);
408 static int parse_adaptation_sets(AVFormatContext *s)
410 WebMDashMuxContext *w = s->priv_data;
411 char *p = w->adaptation_sets;
413 enum { new_set, parsed_id, parsing_streams } state;
414 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
416 while (p < w->adaptation_sets + strlen(w->adaptation_sets)) {
419 else if (state == new_set && !strncmp(p, "id=", 3)) {
420 w->as = av_realloc(w->as, sizeof(*w->as) * ++w->nb_as);
422 return AVERROR(ENOMEM);
423 w->as[w->nb_as - 1].nb_streams = 0;
424 w->as[w->nb_as - 1].streams = NULL;
425 p += 3; // consume "id="
426 q = w->as[w->nb_as - 1].id;
427 while (*p != ',') *q++ = *p++;
431 } else if (state == parsed_id && !strncmp(p, "streams=", 8)) {
432 p += 8; // consume "streams="
433 state = parsing_streams;
434 } else if (state == parsing_streams) {
435 struct AdaptationSet *as = &w->as[w->nb_as - 1];
437 while (*q != '\0' && *q != ',' && *q != ' ') q++;
438 as->streams = av_realloc(as->streams, sizeof(*as->streams) * ++as->nb_streams);
439 if (as->streams == NULL)
440 return AVERROR(ENOMEM);
441 as->streams[as->nb_streams - 1] = to_integer(p, q - p + 1);
442 if (as->streams[as->nb_streams - 1] < 0) return -1;
443 if (*q == '\0') break;
444 if (*q == ' ') state = new_set;
453 static int webm_dash_manifest_write_header(AVFormatContext *s)
457 WebMDashMuxContext *w = s->priv_data;
458 parse_adaptation_sets(s);
460 avio_printf(s->pb, "<Period id=\"0\"");
461 avio_printf(s->pb, " start=\"PT%gS\"", start);
463 avio_printf(s->pb, " duration=\"PT%gS\"", get_duration(s));
465 avio_printf(s->pb, " >\n");
467 for (i = 0; i < w->nb_as; i++) {
468 if (write_adaptation_set(s, i) < 0) return -1;
471 avio_printf(s->pb, "</Period>\n");
476 static int webm_dash_manifest_write_packet(AVFormatContext *s, AVPacket *pkt)
481 static int webm_dash_manifest_write_trailer(AVFormatContext *s)
483 WebMDashMuxContext *w = s->priv_data;
485 for (i = 0; i < w->nb_as; i++) {
486 av_freep(&w->as[i].streams);
492 #define OFFSET(x) offsetof(WebMDashMuxContext, x)
493 static const AVOption options[] = {
494 { "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 },
495 { "debug_mode", "[private option - users should never set this]. set this to 1 to create deterministic output", OFFSET(debug_mode), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
496 { "live", "set this to 1 to create a live stream manifest", OFFSET(is_live), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
497 { "chunk_start_index", "start index of the chunk", OFFSET(chunk_start_index), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
498 { "chunk_duration_ms", "duration of each chunk (in milliseconds)", OFFSET(chunk_duration), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
499 { "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, AV_OPT_FLAG_ENCODING_PARAM },
500 { "time_shift_buffer_depth", "Smallest time (in seconds) shifting buffer for which any Representation is guaranteed to be available.", OFFSET(time_shift_buffer_depth), AV_OPT_TYPE_DOUBLE, { .dbl = 60.0 }, 1.0, DBL_MAX, AV_OPT_FLAG_ENCODING_PARAM },
504 #if CONFIG_WEBM_DASH_MANIFEST_MUXER
505 static const AVClass webm_dash_class = {
506 .class_name = "WebM DASH Manifest muxer",
507 .item_name = av_default_item_name,
509 .version = LIBAVUTIL_VERSION_INT,
512 AVOutputFormat ff_webm_dash_manifest_muxer = {
513 .name = "webm_dash_manifest",
514 .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
515 .mime_type = "application/xml",
517 .priv_data_size = sizeof(WebMDashMuxContext),
518 .write_header = webm_dash_manifest_write_header,
519 .write_packet = webm_dash_manifest_write_packet,
520 .write_trailer = webm_dash_manifest_write_trailer,
521 .priv_class = &webm_dash_class,