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