]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
197af199561226ca656acab8a5578f1f9d97ef6f
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #if HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time_internal.h"
32
33 #include "avc.h"
34 #include "avformat.h"
35 #include "avio_internal.h"
36 #include "internal.h"
37 #include "isom.h"
38 #include "os_support.h"
39 #include "url.h"
40
41 // See ISO/IEC 23009-1:2014 5.3.9.4.4
42 typedef enum {
43     DASH_TMPL_ID_UNDEFINED = -1,
44     DASH_TMPL_ID_ESCAPE,
45     DASH_TMPL_ID_REP_ID,
46     DASH_TMPL_ID_NUMBER,
47     DASH_TMPL_ID_BANDWIDTH,
48     DASH_TMPL_ID_TIME,
49 } DASHTmplId;
50
51 typedef struct Segment {
52     char file[1024];
53     int64_t start_pos;
54     int range_length, index_length;
55     int64_t time;
56     int duration;
57     int n;
58 } Segment;
59
60 typedef struct OutputStream {
61     AVFormatContext *ctx;
62     int ctx_inited;
63     uint8_t iobuf[32768];
64     URLContext *out;
65     int packets_written;
66     char initfile[1024];
67     int64_t init_start_pos;
68     int init_range_length;
69     int nb_segments, segments_size, segment_index;
70     Segment **segments;
71     int64_t first_pts, start_pts, max_pts;
72     int bit_rate;
73     char bandwidth_str[64];
74
75     char codec_str[100];
76 } OutputStream;
77
78 typedef struct DASHContext {
79     const AVClass *class;  /* Class for private options. */
80     int window_size;
81     int extra_window_size;
82     int min_seg_duration;
83     int remove_at_exit;
84     int use_template;
85     int use_timeline;
86     int single_file;
87     OutputStream *streams;
88     int has_video, has_audio;
89     int64_t last_duration;
90     int64_t total_duration;
91     char availability_start_time[100];
92     char dirname[1024];
93     const char *single_file_name;
94     const char *init_seg_name;
95     const char *media_seg_name;
96 } DASHContext;
97
98 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
99 {
100     OutputStream *os = opaque;
101     if (os->out)
102         ffurl_write(os->out, buf, buf_size);
103     return buf_size;
104 }
105
106 // RFC 6381
107 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
108                           char *str, int size)
109 {
110     const AVCodecTag *tags[2] = { NULL, NULL };
111     uint32_t tag;
112     if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
113         tags[0] = ff_codec_movvideo_tags;
114     else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
115         tags[0] = ff_codec_movaudio_tags;
116     else
117         return;
118
119     tag = av_codec_get_tag(tags, codec->codec_id);
120     if (!tag)
121         return;
122     if (size < 5)
123         return;
124
125     AV_WL32(str, tag);
126     str[4] = '\0';
127     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
128         uint32_t oti;
129         tags[0] = ff_mp4_obj_type;
130         oti = av_codec_get_tag(tags, codec->codec_id);
131         if (oti)
132             av_strlcatf(str, size, ".%02x", oti);
133         else
134             return;
135
136         if (tag == MKTAG('m', 'p', '4', 'a')) {
137             if (codec->extradata_size >= 2) {
138                 int aot = codec->extradata[0] >> 3;
139                 if (aot == 31)
140                     aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
141                 av_strlcatf(str, size, ".%d", aot);
142             }
143         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
144             // Unimplemented, should output ProfileLevelIndication as a decimal number
145             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
146         }
147     } else if (!strcmp(str, "avc1")) {
148         uint8_t *tmpbuf = NULL;
149         uint8_t *extradata = codec->extradata;
150         int extradata_size = codec->extradata_size;
151         if (!extradata_size)
152             return;
153         if (extradata[0] != 1) {
154             AVIOContext *pb;
155             if (avio_open_dyn_buf(&pb) < 0)
156                 return;
157             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
158                 ffio_free_dyn_buf(&pb);
159                 return;
160             }
161             extradata_size = avio_close_dyn_buf(pb, &extradata);
162             tmpbuf = extradata;
163         }
164
165         if (extradata_size >= 4)
166             av_strlcatf(str, size, ".%02x%02x%02x",
167                         extradata[1], extradata[2], extradata[3]);
168         av_free(tmpbuf);
169     }
170 }
171
172 static void dash_free(AVFormatContext *s)
173 {
174     DASHContext *c = s->priv_data;
175     int i, j;
176     if (!c->streams)
177         return;
178     for (i = 0; i < s->nb_streams; i++) {
179         OutputStream *os = &c->streams[i];
180         if (os->ctx && os->ctx_inited)
181             av_write_trailer(os->ctx);
182         if (os->ctx && os->ctx->pb)
183             av_free(os->ctx->pb);
184         ffurl_close(os->out);
185         os->out =  NULL;
186         if (os->ctx)
187             avformat_free_context(os->ctx);
188         for (j = 0; j < os->nb_segments; j++)
189             av_free(os->segments[j]);
190         av_free(os->segments);
191     }
192     av_freep(&c->streams);
193 }
194
195 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
196 {
197     int i, start_index = 0, start_number = 1;
198     if (c->window_size) {
199         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
200         start_number = FFMAX(os->segment_index - c->window_size, 1);
201     }
202
203     if (c->use_template) {
204         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
205         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
206         if (!c->use_timeline)
207             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
208         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
209         if (c->use_timeline) {
210             int64_t cur_time = 0;
211             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
212             for (i = start_index; i < os->nb_segments; ) {
213                 Segment *seg = os->segments[i];
214                 int repeat = 0;
215                 avio_printf(out, "\t\t\t\t\t\t<S ");
216                 if (i == start_index || seg->time != cur_time) {
217                     cur_time = seg->time;
218                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
219                 }
220                 avio_printf(out, "d=\"%d\" ", seg->duration);
221                 while (i + repeat + 1 < os->nb_segments &&
222                        os->segments[i + repeat + 1]->duration == seg->duration &&
223                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
224                     repeat++;
225                 if (repeat > 0)
226                     avio_printf(out, "r=\"%d\" ", repeat);
227                 avio_printf(out, "/>\n");
228                 i += 1 + repeat;
229                 cur_time += (1 + repeat) * seg->duration;
230             }
231             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
232         }
233         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
234     } else if (c->single_file) {
235         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
236         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
237         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);
238         for (i = start_index; i < os->nb_segments; i++) {
239             Segment *seg = os->segments[i];
240             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
241             if (seg->index_length)
242                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
243             avio_printf(out, "/>\n");
244         }
245         avio_printf(out, "\t\t\t\t</SegmentList>\n");
246     } else {
247         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
248         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
249         for (i = start_index; i < os->nb_segments; i++) {
250             Segment *seg = os->segments[i];
251             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
252         }
253         avio_printf(out, "\t\t\t\t</SegmentList>\n");
254     }
255 }
256
257 static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
258                                     size_t format_tag_size, const char **ptr) {
259     const char *next_ptr;
260     DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
261
262     if (av_strstart(identifier, "$$", &next_ptr)) {
263         id_type = DASH_TMPL_ID_ESCAPE;
264         *ptr = next_ptr;
265     } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
266         id_type = DASH_TMPL_ID_REP_ID;
267         // default to basic format, as $RepresentationID$ identifiers
268         // are not allowed to have custom format-tags.
269         av_strlcpy(format_tag, "%d", format_tag_size);
270         *ptr = next_ptr;
271     } else { // the following identifiers may have an explicit format_tag
272         if (av_strstart(identifier, "$Number", &next_ptr))
273             id_type = DASH_TMPL_ID_NUMBER;
274         else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
275             id_type = DASH_TMPL_ID_BANDWIDTH;
276         else if (av_strstart(identifier, "$Time", &next_ptr))
277             id_type = DASH_TMPL_ID_TIME;
278         else
279             id_type = DASH_TMPL_ID_UNDEFINED;
280
281         // next parse the dash format-tag and generate a c-string format tag
282         // (next_ptr now points at the first '%' at the beginning of the format-tag)
283         if (id_type != DASH_TMPL_ID_UNDEFINED) {
284             const char *number_format = (id_type == DASH_TMPL_ID_TIME) ? PRId64 : "d";
285             if (next_ptr[0] == '$') { // no dash format-tag
286                 snprintf(format_tag, format_tag_size, "%%%s", number_format);
287                 *ptr = &next_ptr[1];
288             } else {
289                 const char *width_ptr;
290                 // only tolerate single-digit width-field (i.e. up to 9-digit width)
291                 if (av_strstart(next_ptr, "%0", &width_ptr) &&
292                     av_isdigit(width_ptr[0]) &&
293                     av_strstart(&width_ptr[1], "d$", &next_ptr)) {
294                     // yes, we're using a format tag to build format_tag.
295                     snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
296                     *ptr = next_ptr;
297                 } else {
298                     av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
299                                                  "closing '$' character or a format-string like '%%0[width]d', "
300                                                  "where width must be a single digit\n", next_ptr);
301                     id_type = DASH_TMPL_ID_UNDEFINED;
302                 }
303             }
304         }
305     }
306     return id_type;
307 }
308
309 static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
310                                   const char *template, int rep_id,
311                                   int number, int bit_rate,
312                                   int64_t time) {
313     int dst_pos = 0;
314     const char *t_cur = template;
315     while (dst_pos < buffer_size - 1 && *t_cur) {
316         char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
317         int n = 0;
318         DASHTmplId id_type;
319         const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
320         if (t_next) {
321             int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
322             av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
323             // advance
324             dst_pos += num_copy_bytes;
325             t_cur = t_next;
326         } else { // no more DASH identifiers to substitute - just copy the rest over and break
327             av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
328             break;
329         }
330
331         if (dst_pos >= buffer_size - 1 || !*t_cur)
332             break;
333
334         // t_cur is now pointing to a '$' character
335         id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
336         switch (id_type) {
337         case DASH_TMPL_ID_ESCAPE:
338             av_strlcpy(&dst[dst_pos], "$", 2);
339             n = 1;
340             break;
341         case DASH_TMPL_ID_REP_ID:
342             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
343             break;
344         case DASH_TMPL_ID_NUMBER:
345             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
346             break;
347         case DASH_TMPL_ID_BANDWIDTH:
348             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
349             break;
350         case DASH_TMPL_ID_TIME:
351             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
352             break;
353         case DASH_TMPL_ID_UNDEFINED:
354             // copy over one byte and advance
355             av_strlcpy(&dst[dst_pos], t_cur, 2);
356             n = 1;
357             t_next = &t_cur[1];
358             break;
359         }
360         // t_next points just past the processed identifier
361         // n is the number of bytes that were attempted to be written to dst
362         // (may have failed to write all because buffer_size).
363
364         // advance
365         dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
366         t_cur = t_next;
367     }
368 }
369
370 static char *xmlescape(const char *str) {
371     int outlen = strlen(str)*3/2 + 6;
372     char *out = av_realloc(NULL, outlen + 1);
373     int pos = 0;
374     if (!out)
375         return NULL;
376     for (; *str; str++) {
377         if (pos + 6 > outlen) {
378             char *tmp;
379             outlen = 2 * outlen + 6;
380             tmp = av_realloc(out, outlen + 1);
381             if (!tmp) {
382                 av_free(out);
383                 return NULL;
384             }
385             out = tmp;
386         }
387         if (*str == '&') {
388             memcpy(&out[pos], "&amp;", 5);
389             pos += 5;
390         } else if (*str == '<') {
391             memcpy(&out[pos], "&lt;", 4);
392             pos += 4;
393         } else if (*str == '>') {
394             memcpy(&out[pos], "&gt;", 4);
395             pos += 4;
396         } else if (*str == '\'') {
397             memcpy(&out[pos], "&apos;", 6);
398             pos += 6;
399         } else if (*str == '\"') {
400             memcpy(&out[pos], "&quot;", 6);
401             pos += 6;
402         } else {
403             out[pos++] = *str;
404         }
405     }
406     out[pos] = '\0';
407     return out;
408 }
409
410 static void write_time(AVIOContext *out, int64_t time)
411 {
412     int seconds = time / AV_TIME_BASE;
413     int fractions = time % AV_TIME_BASE;
414     int minutes = seconds / 60;
415     int hours = minutes / 60;
416     seconds %= 60;
417     minutes %= 60;
418     avio_printf(out, "PT");
419     if (hours)
420         avio_printf(out, "%dH", hours);
421     if (hours || minutes)
422         avio_printf(out, "%dM", minutes);
423     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
424 }
425
426 static int write_manifest(AVFormatContext *s, int final)
427 {
428     DASHContext *c = s->priv_data;
429     AVIOContext *out;
430     char temp_filename[1024];
431     int ret, i;
432     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
433
434     snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
435     ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
436     if (ret < 0) {
437         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
438         return ret;
439     }
440     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
441     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
442                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
443                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
444                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
445                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
446                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
447     if (final) {
448         avio_printf(out, "\tmediaPresentationDuration=\"");
449         write_time(out, c->total_duration);
450         avio_printf(out, "\"\n");
451     } else {
452         int64_t update_period = c->last_duration / AV_TIME_BASE;
453         if (c->use_template && !c->use_timeline)
454             update_period = 500;
455         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
456         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
457         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
458             time_t t = time(NULL);
459             struct tm *ptm, tmbuf;
460             ptm = gmtime_r(&t, &tmbuf);
461             if (ptm) {
462                 if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
463                               "%Y-%m-%dT%H:%M:%S", ptm))
464                     c->availability_start_time[0] = '\0';
465             }
466         }
467         if (c->availability_start_time[0])
468             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
469         if (c->window_size && c->use_template) {
470             avio_printf(out, "\ttimeShiftBufferDepth=\"");
471             write_time(out, c->last_duration * c->window_size);
472             avio_printf(out, "\"\n");
473         }
474     }
475     avio_printf(out, "\tminBufferTime=\"");
476     write_time(out, c->last_duration);
477     avio_printf(out, "\">\n");
478     avio_printf(out, "\t<ProgramInformation>\n");
479     if (title) {
480         char *escaped = xmlescape(title->value);
481         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
482         av_free(escaped);
483     }
484     avio_printf(out, "\t</ProgramInformation>\n");
485     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
486         OutputStream *os = &c->streams[0];
487         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
488         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
489         avio_printf(out, "\t<Period start=\"");
490         write_time(out, start_time);
491         avio_printf(out, "\">\n");
492     } else {
493         avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
494     }
495
496     if (c->has_video) {
497         avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
498         for (i = 0; i < s->nb_streams; i++) {
499             AVStream *st = s->streams[i];
500             OutputStream *os = &c->streams[i];
501             if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
502                 continue;
503             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);
504             output_segment_list(&c->streams[i], out, c);
505             avio_printf(out, "\t\t\t</Representation>\n");
506         }
507         avio_printf(out, "\t\t</AdaptationSet>\n");
508     }
509     if (c->has_audio) {
510         avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
511         for (i = 0; i < s->nb_streams; i++) {
512             AVStream *st = s->streams[i];
513             OutputStream *os = &c->streams[i];
514             if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
515                 continue;
516             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->sample_rate);
517             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
518             output_segment_list(&c->streams[i], out, c);
519             avio_printf(out, "\t\t\t</Representation>\n");
520         }
521         avio_printf(out, "\t\t</AdaptationSet>\n");
522     }
523     avio_printf(out, "\t</Period>\n");
524     avio_printf(out, "</MPD>\n");
525     avio_flush(out);
526     avio_close(out);
527     return ff_rename(temp_filename, s->filename);
528 }
529
530 static int dash_write_header(AVFormatContext *s)
531 {
532     DASHContext *c = s->priv_data;
533     int ret = 0, i;
534     AVOutputFormat *oformat;
535     char *ptr;
536     char basename[1024];
537
538     if (c->single_file_name)
539         c->single_file = 1;
540     if (c->single_file)
541         c->use_template = 0;
542
543     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
544     ptr = strrchr(c->dirname, '/');
545     if (ptr) {
546         av_strlcpy(basename, &ptr[1], sizeof(basename));
547         ptr[1] = '\0';
548     } else {
549         c->dirname[0] = '\0';
550         av_strlcpy(basename, s->filename, sizeof(basename));
551     }
552
553     ptr = strrchr(basename, '.');
554     if (ptr)
555         *ptr = '\0';
556
557     oformat = av_guess_format("mp4", NULL, NULL);
558     if (!oformat) {
559         ret = AVERROR_MUXER_NOT_FOUND;
560         goto fail;
561     }
562
563     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
564     if (!c->streams) {
565         ret = AVERROR(ENOMEM);
566         goto fail;
567     }
568
569     for (i = 0; i < s->nb_streams; i++) {
570         OutputStream *os = &c->streams[i];
571         AVFormatContext *ctx;
572         AVStream *st;
573         AVDictionary *opts = NULL;
574         char filename[1024];
575
576         os->bit_rate = s->streams[i]->codec->bit_rate;
577         if (os->bit_rate) {
578             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
579                      " bandwidth=\"%d\"", os->bit_rate);
580         } else {
581             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
582                         AV_LOG_ERROR : AV_LOG_WARNING;
583             av_log(s, level, "No bit rate set for stream %d\n", i);
584             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
585                 ret = AVERROR(EINVAL);
586                 goto fail;
587             }
588         }
589
590         ctx = avformat_alloc_context();
591         if (!ctx) {
592             ret = AVERROR(ENOMEM);
593             goto fail;
594         }
595         os->ctx = ctx;
596         ctx->oformat = oformat;
597         ctx->interrupt_callback = s->interrupt_callback;
598
599         if (!(st = avformat_new_stream(ctx, NULL))) {
600             ret = AVERROR(ENOMEM);
601             goto fail;
602         }
603         avcodec_copy_context(st->codec, s->streams[i]->codec);
604         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
605         st->time_base = s->streams[i]->time_base;
606         ctx->avoid_negative_ts = s->avoid_negative_ts;
607
608         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
609         if (!ctx->pb) {
610             ret = AVERROR(ENOMEM);
611             goto fail;
612         }
613
614         if (c->single_file) {
615             if (c->single_file_name)
616                 dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
617             else
618                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
619         } else {
620             dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
621         }
622         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
623         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
624         if (ret < 0)
625             goto fail;
626         os->init_start_pos = 0;
627
628         av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
629         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
630              goto fail;
631         }
632         os->ctx_inited = 1;
633         avio_flush(ctx->pb);
634         av_dict_free(&opts);
635
636         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
637
638         s->streams[i]->time_base = st->time_base;
639         // If the muxer wants to shift timestamps, request to have them shifted
640         // already before being handed to this muxer, so we don't have mismatches
641         // between the MPD and the actual segments.
642         s->avoid_negative_ts = ctx->avoid_negative_ts;
643         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
644             c->has_video = 1;
645         else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
646             c->has_audio = 1;
647
648         set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
649         os->first_pts = AV_NOPTS_VALUE;
650         os->max_pts = AV_NOPTS_VALUE;
651         os->segment_index = 1;
652     }
653
654     if (!c->has_video && c->min_seg_duration <= 0) {
655         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
656         ret = AVERROR(EINVAL);
657     }
658     ret = write_manifest(s, 0);
659     if (!ret)
660         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
661
662 fail:
663     if (ret)
664         dash_free(s);
665     return ret;
666 }
667
668 static int add_segment(OutputStream *os, const char *file,
669                        int64_t time, int duration,
670                        int64_t start_pos, int64_t range_length,
671                        int64_t index_length)
672 {
673     int err;
674     Segment *seg;
675     if (os->nb_segments >= os->segments_size) {
676         os->segments_size = (os->segments_size + 1) * 2;
677         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
678                                os->segments_size)) < 0) {
679             os->segments_size = 0;
680             os->nb_segments = 0;
681             return err;
682         }
683     }
684     seg = av_mallocz(sizeof(*seg));
685     if (!seg)
686         return AVERROR(ENOMEM);
687     av_strlcpy(seg->file, file, sizeof(seg->file));
688     seg->time = time;
689     if (seg->time < 0) // If pts<0, it is expected to be cut away with an edit list
690         seg->time = 0;
691     seg->duration = duration;
692     seg->start_pos = start_pos;
693     seg->range_length = range_length;
694     seg->index_length = index_length;
695     os->segments[os->nb_segments++] = seg;
696     os->segment_index++;
697     return 0;
698 }
699
700 static void write_styp(AVIOContext *pb)
701 {
702     avio_wb32(pb, 24);
703     ffio_wfourcc(pb, "styp");
704     ffio_wfourcc(pb, "msdh");
705     avio_wb32(pb, 0); /* minor */
706     ffio_wfourcc(pb, "msdh");
707     ffio_wfourcc(pb, "msix");
708 }
709
710 static void find_index_range(AVFormatContext *s, const char *full_path,
711                              int64_t pos, int *index_length)
712 {
713     uint8_t buf[8];
714     URLContext *fd;
715     int ret;
716
717     ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
718     if (ret < 0)
719         return;
720     if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
721         ffurl_close(fd);
722         return;
723     }
724     ret = ffurl_read(fd, buf, 8);
725     ffurl_close(fd);
726     if (ret < 8)
727         return;
728     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
729         return;
730     *index_length = AV_RB32(&buf[0]);
731 }
732
733 static int dash_flush(AVFormatContext *s, int final, int stream)
734 {
735     DASHContext *c = s->priv_data;
736     int i, ret = 0;
737     int cur_flush_segment_index = 0;
738     if (stream >= 0)
739         cur_flush_segment_index = c->streams[stream].segment_index;
740
741     for (i = 0; i < s->nb_streams; i++) {
742         OutputStream *os = &c->streams[i];
743         char filename[1024] = "", full_path[1024], temp_path[1024];
744         int64_t start_pos;
745         int range_length, index_length = 0;
746
747         if (!os->packets_written)
748             continue;
749
750         // Flush the single stream that got a keyframe right now.
751         // Flush all audio streams as well, in sync with video keyframes,
752         // but not the other video streams.
753         if (stream >= 0 && i != stream) {
754             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
755                 continue;
756             // Make sure we don't flush audio streams multiple times, when
757             // all video streams are flushed one at a time.
758             if (c->has_video && os->segment_index > cur_flush_segment_index)
759                 continue;
760         }
761
762         if (!os->init_range_length) {
763             av_write_frame(os->ctx, NULL);
764             os->init_range_length = avio_tell(os->ctx->pb);
765             if (!c->single_file) {
766                 ffurl_close(os->out);
767                 os->out = NULL;
768             }
769         }
770
771         start_pos = avio_tell(os->ctx->pb);
772
773         if (!c->single_file) {
774             dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
775             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
776             snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
777             ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
778             if (ret < 0)
779                 break;
780             write_styp(os->ctx->pb);
781         } else {
782             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
783         }
784
785         av_write_frame(os->ctx, NULL);
786         avio_flush(os->ctx->pb);
787         os->packets_written = 0;
788
789         range_length = avio_tell(os->ctx->pb) - start_pos;
790         if (c->single_file) {
791             find_index_range(s, full_path, start_pos, &index_length);
792         } else {
793             ffurl_close(os->out);
794             os->out = NULL;
795             ret = ff_rename(temp_path, full_path);
796             if (ret < 0)
797                 break;
798         }
799         add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
800         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
801     }
802
803     if (c->window_size || (final && c->remove_at_exit)) {
804         for (i = 0; i < s->nb_streams; i++) {
805             OutputStream *os = &c->streams[i];
806             int j;
807             int remove = os->nb_segments - c->window_size - c->extra_window_size;
808             if (final && c->remove_at_exit)
809                 remove = os->nb_segments;
810             if (remove > 0) {
811                 for (j = 0; j < remove; j++) {
812                     char filename[1024];
813                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
814                     unlink(filename);
815                     av_free(os->segments[j]);
816                 }
817                 os->nb_segments -= remove;
818                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
819             }
820         }
821     }
822
823     if (ret >= 0)
824         ret = write_manifest(s, final);
825     return ret;
826 }
827
828 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
829 {
830     DASHContext *c = s->priv_data;
831     AVStream *st = s->streams[pkt->stream_index];
832     OutputStream *os = &c->streams[pkt->stream_index];
833     int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
834     int ret;
835
836     // If forcing the stream to start at 0, the mp4 muxer will set the start
837     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
838     if (os->first_pts == AV_NOPTS_VALUE &&
839         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
840         pkt->pts -= pkt->dts;
841         pkt->dts  = 0;
842     }
843
844     if (os->first_pts == AV_NOPTS_VALUE)
845         os->first_pts = pkt->pts;
846
847     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
848         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
849         av_compare_ts(pkt->pts - os->first_pts, st->time_base,
850                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
851         int64_t prev_duration = c->last_duration;
852
853         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
854                                         st->time_base,
855                                         AV_TIME_BASE_Q);
856         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
857                                          st->time_base,
858                                          AV_TIME_BASE_Q);
859
860         if ((!c->use_timeline || !c->use_template) && prev_duration) {
861             if (c->last_duration < prev_duration*9/10 ||
862                 c->last_duration > prev_duration*11/10) {
863                 av_log(s, AV_LOG_WARNING,
864                        "Segment durations differ too much, enable use_timeline "
865                        "and use_template, or keep a stricter keyframe interval\n");
866             }
867         }
868
869         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
870             return ret;
871     }
872
873     if (!os->packets_written) {
874         // If we wrote a previous segment, adjust the start time of the segment
875         // to the end of the previous one (which is the same as the mp4 muxer
876         // does). This avoids gaps in the timeline.
877         if (os->max_pts != AV_NOPTS_VALUE)
878             os->start_pts = os->max_pts;
879         else
880             os->start_pts = pkt->pts;
881     }
882     if (os->max_pts == AV_NOPTS_VALUE)
883         os->max_pts = pkt->pts + pkt->duration;
884     else
885         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
886     os->packets_written++;
887     return ff_write_chained(os->ctx, 0, pkt, s);
888 }
889
890 static int dash_write_trailer(AVFormatContext *s)
891 {
892     DASHContext *c = s->priv_data;
893
894     if (s->nb_streams > 0) {
895         OutputStream *os = &c->streams[0];
896         // If no segments have been written so far, try to do a crude
897         // guess of the segment duration
898         if (!c->last_duration)
899             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
900                                             s->streams[0]->time_base,
901                                             AV_TIME_BASE_Q);
902         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
903                                          s->streams[0]->time_base,
904                                          AV_TIME_BASE_Q);
905     }
906     dash_flush(s, 1, -1);
907
908     if (c->remove_at_exit) {
909         char filename[1024];
910         int i;
911         for (i = 0; i < s->nb_streams; i++) {
912             OutputStream *os = &c->streams[i];
913             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
914             unlink(filename);
915         }
916         unlink(s->filename);
917     }
918
919     dash_free(s);
920     return 0;
921 }
922
923 #define OFFSET(x) offsetof(DASHContext, x)
924 #define E AV_OPT_FLAG_ENCODING_PARAM
925 static const AVOption options[] = {
926     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
927     { "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 },
928     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
929     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
930     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
931     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
932     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
933     { "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 },
934     { "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 },
935     { "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 },
936     { NULL },
937 };
938
939 static const AVClass dash_class = {
940     .class_name = "dash muxer",
941     .item_name  = av_default_item_name,
942     .option     = options,
943     .version    = LIBAVUTIL_VERSION_INT,
944 };
945
946 AVOutputFormat ff_dash_muxer = {
947     .name           = "dash",
948     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
949     .priv_data_size = sizeof(DASHContext),
950     .audio_codec    = AV_CODEC_ID_AAC,
951     .video_codec    = AV_CODEC_ID_H264,
952     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
953     .write_header   = dash_write_header,
954     .write_packet   = dash_write_packet,
955     .write_trailer  = dash_write_trailer,
956     .codec_tag      = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
957     .priv_class     = &dash_class,
958 };