2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, Luca Barbato
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 HLSSegment {
36 double duration; /* in seconds */
38 struct HLSSegment *next;
41 typedef struct HLSContext {
42 const AVClass *class; // Class for private options.
45 int64_t start_sequence;
46 AVOutputFormat *oformat;
50 float time; // Set by a private option.
51 int max_nb_segments; // Set by a private option.
52 int wrap; // Set by a private option.
54 int64_t recording_time;
58 double duration; // last segment duration computed so far, in seconds
62 HLSSegment *last_segment;
70 static int hls_mux_init(AVFormatContext *s)
72 HLSContext *hls = s->priv_data;
76 hls->avf = oc = avformat_alloc_context();
78 return AVERROR(ENOMEM);
80 oc->oformat = hls->oformat;
81 oc->interrupt_callback = s->interrupt_callback;
82 av_dict_copy(&oc->metadata, s->metadata, 0);
84 for (i = 0; i < s->nb_streams; i++) {
86 if (!(st = avformat_new_stream(oc, NULL)))
87 return AVERROR(ENOMEM);
88 avcodec_copy_context(st->codec, s->streams[i]->codec);
89 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
95 /* Create a new segment and append it to the segment list */
96 static int hls_append_segment(HLSContext *hls, double duration)
98 HLSSegment *en = av_malloc(sizeof(*en));
101 return AVERROR(ENOMEM);
103 av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
105 en->duration = duration;
111 hls->last_segment->next = en;
113 hls->last_segment = en;
115 if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
117 hls->segments = en->next;
127 static void hls_free_segments(HLSContext *hls)
129 HLSSegment *p = hls->segments, *en;
138 static int hls_window(AVFormatContext *s, int last)
140 HLSContext *hls = s->priv_data;
142 int target_duration = 0;
144 int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
146 if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
147 &s->interrupt_callback, NULL)) < 0)
150 for (en = hls->segments; en; en = en->next) {
151 if (target_duration < en->duration)
152 target_duration = ceil(en->duration);
155 avio_printf(hls->pb, "#EXTM3U\n");
156 avio_printf(hls->pb, "#EXT-X-VERSION:3\n");
157 avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
158 avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
160 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
163 for (en = hls->segments; en; en = en->next) {
164 avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
166 avio_printf(hls->pb, "%s", hls->baseurl);
167 avio_printf(hls->pb, "%s\n", en->filename);
171 avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
174 avio_closep(&hls->pb);
178 static int hls_start(AVFormatContext *s)
180 HLSContext *c = s->priv_data;
181 AVFormatContext *oc = c->avf;
184 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
185 c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
186 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
187 return AVERROR(EINVAL);
191 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
192 &s->interrupt_callback, NULL)) < 0)
195 if (oc->oformat->priv_class && oc->priv_data)
196 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
201 static int hls_write_header(AVFormatContext *s)
203 HLSContext *hls = s->priv_data;
206 const char *pattern = "%d.ts";
207 int basename_size = strlen(s->filename) + strlen(pattern) + 1;
209 hls->sequence = hls->start_sequence;
210 hls->recording_time = hls->time * AV_TIME_BASE;
211 hls->start_pts = AV_NOPTS_VALUE;
213 for (i = 0; i < s->nb_streams; i++)
215 s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
217 if (hls->has_video > 1)
218 av_log(s, AV_LOG_WARNING,
219 "More than a single video stream present, "
220 "expect issues decoding it.\n");
222 hls->oformat = av_guess_format("mpegts", NULL, NULL);
225 ret = AVERROR_MUXER_NOT_FOUND;
229 hls->basename = av_malloc(basename_size);
231 if (!hls->basename) {
232 ret = AVERROR(ENOMEM);
236 strcpy(hls->basename, s->filename);
238 p = strrchr(hls->basename, '.');
243 av_strlcat(hls->basename, pattern, basename_size);
245 if ((ret = hls_mux_init(s)) < 0)
248 if ((ret = hls_start(s)) < 0)
251 if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
257 av_free(hls->basename);
259 avformat_free_context(hls->avf);
264 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
266 HLSContext *hls = s->priv_data;
267 AVFormatContext *oc = hls->avf;
268 AVStream *st = s->streams[pkt->stream_index];
269 int64_t end_pts = hls->recording_time * hls->number;
271 int ret, can_split = 1;
273 if (hls->start_pts == AV_NOPTS_VALUE) {
274 hls->start_pts = pkt->pts;
275 hls->end_pts = pkt->pts;
278 if (hls->has_video) {
279 can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
280 pkt->flags & AV_PKT_FLAG_KEY;
281 is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
283 if (pkt->pts == AV_NOPTS_VALUE)
284 is_ref_pkt = can_split = 0;
287 hls->duration = (double)(pkt->pts - hls->end_pts)
288 * st->time_base.num / st->time_base.den;
290 if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
291 end_pts, AV_TIME_BASE_Q) >= 0) {
292 ret = hls_append_segment(hls, hls->duration);
296 hls->end_pts = pkt->pts;
299 av_write_frame(oc, NULL); /* Flush any buffered data */
309 if ((ret = hls_window(s, 0)) < 0)
313 ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
318 static int hls_write_trailer(struct AVFormatContext *s)
320 HLSContext *hls = s->priv_data;
321 AVFormatContext *oc = hls->avf;
323 av_write_trailer(oc);
324 avio_closep(&oc->pb);
325 avformat_free_context(oc);
326 av_free(hls->basename);
327 hls_append_segment(hls, hls->duration);
330 hls_free_segments(hls);
335 #define OFFSET(x) offsetof(HLSContext, x)
336 #define E AV_OPT_FLAG_ENCODING_PARAM
337 static const AVOption options[] = {
338 {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
339 {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
340 {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
341 {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
342 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
346 static const AVClass hls_class = {
347 .class_name = "hls muxer",
348 .item_name = av_default_item_name,
350 .version = LIBAVUTIL_VERSION_INT,
354 AVOutputFormat ff_hls_muxer = {
356 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
357 .extensions = "m3u8",
358 .priv_data_size = sizeof(HLSContext),
359 .audio_codec = AV_CODEC_ID_AAC,
360 .video_codec = AV_CODEC_ID_H264,
361 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
362 .write_header = hls_write_header,
363 .write_packet = hls_write_packet,
364 .write_trailer = hls_write_trailer,
365 .priv_class = &hls_class,