]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
5a966fe3ade7c91b615eee18c43041964985defb
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
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 #include "config.h"
23 #if HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
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"
35
36 #include "avc.h"
37 #include "avformat.h"
38 #include "avio_internal.h"
39 #include "internal.h"
40 #include "isom.h"
41 #include "os_support.h"
42 #include "url.h"
43 #include "dash.h"
44
45 typedef struct Segment {
46     char file[1024];
47     int64_t start_pos;
48     int range_length, index_length;
49     int64_t time;
50     int duration;
51     int n;
52 } Segment;
53
54 typedef struct AdaptationSet {
55     char id[10];
56     enum AVMediaType media_type;
57 } AdaptationSet;
58
59 typedef struct OutputStream {
60     AVFormatContext *ctx;
61     int ctx_inited, as_idx;
62     uint8_t iobuf[32768];
63     AVIOContext *out;
64     int packets_written;
65     char initfile[1024];
66     int64_t init_start_pos;
67     int init_range_length;
68     int nb_segments, segments_size, segment_index;
69     Segment **segments;
70     int64_t first_pts, start_pts, max_pts;
71     int64_t last_dts;
72     int bit_rate;
73     char bandwidth_str[64];
74
75     char codec_str[100];
76 } OutputStream;
77
78 typedef struct DASHContext {
79     const AVClass *class;  /* Class for private options. */
80     char *adaptation_sets;
81     AdaptationSet *as;
82     int nb_as;
83     int window_size;
84     int extra_window_size;
85     int min_seg_duration;
86     int remove_at_exit;
87     int use_template;
88     int use_timeline;
89     int single_file;
90     OutputStream *streams;
91     int has_video;
92     int64_t last_duration;
93     int64_t total_duration;
94     char availability_start_time[100];
95     char dirname[1024];
96     const char *single_file_name;
97     const char *init_seg_name;
98     const char *media_seg_name;
99     AVRational min_frame_rate, max_frame_rate;
100     int ambiguous_frame_rate;
101     const char *utc_timing_url;
102 } DASHContext;
103
104 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
105 {
106     OutputStream *os = opaque;
107     if (os->out)
108         avio_write(os->out, buf, buf_size);
109     return buf_size;
110 }
111
112 // RFC 6381
113 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
114                           char *str, int size)
115 {
116     const AVCodecTag *tags[2] = { NULL, NULL };
117     uint32_t tag;
118     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
119         tags[0] = ff_codec_movvideo_tags;
120     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
121         tags[0] = ff_codec_movaudio_tags;
122     else
123         return;
124
125     tag = av_codec_get_tag(tags, par->codec_id);
126     if (!tag)
127         return;
128     if (size < 5)
129         return;
130
131     AV_WL32(str, tag);
132     str[4] = '\0';
133     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
134         uint32_t oti;
135         tags[0] = ff_mp4_obj_type;
136         oti = av_codec_get_tag(tags, par->codec_id);
137         if (oti)
138             av_strlcatf(str, size, ".%02"PRIx32, oti);
139         else
140             return;
141
142         if (tag == MKTAG('m', 'p', '4', 'a')) {
143             if (par->extradata_size >= 2) {
144                 int aot = par->extradata[0] >> 3;
145                 if (aot == 31)
146                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
147                 av_strlcatf(str, size, ".%d", aot);
148             }
149         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
150             // Unimplemented, should output ProfileLevelIndication as a decimal number
151             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
152         }
153     } else if (!strcmp(str, "avc1")) {
154         uint8_t *tmpbuf = NULL;
155         uint8_t *extradata = par->extradata;
156         int extradata_size = par->extradata_size;
157         if (!extradata_size)
158             return;
159         if (extradata[0] != 1) {
160             AVIOContext *pb;
161             if (avio_open_dyn_buf(&pb) < 0)
162                 return;
163             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
164                 ffio_free_dyn_buf(&pb);
165                 return;
166             }
167             extradata_size = avio_close_dyn_buf(pb, &extradata);
168             tmpbuf = extradata;
169         }
170
171         if (extradata_size >= 4)
172             av_strlcatf(str, size, ".%02x%02x%02x",
173                         extradata[1], extradata[2], extradata[3]);
174         av_free(tmpbuf);
175     }
176 }
177
178 static void dash_free(AVFormatContext *s)
179 {
180     DASHContext *c = s->priv_data;
181     int i, j;
182
183     if (c->as) {
184         av_freep(&c->as);
185         c->nb_as = 0;
186     }
187
188     if (!c->streams)
189         return;
190     for (i = 0; i < s->nb_streams; i++) {
191         OutputStream *os = &c->streams[i];
192         if (os->ctx && os->ctx_inited)
193             av_write_trailer(os->ctx);
194         if (os->ctx && os->ctx->pb)
195             av_free(os->ctx->pb);
196         ff_format_io_close(s, &os->out);
197         if (os->ctx)
198             avformat_free_context(os->ctx);
199         for (j = 0; j < os->nb_segments; j++)
200             av_free(os->segments[j]);
201         av_free(os->segments);
202     }
203     av_freep(&c->streams);
204 }
205
206 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
207 {
208     int i, start_index = 0, start_number = 1;
209     if (c->window_size) {
210         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
211         start_number = FFMAX(os->segment_index - c->window_size, 1);
212     }
213
214     if (c->use_template) {
215         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
216         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
217         if (!c->use_timeline)
218             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
219         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
220         if (c->use_timeline) {
221             int64_t cur_time = 0;
222             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
223             for (i = start_index; i < os->nb_segments; ) {
224                 Segment *seg = os->segments[i];
225                 int repeat = 0;
226                 avio_printf(out, "\t\t\t\t\t\t<S ");
227                 if (i == start_index || seg->time != cur_time) {
228                     cur_time = seg->time;
229                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
230                 }
231                 avio_printf(out, "d=\"%d\" ", seg->duration);
232                 while (i + repeat + 1 < os->nb_segments &&
233                        os->segments[i + repeat + 1]->duration == seg->duration &&
234                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
235                     repeat++;
236                 if (repeat > 0)
237                     avio_printf(out, "r=\"%d\" ", repeat);
238                 avio_printf(out, "/>\n");
239                 i += 1 + repeat;
240                 cur_time += (1 + repeat) * seg->duration;
241             }
242             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
243         }
244         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
245     } else if (c->single_file) {
246         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
247         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
248         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);
249         for (i = start_index; i < os->nb_segments; i++) {
250             Segment *seg = os->segments[i];
251             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
252             if (seg->index_length)
253                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
254             avio_printf(out, "/>\n");
255         }
256         avio_printf(out, "\t\t\t\t</SegmentList>\n");
257     } else {
258         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
259         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
260         for (i = start_index; i < os->nb_segments; i++) {
261             Segment *seg = os->segments[i];
262             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
263         }
264         avio_printf(out, "\t\t\t\t</SegmentList>\n");
265     }
266 }
267
268 static char *xmlescape(const char *str) {
269     int outlen = strlen(str)*3/2 + 6;
270     char *out = av_realloc(NULL, outlen + 1);
271     int pos = 0;
272     if (!out)
273         return NULL;
274     for (; *str; str++) {
275         if (pos + 6 > outlen) {
276             char *tmp;
277             outlen = 2 * outlen + 6;
278             tmp = av_realloc(out, outlen + 1);
279             if (!tmp) {
280                 av_free(out);
281                 return NULL;
282             }
283             out = tmp;
284         }
285         if (*str == '&') {
286             memcpy(&out[pos], "&amp;", 5);
287             pos += 5;
288         } else if (*str == '<') {
289             memcpy(&out[pos], "&lt;", 4);
290             pos += 4;
291         } else if (*str == '>') {
292             memcpy(&out[pos], "&gt;", 4);
293             pos += 4;
294         } else if (*str == '\'') {
295             memcpy(&out[pos], "&apos;", 6);
296             pos += 6;
297         } else if (*str == '\"') {
298             memcpy(&out[pos], "&quot;", 6);
299             pos += 6;
300         } else {
301             out[pos++] = *str;
302         }
303     }
304     out[pos] = '\0';
305     return out;
306 }
307
308 static void write_time(AVIOContext *out, int64_t time)
309 {
310     int seconds = time / AV_TIME_BASE;
311     int fractions = time % AV_TIME_BASE;
312     int minutes = seconds / 60;
313     int hours = minutes / 60;
314     seconds %= 60;
315     minutes %= 60;
316     avio_printf(out, "PT");
317     if (hours)
318         avio_printf(out, "%dH", hours);
319     if (hours || minutes)
320         avio_printf(out, "%dM", minutes);
321     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
322 }
323
324 static void format_date_now(char *buf, int size)
325 {
326     time_t t = time(NULL);
327     struct tm *ptm, tmbuf;
328     ptm = gmtime_r(&t, &tmbuf);
329     if (ptm) {
330         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
331             buf[0] = '\0';
332     }
333 }
334
335 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
336 {
337     DASHContext *c = s->priv_data;
338     AdaptationSet *as = &c->as[as_index];
339     int i;
340
341     avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
342                 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
343     if (as->media_type == AVMEDIA_TYPE_VIDEO && c->max_frame_rate.num && !c->ambiguous_frame_rate)
344         avio_printf(out, " %s=\"%d/%d\"", (av_cmp_q(c->min_frame_rate, c->max_frame_rate) < 0) ? "maxFrameRate" : "frameRate", c->max_frame_rate.num, c->max_frame_rate.den);
345     avio_printf(out, ">\n");
346
347     for (i = 0; i < s->nb_streams; i++) {
348         OutputStream *os = &c->streams[i];
349
350         if (os->as_idx - 1 != as_index)
351             continue;
352
353         if (as->media_type == AVMEDIA_TYPE_VIDEO) {
354             AVStream *st = s->streams[i];
355             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
356                 i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
357             if (st->avg_frame_rate.num)
358                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
359             avio_printf(out, ">\n");
360         } else {
361             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
362                 i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
363             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
364                 s->streams[i]->codecpar->channels);
365         }
366         output_segment_list(os, out, c);
367         avio_printf(out, "\t\t\t</Representation>\n");
368     }
369     avio_printf(out, "\t\t</AdaptationSet>\n");
370
371     return 0;
372 }
373
374 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
375 {
376     DASHContext *c = s->priv_data;
377
378     void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
379     if (!mem)
380         return AVERROR(ENOMEM);
381     c->as = mem;
382     ++c->nb_as;
383
384     *as = &c->as[c->nb_as - 1];
385     memset(*as, 0, sizeof(**as));
386     (*as)->media_type = type;
387
388     return 0;
389 }
390
391 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
392 {
393     DASHContext *c = s->priv_data;
394     AdaptationSet *as = &c->as[as_idx - 1];
395     OutputStream *os = &c->streams[i];
396
397     if (as->media_type != s->streams[i]->codecpar->codec_type) {
398         av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
399         return AVERROR(EINVAL);
400     } else if (os->as_idx) {
401         av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
402         return AVERROR(EINVAL);
403     }
404     os->as_idx = as_idx;
405
406     return 0;
407 }
408
409 static int parse_adaptation_sets(AVFormatContext *s)
410 {
411     DASHContext *c = s->priv_data;
412     const char *p = c->adaptation_sets;
413     enum { new_set, parse_id, parsing_streams } state;
414     AdaptationSet *as;
415     int i, n, ret;
416
417     // default: one AdaptationSet for each stream
418     if (!p) {
419         for (i = 0; i < s->nb_streams; i++) {
420             if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
421                 return ret;
422             snprintf(as->id, sizeof(as->id), "%d", i);
423
424             c->streams[i].as_idx = c->nb_as;
425         }
426         goto end;
427     }
428
429     // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
430     state = new_set;
431     while (*p) {
432         if (*p == ' ') {
433             p++;
434             continue;
435         } else if (state == new_set && av_strstart(p, "id=", &p)) {
436
437             if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
438                 return ret;
439
440             n = strcspn(p, ",");
441             snprintf(as->id, sizeof(as->id), "%.*s", n, p);
442
443             p += n;
444             if (*p)
445                 p++;
446             state = parse_id;
447         } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
448             state = parsing_streams;
449         } else if (state == parsing_streams) {
450             AdaptationSet *as = &c->as[c->nb_as - 1];
451             char idx_str[8], *end_str;
452
453             n = strcspn(p, " ,");
454             snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
455             p += n;
456
457             // if value is "a" or "v", map all streams of that type
458             if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
459                 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
460                 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
461
462                 for (i = 0; i < s->nb_streams; i++) {
463                     if (s->streams[i]->codecpar->codec_type != type)
464                         continue;
465
466                     as->media_type = s->streams[i]->codecpar->codec_type;
467
468                     if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
469                         return ret;
470                 }
471             } else { // select single stream
472                 i = strtol(idx_str, &end_str, 10);
473                 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
474                     av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
475                     return AVERROR(EINVAL);
476                 }
477                 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
478
479                 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
480                     as->media_type = s->streams[i]->codecpar->codec_type;
481                 }
482
483                 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
484                     return ret;
485             }
486
487             if (*p == ' ')
488                 state = new_set;
489             if (*p)
490                 p++;
491         } else {
492             return AVERROR(EINVAL);
493         }
494     }
495
496 end:
497     // check for unassigned streams
498     for (i = 0; i < s->nb_streams; i++) {
499         OutputStream *os = &c->streams[i];
500         if (!os->as_idx) {
501             av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
502             return AVERROR(EINVAL);
503         }
504     }
505     return 0;
506 }
507
508 static int write_manifest(AVFormatContext *s, int final)
509 {
510     DASHContext *c = s->priv_data;
511     AVIOContext *out;
512     char temp_filename[1024];
513     int ret, i;
514     const char *proto = avio_find_protocol_name(s->filename);
515     int use_rename = proto && !strcmp(proto, "file");
516     static unsigned int warned_non_file = 0;
517     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
518
519     if (!use_rename && !warned_non_file++)
520         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
521
522     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
523     ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
524     if (ret < 0) {
525         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
526         return ret;
527     }
528     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
529     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
530                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
531                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
532                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
533                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
534                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
535     if (final) {
536         avio_printf(out, "\tmediaPresentationDuration=\"");
537         write_time(out, c->total_duration);
538         avio_printf(out, "\"\n");
539     } else {
540         int64_t update_period = c->last_duration / AV_TIME_BASE;
541         char now_str[100];
542         if (c->use_template && !c->use_timeline)
543             update_period = 500;
544         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
545         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
546         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
547             format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
548         }
549         if (c->availability_start_time[0])
550             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
551         format_date_now(now_str, sizeof(now_str));
552         if (now_str[0])
553             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
554         if (c->window_size && c->use_template) {
555             avio_printf(out, "\ttimeShiftBufferDepth=\"");
556             write_time(out, c->last_duration * c->window_size);
557             avio_printf(out, "\"\n");
558         }
559     }
560     avio_printf(out, "\tminBufferTime=\"");
561     write_time(out, c->last_duration * 2);
562     avio_printf(out, "\">\n");
563     avio_printf(out, "\t<ProgramInformation>\n");
564     if (title) {
565         char *escaped = xmlescape(title->value);
566         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
567         av_free(escaped);
568     }
569     avio_printf(out, "\t</ProgramInformation>\n");
570     if (c->utc_timing_url)
571         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
572
573     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
574         OutputStream *os = &c->streams[0];
575         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
576         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
577         avio_printf(out, "\t<Period id=\"0\" start=\"");
578         write_time(out, start_time);
579         avio_printf(out, "\">\n");
580     } else {
581         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
582     }
583
584     for (i = 0; i < c->nb_as; i++) {
585         if ((ret = write_adaptation_set(s, out, i)) < 0)
586             return ret;
587     }
588     avio_printf(out, "\t</Period>\n");
589     avio_printf(out, "</MPD>\n");
590     avio_flush(out);
591     ff_format_io_close(s, &out);
592
593     if (use_rename)
594         return avpriv_io_move(temp_filename, s->filename);
595
596     return 0;
597 }
598
599 static int dash_init(AVFormatContext *s)
600 {
601     DASHContext *c = s->priv_data;
602     int ret = 0, i;
603     AVOutputFormat *oformat;
604     char *ptr;
605     char basename[1024];
606
607     if (c->single_file_name)
608         c->single_file = 1;
609     if (c->single_file)
610         c->use_template = 0;
611     c->ambiguous_frame_rate = 0;
612
613     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
614     ptr = strrchr(c->dirname, '/');
615     if (ptr) {
616         av_strlcpy(basename, &ptr[1], sizeof(basename));
617         ptr[1] = '\0';
618     } else {
619         c->dirname[0] = '\0';
620         av_strlcpy(basename, s->filename, sizeof(basename));
621     }
622
623     ptr = strrchr(basename, '.');
624     if (ptr)
625         *ptr = '\0';
626
627     oformat = av_guess_format("mp4", NULL, NULL);
628     if (!oformat)
629         return AVERROR_MUXER_NOT_FOUND;
630
631     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
632     if (!c->streams)
633         return AVERROR(ENOMEM);
634
635     if ((ret = parse_adaptation_sets(s)) < 0)
636         return ret;
637
638     for (i = 0; i < s->nb_streams; i++) {
639         OutputStream *os = &c->streams[i];
640         AVFormatContext *ctx;
641         AVStream *st;
642         AVDictionary *opts = NULL;
643         char filename[1024];
644
645         os->bit_rate = s->streams[i]->codecpar->bit_rate;
646         if (os->bit_rate) {
647             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
648                      " bandwidth=\"%d\"", os->bit_rate);
649         } else {
650             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
651                         AV_LOG_ERROR : AV_LOG_WARNING;
652             av_log(s, level, "No bit rate set for stream %d\n", i);
653             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
654                 return AVERROR(EINVAL);
655         }
656
657         ctx = avformat_alloc_context();
658         if (!ctx)
659             return AVERROR(ENOMEM);
660         os->ctx = ctx;
661         ctx->oformat = oformat;
662         ctx->interrupt_callback = s->interrupt_callback;
663         ctx->opaque             = s->opaque;
664         ctx->io_close           = s->io_close;
665         ctx->io_open            = s->io_open;
666
667         if (!(st = avformat_new_stream(ctx, NULL)))
668             return AVERROR(ENOMEM);
669         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
670         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
671         st->time_base = s->streams[i]->time_base;
672         ctx->avoid_negative_ts = s->avoid_negative_ts;
673         ctx->flags = s->flags;
674
675         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
676         if (!ctx->pb)
677             return AVERROR(ENOMEM);
678
679         if (c->single_file) {
680             if (c->single_file_name)
681                 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
682             else
683                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
684         } else {
685             ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
686         }
687         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
688         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
689         if (ret < 0)
690             return ret;
691         os->init_start_pos = 0;
692
693         av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
694         if ((ret = avformat_init_output(ctx, &opts)) < 0)
695             return ret;
696         os->ctx_inited = 1;
697         avio_flush(ctx->pb);
698         av_dict_free(&opts);
699
700         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
701
702         s->streams[i]->time_base = st->time_base;
703         // If the muxer wants to shift timestamps, request to have them shifted
704         // already before being handed to this muxer, so we don't have mismatches
705         // between the MPD and the actual segments.
706         s->avoid_negative_ts = ctx->avoid_negative_ts;
707         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
708             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
709             if (avg_frame_rate.num > 0) {
710                 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
711                     c->min_frame_rate = avg_frame_rate;
712                 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
713                     c->max_frame_rate = avg_frame_rate;
714             } else {
715                 c->ambiguous_frame_rate = 1;
716             }
717             c->has_video = 1;
718         }
719
720         set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
721         os->first_pts = AV_NOPTS_VALUE;
722         os->max_pts = AV_NOPTS_VALUE;
723         os->last_dts = AV_NOPTS_VALUE;
724         os->segment_index = 1;
725     }
726
727     if (!c->has_video && c->min_seg_duration <= 0) {
728         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
729         return AVERROR(EINVAL);
730     }
731     return 0;
732 }
733
734 static int dash_write_header(AVFormatContext *s)
735 {
736     DASHContext *c = s->priv_data;
737     int i, ret;
738     for (i = 0; i < s->nb_streams; i++) {
739         OutputStream *os = &c->streams[i];
740         if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
741             dash_free(s);
742             return ret;
743         }
744     }
745     ret = write_manifest(s, 0);
746     if (!ret)
747         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
748     return ret;
749 }
750
751 static int add_segment(OutputStream *os, const char *file,
752                        int64_t time, int duration,
753                        int64_t start_pos, int64_t range_length,
754                        int64_t index_length)
755 {
756     int err;
757     Segment *seg;
758     if (os->nb_segments >= os->segments_size) {
759         os->segments_size = (os->segments_size + 1) * 2;
760         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
761                                os->segments_size)) < 0) {
762             os->segments_size = 0;
763             os->nb_segments = 0;
764             return err;
765         }
766     }
767     seg = av_mallocz(sizeof(*seg));
768     if (!seg)
769         return AVERROR(ENOMEM);
770     av_strlcpy(seg->file, file, sizeof(seg->file));
771     seg->time = time;
772     seg->duration = duration;
773     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
774         seg->duration += seg->time;
775         seg->time = 0;
776     }
777     seg->start_pos = start_pos;
778     seg->range_length = range_length;
779     seg->index_length = index_length;
780     os->segments[os->nb_segments++] = seg;
781     os->segment_index++;
782     return 0;
783 }
784
785 static void write_styp(AVIOContext *pb)
786 {
787     avio_wb32(pb, 24);
788     ffio_wfourcc(pb, "styp");
789     ffio_wfourcc(pb, "msdh");
790     avio_wb32(pb, 0); /* minor */
791     ffio_wfourcc(pb, "msdh");
792     ffio_wfourcc(pb, "msix");
793 }
794
795 static void find_index_range(AVFormatContext *s, const char *full_path,
796                              int64_t pos, int *index_length)
797 {
798     uint8_t buf[8];
799     AVIOContext *pb;
800     int ret;
801
802     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
803     if (ret < 0)
804         return;
805     if (avio_seek(pb, pos, SEEK_SET) != pos) {
806         ff_format_io_close(s, &pb);
807         return;
808     }
809     ret = avio_read(pb, buf, 8);
810     ff_format_io_close(s, &pb);
811     if (ret < 8)
812         return;
813     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
814         return;
815     *index_length = AV_RB32(&buf[0]);
816 }
817
818 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
819                                    AVCodecParameters *par)
820 {
821     uint8_t *extradata;
822
823     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
824         return 0;
825
826     extradata = av_malloc(par->extradata_size);
827
828     if (!extradata)
829         return AVERROR(ENOMEM);
830
831     memcpy(extradata, par->extradata, par->extradata_size);
832
833     os->ctx->streams[0]->codecpar->extradata = extradata;
834     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
835
836     set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
837
838     return 0;
839 }
840
841 static int dash_flush(AVFormatContext *s, int final, int stream)
842 {
843     DASHContext *c = s->priv_data;
844     int i, ret = 0;
845
846     const char *proto = avio_find_protocol_name(s->filename);
847     int use_rename = proto && !strcmp(proto, "file");
848
849     int cur_flush_segment_index = 0;
850     if (stream >= 0)
851         cur_flush_segment_index = c->streams[stream].segment_index;
852
853     for (i = 0; i < s->nb_streams; i++) {
854         OutputStream *os = &c->streams[i];
855         char filename[1024] = "", full_path[1024], temp_path[1024];
856         int64_t start_pos;
857         int range_length, index_length = 0;
858
859         if (!os->packets_written)
860             continue;
861
862         // Flush the single stream that got a keyframe right now.
863         // Flush all audio streams as well, in sync with video keyframes,
864         // but not the other video streams.
865         if (stream >= 0 && i != stream) {
866             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
867                 continue;
868             // Make sure we don't flush audio streams multiple times, when
869             // all video streams are flushed one at a time.
870             if (c->has_video && os->segment_index > cur_flush_segment_index)
871                 continue;
872         }
873
874         if (!os->init_range_length) {
875             av_write_frame(os->ctx, NULL);
876             os->init_range_length = avio_tell(os->ctx->pb);
877             if (!c->single_file)
878                 ff_format_io_close(s, &os->out);
879         }
880
881         start_pos = avio_tell(os->ctx->pb);
882
883         if (!c->single_file) {
884             ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
885             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
886             snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
887             ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
888             if (ret < 0)
889                 break;
890             write_styp(os->ctx->pb);
891         } else {
892             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
893         }
894
895         av_write_frame(os->ctx, NULL);
896         avio_flush(os->ctx->pb);
897         os->packets_written = 0;
898
899         range_length = avio_tell(os->ctx->pb) - start_pos;
900         if (c->single_file) {
901             find_index_range(s, full_path, start_pos, &index_length);
902         } else {
903             ff_format_io_close(s, &os->out);
904
905             if (use_rename) {
906                 ret = avpriv_io_move(temp_path, full_path);
907                 if (ret < 0)
908                     break;
909             }
910         }
911
912         if (!os->bit_rate) {
913             // calculate average bitrate of first segment
914             int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
915             if (bitrate >= 0) {
916                 os->bit_rate = bitrate;
917                 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
918                      " bandwidth=\"%d\"", os->bit_rate);
919             }
920         }
921         add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
922         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
923     }
924
925     if (c->window_size || (final && c->remove_at_exit)) {
926         for (i = 0; i < s->nb_streams; i++) {
927             OutputStream *os = &c->streams[i];
928             int j;
929             int remove = os->nb_segments - c->window_size - c->extra_window_size;
930             if (final && c->remove_at_exit)
931                 remove = os->nb_segments;
932             if (remove > 0) {
933                 for (j = 0; j < remove; j++) {
934                     char filename[1024];
935                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
936                     unlink(filename);
937                     av_free(os->segments[j]);
938                 }
939                 os->nb_segments -= remove;
940                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
941             }
942         }
943     }
944
945     if (ret >= 0)
946         ret = write_manifest(s, final);
947     return ret;
948 }
949
950 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
951 {
952     DASHContext *c = s->priv_data;
953     AVStream *st = s->streams[pkt->stream_index];
954     OutputStream *os = &c->streams[pkt->stream_index];
955     int ret;
956
957     ret = update_stream_extradata(s, os, st->codecpar);
958     if (ret < 0)
959         return ret;
960
961     // Fill in a heuristic guess of the packet duration, if none is available.
962     // The mp4 muxer will do something similar (for the last packet in a fragment)
963     // if nothing is set (setting it for the other packets doesn't hurt).
964     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
965     // invoke its heuristic (this doesn't have to be identical to that algorithm),
966     // so that we know the exact timestamps of fragments.
967     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
968         pkt->duration = pkt->dts - os->last_dts;
969     os->last_dts = pkt->dts;
970
971     // If forcing the stream to start at 0, the mp4 muxer will set the start
972     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
973     if (os->first_pts == AV_NOPTS_VALUE &&
974         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
975         pkt->pts -= pkt->dts;
976         pkt->dts  = 0;
977     }
978
979     if (os->first_pts == AV_NOPTS_VALUE)
980         os->first_pts = pkt->pts;
981
982     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
983         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
984         av_compare_ts(pkt->pts - os->start_pts, st->time_base,
985                       c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
986         int64_t prev_duration = c->last_duration;
987
988         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
989                                         st->time_base,
990                                         AV_TIME_BASE_Q);
991         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
992                                          st->time_base,
993                                          AV_TIME_BASE_Q);
994
995         if ((!c->use_timeline || !c->use_template) && prev_duration) {
996             if (c->last_duration < prev_duration*9/10 ||
997                 c->last_duration > prev_duration*11/10) {
998                 av_log(s, AV_LOG_WARNING,
999                        "Segment durations differ too much, enable use_timeline "
1000                        "and use_template, or keep a stricter keyframe interval\n");
1001             }
1002         }
1003
1004         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1005             return ret;
1006     }
1007
1008     if (!os->packets_written) {
1009         // If we wrote a previous segment, adjust the start time of the segment
1010         // to the end of the previous one (which is the same as the mp4 muxer
1011         // does). This avoids gaps in the timeline.
1012         if (os->max_pts != AV_NOPTS_VALUE)
1013             os->start_pts = os->max_pts;
1014         else
1015             os->start_pts = pkt->pts;
1016     }
1017     if (os->max_pts == AV_NOPTS_VALUE)
1018         os->max_pts = pkt->pts + pkt->duration;
1019     else
1020         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1021     os->packets_written++;
1022     return ff_write_chained(os->ctx, 0, pkt, s, 0);
1023 }
1024
1025 static int dash_write_trailer(AVFormatContext *s)
1026 {
1027     DASHContext *c = s->priv_data;
1028
1029     if (s->nb_streams > 0) {
1030         OutputStream *os = &c->streams[0];
1031         // If no segments have been written so far, try to do a crude
1032         // guess of the segment duration
1033         if (!c->last_duration)
1034             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1035                                             s->streams[0]->time_base,
1036                                             AV_TIME_BASE_Q);
1037         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1038                                          s->streams[0]->time_base,
1039                                          AV_TIME_BASE_Q);
1040     }
1041     dash_flush(s, 1, -1);
1042
1043     if (c->remove_at_exit) {
1044         char filename[1024];
1045         int i;
1046         for (i = 0; i < s->nb_streams; i++) {
1047             OutputStream *os = &c->streams[i];
1048             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1049             unlink(filename);
1050         }
1051         unlink(s->filename);
1052     }
1053
1054     return 0;
1055 }
1056
1057 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1058 {
1059     DASHContext *c = s->priv_data;
1060     OutputStream *os = &c->streams[avpkt->stream_index];
1061     AVFormatContext *oc = os->ctx;
1062     if (oc->oformat->check_bitstream) {
1063         int ret;
1064         AVPacket pkt = *avpkt;
1065         pkt.stream_index = 0;
1066         ret = oc->oformat->check_bitstream(oc, &pkt);
1067         if (ret == 1) {
1068             AVStream *st = s->streams[avpkt->stream_index];
1069             AVStream *ost = oc->streams[0];
1070             st->internal->bsfcs = ost->internal->bsfcs;
1071             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1072             ost->internal->bsfcs = NULL;
1073             ost->internal->nb_bsfcs = 0;
1074         }
1075         return ret;
1076     }
1077     return 1;
1078 }
1079
1080 #define OFFSET(x) offsetof(DASHContext, x)
1081 #define E AV_OPT_FLAG_ENCODING_PARAM
1082 static const AVOption options[] = {
1083     { "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 },
1084     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1085     { "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 },
1086     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
1087     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1088     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1089     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1090     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1091     { "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 },
1092     { "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 },
1093     { "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 },
1094     { "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 },
1095     { NULL },
1096 };
1097
1098 static const AVClass dash_class = {
1099     .class_name = "dash muxer",
1100     .item_name  = av_default_item_name,
1101     .option     = options,
1102     .version    = LIBAVUTIL_VERSION_INT,
1103 };
1104
1105 AVOutputFormat ff_dash_muxer = {
1106     .name           = "dash",
1107     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1108     .priv_data_size = sizeof(DASHContext),
1109     .audio_codec    = AV_CODEC_ID_AAC,
1110     .video_codec    = AV_CODEC_ID_H264,
1111     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1112     .init           = dash_init,
1113     .write_header   = dash_write_header,
1114     .write_packet   = dash_write_packet,
1115     .write_trailer  = dash_write_trailer,
1116     .deinit         = dash_free,
1117     .check_bitstream = dash_check_bitstream,
1118     .priv_class     = &dash_class,
1119 };