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/avassert.h"
26 #include "libavutil/mathematics.h"
27 #include "libavutil/parseutils.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/log.h"
35 typedef struct HLSSegment {
37 double duration; /* in seconds */
41 struct HLSSegment *next;
44 typedef enum HLSFlags {
45 // Generate a single media file and use byte ranges in the playlist.
46 HLS_SINGLE_FILE = (1 << 0),
49 typedef struct HLSContext {
50 const AVClass *class; // Class for private options.
53 int64_t start_sequence;
54 AVOutputFormat *oformat;
58 float time; // Set by a private option.
59 int max_nb_segments; // Set by a private option.
60 int wrap; // Set by a private option.
61 uint32_t flags; // enum HLSFlags
64 int64_t recording_time;
68 double duration; // last segment duration computed so far, in seconds
69 int64_t start_pos; // last segment starting position
70 int64_t size; // last segment size
74 HLSSegment *last_segment;
78 char *format_options_str;
79 AVDictionary *format_options;
84 static int hls_mux_init(AVFormatContext *s)
86 HLSContext *hls = s->priv_data;
90 hls->avf = oc = avformat_alloc_context();
92 return AVERROR(ENOMEM);
94 oc->oformat = hls->oformat;
95 oc->interrupt_callback = s->interrupt_callback;
96 av_dict_copy(&oc->metadata, s->metadata, 0);
98 for (i = 0; i < s->nb_streams; i++) {
100 if (!(st = avformat_new_stream(oc, NULL)))
101 return AVERROR(ENOMEM);
102 avcodec_copy_context(st->codec, s->streams[i]->codec);
103 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
104 st->time_base = s->streams[i]->time_base;
111 /* Create a new segment and append it to the segment list */
112 static int hls_append_segment(HLSContext *hls, double duration, int64_t pos,
115 HLSSegment *en = av_malloc(sizeof(*en));
118 return AVERROR(ENOMEM);
120 av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
122 en->duration = duration;
130 hls->last_segment->next = en;
132 hls->last_segment = en;
134 if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
136 hls->segments = en->next;
146 static void hls_free_segments(HLSContext *hls)
148 HLSSegment *p = hls->segments, *en;
157 static int hls_window(AVFormatContext *s, int last)
159 HLSContext *hls = s->priv_data;
161 int target_duration = 0;
163 int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
164 int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
166 if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
167 &s->interrupt_callback, NULL)) < 0)
170 for (en = hls->segments; en; en = en->next) {
171 if (target_duration < en->duration)
172 target_duration = ceil(en->duration);
175 avio_printf(hls->pb, "#EXTM3U\n");
176 avio_printf(hls->pb, "#EXT-X-VERSION:%d\n", version);
177 if (hls->allowcache == 0 || hls->allowcache == 1) {
178 avio_printf(hls->pb, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
180 avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
181 avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
183 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
186 for (en = hls->segments; en; en = en->next) {
187 avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
188 if (hls->flags & HLS_SINGLE_FILE)
189 avio_printf(hls->pb, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
192 avio_printf(hls->pb, "%s", hls->baseurl);
193 avio_printf(hls->pb, "%s\n", en->filename);
197 avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
200 avio_closep(&hls->pb);
204 static int hls_start(AVFormatContext *s)
206 HLSContext *c = s->priv_data;
207 AVFormatContext *oc = c->avf;
210 if (c->flags & HLS_SINGLE_FILE)
211 av_strlcpy(oc->filename, c->basename,
212 sizeof(oc->filename));
214 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
215 c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
216 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
217 return AVERROR(EINVAL);
221 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
222 &s->interrupt_callback, NULL)) < 0)
225 if (oc->oformat->priv_class && oc->priv_data)
226 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
231 static int hls_write_header(AVFormatContext *s)
233 HLSContext *hls = s->priv_data;
236 const char *pattern = "%d.ts";
237 AVDictionary *options = NULL;
238 int basename_size = strlen(s->filename) + strlen(pattern) + 1;
240 hls->sequence = hls->start_sequence;
241 hls->recording_time = hls->time * AV_TIME_BASE;
242 hls->start_pts = AV_NOPTS_VALUE;
244 if (hls->flags & HLS_SINGLE_FILE)
247 if (hls->format_options_str) {
248 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
250 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
255 for (i = 0; i < s->nb_streams; i++)
257 s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
259 if (hls->has_video > 1)
260 av_log(s, AV_LOG_WARNING,
261 "More than a single video stream present, "
262 "expect issues decoding it.\n");
264 hls->oformat = av_guess_format("mpegts", NULL, NULL);
267 ret = AVERROR_MUXER_NOT_FOUND;
271 hls->basename = av_malloc(basename_size);
273 if (!hls->basename) {
274 ret = AVERROR(ENOMEM);
278 strcpy(hls->basename, s->filename);
280 p = strrchr(hls->basename, '.');
285 av_strlcat(hls->basename, pattern, basename_size);
287 if ((ret = hls_mux_init(s)) < 0)
290 if ((ret = hls_start(s)) < 0)
293 av_dict_copy(&options, hls->format_options, 0);
294 ret = avformat_write_header(hls->avf, &options);
295 if (av_dict_count(options)) {
296 av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
297 ret = AVERROR(EINVAL);
300 av_assert0(s->nb_streams == hls->avf->nb_streams);
301 for (i = 0; i < s->nb_streams; i++) {
302 AVStream *inner_st = hls->avf->streams[i];
303 AVStream *outer_st = s->streams[i];
304 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
308 av_dict_free(&options);
310 av_free(hls->basename);
312 avformat_free_context(hls->avf);
317 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
319 HLSContext *hls = s->priv_data;
320 AVFormatContext *oc = hls->avf;
321 AVStream *st = s->streams[pkt->stream_index];
322 int64_t end_pts = hls->recording_time * hls->number;
324 int ret, can_split = 1;
326 if (hls->start_pts == AV_NOPTS_VALUE) {
327 hls->start_pts = pkt->pts;
328 hls->end_pts = pkt->pts;
331 if (hls->has_video) {
332 can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
333 pkt->flags & AV_PKT_FLAG_KEY;
334 is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
336 if (pkt->pts == AV_NOPTS_VALUE)
337 is_ref_pkt = can_split = 0;
340 hls->duration = (double)(pkt->pts - hls->end_pts)
341 * st->time_base.num / st->time_base.den;
343 if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
344 end_pts, AV_TIME_BASE_Q) >= 0) {
345 int64_t new_start_pos;
346 av_write_frame(oc, NULL); /* Flush any buffered data */
348 new_start_pos = avio_tell(hls->avf->pb);
349 hls->size = new_start_pos - hls->start_pos;
350 ret = hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
351 hls->start_pos = new_start_pos;
355 hls->end_pts = pkt->pts;
358 if (hls->flags & HLS_SINGLE_FILE) {
359 if (hls->avf->oformat->priv_class && hls->avf->priv_data)
360 av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
373 if ((ret = hls_window(s, 0)) < 0)
377 ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
382 static int hls_write_trailer(struct AVFormatContext *s)
384 HLSContext *hls = s->priv_data;
385 AVFormatContext *oc = hls->avf;
387 av_write_trailer(oc);
388 hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
389 avio_closep(&oc->pb);
390 avformat_free_context(oc);
391 av_free(hls->basename);
392 hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
395 hls_free_segments(hls);
400 #define OFFSET(x) offsetof(HLSContext, x)
401 #define E AV_OPT_FLAG_ENCODING_PARAM
402 static const AVOption options[] = {
403 {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
404 {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
405 {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
406 {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
407 {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
408 {"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},
409 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
410 {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
411 {"single_file", "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX, E, "flags"},
416 static const AVClass hls_class = {
417 .class_name = "hls muxer",
418 .item_name = av_default_item_name,
420 .version = LIBAVUTIL_VERSION_INT,
424 AVOutputFormat ff_hls_muxer = {
426 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
427 .extensions = "m3u8",
428 .priv_data_size = sizeof(HLSContext),
429 .audio_codec = AV_CODEC_ID_AAC,
430 .video_codec = AV_CODEC_ID_H264,
431 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
432 .write_header = hls_write_header,
433 .write_packet = hls_write_packet,
434 .write_trailer = hls_write_trailer,
435 .priv_class = &hls_class,