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.

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