You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

553 lines
15KB

  1. /*
  2. * Apple HTTP Live Streaming segmenter
  3. * Copyright (c) 2012, Luca Barbato
  4. *
  5. * This file is part of Libav.
  6. *
  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.
  11. *
  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.
  16. *
  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
  20. */
  21. #include <float.h>
  22. #include <stdint.h>
  23. #include <config.h>
  24. #if CONFIG_GCRYPT
  25. #include <gcrypt.h>
  26. #elif CONFIG_OPENSSL
  27. #include <openssl/rand.h>
  28. #endif
  29. #include "libavutil/mathematics.h"
  30. #include "libavutil/parseutils.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/opt.h"
  34. #include "libavutil/random_seed.h"
  35. #include "libavutil/log.h"
  36. #include "avformat.h"
  37. #include "internal.h"
  38. typedef struct ListEntry {
  39. char name[1024];
  40. int64_t duration; // segment duration in AV_TIME_BASE units
  41. struct ListEntry *next;
  42. } ListEntry;
  43. typedef struct HLSContext {
  44. const AVClass *class; // Class for private options.
  45. unsigned number;
  46. int64_t sequence;
  47. int64_t start_sequence;
  48. AVOutputFormat *oformat;
  49. AVFormatContext *avf;
  50. float time; // Set by a private option.
  51. int size; // Set by a private option.
  52. int wrap; // Set by a private option.
  53. int version; // Set by a private option.
  54. int allowcache;
  55. int64_t recording_time;
  56. int has_video;
  57. // The following timestamps are in AV_TIME_BASE units.
  58. int64_t start_pts;
  59. int64_t end_pts;
  60. int64_t duration; // last segment duration computed so far.
  61. int nb_entries;
  62. ListEntry *list;
  63. ListEntry *end_list;
  64. char *basename;
  65. char *baseurl;
  66. int encrypt; // Set by a private option.
  67. char *key; // Set by a private option.
  68. int key_len;
  69. char *key_url; // Set by a private option.
  70. char *iv; // Set by a private option.
  71. int iv_len;
  72. char *key_basename;
  73. AVDictionary *enc_opts;
  74. } HLSContext;
  75. static int randomize(uint8_t *buf, int len)
  76. {
  77. #if CONFIG_GCRYPT
  78. gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
  79. return 0;
  80. #elif CONFIG_OPENSSL
  81. if (RAND_bytes(buf, len))
  82. return 0;
  83. return AVERROR(EIO);
  84. #else
  85. return AVERROR(ENOSYS);
  86. #endif
  87. }
  88. static void free_encryption(AVFormatContext *s)
  89. {
  90. HLSContext *hls = s->priv_data;
  91. av_dict_free(&hls->enc_opts);
  92. av_freep(&hls->key_basename);
  93. }
  94. static int dict_set_bin(AVDictionary **dict, const char *key, uint8_t *buf)
  95. {
  96. char hex[33];
  97. ff_data_to_hex(hex, buf, sizeof(buf), 0);
  98. hex[32] = '\0';
  99. return av_dict_set(dict, key, hex, 0);
  100. }
  101. static int setup_encryption(AVFormatContext *s)
  102. {
  103. HLSContext *hls = s->priv_data;
  104. AVIOContext *out = NULL;
  105. int len, ret;
  106. uint8_t buf[16];
  107. uint8_t *k;
  108. len = strlen(hls->basename) + 4 + 1;
  109. hls->key_basename = av_mallocz(len);
  110. if (!hls->key_basename)
  111. return AVERROR(ENOMEM);
  112. av_strlcpy(hls->key_basename, hls->basename + 7, len);
  113. av_strlcat(hls->key_basename, ".key", len);
  114. if (hls->key) {
  115. if (hls->key_len != 16) {
  116. av_log(s, AV_LOG_ERROR,
  117. "Invalid key size %d, expected 16-bytes hex-coded key\n",
  118. hls->key_len);
  119. return AVERROR(EINVAL);
  120. }
  121. if ((ret = dict_set_bin(&hls->enc_opts, "key", hls->key)) < 0)
  122. return ret;
  123. k = hls->key;
  124. } else {
  125. if ((ret = randomize(buf, sizeof(buf))) < 0) {
  126. av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
  127. return ret;
  128. }
  129. if ((ret = dict_set_bin(&hls->enc_opts, "key", buf)) < 0)
  130. return ret;
  131. k = buf;
  132. }
  133. if (hls->iv) {
  134. if (hls->iv_len != 16) {
  135. av_log(s, AV_LOG_ERROR,
  136. "Invalid key size %d, expected 16-bytes hex-coded initialization vector\n",
  137. hls->iv_len);
  138. return AVERROR(EINVAL);
  139. }
  140. if ((ret = dict_set_bin(&hls->enc_opts, "iv", hls->iv)) < 0)
  141. return ret;
  142. }
  143. if ((ret = s->io_open(s, &out, hls->key_basename, AVIO_FLAG_WRITE, NULL)) < 0)
  144. return ret;
  145. avio_write(out, k, 16);
  146. avio_close(out);
  147. return 0;
  148. }
  149. static int hls_mux_init(AVFormatContext *s)
  150. {
  151. HLSContext *hls = s->priv_data;
  152. AVFormatContext *oc;
  153. int i;
  154. hls->avf = oc = avformat_alloc_context();
  155. if (!oc)
  156. return AVERROR(ENOMEM);
  157. oc->oformat = hls->oformat;
  158. oc->interrupt_callback = s->interrupt_callback;
  159. oc->opaque = s->opaque;
  160. oc->io_open = s->io_open;
  161. oc->io_close = s->io_close;
  162. for (i = 0; i < s->nb_streams; i++) {
  163. AVStream *st;
  164. if (!(st = avformat_new_stream(oc, NULL)))
  165. return AVERROR(ENOMEM);
  166. avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
  167. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  168. st->time_base = s->streams[i]->time_base;
  169. }
  170. return 0;
  171. }
  172. static int append_entry(HLSContext *hls, int64_t duration)
  173. {
  174. ListEntry *en = av_malloc(sizeof(*en));
  175. if (!en)
  176. return AVERROR(ENOMEM);
  177. av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
  178. en->duration = duration;
  179. en->next = NULL;
  180. if (!hls->list)
  181. hls->list = en;
  182. else
  183. hls->end_list->next = en;
  184. hls->end_list = en;
  185. if (hls->nb_entries >= hls->size) {
  186. en = hls->list;
  187. hls->list = en->next;
  188. av_free(en);
  189. } else
  190. hls->nb_entries++;
  191. hls->sequence++;
  192. return 0;
  193. }
  194. static void free_entries(HLSContext *hls)
  195. {
  196. ListEntry *p = hls->list, *en;
  197. while(p) {
  198. en = p;
  199. p = p->next;
  200. av_free(en);
  201. }
  202. }
  203. static int hls_window(AVFormatContext *s, int last)
  204. {
  205. HLSContext *hls = s->priv_data;
  206. ListEntry *en;
  207. int64_t target_duration = 0;
  208. int ret = 0;
  209. AVIOContext *out = NULL;
  210. char temp_filename[1024];
  211. int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->size);
  212. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  213. if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL)) < 0)
  214. goto fail;
  215. for (en = hls->list; en; en = en->next) {
  216. if (target_duration < en->duration)
  217. target_duration = en->duration;
  218. }
  219. avio_printf(out, "#EXTM3U\n");
  220. avio_printf(out, "#EXT-X-VERSION:%d\n", hls->version);
  221. if (hls->allowcache == 0 || hls->allowcache == 1) {
  222. avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  223. }
  224. avio_printf(out, "#EXT-X-TARGETDURATION:%"PRId64"\n",
  225. av_rescale_rnd(target_duration, 1, AV_TIME_BASE,
  226. AV_ROUND_UP));
  227. avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  228. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
  229. sequence);
  230. for (en = hls->list; en; en = en->next) {
  231. if (hls->encrypt) {
  232. char *key_url;
  233. if (hls->key_url)
  234. key_url = hls->key_url;
  235. else
  236. key_url = hls->baseurl;
  237. avio_printf(out, "#EXT-X-KEY:METHOD=AES-128");
  238. avio_printf(out, ",URI=\"");
  239. if (key_url)
  240. avio_printf(out, "%s", key_url);
  241. avio_printf(out, "%s\"", av_basename(hls->key_basename));
  242. if (hls->iv)
  243. avio_printf(out, ",IV=\"0x%s\"", hls->iv);
  244. avio_printf(out, "\n");
  245. }
  246. if (hls->version > 2)
  247. avio_printf(out, "#EXTINF:%f\n",
  248. (double)en->duration / AV_TIME_BASE);
  249. else
  250. avio_printf(out, "#EXTINF:%"PRId64",\n",
  251. av_rescale(en->duration, 1, AV_TIME_BASE));
  252. if (hls->baseurl)
  253. avio_printf(out, "%s", hls->baseurl);
  254. avio_printf(out, "%s\n", en->name);
  255. }
  256. if (last)
  257. avio_printf(out, "#EXT-X-ENDLIST\n");
  258. fail:
  259. ff_format_io_close(s, &out);
  260. if (ret >= 0)
  261. ff_rename(temp_filename, s->filename);
  262. return ret;
  263. }
  264. static int hls_start(AVFormatContext *s)
  265. {
  266. HLSContext *c = s->priv_data;
  267. AVFormatContext *oc = c->avf;
  268. int err = 0;
  269. AVDictionary *opts = NULL;
  270. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  271. c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0)
  272. return AVERROR(EINVAL);
  273. c->number++;
  274. if (c->encrypt) {
  275. if ((err = av_dict_copy(&opts, c->enc_opts, 0)) < 0)
  276. return err;
  277. if (!c->iv) {
  278. uint8_t iv[16] = { 0 };
  279. char buf[33];
  280. AV_WB64(iv + 8, c->sequence);
  281. ff_data_to_hex(buf, iv, sizeof(iv), 0);
  282. buf[32] = '\0';
  283. if ((err = av_dict_set(&opts, "iv", buf, 0)) < 0)
  284. goto fail;
  285. }
  286. }
  287. if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &opts)) < 0)
  288. return err;
  289. if (oc->oformat->priv_class && oc->priv_data)
  290. av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
  291. fail:
  292. av_dict_free(&opts);
  293. return err;
  294. }
  295. static int hls_setup(AVFormatContext *s)
  296. {
  297. HLSContext *hls = s->priv_data;
  298. const char *pattern = "%d.ts";
  299. int basename_size = strlen(s->filename) + strlen(pattern) + 1;
  300. char *p;
  301. if (hls->encrypt)
  302. basename_size += 7;
  303. hls->basename = av_mallocz(basename_size);
  304. if (!hls->basename)
  305. return AVERROR(ENOMEM);
  306. // TODO: support protocol nesting?
  307. if (hls->encrypt)
  308. strcpy(hls->basename, "crypto:");
  309. av_strlcat(hls->basename, s->filename, basename_size);
  310. p = strrchr(hls->basename, '.');
  311. if (p)
  312. *p = '\0';
  313. if (hls->encrypt) {
  314. int ret = setup_encryption(s);
  315. if (ret < 0)
  316. return ret;
  317. }
  318. av_strlcat(hls->basename, pattern, basename_size);
  319. return 0;
  320. }
  321. static int hls_write_header(AVFormatContext *s)
  322. {
  323. HLSContext *hls = s->priv_data;
  324. int ret, i;
  325. hls->sequence = hls->start_sequence;
  326. hls->recording_time = hls->time * AV_TIME_BASE;
  327. hls->start_pts = AV_NOPTS_VALUE;
  328. for (i = 0; i < s->nb_streams; i++)
  329. hls->has_video +=
  330. s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
  331. if (hls->has_video > 1)
  332. av_log(s, AV_LOG_WARNING,
  333. "More than a single video stream present, "
  334. "expect issues decoding it.\n");
  335. hls->oformat = av_guess_format("mpegts", NULL, NULL);
  336. if (!hls->oformat) {
  337. ret = AVERROR_MUXER_NOT_FOUND;
  338. goto fail;
  339. }
  340. if ((ret = hls_setup(s)) < 0)
  341. goto fail;
  342. if ((ret = hls_mux_init(s)) < 0)
  343. goto fail;
  344. if ((ret = hls_start(s)) < 0)
  345. goto fail;
  346. if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
  347. return ret;
  348. fail:
  349. if (ret) {
  350. av_free(hls->basename);
  351. if (hls->avf)
  352. avformat_free_context(hls->avf);
  353. free_encryption(s);
  354. }
  355. return ret;
  356. }
  357. static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
  358. {
  359. HLSContext *hls = s->priv_data;
  360. AVFormatContext *oc = hls->avf;
  361. AVStream *st = s->streams[pkt->stream_index];
  362. int64_t end_pts = hls->recording_time * hls->number;
  363. int64_t pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
  364. int ret, can_split = 1;
  365. if (hls->start_pts == AV_NOPTS_VALUE) {
  366. hls->start_pts = pts;
  367. hls->end_pts = pts;
  368. }
  369. if (hls->has_video) {
  370. can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  371. pkt->flags & AV_PKT_FLAG_KEY;
  372. }
  373. if (pkt->pts == AV_NOPTS_VALUE)
  374. can_split = 0;
  375. else
  376. hls->duration = pts - hls->end_pts;
  377. if (can_split && pts - hls->start_pts >= end_pts) {
  378. ret = append_entry(hls, hls->duration);
  379. if (ret)
  380. return ret;
  381. hls->end_pts = pts;
  382. hls->duration = 0;
  383. av_write_frame(oc, NULL); /* Flush any buffered data */
  384. ff_format_io_close(s, &oc->pb);
  385. ret = hls_start(s);
  386. if (ret)
  387. return ret;
  388. oc = hls->avf;
  389. if ((ret = hls_window(s, 0)) < 0)
  390. return ret;
  391. }
  392. ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
  393. return ret;
  394. }
  395. static int hls_write_trailer(struct AVFormatContext *s)
  396. {
  397. HLSContext *hls = s->priv_data;
  398. AVFormatContext *oc = hls->avf;
  399. av_write_trailer(oc);
  400. ff_format_io_close(s, &oc->pb);
  401. avformat_free_context(oc);
  402. av_free(hls->basename);
  403. append_entry(hls, hls->duration);
  404. hls_window(s, 1);
  405. free_entries(hls);
  406. free_encryption(s);
  407. return 0;
  408. }
  409. #define OFFSET(x) offsetof(HLSContext, x)
  410. #define E AV_OPT_FLAG_ENCODING_PARAM
  411. static const AVOption options[] = {
  412. {"start_number", "first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
  413. {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
  414. {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
  415. {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  416. {"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},
  417. {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  418. {"hls_version", "protocol version", OFFSET(version), AV_OPT_TYPE_INT, {.i64 = 3}, 2, 3, E},
  419. {"hls_enc", "AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
  420. {"hls_enc_key", "use the specified hex-coded 16byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = E},
  421. {"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},
  422. {"hls_enc_iv", "use the specified hex-coded 16byte initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = E},
  423. { NULL },
  424. };
  425. static const AVClass hls_class = {
  426. .class_name = "hls muxer",
  427. .item_name = av_default_item_name,
  428. .option = options,
  429. .version = LIBAVUTIL_VERSION_INT,
  430. };
  431. AVOutputFormat ff_hls_muxer = {
  432. .name = "hls",
  433. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  434. .extensions = "m3u8",
  435. .priv_data_size = sizeof(HLSContext),
  436. .audio_codec = AV_CODEC_ID_AAC,
  437. .video_codec = AV_CODEC_ID_H264,
  438. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  439. .write_header = hls_write_header,
  440. .write_packet = hls_write_packet,
  441. .write_trailer = hls_write_trailer,
  442. .priv_class = &hls_class,
  443. };