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