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
30 #include <openssl/rand.h>
33 #include "libavutil/mathematics.h"
34 #include "libavutil/parseutils.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/random_seed.h"
39 #include "libavutil/log.h"
44 typedef struct ListEntry {
46 int64_t duration; // segment duration in AV_TIME_BASE units
47 struct ListEntry *next;
50 typedef struct HLSContext {
51 const AVClass *class; // Class for private options.
54 int64_t start_sequence;
55 AVOutputFormat *oformat;
57 float time; // Set by a private option.
58 int size; // Set by a private option.
59 int wrap; // Set by a private option.
60 int version; // Set by a private option.
62 int64_t recording_time;
64 // The following timestamps are in AV_TIME_BASE units.
67 int64_t duration; // last segment duration computed so far.
74 int encrypt; // Set by a private option.
75 char *key; // Set by a private option.
77 char *key_url; // Set by a private option.
78 char *iv; // Set by a private option.
83 AVDictionary *enc_opts;
87 static int randomize(uint8_t *buf, int len)
90 gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
93 if (RAND_bytes(buf, len))
97 return AVERROR(ENOSYS);
101 static void free_encryption(AVFormatContext *s)
103 HLSContext *hls = s->priv_data;
105 av_dict_free(&hls->enc_opts);
107 av_freep(&hls->key_basename);
110 static int dict_set_bin(AVDictionary **dict, const char *key, uint8_t *buf)
114 ff_data_to_hex(hex, buf, sizeof(buf), 0);
117 return av_dict_set(dict, key, hex, 0);
120 static int setup_encryption(AVFormatContext *s)
122 HLSContext *hls = s->priv_data;
123 AVIOContext *out = NULL;
128 len = strlen(hls->basename) + 4 + 1;
129 hls->key_basename = av_mallocz(len);
130 if (!hls->key_basename)
131 return AVERROR(ENOMEM);
133 av_strlcpy(hls->key_basename, hls->basename + 7, len);
134 av_strlcat(hls->key_basename, ".key", len);
137 if (hls->key_len != 16) {
138 av_log(s, AV_LOG_ERROR,
139 "Invalid key size %d, expected 16-bytes hex-coded key\n",
141 return AVERROR(EINVAL);
144 if ((ret = dict_set_bin(&hls->enc_opts, "key", hls->key)) < 0)
148 if ((ret = randomize(buf, sizeof(buf))) < 0) {
149 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
153 if ((ret = dict_set_bin(&hls->enc_opts, "key", buf)) < 0)
159 if (hls->iv_len != 16) {
160 av_log(s, AV_LOG_ERROR,
161 "Invalid key size %d, expected 16-bytes hex-coded initialization vector\n",
163 return AVERROR(EINVAL);
166 if ((ret = dict_set_bin(&hls->enc_opts, "iv", hls->iv)) < 0)
170 if ((ret = s->io_open(s, &out, hls->key_basename, AVIO_FLAG_WRITE, NULL)) < 0)
173 avio_write(out, k, 16);
180 static int hls_mux_init(AVFormatContext *s)
182 HLSContext *hls = s->priv_data;
186 hls->avf = oc = avformat_alloc_context();
188 return AVERROR(ENOMEM);
190 oc->oformat = hls->oformat;
191 oc->interrupt_callback = s->interrupt_callback;
192 oc->opaque = s->opaque;
193 oc->io_open = s->io_open;
194 oc->io_close = s->io_close;
196 for (i = 0; i < s->nb_streams; i++) {
198 if (!(st = avformat_new_stream(oc, NULL)))
199 return AVERROR(ENOMEM);
200 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
201 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
202 st->time_base = s->streams[i]->time_base;
208 static int append_entry(HLSContext *hls, int64_t duration)
210 ListEntry *en = av_malloc(sizeof(*en));
213 return AVERROR(ENOMEM);
215 av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
217 en->duration = duration;
223 hls->end_list->next = en;
227 if (hls->nb_entries >= hls->size) {
229 hls->list = en->next;
239 static void free_entries(HLSContext *hls)
241 ListEntry *p = hls->list, *en;
250 static int hls_window(AVFormatContext *s, int last)
252 HLSContext *hls = s->priv_data;
254 int64_t target_duration = 0;
256 AVIOContext *out = NULL;
257 char temp_filename[1024];
258 int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->size);
260 snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
261 if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL)) < 0)
264 for (en = hls->list; en; en = en->next) {
265 if (target_duration < en->duration)
266 target_duration = en->duration;
269 avio_printf(out, "#EXTM3U\n");
270 avio_printf(out, "#EXT-X-VERSION:%d\n", hls->version);
271 if (hls->allowcache == 0 || hls->allowcache == 1) {
272 avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
274 avio_printf(out, "#EXT-X-TARGETDURATION:%"PRId64"\n",
275 av_rescale_rnd(target_duration, 1, AV_TIME_BASE,
277 avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
279 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
282 for (en = hls->list; en; en = en->next) {
287 key_url = hls->key_url;
289 key_url = hls->baseurl;
291 avio_printf(out, "#EXT-X-KEY:METHOD=AES-128");
292 avio_printf(out, ",URI=\"");
294 avio_printf(out, "%s", key_url);
295 avio_printf(out, "%s\"", av_basename(hls->key_basename));
297 avio_printf(out, ",IV=\"0x%s\"", hls->iv);
298 avio_printf(out, "\n");
301 if (hls->version > 2)
302 avio_printf(out, "#EXTINF:%f\n",
303 (double)en->duration / AV_TIME_BASE);
305 avio_printf(out, "#EXTINF:%"PRId64",\n",
306 av_rescale(en->duration, 1, AV_TIME_BASE));
308 avio_printf(out, "%s", hls->baseurl);
309 avio_printf(out, "%s\n", en->name);
313 avio_printf(out, "#EXT-X-ENDLIST\n");
316 ff_format_io_close(s, &out);
318 ff_rename(temp_filename, s->filename);
322 static int hls_start(AVFormatContext *s)
324 HLSContext *c = s->priv_data;
325 AVFormatContext *oc = c->avf;
327 AVDictionary *opts = NULL;
330 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
331 c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0)
332 return AVERROR(EINVAL);
336 if ((err = av_dict_copy(&opts, c->enc_opts, 0)) < 0)
339 uint8_t iv[16] = { 0 };
342 AV_WB64(iv + 8, c->sequence);
343 ff_data_to_hex(buf, iv, sizeof(iv), 0);
346 if ((err = av_dict_set(&opts, "iv", buf, 0)) < 0)
351 if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &opts)) < 0)
354 if (oc->oformat->priv_class && oc->priv_data)
355 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
363 static int hls_setup(AVFormatContext *s)
365 HLSContext *hls = s->priv_data;
366 const char *pattern = "%d.ts";
367 int basename_size = strlen(s->filename) + strlen(pattern) + 1;
373 hls->basename = av_mallocz(basename_size);
375 return AVERROR(ENOMEM);
377 // TODO: support protocol nesting?
379 strcpy(hls->basename, "crypto:");
381 av_strlcat(hls->basename, s->filename, basename_size);
383 p = strrchr(hls->basename, '.');
389 int ret = setup_encryption(s);
394 av_strlcat(hls->basename, pattern, basename_size);
399 static int hls_write_header(AVFormatContext *s)
401 HLSContext *hls = s->priv_data;
404 hls->sequence = hls->start_sequence;
405 hls->recording_time = hls->time * AV_TIME_BASE;
406 hls->start_pts = AV_NOPTS_VALUE;
408 for (i = 0; i < s->nb_streams; i++)
410 s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
412 if (hls->has_video > 1)
413 av_log(s, AV_LOG_WARNING,
414 "More than a single video stream present, "
415 "expect issues decoding it.\n");
417 hls->oformat = av_guess_format("mpegts", NULL, NULL);
420 ret = AVERROR_MUXER_NOT_FOUND;
424 if ((ret = hls_setup(s)) < 0)
427 if ((ret = hls_mux_init(s)) < 0)
430 if ((ret = hls_start(s)) < 0)
433 if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
439 av_free(hls->basename);
441 avformat_free_context(hls->avf);
448 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
450 HLSContext *hls = s->priv_data;
451 AVFormatContext *oc = hls->avf;
452 AVStream *st = s->streams[pkt->stream_index];
453 int64_t end_pts = hls->recording_time * hls->number;
454 int64_t pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
455 int ret, can_split = 1;
457 if (hls->start_pts == AV_NOPTS_VALUE) {
458 hls->start_pts = pts;
462 if (hls->has_video) {
463 can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
464 pkt->flags & AV_PKT_FLAG_KEY;
466 if (pkt->pts == AV_NOPTS_VALUE)
469 hls->duration = pts - hls->end_pts;
471 if (can_split && pts - hls->start_pts >= end_pts) {
472 ret = append_entry(hls, hls->duration);
479 av_write_frame(oc, NULL); /* Flush any buffered data */
480 ff_format_io_close(s, &oc->pb);
489 if ((ret = hls_window(s, 0)) < 0)
493 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
498 static int hls_write_trailer(struct AVFormatContext *s)
500 HLSContext *hls = s->priv_data;
501 AVFormatContext *oc = hls->avf;
503 av_write_trailer(oc);
504 ff_format_io_close(s, &oc->pb);
505 avformat_free_context(oc);
506 av_free(hls->basename);
507 append_entry(hls, hls->duration);
515 #define OFFSET(x) offsetof(HLSContext, x)
516 #define E AV_OPT_FLAG_ENCODING_PARAM
517 static const AVOption options[] = {
518 {"start_number", "first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
519 {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
520 {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
521 {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
522 {"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},
523 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
524 {"hls_version", "protocol version", OFFSET(version), AV_OPT_TYPE_INT, {.i64 = 3}, 2, 3, E},
525 {"hls_enc", "AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
526 {"hls_enc_key", "use the specified hex-coded 16byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = E},
527 {"hls_enc_key_url", "url to access the key to decrypt the segments", OFFSET(key_url), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
528 {"hls_enc_iv", "use the specified hex-coded 16byte initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = E},
532 static const AVClass hls_class = {
533 .class_name = "hls muxer",
534 .item_name = av_default_item_name,
536 .version = LIBAVUTIL_VERSION_INT,
540 AVOutputFormat ff_hls_muxer = {
542 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
543 .extensions = "m3u8",
544 .priv_data_size = sizeof(HLSContext),
545 .audio_codec = AV_CODEC_ID_AAC,
546 .video_codec = AV_CODEC_ID_H264,
547 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
548 .write_header = hls_write_header,
549 .write_packet = hls_write_packet,
550 .write_trailer = hls_write_trailer,
551 .priv_class = &hls_class,