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