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.

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