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