]> git.sesse.net Git - ffmpeg/blob - libavformat/webmdashenc.c
Merge commit '15ec053c4c0b198a2e93eb8e60c8f41e091e0c40'
[ffmpeg] / libavformat / webmdashenc.c
1 /*
2  * WebM DASH Manifest XML muxer
3  * Copyright (c) 2014 Vignesh Venkatasubramanian
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /*
23  * WebM DASH Specification:
24  * https://sites.google.com/a/webmproject.org/wiki/adaptive-streaming/webm-dash-specification
25  */
26
27 #include <stdint.h>
28 #include <string.h>
29
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "matroska.h"
33
34 #include "libavutil/avstring.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/opt.h"
37
38 typedef struct AdaptationSet {
39     char id[10];
40     int *streams;
41     int nb_streams;
42 } AdaptationSet;
43
44 typedef struct WebMDashMuxContext {
45     const AVClass  *class;
46     char *adaptation_sets;
47     AdaptationSet *as;
48     int nb_as;
49 } WebMDashMuxContext;
50
51 static const char *get_codec_name(int codec_id)
52 {
53     switch (codec_id) {
54         case AV_CODEC_ID_VP8:
55             return "vp8";
56         case AV_CODEC_ID_VP9:
57             return "vp9";
58         case AV_CODEC_ID_VORBIS:
59             return "vorbis";
60         case AV_CODEC_ID_OPUS:
61             return "opus";
62     }
63     return NULL;
64 }
65
66 static double get_duration(AVFormatContext *s)
67 {
68     int i = 0;
69     double max = 0.0;
70     for (i = 0; i < s->nb_streams; i++) {
71         AVDictionaryEntry *duration = av_dict_get(s->streams[i]->metadata,
72                                                   DURATION, NULL, 0);
73         if (!duration || atof(duration->value) < 0) continue;
74         if (atof(duration->value) > max) max = atof(duration->value);
75     }
76     return max / 1000;
77 }
78
79 static void write_header(AVFormatContext *s)
80 {
81     double min_buffer_time = 1.0;
82     avio_printf(s->pb, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
83     avio_printf(s->pb, "<MPD\n");
84     avio_printf(s->pb, "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
85     avio_printf(s->pb, "  xmlns=\"urn:mpeg:DASH:schema:MPD:2011\"\n");
86     avio_printf(s->pb, "  xsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011\"\n");
87     avio_printf(s->pb, "  type=\"static\"\n");
88     avio_printf(s->pb, "  mediaPresentationDuration=\"PT%gS\"\n",
89                 get_duration(s));
90     avio_printf(s->pb, "  minBufferTime=\"PT%gS\"\n",
91                 min_buffer_time);
92     avio_printf(s->pb, "  profiles=\"urn:webm:dash:profile:webm-on-demand:2012\"");
93     avio_printf(s->pb, ">\n");
94 }
95
96 static void write_footer(AVFormatContext *s)
97 {
98     avio_printf(s->pb, "</MPD>\n");
99 }
100
101 static int subsegment_alignment(AVFormatContext *s, AdaptationSet *as) {
102     int i;
103     AVDictionaryEntry *gold = av_dict_get(s->streams[as->streams[0]]->metadata,
104                                           CUE_TIMESTAMPS, NULL, 0);
105     if (!gold) return 0;
106     for (i = 1; i < as->nb_streams; i++) {
107         AVDictionaryEntry *ts = av_dict_get(s->streams[as->streams[i]]->metadata,
108                                             CUE_TIMESTAMPS, NULL, 0);
109         if (!ts || strncmp(gold->value, ts->value, strlen(gold->value))) return 0;
110     }
111     return 1;
112 }
113
114 static int bitstream_switching(AVFormatContext *s, AdaptationSet *as) {
115     int i;
116     AVDictionaryEntry *gold_track_num = av_dict_get(s->streams[as->streams[0]]->metadata,
117                                                     TRACK_NUMBER, NULL, 0);
118     AVCodecContext *gold_codec = s->streams[as->streams[0]]->codec;
119     if (!gold_track_num) return 0;
120     for (i = 1; i < as->nb_streams; i++) {
121         AVDictionaryEntry *track_num = av_dict_get(s->streams[as->streams[i]]->metadata,
122                                                    TRACK_NUMBER, NULL, 0);
123         AVCodecContext *codec = s->streams[as->streams[i]]->codec;
124         if (!track_num ||
125             strncmp(gold_track_num->value, track_num->value, strlen(gold_track_num->value)) ||
126             gold_codec->codec_id != codec->codec_id ||
127             gold_codec->extradata_size != codec->extradata_size ||
128             memcmp(gold_codec->extradata, codec->extradata, codec->extradata_size)) {
129             return 0;
130         }
131     }
132     return 1;
133 }
134
135 /*
136  * Writes a Representation within an Adaptation Set. Returns 0 on success and
137  * < 0 on failure.
138  */
139 static int write_representation(AVFormatContext *s, AVStream *stream, int id,
140                                 int output_width, int output_height,
141                                 int output_sample_rate) {
142     AVDictionaryEntry *irange = av_dict_get(stream->metadata, INITIALIZATION_RANGE, NULL, 0);
143     AVDictionaryEntry *cues_start = av_dict_get(stream->metadata, CUES_START, NULL, 0);
144     AVDictionaryEntry *cues_end = av_dict_get(stream->metadata, CUES_END, NULL, 0);
145     AVDictionaryEntry *filename = av_dict_get(stream->metadata, FILENAME, NULL, 0);
146     AVDictionaryEntry *bandwidth = av_dict_get(stream->metadata, BANDWIDTH, NULL, 0);
147     if (!irange || cues_start == NULL || cues_end == NULL || filename == NULL ||
148         !bandwidth) {
149         return -1;
150     }
151     avio_printf(s->pb, "<Representation id=\"%d\"", id);
152     avio_printf(s->pb, " bandwidth=\"%s\"", bandwidth->value);
153     if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_width)
154         avio_printf(s->pb, " width=\"%d\"", stream->codec->width);
155     if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_height)
156         avio_printf(s->pb, " height=\"%d\"", stream->codec->height);
157     if (stream->codec->codec_type = AVMEDIA_TYPE_AUDIO && output_sample_rate)
158         avio_printf(s->pb, " audioSamplingRate=\"%d\"", stream->codec->sample_rate);
159     avio_printf(s->pb, ">\n");
160     avio_printf(s->pb, "<BaseURL>%s</BaseURL>\n", filename->value);
161     avio_printf(s->pb, "<SegmentBase\n");
162     avio_printf(s->pb, "  indexRange=\"%s-%s\">\n", cues_start->value, cues_end->value);
163     avio_printf(s->pb, "<Initialization\n");
164     avio_printf(s->pb, "  range=\"0-%s\" />\n", irange->value);
165     avio_printf(s->pb, "</SegmentBase>\n");
166     avio_printf(s->pb, "</Representation>\n");
167     return 0;
168 }
169
170 /*
171  * Checks if width of all streams are the same. Returns 1 if true, 0 otherwise.
172  */
173 static int check_matching_width(AVFormatContext *s, AdaptationSet *as) {
174     int first_width, i;
175     if (as->nb_streams < 2) return 1;
176     first_width = s->streams[as->streams[0]]->codec->width;
177     for (i = 1; i < as->nb_streams; i++)
178         if (first_width != s->streams[as->streams[i]]->codec->width)
179           return 0;
180     return 1;
181 }
182
183 /*
184  * Checks if height of all streams are the same. Returns 1 if true, 0 otherwise.
185  */
186 static int check_matching_height(AVFormatContext *s, AdaptationSet *as) {
187     int first_height, i;
188     if (as->nb_streams < 2) return 1;
189     first_height = s->streams[as->streams[0]]->codec->height;
190     for (i = 1; i < as->nb_streams; i++)
191         if (first_height != s->streams[as->streams[i]]->codec->height)
192           return 0;
193     return 1;
194 }
195
196 /*
197  * Checks if sample rate of all streams are the same. Returns 1 if true, 0 otherwise.
198  */
199 static int check_matching_sample_rate(AVFormatContext *s, AdaptationSet *as) {
200     int first_sample_rate, i;
201     if (as->nb_streams < 2) return 1;
202     first_sample_rate = s->streams[as->streams[0]]->codec->sample_rate;
203     for (i = 1; i < as->nb_streams; i++)
204         if (first_sample_rate != s->streams[as->streams[i]]->codec->sample_rate)
205           return 0;
206     return 1;
207 }
208
209 /*
210  * Writes an Adaptation Set. Returns 0 on success and < 0 on failure.
211  */
212 static int write_adaptation_set(AVFormatContext *s, int as_index)
213 {
214     WebMDashMuxContext *w = s->priv_data;
215     AdaptationSet *as = &w->as[as_index];
216     AVCodecContext *codec = s->streams[as->streams[0]]->codec;
217     AVDictionaryEntry *lang;
218     int i;
219     static const char boolean[2][6] = { "false", "true" };
220     int subsegmentStartsWithSAP = 1;
221
222     // Width, Height and Sample Rate will go in the AdaptationSet tag if they
223     // are the same for all contained Representations. otherwise, they will go
224     // on their respective Representation tag.
225     int width_in_as = 1, height_in_as = 1, sample_rate_in_as = 1;
226     if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
227       width_in_as = check_matching_width(s, as);
228       height_in_as = check_matching_height(s, as);
229     } else {
230       sample_rate_in_as = check_matching_sample_rate(s, as);
231     }
232
233     avio_printf(s->pb, "<AdaptationSet id=\"%s\"", as->id);
234     avio_printf(s->pb, " mimeType=\"%s/webm\"",
235                 codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
236     avio_printf(s->pb, " codecs=\"%s\"", get_codec_name(codec->codec_id));
237
238     lang = av_dict_get(s->streams[as->streams[0]]->metadata, "language", NULL, 0);
239     if (lang) avio_printf(s->pb, " lang=\"%s\"", lang->value);
240
241     if (codec->codec_type == AVMEDIA_TYPE_VIDEO && width_in_as)
242         avio_printf(s->pb, " width=\"%d\"", codec->width);
243     if (codec->codec_type == AVMEDIA_TYPE_VIDEO && height_in_as)
244         avio_printf(s->pb, " height=\"%d\"", codec->height);
245     if (codec->codec_type == AVMEDIA_TYPE_AUDIO && sample_rate_in_as)
246         avio_printf(s->pb, " audioSamplingRate=\"%d\"", codec->sample_rate);
247
248     avio_printf(s->pb, " bitstreamSwitching=\"%s\"",
249                 boolean[bitstream_switching(s, as)]);
250     avio_printf(s->pb, " subsegmentAlignment=\"%s\"",
251                 boolean[subsegment_alignment(s, as)]);
252
253     for (i = 0; i < as->nb_streams; i++) {
254         AVDictionaryEntry *kf = av_dict_get(s->streams[as->streams[i]]->metadata,
255                                             CLUSTER_KEYFRAME, NULL, 0);
256         if (!kf || !strncmp(kf->value, "0", 1)) subsegmentStartsWithSAP = 0;
257     }
258     avio_printf(s->pb, " subsegmentStartsWithSAP=\"%d\"", subsegmentStartsWithSAP);
259     avio_printf(s->pb, ">\n");
260
261     for (i = 0; i < as->nb_streams; i++) {
262         write_representation(s, s->streams[as->streams[i]], i,
263                              !width_in_as, !height_in_as, !sample_rate_in_as);
264     }
265     avio_printf(s->pb, "</AdaptationSet>\n");
266     return 0;
267 }
268
269 static int to_integer(char *p, int len)
270 {
271     int ret;
272     char *q = av_malloc(sizeof(char) * len);
273     if (!q) return -1;
274     av_strlcpy(q, p, len);
275     ret = atoi(q);
276     av_free(q);
277     return ret;
278 }
279
280 static int parse_adaptation_sets(AVFormatContext *s)
281 {
282     WebMDashMuxContext *w = s->priv_data;
283     char *p = w->adaptation_sets;
284     char *q;
285     enum { new_set, parsed_id, parsing_streams } state;
286     // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
287     state = new_set;
288     while (p < w->adaptation_sets + strlen(w->adaptation_sets)) {
289         if (*p == ' ')
290             continue;
291         else if (state == new_set && !strncmp(p, "id=", 3)) {
292             w->as = av_realloc(w->as, sizeof(*w->as) * ++w->nb_as);
293             if (w->as == NULL) return -1;
294             w->as[w->nb_as - 1].nb_streams = 0;
295             w->as[w->nb_as - 1].streams = NULL;
296             p += 3; // consume "id="
297             q = w->as[w->nb_as - 1].id;
298             while (*p != ',') *q++ = *p++;
299             *q = 0;
300             p++;
301             state = parsed_id;
302         } else if (state == parsed_id && !strncmp(p, "streams=", 8)) {
303             p += 8; // consume "streams="
304             state = parsing_streams;
305         } else if (state == parsing_streams) {
306             struct AdaptationSet *as = &w->as[w->nb_as - 1];
307             q = p;
308             while (*q != '\0' && *q != ',' && *q != ' ') q++;
309             as->streams = av_realloc(as->streams, sizeof(*as->streams) * ++as->nb_streams);
310             if (as->streams == NULL) return -1;
311             as->streams[as->nb_streams - 1] = to_integer(p, q - p + 1);
312             if (as->streams[as->nb_streams - 1] < 0) return -1;
313             if (*q == '\0') break;
314             if (*q == ' ') state = new_set;
315             p = ++q;
316         } else {
317             return -1;
318         }
319     }
320     return 0;
321 }
322
323 static int webm_dash_manifest_write_header(AVFormatContext *s)
324 {
325     int i;
326     double start = 0.0;
327     WebMDashMuxContext *w = s->priv_data;
328     parse_adaptation_sets(s);
329     write_header(s);
330     avio_printf(s->pb, "<Period id=\"0\"");
331     avio_printf(s->pb, " start=\"PT%gS\"", start);
332     avio_printf(s->pb, " duration=\"PT%gS\"", get_duration(s));
333     avio_printf(s->pb, " >\n");
334
335     for (i = 0; i < w->nb_as; i++) {
336         if (write_adaptation_set(s, i) < 0) return -1;
337     }
338
339     avio_printf(s->pb, "</Period>\n");
340     write_footer(s);
341     return 0;
342 }
343
344 static int webm_dash_manifest_write_packet(AVFormatContext *s, AVPacket *pkt)
345 {
346     return AVERROR_EOF;
347 }
348
349 static int webm_dash_manifest_write_trailer(AVFormatContext *s)
350 {
351     WebMDashMuxContext *w = s->priv_data;
352     int i;
353     for (i = 0; i < w->nb_as; i++) {
354         av_freep(&w->as[i].streams);
355     }
356     av_freep(&w->as);
357     return 0;
358 }
359
360 #define OFFSET(x) offsetof(WebMDashMuxContext, x)
361 static const AVOption options[] = {
362     { "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 },
363     { NULL },
364 };
365
366 #if CONFIG_WEBM_DASH_MANIFEST_MUXER
367 static const AVClass webm_dash_class = {
368     .class_name = "WebM DASH Manifest muxer",
369     .item_name  = av_default_item_name,
370     .option     = options,
371     .version    = LIBAVUTIL_VERSION_INT,
372 };
373
374 AVOutputFormat ff_webm_dash_manifest_muxer = {
375     .name              = "webm_dash_manifest",
376     .long_name         = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
377     .mime_type         = "application/xml",
378     .extensions        = "xml",
379     .priv_data_size    = sizeof(WebMDashMuxContext),
380     .write_header      = webm_dash_manifest_write_header,
381     .write_packet      = webm_dash_manifest_write_packet,
382     .write_trailer     = webm_dash_manifest_write_trailer,
383     .priv_class        = &webm_dash_class,
384 };
385 #endif