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