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