hlsenc: stand alone hls segmenter
[libav.git] / libavformat / hlsenc.c
CommitLineData
22a0827d
LB
1/*
2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, 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 "libavutil/mathematics.h"
25#include "libavutil/parseutils.h"
26#include "libavutil/avstring.h"
27#include "libavutil/opt.h"
28#include "libavutil/log.h"
29
30#include "avformat.h"
31#include "internal.h"
32
33typedef struct ListEntry {
34 char name[1024];
35 int duration;
36 struct ListEntry *next;
37} ListEntry;
38
39typedef struct HLSContext {
40 const AVClass *class; // Class for private options.
41 int number;
42 AVOutputFormat *oformat;
43 AVFormatContext *avf;
44 float time; // Set by a private option.
45 int size; // Set by a private option.
46 int wrap; // Set by a private option.
47 int64_t recording_time;
48 int has_video;
49 int64_t start_pts;
50 int64_t end_pts;
51 ListEntry *list;
52 ListEntry *end_list;
53 char *basename;
54 AVIOContext *pb;
55} HLSContext;
56
57static int hls_mux_init(AVFormatContext *s)
58{
59 HLSContext *hls = s->priv_data;
60 AVFormatContext *oc;
61 int i;
62
63 hls->avf = oc = avformat_alloc_context();
64 if (!oc)
65 return AVERROR(ENOMEM);
66
67 oc->oformat = hls->oformat;
68 oc->interrupt_callback = s->interrupt_callback;
69
70 for (i = 0; i < s->nb_streams; i++) {
71 AVStream *st;
72 if (!(st = avformat_new_stream(oc, NULL)))
73 return AVERROR(ENOMEM);
74 avcodec_copy_context(st->codec, s->streams[i]->codec);
75 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
76 }
77
78 return 0;
79}
80
81static int append_entry(HLSContext *hls, uint64_t duration)
82{
83 ListEntry *en = av_malloc(sizeof(*en));
84
85 if (!en)
86 return AVERROR(ENOMEM);
87
88 av_get_frame_filename(en->name, sizeof(en->name), hls->basename,
89 hls->number -1);
90
91 en->duration = duration;
92 en->next = NULL;
93
94 if (!hls->list)
95 hls->list = en;
96 else
97 hls->end_list->next = en;
98
99 hls->end_list = en;
100
101 if (hls->number >= hls->size) {
102 en = hls->list;
103 hls->list = en->next;
104 av_free(en);
105 }
106
107 return 0;
108}
109
110static void free_entries(HLSContext *hls)
111{
112 ListEntry *p = hls->list, *en;
113
114 while(p) {
115 en = p;
116 p = p->next;
117 av_free(en);
118 }
119}
120
121static int hls_window(AVFormatContext *s, int last)
122{
123 HLSContext *hls = s->priv_data;
124 ListEntry *en;
125 int ret = 0;
126
127 if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
128 &s->interrupt_callback, NULL)) < 0)
129 goto fail;
130
131 avio_printf(hls->pb, "#EXTM3U\n");
132 avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
133 avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", (int)hls->time);
134 avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%d\n",
135 FFMAX(0, hls->number - hls->size));
136
137 for (en = hls->list; en; en = en->next) {
138 avio_printf(hls->pb, "#EXTINF:%d,\n", en->duration);
139 avio_printf(hls->pb, "%s\n", en->name);
140 }
141
142 if (last)
143 avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
144
145fail:
146 avio_closep(&hls->pb);
147 return ret;
148}
149
150static int hls_start(AVFormatContext *s)
151{
152 HLSContext *c = s->priv_data;
153 AVFormatContext *oc = c->avf;
154 int err = 0;
155
156 if (c->wrap)
157 c->number %= c->wrap;
158
159 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
160 c->basename, c->number++) < 0)
161 return AVERROR(EINVAL);
162
163 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
164 &s->interrupt_callback, NULL)) < 0)
165 return err;
166
167 if (oc->oformat->priv_class && oc->priv_data)
168 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
169
170 return 0;
171}
172
173static int hls_write_header(AVFormatContext *s)
174{
175 HLSContext *hls = s->priv_data;
176 int ret, i;
177 char *p;
178 const char *pattern = "%d.ts";
179 int basename_size = strlen(s->filename) + strlen(pattern);
180
181 hls->number = 0;
182
183 hls->recording_time = hls->time * 1000000;
184 hls->start_pts = AV_NOPTS_VALUE;
185
186 for (i = 0; i < s->nb_streams; i++)
187 hls->has_video +=
188 s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
189
190 if (hls->has_video > 1)
191 av_log(s, AV_LOG_WARNING,
192 "More than a single video stream present, "
193 "expect issues decoding it.\n");
194
195 hls->oformat = av_guess_format("mpegts", NULL, NULL);
196
197 if (!hls->oformat) {
198 ret = AVERROR_MUXER_NOT_FOUND;
199 goto fail;
200 }
201
202 hls->basename = av_malloc(basename_size);
203
204 if (!hls->basename) {
205 ret = AVERROR(ENOMEM);
206 goto fail;
207 }
208
209 strcpy(hls->basename, s->filename);
210
211 p = strrchr(hls->basename, '.');
212
213 if (p)
214 *p = '\0';
215
216 av_strlcat(hls->basename, "%d.ts", basename_size);
217
218 if ((ret = hls_mux_init(s)) < 0)
219 goto fail;
220
221 if ((ret = hls_start(s)) < 0)
222 goto fail;
223
224 if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
225 return ret;
226
227
228fail:
229 if (ret) {
230 av_free(hls->basename);
231 if (hls->avf)
232 avformat_free_context(hls->avf);
233 }
234 return ret;
235}
236
237static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
238{
239 HLSContext *hls = s->priv_data;
240 AVFormatContext *oc = hls->avf;
241 AVStream *st = s->streams[pkt->stream_index];
242 int64_t end_pts = hls->recording_time * hls->number;
243 int ret;
244
245 if (hls->start_pts == AV_NOPTS_VALUE) {
246 hls->start_pts = pkt->pts;
247 hls->end_pts = pkt->pts;
248 }
249 end_pts += hls->start_pts;
250
251 if ((hls->has_video && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
252 av_compare_ts(pkt->pts, st->time_base, end_pts, AV_TIME_BASE_Q) >= 0 &&
253 pkt->flags & AV_PKT_FLAG_KEY) {
254
255 append_entry(hls, av_rescale(pkt->pts - hls->end_pts,
256 st->time_base.num,
257 st->time_base.den));
258 hls->end_pts = pkt->pts;
259
260 av_write_frame(oc, NULL); /* Flush any buffered data */
261 avio_close(oc->pb);
262
263 ret = hls_start(s);
264
265 if (ret)
266 return ret;
267
268 oc = hls->avf;
269
270 if ((ret = hls_window(s, 0)) < 0)
271 return ret;
272 }
273
274 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
275
276 return ret;
277}
278
279static int hls_write_trailer(struct AVFormatContext *s)
280{
281 HLSContext *hls = s->priv_data;
282 AVFormatContext *oc = hls->avf;
283
284 av_write_trailer(oc);
285 avio_closep(&oc->pb);
286 avformat_free_context(oc);
287 av_free(hls->basename);
288 hls_window(s, 1);
289
290 free_entries(hls);
291 avio_close(hls->pb);
292 return 0;
293}
294
295#define OFFSET(x) offsetof(HLSContext, x)
296#define E AV_OPT_FLAG_ENCODING_PARAM
297static const AVOption options[] = {
298 {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
299 {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
300 {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
301 { NULL },
302};
303
304static const AVClass hls_class = {
305 .class_name = "hls muxer",
306 .item_name = av_default_item_name,
307 .option = options,
308 .version = LIBAVUTIL_VERSION_INT,
309};
310
311
312AVOutputFormat ff_hls_muxer = {
313 .name = "hls",
314 .long_name = NULL_IF_CONFIG_SMALL("hls"),
315 .extensions = "m3u8",
316 .priv_data_size = sizeof(HLSContext),
317 .audio_codec = AV_CODEC_ID_MP2,
318 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
319 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
320 .write_header = hls_write_header,
321 .write_packet = hls_write_packet,
322 .write_trailer = hls_write_trailer,
323 .priv_class = &hls_class,
324};