Browse code

Merge commit 'fe5e6e34c05e274f98528be4f77f3c474473f977'

* commit 'fe5e6e34c05e274f98528be4f77f3c474473f977':
lavf: Add an MPEG-DASH ISOFF segmenting muxer

Conflicts:
Changelog
libavformat/Makefile
libavformat/allformats.c
libavformat/version.h

Merged-by: Michael Niedermayer <michaelni@gmx.at>

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