]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
fate: Add hap-chunk ref file
[ffmpeg] / libavformat / segment.c
1 /*
2  * Generic segmenter
3  * Copyright (c) 2011, Luca Barbato
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 <float.h>
23
24 #include "avformat.h"
25 #include "internal.h"
26
27 #include "libavutil/log.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/parseutils.h"
31 #include "libavutil/mathematics.h"
32
33 typedef struct SegmentContext {
34     const AVClass *class;  /**< Class for private options. */
35     int number;
36     AVOutputFormat *oformat;
37     AVFormatContext *avf;
38     char *format;          /**< Set by a private option. */
39     char *list;            /**< Set by a private option. */
40     char *entry_prefix;    /**< Set by a private option. */
41     int  list_type;        /**< Set by a private option. */
42     float time;            /**< Set by a private option. */
43     int  size;             /**< Set by a private option. */
44     int  wrap;             /**< Set by a private option. */
45     int  individual_header_trailer; /**< Set by a private option. */
46     int  write_header_trailer; /**< Set by a private option. */
47     int64_t offset_time;
48     int64_t recording_time;
49     int has_video;
50     AVIOContext *pb;
51 } SegmentContext;
52
53 enum {
54     LIST_FLAT,
55     LIST_HLS
56 };
57
58 static int segment_mux_init(AVFormatContext *s)
59 {
60     SegmentContext *seg = s->priv_data;
61     AVFormatContext *oc;
62     int i;
63
64     seg->avf = oc = avformat_alloc_context();
65     if (!oc)
66         return AVERROR(ENOMEM);
67
68     oc->oformat            = seg->oformat;
69     oc->interrupt_callback = s->interrupt_callback;
70
71     for (i = 0; i < s->nb_streams; i++) {
72         AVStream *st;
73         if (!(st = avformat_new_stream(oc, NULL)))
74             return AVERROR(ENOMEM);
75         avcodec_copy_context(st->codec, s->streams[i]->codec);
76         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
77         st->time_base = s->streams[i]->time_base;
78     }
79
80     return 0;
81 }
82
83 static int segment_hls_window(AVFormatContext *s, int last)
84 {
85     SegmentContext *seg = s->priv_data;
86     int i, ret = 0;
87     char buf[1024];
88
89     if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
90                               &s->interrupt_callback, NULL)) < 0)
91         goto fail;
92
93     avio_printf(seg->pb, "#EXTM3U\n");
94     avio_printf(seg->pb, "#EXT-X-VERSION:3\n");
95     avio_printf(seg->pb, "#EXT-X-TARGETDURATION:%d\n", (int)seg->time);
96     avio_printf(seg->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",
97                 FFMAX(0, seg->number - seg->size));
98
99     av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
100            FFMAX(0, seg->number - seg->size));
101
102     for (i = FFMAX(0, seg->number - seg->size);
103          i < seg->number; i++) {
104         avio_printf(seg->pb, "#EXTINF:%d,\n", (int)seg->time);
105         if (seg->entry_prefix) {
106             avio_printf(seg->pb, "%s", seg->entry_prefix);
107         }
108         ret = av_get_frame_filename(buf, sizeof(buf), s->filename, i);
109         if (ret < 0) {
110             ret = AVERROR(EINVAL);
111             goto fail;
112         }
113         avio_printf(seg->pb, "%s\n", buf);
114     }
115
116     if (last)
117         avio_printf(seg->pb, "#EXT-X-ENDLIST\n");
118 fail:
119     avio_closep(&seg->pb);
120     return ret;
121 }
122
123 static int segment_start(AVFormatContext *s, int write_header)
124 {
125     SegmentContext *c = s->priv_data;
126     AVFormatContext *oc = c->avf;
127     int err = 0;
128
129     if (write_header) {
130         avformat_free_context(oc);
131         c->avf = NULL;
132         if ((err = segment_mux_init(s)) < 0)
133             return err;
134         oc = c->avf;
135     }
136
137     if (c->wrap)
138         c->number %= c->wrap;
139
140     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
141                               s->filename, c->number++) < 0)
142         return AVERROR(EINVAL);
143
144     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
145                           &s->interrupt_callback, NULL)) < 0)
146         return err;
147
148     if (oc->oformat->priv_class && oc->priv_data)
149         av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
150
151     if (write_header) {
152         if ((err = avformat_write_header(oc, NULL)) < 0)
153             return err;
154     }
155
156     return 0;
157 }
158
159 static int segment_end(AVFormatContext *oc, int write_trailer)
160 {
161     int ret = 0;
162
163     av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
164     if (write_trailer)
165         av_write_trailer(oc);
166     avio_close(oc->pb);
167
168     return ret;
169 }
170
171 static int open_null_ctx(AVIOContext **ctx)
172 {
173     int buf_size = 32768;
174     uint8_t *buf = av_malloc(buf_size);
175     if (!buf)
176         return AVERROR(ENOMEM);
177     *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
178     if (!*ctx) {
179         av_free(buf);
180         return AVERROR(ENOMEM);
181     }
182     return 0;
183 }
184
185 static void close_null_ctx(AVIOContext *pb)
186 {
187     av_free(pb->buffer);
188     av_free(pb);
189 }
190
191 static void seg_free_context(SegmentContext *seg)
192 {
193     avio_closep(&seg->pb);
194     avformat_free_context(seg->avf);
195     seg->avf = NULL;
196 }
197
198 static int seg_write_header(AVFormatContext *s)
199 {
200     SegmentContext *seg = s->priv_data;
201     AVFormatContext *oc = NULL;
202     int ret, i;
203
204     seg->number = 0;
205     seg->offset_time = 0;
206     seg->recording_time = seg->time * 1000000;
207     if (!seg->write_header_trailer)
208         seg->individual_header_trailer = 0;
209
210     if (seg->list && seg->list_type != LIST_HLS)
211         if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
212                               &s->interrupt_callback, NULL)) < 0)
213             goto fail;
214
215     for (i = 0; i < s->nb_streams; i++)
216         seg->has_video +=
217             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
218
219     if (seg->has_video > 1)
220         av_log(s, AV_LOG_WARNING,
221                "More than a single video stream present, "
222                "expect issues decoding it.\n");
223
224     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
225
226     if (!seg->oformat) {
227         ret = AVERROR_MUXER_NOT_FOUND;
228         goto fail;
229     }
230     if (seg->oformat->flags & AVFMT_NOFILE) {
231         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
232                seg->oformat->name);
233         ret = AVERROR(EINVAL);
234         goto fail;
235     }
236
237     if ((ret = segment_mux_init(s)) < 0)
238         goto fail;
239     oc = seg->avf;
240
241     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
242                               s->filename, seg->number++) < 0) {
243         ret = AVERROR(EINVAL);
244         goto fail;
245     }
246
247     if (seg->write_header_trailer) {
248         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
249                               &s->interrupt_callback, NULL)) < 0)
250             goto fail;
251     } else {
252         if ((ret = open_null_ctx(&oc->pb)) < 0)
253             goto fail;
254     }
255
256     if ((ret = avformat_write_header(oc, NULL)) < 0) {
257         avio_close(oc->pb);
258         goto fail;
259     }
260
261     if (!seg->write_header_trailer) {
262         close_null_ctx(oc->pb);
263         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
264                               &s->interrupt_callback, NULL)) < 0)
265             goto fail;
266     }
267
268     if (seg->list) {
269         if (seg->list_type == LIST_HLS) {
270             if ((ret = segment_hls_window(s, 0)) < 0)
271                 goto fail;
272         } else {
273             avio_printf(seg->pb, "%s\n", oc->filename);
274             avio_flush(seg->pb);
275         }
276     }
277
278 fail:
279     if (ret < 0)
280         seg_free_context(seg);
281
282     return ret;
283 }
284
285 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
286 {
287     SegmentContext *seg = s->priv_data;
288     AVFormatContext *oc = seg->avf;
289     AVStream *st = s->streams[pkt->stream_index];
290     int64_t end_pts = seg->recording_time * seg->number;
291     int ret, can_split = 1;
292
293     if (!oc)
294         return AVERROR(EINVAL);
295
296     if (seg->has_video) {
297         can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
298                     pkt->flags & AV_PKT_FLAG_KEY;
299     }
300
301     if (can_split && av_compare_ts(pkt->pts, st->time_base, end_pts,
302                                    AV_TIME_BASE_Q) >= 0) {
303         av_log(s, AV_LOG_DEBUG, "Next segment starts at %d %"PRId64"\n",
304                pkt->stream_index, pkt->pts);
305
306         ret = segment_end(oc, seg->individual_header_trailer);
307
308         if (!ret)
309             ret = segment_start(s, seg->individual_header_trailer);
310
311         if (ret)
312             goto fail;
313
314         oc = seg->avf;
315
316         if (seg->list) {
317             if (seg->list_type == LIST_HLS) {
318                 if ((ret = segment_hls_window(s, 0)) < 0)
319                     goto fail;
320             } else {
321                 avio_printf(seg->pb, "%s\n", oc->filename);
322                 avio_flush(seg->pb);
323                 if (seg->size && !(seg->number % seg->size)) {
324                     avio_closep(&seg->pb);
325                     if ((ret = avio_open2(&seg->pb, seg->list, AVIO_FLAG_WRITE,
326                                           &s->interrupt_callback, NULL)) < 0)
327                         goto fail;
328                 }
329             }
330         }
331     }
332
333     ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
334
335 fail:
336     if (ret < 0)
337         seg_free_context(seg);
338
339     return ret;
340 }
341
342 static int seg_write_trailer(struct AVFormatContext *s)
343 {
344     SegmentContext *seg = s->priv_data;
345     AVFormatContext *oc = seg->avf;
346     int ret = 0;
347
348     if (!oc)
349         goto fail;
350
351     if (!seg->write_header_trailer) {
352         if ((ret = segment_end(oc, 0)) < 0)
353             goto fail;
354         if ((ret = open_null_ctx(&oc->pb)) < 0)
355             goto fail;
356         ret = av_write_trailer(oc);
357         close_null_ctx(oc->pb);
358     } else {
359         ret = segment_end(oc, 1);
360     }
361
362     if (ret < 0)
363         goto fail;
364
365     if (seg->list && seg->list_type == LIST_HLS) {
366         if ((ret = segment_hls_window(s, 1) < 0))
367             goto fail;
368     }
369
370 fail:
371     avio_close(seg->pb);
372     avformat_free_context(oc);
373     return ret;
374 }
375
376 #define OFFSET(x) offsetof(SegmentContext, x)
377 #define E AV_OPT_FLAG_ENCODING_PARAM
378 static const AVOption options[] = {
379     { "segment_format",    "container format used for the segments",  OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
380     { "segment_time",      "segment length in seconds",               OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E },
381     { "segment_list",      "output the segment list",                 OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
382     { "segment_list_size", "maximum number of playlist entries",      OFFSET(size),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E },
383     { "segment_list_type", "segment list format",                     OFFSET(list_type),    AV_OPT_TYPE_INT,    {.i64 = LIST_FLAT},     0, 2, E, "list_type" },
384     {   "flat",            "plain list (default)",                    0,               AV_OPT_TYPE_CONST,  {.i64 = LIST_FLAT}, 0, 0, E, "list_type" },
385     {   "hls",             "Apple HTTP Live Streaming compatible",    0,               AV_OPT_TYPE_CONST,  {.i64 = LIST_HLS},  0, 0, E, "list_type" },
386     { "segment_wrap",      "number after which the index wraps",      OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E },
387     { "segment_list_entry_prefix",  "base url prefix for segments",   OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
388     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
389     { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
390     { NULL },
391 };
392
393 static const AVClass seg_class = {
394     .class_name = "segment muxer",
395     .item_name  = av_default_item_name,
396     .option     = options,
397     .version    = LIBAVUTIL_VERSION_INT,
398 };
399
400
401 AVOutputFormat ff_segment_muxer = {
402     .name           = "segment",
403     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
404     .priv_data_size = sizeof(SegmentContext),
405     .flags          = AVFMT_NOFILE,
406     .write_header   = seg_write_header,
407     .write_packet   = seg_write_packet,
408     .write_trailer  = seg_write_trailer,
409     .priv_class     = &seg_class,
410 };