2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, Luca Barbato
5 * This file is part of Libav.
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.
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.
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
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/log.h"
34 typedef struct ListEntry {
36 int64_t duration; // segment duration in AV_TIME_BASE units
37 struct ListEntry *next;
40 typedef struct HLSContext {
41 const AVClass *class; // Class for private options.
44 int64_t start_sequence;
45 AVOutputFormat *oformat;
47 float time; // Set by a private option.
48 int size; // Set by a private option.
49 int wrap; // Set by a private option.
50 int version; // Set by a private option.
52 int64_t recording_time;
54 // The following timestamps are in AV_TIME_BASE units.
57 int64_t duration; // last segment duration computed so far.
65 static int hls_mux_init(AVFormatContext *s)
67 HLSContext *hls = s->priv_data;
71 hls->avf = oc = avformat_alloc_context();
73 return AVERROR(ENOMEM);
75 oc->oformat = hls->oformat;
76 oc->interrupt_callback = s->interrupt_callback;
78 for (i = 0; i < s->nb_streams; i++) {
80 if (!(st = avformat_new_stream(oc, NULL)))
81 return AVERROR(ENOMEM);
82 avcodec_copy_context(st->codec, s->streams[i]->codec);
83 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
84 st->time_base = s->streams[i]->time_base;
90 static int append_entry(HLSContext *hls, int64_t duration)
92 ListEntry *en = av_malloc(sizeof(*en));
95 return AVERROR(ENOMEM);
97 av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
99 en->duration = duration;
105 hls->end_list->next = en;
109 if (hls->nb_entries >= hls->size) {
111 hls->list = en->next;
121 static void free_entries(HLSContext *hls)
123 ListEntry *p = hls->list, *en;
132 static int hls_window(AVFormatContext *s, int last)
134 HLSContext *hls = s->priv_data;
136 int64_t target_duration = 0;
138 AVIOContext *out = NULL;
139 char temp_filename[1024];
140 int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->size);
142 snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
143 if ((ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE,
144 &s->interrupt_callback, NULL)) < 0)
147 for (en = hls->list; en; en = en->next) {
148 if (target_duration < en->duration)
149 target_duration = en->duration;
152 avio_printf(out, "#EXTM3U\n");
153 avio_printf(out, "#EXT-X-VERSION:%d\n", hls->version);
154 if (hls->allowcache == 0 || hls->allowcache == 1) {
155 avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
157 avio_printf(out, "#EXT-X-TARGETDURATION:%"PRId64"\n",
158 av_rescale_rnd(target_duration, 1, AV_TIME_BASE,
160 avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
162 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
165 for (en = hls->list; en; en = en->next) {
166 if (hls->version > 2)
167 avio_printf(out, "#EXTINF:%f\n",
168 (double)en->duration / AV_TIME_BASE);
170 avio_printf(out, "#EXTINF:%"PRId64",\n",
171 av_rescale(en->duration, 1, AV_TIME_BASE));
173 avio_printf(out, "%s", hls->baseurl);
174 avio_printf(out, "%s\n", en->name);
178 avio_printf(out, "#EXT-X-ENDLIST\n");
183 ff_rename(temp_filename, s->filename);
187 static int hls_start(AVFormatContext *s)
189 HLSContext *c = s->priv_data;
190 AVFormatContext *oc = c->avf;
193 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
194 c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0)
195 return AVERROR(EINVAL);
198 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
199 &s->interrupt_callback, NULL)) < 0)
202 if (oc->oformat->priv_class && oc->priv_data)
203 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
208 static int hls_write_header(AVFormatContext *s)
210 HLSContext *hls = s->priv_data;
213 const char *pattern = "%d.ts";
214 int basename_size = strlen(s->filename) + strlen(pattern) + 1;
216 hls->sequence = hls->start_sequence;
217 hls->recording_time = hls->time * AV_TIME_BASE;
218 hls->start_pts = AV_NOPTS_VALUE;
220 for (i = 0; i < s->nb_streams; i++)
222 s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
224 if (hls->has_video > 1)
225 av_log(s, AV_LOG_WARNING,
226 "More than a single video stream present, "
227 "expect issues decoding it.\n");
229 hls->oformat = av_guess_format("mpegts", NULL, NULL);
232 ret = AVERROR_MUXER_NOT_FOUND;
236 hls->basename = av_malloc(basename_size);
238 if (!hls->basename) {
239 ret = AVERROR(ENOMEM);
243 strcpy(hls->basename, s->filename);
245 p = strrchr(hls->basename, '.');
250 av_strlcat(hls->basename, pattern, basename_size);
252 if ((ret = hls_mux_init(s)) < 0)
255 if ((ret = hls_start(s)) < 0)
258 if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
264 av_free(hls->basename);
266 avformat_free_context(hls->avf);
271 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
273 HLSContext *hls = s->priv_data;
274 AVFormatContext *oc = hls->avf;
275 AVStream *st = s->streams[pkt->stream_index];
276 int64_t end_pts = hls->recording_time * hls->number;
277 int64_t pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
278 int ret, can_split = 1;
280 if (hls->start_pts == AV_NOPTS_VALUE) {
281 hls->start_pts = pts;
285 if (hls->has_video) {
286 can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
287 pkt->flags & AV_PKT_FLAG_KEY;
289 if (pkt->pts == AV_NOPTS_VALUE)
292 hls->duration = pts - hls->end_pts;
294 if (can_split && pts - hls->start_pts >= end_pts) {
295 ret = append_entry(hls, hls->duration);
302 av_write_frame(oc, NULL); /* Flush any buffered data */
312 if ((ret = hls_window(s, 0)) < 0)
316 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
321 static int hls_write_trailer(struct AVFormatContext *s)
323 HLSContext *hls = s->priv_data;
324 AVFormatContext *oc = hls->avf;
326 av_write_trailer(oc);
327 avio_closep(&oc->pb);
328 avformat_free_context(oc);
329 av_free(hls->basename);
330 append_entry(hls, hls->duration);
337 #define OFFSET(x) offsetof(HLSContext, x)
338 #define E AV_OPT_FLAG_ENCODING_PARAM
339 static const AVOption options[] = {
340 {"start_number", "first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
341 {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
342 {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
343 {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
344 {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
345 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
346 {"hls_version", "protocol version", OFFSET(version), AV_OPT_TYPE_INT, {.i64 = 3}, 2, 3, E},
350 static const AVClass hls_class = {
351 .class_name = "hls muxer",
352 .item_name = av_default_item_name,
354 .version = LIBAVUTIL_VERSION_INT,
358 AVOutputFormat ff_hls_muxer = {
360 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
361 .extensions = "m3u8",
362 .priv_data_size = sizeof(HLSContext),
363 .audio_codec = AV_CODEC_ID_AAC,
364 .video_codec = AV_CODEC_ID_H264,
365 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
366 .write_header = hls_write_header,
367 .write_packet = hls_write_packet,
368 .write_trailer = hls_write_trailer,
369 .priv_class = &hls_class,