dashenc: Don't require the stream bitrate to be known
[ffmpeg.git] / 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 typedef struct Segment {
42     char file[1024];
43     int64_t start_pos;
44     int range_length, index_length;
45     int64_t time;
46     int duration;
47     int n;
48 } Segment;
49
50 typedef struct OutputStream {
51     AVFormatContext *ctx;
52     int ctx_inited;
53     uint8_t iobuf[32768];
54     URLContext *out;
55     int packets_written;
56     char initfile[1024];
57     int64_t init_start_pos;
58     int init_range_length;
59     int nb_segments, segments_size, segment_index;
60     Segment **segments;
61     int64_t first_dts, start_dts, end_dts;
62     char bandwidth_str[64];
63
64     char codec_str[100];
65 } OutputStream;
66
67 typedef struct DASHContext {
68     const AVClass *class;  /* Class for private options. */
69     int window_size;
70     int extra_window_size;
71     int min_seg_duration;
72     int remove_at_exit;
73     int use_template;
74     int use_timeline;
75     int single_file;
76     OutputStream *streams;
77     int has_video, has_audio;
78     int nb_segments;
79     int last_duration;
80     int total_duration;
81     char availability_start_time[100];
82     char dirname[1024];
83 } DASHContext;
84
85 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
86 {
87     OutputStream *os = opaque;
88     if (os->out)
89         ffurl_write(os->out, buf, buf_size);
90     return buf_size;
91 }
92
93 // RFC 6381
94 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
95                           char *str, int size)
96 {
97     const AVCodecTag *tags[2] = { NULL, NULL };
98     uint32_t tag;
99     if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
100         tags[0] = ff_codec_movvideo_tags;
101     else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
102         tags[0] = ff_codec_movaudio_tags;
103     else
104         return;
105
106     tag = av_codec_get_tag(tags, codec->codec_id);
107     if (!tag)
108         return;
109     if (size < 5)
110         return;
111
112     AV_WL32(str, tag);
113     str[4] = '\0';
114     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
115         uint32_t oti;
116         tags[0] = ff_mp4_obj_type;
117         oti = av_codec_get_tag(tags, codec->codec_id);
118         if (oti)
119             av_strlcatf(str, size, ".%02x", oti);
120         else
121             return;
122
123         if (tag == MKTAG('m', 'p', '4', 'a')) {
124             if (codec->extradata_size >= 2) {
125                 int aot = codec->extradata[0] >> 3;
126                 if (aot == 31)
127                     aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
128                 av_strlcatf(str, size, ".%d", aot);
129             }
130         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
131             // Unimplemented, should output ProfileLevelIndication as a decimal number
132             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
133         }
134     } else if (!strcmp(str, "avc1")) {
135         uint8_t *tmpbuf = NULL;
136         uint8_t *extradata = codec->extradata;
137         int extradata_size = codec->extradata_size;
138         if (!extradata_size)
139             return;
140         if (extradata[0] != 1) {
141             AVIOContext *pb;
142             if (avio_open_dyn_buf(&pb) < 0)
143                 return;
144             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
145                 avio_close_dyn_buf(pb, &tmpbuf);
146                 av_free(tmpbuf);
147                 return;
148             }
149             extradata_size = avio_close_dyn_buf(pb, &extradata);
150             tmpbuf = extradata;
151         }
152
153         if (extradata_size >= 4)
154             av_strlcatf(str, size, ".%02x%02x%02x",
155                         extradata[1], extradata[2], extradata[3]);
156         av_free(tmpbuf);
157     }
158 }
159
160 static void dash_free(AVFormatContext *s)
161 {
162     DASHContext *c = s->priv_data;
163     int i, j;
164     if (!c->streams)
165         return;
166     for (i = 0; i < s->nb_streams; i++) {
167         OutputStream *os = &c->streams[i];
168         if (os->ctx && os->ctx_inited)
169             av_write_trailer(os->ctx);
170         if (os->ctx && os->ctx->pb)
171             av_free(os->ctx->pb);
172         ffurl_close(os->out);
173         os->out =  NULL;
174         if (os->ctx)
175             avformat_free_context(os->ctx);
176         for (j = 0; j < os->nb_segments; j++)
177             av_free(os->segments[j]);
178         av_free(os->segments);
179     }
180     av_freep(&c->streams);
181 }
182
183 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
184 {
185     int i, start_index = 0, start_number = 1;
186     if (c->window_size) {
187         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
188         start_number = FFMAX(os->segment_index - c->window_size, 1);
189     }
190
191     if (c->use_template) {
192         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
193         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
194         if (!c->use_timeline)
195             avio_printf(out, "duration=\"%d\" ", c->last_duration);
196         avio_printf(out, "initialization=\"init-stream$RepresentationID$.m4s\" media=\"chunk-stream$RepresentationID$-$Number%%05d$.m4s\" startNumber=\"%d\">\n", c->use_timeline ? start_number : 1);
197         if (c->use_timeline) {
198             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
199             for (i = start_index; i < os->nb_segments; ) {
200                 Segment *seg = os->segments[i];
201                 int repeat = 0;
202                 avio_printf(out, "\t\t\t\t\t\t<S ");
203                 if (i == start_index)
204                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
205                 avio_printf(out, "d=\"%d\" ", seg->duration);
206                 while (i + repeat + 1 < os->nb_segments && os->segments[i + repeat + 1]->duration == seg->duration)
207                     repeat++;
208                 if (repeat > 0)
209                     avio_printf(out, "r=\"%d\" ", repeat);
210                 avio_printf(out, "/>\n");
211                 i += 1 + repeat;
212             }
213             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
214         }
215         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
216     } else if (c->single_file) {
217         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
218         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
219         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);
220         for (i = start_index; i < os->nb_segments; i++) {
221             Segment *seg = os->segments[i];
222             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
223             if (seg->index_length)
224                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
225             avio_printf(out, "/>\n");
226         }
227         avio_printf(out, "\t\t\t\t</SegmentList>\n");
228     } else {
229         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
230         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
231         for (i = start_index; i < os->nb_segments; i++) {
232             Segment *seg = os->segments[i];
233             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
234         }
235         avio_printf(out, "\t\t\t\t</SegmentList>\n");
236     }
237 }
238
239 static char *xmlescape(const char *str) {
240     int outlen = strlen(str)*3/2 + 6;
241     char *out = av_realloc(NULL, outlen + 1);
242     int pos = 0;
243     if (!out)
244         return NULL;
245     for (; *str; str++) {
246         if (pos + 6 > outlen) {
247             char *tmp;
248             outlen = 2 * outlen + 6;
249             tmp = av_realloc(out, outlen + 1);
250             if (!tmp) {
251                 av_free(out);
252                 return NULL;
253             }
254             out = tmp;
255         }
256         if (*str == '&') {
257             memcpy(&out[pos], "&amp;", 5);
258             pos += 5;
259         } else if (*str == '<') {
260             memcpy(&out[pos], "&lt;", 4);
261             pos += 4;
262         } else if (*str == '>') {
263             memcpy(&out[pos], "&gt;", 4);
264             pos += 4;
265         } else if (*str == '\'') {
266             memcpy(&out[pos], "&apos;", 6);
267             pos += 6;
268         } else if (*str == '\"') {
269             memcpy(&out[pos], "&quot;", 6);
270             pos += 6;
271         } else {
272             out[pos++] = *str;
273         }
274     }
275     out[pos] = '\0';
276     return out;
277 }
278
279 static void write_time(AVIOContext *out, int64_t time)
280 {
281     int seconds = time / AV_TIME_BASE;
282     int fractions = time % AV_TIME_BASE;
283     int minutes = seconds / 60;
284     int hours = minutes / 60;
285     seconds %= 60;
286     minutes %= 60;
287     avio_printf(out, "PT");
288     if (hours)
289         avio_printf(out, "%dH", hours);
290     if (hours || minutes)
291         avio_printf(out, "%dM", minutes);
292     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
293 }
294
295 static int write_manifest(AVFormatContext *s, int final)
296 {
297     DASHContext *c = s->priv_data;
298     AVIOContext *out;
299     char temp_filename[1024];
300     int ret, i;
301     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
302
303     snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
304     ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
305     if (ret < 0) {
306         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
307         return ret;
308     }
309     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
310     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
311                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
312                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
313                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
314                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
315                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
316     if (final) {
317         avio_printf(out, "\tmediaPresentationDuration=\"");
318         write_time(out, c->total_duration);
319         avio_printf(out, "\"\n");
320     } else {
321         int update_period = c->last_duration / AV_TIME_BASE;
322         if (c->use_template && !c->use_timeline)
323             update_period = 500;
324         avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
325         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
326         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
327             time_t t = time(NULL);
328             struct tm *ptm, tmbuf;
329             ptm = gmtime_r(&t, &tmbuf);
330             if (ptm) {
331                 if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
332                               "%Y-%m-%dT%H:%M:%S", ptm))
333                     c->availability_start_time[0] = '\0';
334             }
335         }
336         if (c->availability_start_time[0])
337             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
338         if (c->window_size && c->use_template) {
339             avio_printf(out, "\ttimeShiftBufferDepth=\"");
340             write_time(out, c->last_duration * c->window_size);
341             avio_printf(out, "\"\n");
342         }
343     }
344     avio_printf(out, "\tminBufferTime=\"");
345     write_time(out, c->last_duration);
346     avio_printf(out, "\">\n");
347     avio_printf(out, "\t<ProgramInformation>\n");
348     if (title) {
349         char *escaped = xmlescape(title->value);
350         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
351         av_free(escaped);
352     }
353     avio_printf(out, "\t</ProgramInformation>\n");
354     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
355         OutputStream *os = &c->streams[0];
356         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
357         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
358         avio_printf(out, "\t<Period start=\"");
359         write_time(out, start_time);
360         avio_printf(out, "\">\n");
361     } else {
362         avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
363     }
364
365     if (c->has_video) {
366         avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
367         for (i = 0; i < s->nb_streams; i++) {
368             AVStream *st = s->streams[i];
369             OutputStream *os = &c->streams[i];
370             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
371                 continue;
372             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);
373             output_segment_list(&c->streams[i], out, c);
374             avio_printf(out, "\t\t\t</Representation>\n");
375         }
376         avio_printf(out, "\t\t</AdaptationSet>\n");
377     }
378     if (c->has_audio) {
379         avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
380         for (i = 0; i < s->nb_streams; i++) {
381             AVStream *st = s->streams[i];
382             OutputStream *os = &c->streams[i];
383             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
384                 continue;
385             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);
386             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
387             output_segment_list(&c->streams[i], out, c);
388             avio_printf(out, "\t\t\t</Representation>\n");
389         }
390         avio_printf(out, "\t\t</AdaptationSet>\n");
391     }
392     avio_printf(out, "\t</Period>\n");
393     avio_printf(out, "</MPD>\n");
394     avio_flush(out);
395     avio_close(out);
396     return ff_rename(temp_filename, s->filename);
397 }
398
399 static int dash_write_header(AVFormatContext *s)
400 {
401     DASHContext *c = s->priv_data;
402     int ret = 0, i;
403     AVOutputFormat *oformat;
404     char *ptr;
405     char basename[1024];
406
407     if (c->single_file)
408         c->use_template = 0;
409
410     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
411     ptr = strrchr(c->dirname, '/');
412     if (ptr) {
413         av_strlcpy(basename, &ptr[1], sizeof(basename));
414         ptr[1] = '\0';
415     } else {
416         c->dirname[0] = '\0';
417         av_strlcpy(basename, s->filename, sizeof(basename));
418     }
419
420     ptr = strrchr(basename, '.');
421     if (ptr)
422         *ptr = '\0';
423
424     oformat = av_guess_format("mp4", NULL, NULL);
425     if (!oformat) {
426         ret = AVERROR_MUXER_NOT_FOUND;
427         goto fail;
428     }
429
430     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
431     if (!c->streams) {
432         ret = AVERROR(ENOMEM);
433         goto fail;
434     }
435
436     for (i = 0; i < s->nb_streams; i++) {
437         OutputStream *os = &c->streams[i];
438         AVFormatContext *ctx;
439         AVStream *st;
440         AVDictionary *opts = NULL;
441         char filename[1024];
442
443         if (s->streams[i]->codec->bit_rate) {
444             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
445                      " bandwidth=\"%d\"", s->streams[i]->codec->bit_rate);
446         } else {
447             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
448                         AV_LOG_ERROR : AV_LOG_WARNING;
449             av_log(s, level, "No bit rate set for stream %d\n", i);
450             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
451                 ret = AVERROR(EINVAL);
452                 goto fail;
453             }
454         }
455
456         ctx = avformat_alloc_context();
457         if (!ctx) {
458             ret = AVERROR(ENOMEM);
459             goto fail;
460         }
461         os->ctx = ctx;
462         ctx->oformat = oformat;
463         ctx->interrupt_callback = s->interrupt_callback;
464
465         if (!(st = avformat_new_stream(ctx, NULL))) {
466             ret = AVERROR(ENOMEM);
467             goto fail;
468         }
469         avcodec_copy_context(st->codec, s->streams[i]->codec);
470         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
471         st->time_base = s->streams[i]->time_base;
472         ctx->avoid_negative_ts = s->avoid_negative_ts;
473
474         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
475         if (!ctx->pb) {
476             ret = AVERROR(ENOMEM);
477             goto fail;
478         }
479
480         if (c->single_file)
481             snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
482         else
483             snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
484         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
485         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
486         if (ret < 0)
487             goto fail;
488         os->init_start_pos = 0;
489
490         av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
491         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
492              goto fail;
493         }
494         os->ctx_inited = 1;
495         avio_flush(ctx->pb);
496         av_dict_free(&opts);
497
498         if (c->single_file) {
499             os->init_range_length = avio_tell(ctx->pb);
500         } else {
501             ffurl_close(os->out);
502             os->out = NULL;
503         }
504
505         s->streams[i]->time_base = st->time_base;
506         // If the muxer wants to shift timestamps, request to have them shifted
507         // already before being handed to this muxer, so we don't have mismatches
508         // between the MPD and the actual segments.
509         s->avoid_negative_ts = ctx->avoid_negative_ts;
510         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
511             c->has_video = 1;
512         else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
513             c->has_audio = 1;
514
515         set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
516         os->first_dts = AV_NOPTS_VALUE;
517         os->segment_index = 1;
518     }
519
520     if (!c->has_video && c->min_seg_duration <= 0) {
521         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
522         ret = AVERROR(EINVAL);
523     }
524     ret = write_manifest(s, 0);
525
526 fail:
527     if (ret)
528         dash_free(s);
529     return ret;
530 }
531
532 static int add_segment(OutputStream *os, const char *file,
533                        int64_t time, int duration,
534                        int64_t start_pos, int64_t range_length,
535                        int64_t index_length)
536 {
537     int err;
538     Segment *seg;
539     if (os->nb_segments >= os->segments_size) {
540         os->segments_size = (os->segments_size + 1) * 2;
541         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
542                                os->segments_size)) < 0) {
543             os->segments_size = 0;
544             os->nb_segments = 0;
545             return err;
546         }
547     }
548     seg = av_mallocz(sizeof(*seg));
549     if (!seg)
550         return AVERROR(ENOMEM);
551     av_strlcpy(seg->file, file, sizeof(seg->file));
552     seg->time = time;
553     seg->duration = duration;
554     seg->start_pos = start_pos;
555     seg->range_length = range_length;
556     seg->index_length = index_length;
557     os->segments[os->nb_segments++] = seg;
558     os->segment_index++;
559     return 0;
560 }
561
562 static void write_styp(AVIOContext *pb)
563 {
564     avio_wb32(pb, 24);
565     ffio_wfourcc(pb, "styp");
566     ffio_wfourcc(pb, "msdh");
567     avio_wb32(pb, 0); /* minor */
568     ffio_wfourcc(pb, "msdh");
569     ffio_wfourcc(pb, "msix");
570 }
571
572 static void find_index_range(AVFormatContext *s, const char *dirname,
573                              const char *filename, int64_t pos,
574                              int *index_length)
575 {
576     char full_path[1024];
577     uint8_t buf[8];
578     URLContext *fd;
579     int ret;
580
581     snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
582     ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
583     if (ret < 0)
584         return;
585     if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
586         ffurl_close(fd);
587         return;
588     }
589     ret = ffurl_read(fd, buf, 8);
590     ffurl_close(fd);
591     if (ret < 8)
592         return;
593     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
594         return;
595     *index_length = AV_RB32(&buf[0]);
596 }
597
598 static int dash_flush(AVFormatContext *s, int final)
599 {
600     DASHContext *c = s->priv_data;
601     int i, ret = 0;
602
603     for (i = 0; i < s->nb_streams; i++) {
604         OutputStream *os = &c->streams[i];
605         char filename[1024] = "", full_path[1024], temp_path[1024];
606         int64_t start_pos = avio_tell(os->ctx->pb);
607         int range_length, index_length = 0;
608
609         if (!os->packets_written)
610             continue;
611
612         if (!c->single_file) {
613             snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
614             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
615             snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
616             ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
617             if (ret < 0)
618                 break;
619             write_styp(os->ctx->pb);
620         }
621         av_write_frame(os->ctx, NULL);
622         avio_flush(os->ctx->pb);
623         os->packets_written = 0;
624
625         range_length = avio_tell(os->ctx->pb) - start_pos;
626         if (c->single_file) {
627             find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
628         } else {
629             ffurl_close(os->out);
630             os->out = NULL;
631             ret = ff_rename(temp_path, full_path);
632             if (ret < 0)
633                 break;
634         }
635         add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
636     }
637
638     if (c->window_size || (final && c->remove_at_exit)) {
639         for (i = 0; i < s->nb_streams; i++) {
640             OutputStream *os = &c->streams[i];
641             int j;
642             int remove = os->nb_segments - c->window_size - c->extra_window_size;
643             if (final && c->remove_at_exit)
644                 remove = os->nb_segments;
645             if (remove > 0) {
646                 for (j = 0; j < remove; j++) {
647                     char filename[1024];
648                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
649                     unlink(filename);
650                     av_free(os->segments[j]);
651                 }
652                 os->nb_segments -= remove;
653                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
654             }
655         }
656     }
657
658     if (ret >= 0)
659         ret = write_manifest(s, final);
660     return ret;
661 }
662
663 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
664 {
665     DASHContext *c = s->priv_data;
666     AVStream *st = s->streams[pkt->stream_index];
667     OutputStream *os = &c->streams[pkt->stream_index];
668     int64_t seg_end_duration = (c->nb_segments + 1) * (int64_t) c->min_seg_duration;
669     int ret;
670
671     // If forcing the stream to start at 0, the mp4 muxer will set the start
672     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
673     if (os->first_dts == AV_NOPTS_VALUE &&
674         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
675         pkt->pts -= pkt->dts;
676         pkt->dts  = 0;
677     }
678
679     if (os->first_dts == AV_NOPTS_VALUE)
680         os->first_dts = pkt->dts;
681
682     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
683         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
684         av_compare_ts(pkt->dts - os->first_dts, st->time_base,
685                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
686         int64_t prev_duration = c->last_duration;
687
688         c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
689                                         st->time_base,
690                                         AV_TIME_BASE_Q);
691         c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
692                                          st->time_base,
693                                          AV_TIME_BASE_Q);
694
695         if ((!c->use_timeline || !c->use_template) && prev_duration) {
696             if (c->last_duration < prev_duration*9/10 ||
697                 c->last_duration > prev_duration*11/10) {
698                 av_log(s, AV_LOG_WARNING,
699                        "Segment durations differ too much, enable use_timeline "
700                        "and use_template, or keep a stricter keyframe interval\n");
701             }
702         }
703
704         if ((ret = dash_flush(s, 0)) < 0)
705             return ret;
706         c->nb_segments++;
707     }
708
709     if (!os->packets_written)
710         os->start_dts = pkt->dts;
711     os->end_dts = pkt->dts + pkt->duration;
712     os->packets_written++;
713     return ff_write_chained(os->ctx, 0, pkt, s);
714 }
715
716 static int dash_write_trailer(AVFormatContext *s)
717 {
718     DASHContext *c = s->priv_data;
719
720     if (s->nb_streams > 0) {
721         OutputStream *os = &c->streams[0];
722         // If no segments have been written so far, try to do a crude
723         // guess of the segment duration
724         if (!c->last_duration)
725             c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
726                                             s->streams[0]->time_base,
727                                             AV_TIME_BASE_Q);
728         c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
729                                          s->streams[0]->time_base,
730                                          AV_TIME_BASE_Q);
731     }
732     dash_flush(s, 1);
733
734     if (c->remove_at_exit) {
735         char filename[1024];
736         int i;
737         for (i = 0; i < s->nb_streams; i++) {
738             OutputStream *os = &c->streams[i];
739             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
740             unlink(filename);
741         }
742         unlink(s->filename);
743     }
744
745     dash_free(s);
746     return 0;
747 }
748
749 #define OFFSET(x) offsetof(DASHContext, x)
750 #define E AV_OPT_FLAG_ENCODING_PARAM
751 static const AVOption options[] = {
752     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
753     { "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 },
754     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
755     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
756     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
757     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
758     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
759     { NULL },
760 };
761
762 static const AVClass dash_class = {
763     .class_name = "dash muxer",
764     .item_name  = av_default_item_name,
765     .option     = options,
766     .version    = LIBAVUTIL_VERSION_INT,
767 };
768
769 AVOutputFormat ff_dash_muxer = {
770     .name           = "dash",
771     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
772     .priv_data_size = sizeof(DASHContext),
773     .audio_codec    = AV_CODEC_ID_AAC,
774     .video_codec    = AV_CODEC_ID_H264,
775     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
776     .write_header   = dash_write_header,
777     .write_packet   = dash_write_packet,
778     .write_trailer  = dash_write_trailer,
779     .codec_tag      = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
780     .priv_class     = &dash_class,
781 };