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
28 #include <openssl/rand.h>
31 #include "libavutil/mathematics.h"
32 #include "libavutil/parseutils.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/random_seed.h"
37 #include "libavutil/log.h"
42 typedef struct ListEntry {
44 int64_t duration; // segment duration in AV_TIME_BASE units
45 struct ListEntry *next;
48 typedef struct HLSContext {
49 const AVClass *class; // Class for private options.
52 int64_t start_sequence;
53 AVOutputFormat *oformat;
55 float time; // Set by a private option.
56 int size; // Set by a private option.
57 int wrap; // Set by a private option.
58 int version; // Set by a private option.
60 int64_t recording_time;
62 // The following timestamps are in AV_TIME_BASE units.
65 int64_t duration; // last segment duration computed so far.
72 int encrypt; // Set by a private option.
73 char *key; // Set by a private option.
75 char *key_url; // Set by a private option.
76 char *iv; // Set by a private option.
81 AVDictionary *enc_opts;
85 static int randomize(uint8_t *buf, int len)
88 if (RAND_bytes(buf, len))
92 return AVERROR(ENOSYS);
96 static void free_encryption(AVFormatContext *s)
98 HLSContext *hls = s->priv_data;
100 av_dict_free(&hls->enc_opts);
102 av_freep(&hls->key_basename);
105 static int dict_set_bin(AVDictionary **dict, const char *key,
106 uint8_t *buf, size_t len)
110 ff_data_to_hex(hex, buf, len, 0);
113 return av_dict_set(dict, key, hex, 0);
116 static int setup_encryption(AVFormatContext *s)
118 HLSContext *hls = s->priv_data;
119 AVIOContext *out = NULL;
124 len = strlen(hls->basename) + 4 + 1;
125 hls->key_basename = av_mallocz(len);
126 if (!hls->key_basename)
127 return AVERROR(ENOMEM);
129 av_strlcpy(hls->key_basename, hls->basename + 7, len);
130 av_strlcat(hls->key_basename, ".key", len);
133 if (hls->key_len != 16) {
134 av_log(s, AV_LOG_ERROR,
135 "Invalid key size %d, expected 16-bytes hex-coded key\n",
137 return AVERROR(EINVAL);
140 if ((ret = dict_set_bin(&hls->enc_opts, "key", hls->key, hls->key_len)) < 0)
144 if (hls->start_sequence < 0) {
145 ret = s->io_open(s, &out, hls->key_basename, AVIO_FLAG_READ, NULL);
147 av_log(s, AV_LOG_WARNING,
148 "Cannot recover the key, generating a new one.\n");
150 avio_read(out, buf, 16);
156 if ((ret = randomize(buf, sizeof(buf))) < 0) {
157 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
162 if ((ret = dict_set_bin(&hls->enc_opts, "key", buf, sizeof(buf))) < 0)
168 if (hls->iv_len != 16) {
169 av_log(s, AV_LOG_ERROR,
170 "Invalid key size %d, expected 16-bytes hex-coded initialization vector\n",
172 return AVERROR(EINVAL);
175 if ((ret = dict_set_bin(&hls->enc_opts, "iv", hls->iv, hls->iv_len)) < 0)
179 if ((ret = s->io_open(s, &out, hls->key_basename, AVIO_FLAG_WRITE, NULL)) < 0)
182 avio_write(out, k, 16);
189 static int hls_mux_init(AVFormatContext *s)
191 HLSContext *hls = s->priv_data;
195 hls->avf = oc = avformat_alloc_context();
197 return AVERROR(ENOMEM);
199 oc->oformat = hls->oformat;
200 oc->interrupt_callback = s->interrupt_callback;
201 oc->opaque = s->opaque;
202 oc->io_open = s->io_open;
203 oc->io_close = s->io_close;
205 for (i = 0; i < s->nb_streams; i++) {
207 if (!(st = avformat_new_stream(oc, NULL)))
208 return AVERROR(ENOMEM);
209 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
210 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
211 st->time_base = s->streams[i]->time_base;
217 static int append_entry(HLSContext *hls, int64_t duration, const char *name)
219 ListEntry *en = av_malloc(sizeof(*en));
222 return AVERROR(ENOMEM);
224 av_strlcpy(en->name, name, sizeof(en->name));
226 en->duration = duration;
232 hls->end_list->next = en;
236 if (hls->nb_entries >= hls->size) {
238 hls->list = en->next;
248 static void free_entries(HLSContext *hls)
250 ListEntry *p = hls->list, *en;
259 static int hls_window(AVFormatContext *s, int last)
261 HLSContext *hls = s->priv_data;
263 int64_t target_duration = 0;
265 AVIOContext *out = NULL;
266 char temp_filename[1024];
267 int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->size);
269 snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
270 if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL)) < 0)
273 for (en = hls->list; en; en = en->next) {
274 if (target_duration < en->duration)
275 target_duration = en->duration;
278 avio_printf(out, "#EXTM3U\n");
279 avio_printf(out, "#EXT-X-VERSION:%d\n", hls->version);
280 if (hls->allowcache == 0 || hls->allowcache == 1) {
281 avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
283 avio_printf(out, "#EXT-X-TARGETDURATION:%"PRId64"\n",
284 av_rescale_rnd(target_duration, 1, AV_TIME_BASE,
286 avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
288 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
291 for (en = hls->list; en; en = en->next) {
296 key_url = hls->key_url;
298 key_url = hls->baseurl;
300 avio_printf(out, "#EXT-X-KEY:METHOD=AES-128");
301 avio_printf(out, ",URI=\"");
303 avio_printf(out, "%s", key_url);
304 avio_printf(out, "%s\"", av_basename(hls->key_basename));
306 avio_printf(out, ",IV=\"0x%s\"", hls->iv);
307 avio_printf(out, "\n");
310 if (hls->version > 2)
311 avio_printf(out, "#EXTINF:%f\n",
312 (double)en->duration / AV_TIME_BASE);
314 avio_printf(out, "#EXTINF:%"PRId64",\n",
315 av_rescale(en->duration, 1, AV_TIME_BASE));
317 avio_printf(out, "%s", hls->baseurl);
318 avio_printf(out, "%s\n", en->name);
322 avio_printf(out, "#EXT-X-ENDLIST\n");
325 ff_format_io_close(s, &out);
327 ff_rename(temp_filename, s->filename);
331 static int hls_start(AVFormatContext *s)
333 HLSContext *c = s->priv_data;
334 AVFormatContext *oc = c->avf;
336 AVDictionary *opts = NULL;
339 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
340 c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0)
341 return AVERROR(EINVAL);
345 if ((err = av_dict_copy(&opts, c->enc_opts, 0)) < 0)
348 uint8_t iv[16] = { 0 };
351 AV_WB64(iv + 8, c->sequence);
352 ff_data_to_hex(buf, iv, sizeof(iv), 0);
355 if ((err = av_dict_set(&opts, "iv", buf, 0)) < 0)
360 if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &opts)) < 0)
363 if (oc->oformat->priv_class && oc->priv_data)
364 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
372 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
374 int len = ff_get_line(s, buf, maxlen);
375 while (len > 0 && av_isspace(buf[len - 1]))
380 static int hls_recover(AVFormatContext *s)
382 HLSContext *hls = s->priv_data;
386 int ret, is_segment = 0;
387 int64_t duration = 0;
389 ret = s->io_open(s, &io, s->filename, AVIO_FLAG_READ, NULL);
391 av_log(s, AV_LOG_WARNING,
392 "Cannot recover the playlist, generating a new one.\n");
393 hls->start_sequence = 0;
398 read_chomp_line(io, line, sizeof(line));
399 if (strcmp(line, "#EXTM3U")) {
400 av_log(s, AV_LOG_ERROR,
401 "The playlist file is present but unparsable."
402 " Please remove it.\n");
403 return AVERROR_INVALIDDATA;
406 while (!io->eof_reached) {
407 read_chomp_line(io, line, sizeof(line));
408 if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
409 hls->sequence = hls->start_sequence = atoi(ptr);
410 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
412 duration = atof(ptr) * AV_TIME_BASE;
413 } else if (av_strstart(line, "#", NULL)) {
415 } else if (line[0]) {
417 append_entry(hls, duration, av_basename(line));
426 static int hls_setup(AVFormatContext *s)
428 HLSContext *hls = s->priv_data;
429 const char *pattern = "%d.ts";
430 int basename_size = strlen(s->filename) + strlen(pattern) + 1;
437 hls->basename = av_mallocz(basename_size);
439 return AVERROR(ENOMEM);
441 // TODO: support protocol nesting?
443 strcpy(hls->basename, "crypto:");
445 av_strlcat(hls->basename, s->filename, basename_size);
447 p = strrchr(hls->basename, '.');
453 ret = setup_encryption(s);
458 if (hls->start_sequence < 0) {
459 ret = hls_recover(s);
464 av_strlcat(hls->basename, pattern, basename_size);
469 static int hls_write_header(AVFormatContext *s)
471 HLSContext *hls = s->priv_data;
474 hls->sequence = hls->start_sequence;
475 hls->recording_time = hls->time * AV_TIME_BASE;
476 hls->start_pts = AV_NOPTS_VALUE;
478 for (i = 0; i < s->nb_streams; i++)
480 s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
482 if (hls->has_video > 1)
483 av_log(s, AV_LOG_WARNING,
484 "More than a single video stream present, "
485 "expect issues decoding it.\n");
487 hls->oformat = av_guess_format("mpegts", NULL, NULL);
490 ret = AVERROR_MUXER_NOT_FOUND;
494 if ((ret = hls_setup(s)) < 0)
497 if ((ret = hls_mux_init(s)) < 0)
500 if ((ret = hls_start(s)) < 0)
503 if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
509 av_free(hls->basename);
511 avformat_free_context(hls->avf);
518 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
520 HLSContext *hls = s->priv_data;
521 AVFormatContext *oc = hls->avf;
522 AVStream *st = s->streams[pkt->stream_index];
523 int64_t end_pts = hls->recording_time * hls->number;
524 int64_t pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
525 int ret, can_split = 1;
527 if (hls->start_pts == AV_NOPTS_VALUE) {
528 hls->start_pts = pts;
532 if (hls->has_video) {
533 can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
534 pkt->flags & AV_PKT_FLAG_KEY;
536 if (pkt->pts == AV_NOPTS_VALUE)
539 hls->duration = pts - hls->end_pts;
541 if (can_split && pts - hls->start_pts >= end_pts) {
542 ret = append_entry(hls, hls->duration, av_basename(hls->avf->filename));
549 av_write_frame(oc, NULL); /* Flush any buffered data */
550 ff_format_io_close(s, &oc->pb);
559 if ((ret = hls_window(s, 0)) < 0)
563 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
568 static int hls_write_trailer(struct AVFormatContext *s)
570 HLSContext *hls = s->priv_data;
571 AVFormatContext *oc = hls->avf;
573 av_write_trailer(oc);
574 ff_format_io_close(s, &oc->pb);
575 avformat_free_context(oc);
576 av_free(hls->basename);
577 append_entry(hls, hls->duration, av_basename(hls->avf->filename));
585 #define OFFSET(x) offsetof(HLSContext, x)
586 #define E AV_OPT_FLAG_ENCODING_PARAM
587 static const AVOption options[] = {
588 {"start_number", "first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, -1, INT64_MAX, E, "start_number"},
589 {"recover", "If there is already a m3u8 file in the path, populate the sequence from it", 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, E, "start_number"},
590 {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
591 {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
592 {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
593 {"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},
594 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
595 {"hls_version", "protocol version", OFFSET(version), AV_OPT_TYPE_INT, {.i64 = 3}, 2, 3, E},
596 {"hls_enc", "AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
597 {"hls_enc_key", "use the specified hex-coded 16byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = E},
598 {"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},
599 {"hls_enc_iv", "use the specified hex-coded 16byte initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = E},
603 static const AVClass hls_class = {
604 .class_name = "hls muxer",
605 .item_name = av_default_item_name,
607 .version = LIBAVUTIL_VERSION_INT,
611 AVOutputFormat ff_hls_muxer = {
613 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
614 .extensions = "m3u8",
615 .priv_data_size = sizeof(HLSContext),
616 .audio_codec = AV_CODEC_ID_AAC,
617 .video_codec = AV_CODEC_ID_H264,
618 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
619 .write_header = hls_write_header,
620 .write_packet = hls_write_packet,
621 .write_trailer = hls_write_trailer,
622 .priv_class = &hls_class,