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.

431 lines
13KB

  1. /*
  2. * Apple HTTP Live Streaming segmenter
  3. * Copyright (c) 2012, Luca Barbato
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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 "libavutil/mathematics.h"
  24. #include "libavutil/parseutils.h"
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/log.h"
  28. #include "avformat.h"
  29. #include "internal.h"
  30. typedef struct HLSSegment {
  31. char filename[1024];
  32. double duration; /* in seconds */
  33. int64_t pos;
  34. int64_t size;
  35. struct HLSSegment *next;
  36. } HLSSegment;
  37. typedef enum HLSFlags {
  38. // Generate a single media file and use byte ranges in the playlist.
  39. HLS_SINGLE_FILE = (1 << 0),
  40. } HLSFlags;
  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 max_nb_segments; // Set by a private option.
  50. int wrap; // Set by a private option.
  51. uint32_t flags; // enum HLSFlags
  52. int allowcache;
  53. int64_t recording_time;
  54. int has_video;
  55. int64_t start_pts;
  56. int64_t end_pts;
  57. double duration; // last segment duration computed so far, in seconds
  58. int64_t start_pos; // last segment starting position
  59. int64_t size; // last segment size
  60. int nb_entries;
  61. HLSSegment *segments;
  62. HLSSegment *last_segment;
  63. char *basename;
  64. char *baseurl;
  65. char *format_options_str;
  66. AVDictionary *format_options;
  67. AVIOContext *pb;
  68. } HLSContext;
  69. static int hls_mux_init(AVFormatContext *s)
  70. {
  71. HLSContext *hls = s->priv_data;
  72. AVFormatContext *oc;
  73. int i;
  74. hls->avf = oc = avformat_alloc_context();
  75. if (!oc)
  76. return AVERROR(ENOMEM);
  77. oc->oformat = hls->oformat;
  78. oc->interrupt_callback = s->interrupt_callback;
  79. av_dict_copy(&oc->metadata, s->metadata, 0);
  80. for (i = 0; i < s->nb_streams; i++) {
  81. AVStream *st;
  82. if (!(st = avformat_new_stream(oc, NULL)))
  83. return AVERROR(ENOMEM);
  84. avcodec_copy_context(st->codec, s->streams[i]->codec);
  85. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  86. }
  87. hls->start_pos = 0;
  88. return 0;
  89. }
  90. /* Create a new segment and append it to the segment list */
  91. static int hls_append_segment(HLSContext *hls, double duration, int64_t pos,
  92. int64_t size)
  93. {
  94. HLSSegment *en = av_malloc(sizeof(*en));
  95. if (!en)
  96. return AVERROR(ENOMEM);
  97. av_strlcpy(en->filename, av_basename(hls->avf->filename), sizeof(en->filename));
  98. en->duration = duration;
  99. en->pos = pos;
  100. en->size = size;
  101. en->next = NULL;
  102. if (!hls->segments)
  103. hls->segments = en;
  104. else
  105. hls->last_segment->next = en;
  106. hls->last_segment = en;
  107. if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
  108. en = hls->segments;
  109. hls->segments = en->next;
  110. av_free(en);
  111. } else
  112. hls->nb_entries++;
  113. hls->sequence++;
  114. return 0;
  115. }
  116. static void hls_free_segments(HLSContext *hls)
  117. {
  118. HLSSegment *p = hls->segments, *en;
  119. while(p) {
  120. en = p;
  121. p = p->next;
  122. av_free(en);
  123. }
  124. }
  125. static int hls_window(AVFormatContext *s, int last)
  126. {
  127. HLSContext *hls = s->priv_data;
  128. HLSSegment *en;
  129. int target_duration = 0;
  130. int ret = 0;
  131. int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
  132. int version = hls->flags & HLS_SINGLE_FILE ? 4 : 3;
  133. if ((ret = avio_open2(&hls->pb, s->filename, AVIO_FLAG_WRITE,
  134. &s->interrupt_callback, NULL)) < 0)
  135. goto fail;
  136. for (en = hls->segments; en; en = en->next) {
  137. if (target_duration < en->duration)
  138. target_duration = ceil(en->duration);
  139. }
  140. avio_printf(hls->pb, "#EXTM3U\n");
  141. avio_printf(hls->pb, "#EXT-X-VERSION:%d\n", version);
  142. if (hls->allowcache == 0 || hls->allowcache == 1) {
  143. avio_printf(hls->pb, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  144. }
  145. avio_printf(hls->pb, "#EXT-X-TARGETDURATION:%d\n", target_duration);
  146. avio_printf(hls->pb, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  147. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
  148. sequence);
  149. for (en = hls->segments; en; en = en->next) {
  150. avio_printf(hls->pb, "#EXTINF:%f,\n", en->duration);
  151. if (hls->flags & HLS_SINGLE_FILE)
  152. avio_printf(hls->pb, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
  153. en->size, en->pos);
  154. if (hls->baseurl)
  155. avio_printf(hls->pb, "%s", hls->baseurl);
  156. avio_printf(hls->pb, "%s\n", en->filename);
  157. }
  158. if (last)
  159. avio_printf(hls->pb, "#EXT-X-ENDLIST\n");
  160. fail:
  161. avio_closep(&hls->pb);
  162. return ret;
  163. }
  164. static int hls_start(AVFormatContext *s)
  165. {
  166. HLSContext *c = s->priv_data;
  167. AVFormatContext *oc = c->avf;
  168. int err = 0;
  169. if (c->flags & HLS_SINGLE_FILE)
  170. av_strlcpy(oc->filename, c->basename,
  171. sizeof(oc->filename));
  172. else
  173. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  174. c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0) {
  175. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->basename);
  176. return AVERROR(EINVAL);
  177. }
  178. c->number++;
  179. if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  180. &s->interrupt_callback, NULL)) < 0)
  181. return err;
  182. if (oc->oformat->priv_class && oc->priv_data)
  183. av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
  184. return 0;
  185. }
  186. static int hls_write_header(AVFormatContext *s)
  187. {
  188. HLSContext *hls = s->priv_data;
  189. int ret, i;
  190. char *p;
  191. const char *pattern = "%d.ts";
  192. AVDictionary *options = NULL;
  193. int basename_size = strlen(s->filename) + strlen(pattern) + 1;
  194. hls->sequence = hls->start_sequence;
  195. hls->recording_time = hls->time * AV_TIME_BASE;
  196. hls->start_pts = AV_NOPTS_VALUE;
  197. if (hls->flags & HLS_SINGLE_FILE)
  198. pattern = ".ts";
  199. if (hls->format_options_str) {
  200. ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
  201. if (ret < 0) {
  202. av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
  203. goto fail;
  204. }
  205. }
  206. for (i = 0; i < s->nb_streams; i++)
  207. hls->has_video +=
  208. s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  209. if (hls->has_video > 1)
  210. av_log(s, AV_LOG_WARNING,
  211. "More than a single video stream present, "
  212. "expect issues decoding it.\n");
  213. hls->oformat = av_guess_format("mpegts", NULL, NULL);
  214. if (!hls->oformat) {
  215. ret = AVERROR_MUXER_NOT_FOUND;
  216. goto fail;
  217. }
  218. hls->basename = av_malloc(basename_size);
  219. if (!hls->basename) {
  220. ret = AVERROR(ENOMEM);
  221. goto fail;
  222. }
  223. strcpy(hls->basename, s->filename);
  224. p = strrchr(hls->basename, '.');
  225. if (p)
  226. *p = '\0';
  227. av_strlcat(hls->basename, pattern, basename_size);
  228. if ((ret = hls_mux_init(s)) < 0)
  229. goto fail;
  230. if ((ret = hls_start(s)) < 0)
  231. goto fail;
  232. av_dict_copy(&options, hls->format_options, 0);
  233. ret = avformat_write_header(hls->avf, &options);
  234. if (av_dict_count(options)) {
  235. av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
  236. ret = AVERROR(EINVAL);
  237. goto fail;
  238. }
  239. fail:
  240. av_dict_free(&options);
  241. if (ret) {
  242. av_free(hls->basename);
  243. if (hls->avf)
  244. avformat_free_context(hls->avf);
  245. }
  246. return ret;
  247. }
  248. static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
  249. {
  250. HLSContext *hls = s->priv_data;
  251. AVFormatContext *oc = hls->avf;
  252. AVStream *st = s->streams[pkt->stream_index];
  253. int64_t end_pts = hls->recording_time * hls->number;
  254. int is_ref_pkt = 1;
  255. int ret, can_split = 1;
  256. if (hls->start_pts == AV_NOPTS_VALUE) {
  257. hls->start_pts = pkt->pts;
  258. hls->end_pts = pkt->pts;
  259. }
  260. if (hls->has_video) {
  261. can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  262. pkt->flags & AV_PKT_FLAG_KEY;
  263. is_ref_pkt = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  264. }
  265. if (pkt->pts == AV_NOPTS_VALUE)
  266. is_ref_pkt = can_split = 0;
  267. if (is_ref_pkt)
  268. hls->duration = (double)(pkt->pts - hls->end_pts)
  269. * st->time_base.num / st->time_base.den;
  270. if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
  271. end_pts, AV_TIME_BASE_Q) >= 0) {
  272. int64_t new_start_pos;
  273. av_write_frame(oc, NULL); /* Flush any buffered data */
  274. new_start_pos = avio_tell(hls->avf->pb);
  275. hls->size = new_start_pos - hls->start_pos;
  276. ret = hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
  277. hls->start_pos = new_start_pos;
  278. if (ret)
  279. return ret;
  280. hls->end_pts = pkt->pts;
  281. hls->duration = 0;
  282. if (hls->flags & HLS_SINGLE_FILE) {
  283. if (hls->avf->oformat->priv_class && hls->avf->priv_data)
  284. av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
  285. hls->number++;
  286. } else {
  287. avio_close(oc->pb);
  288. ret = hls_start(s);
  289. }
  290. if (ret)
  291. return ret;
  292. oc = hls->avf;
  293. if ((ret = hls_window(s, 0)) < 0)
  294. return ret;
  295. }
  296. ret = ff_write_chained(oc, pkt->stream_index, pkt, s, 0);
  297. return ret;
  298. }
  299. static int hls_write_trailer(struct AVFormatContext *s)
  300. {
  301. HLSContext *hls = s->priv_data;
  302. AVFormatContext *oc = hls->avf;
  303. av_write_trailer(oc);
  304. hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
  305. avio_closep(&oc->pb);
  306. avformat_free_context(oc);
  307. av_free(hls->basename);
  308. hls_append_segment(hls, hls->duration, hls->start_pos, hls->size);
  309. hls_window(s, 1);
  310. hls_free_segments(hls);
  311. avio_close(hls->pb);
  312. return 0;
  313. }
  314. #define OFFSET(x) offsetof(HLSContext, x)
  315. #define E AV_OPT_FLAG_ENCODING_PARAM
  316. static const AVOption options[] = {
  317. {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
  318. {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
  319. {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
  320. {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  321. {"hls_wrap", "set number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  322. {"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},
  323. {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  324. {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
  325. {"single_file", "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX, E, "flags"},
  326. { NULL },
  327. };
  328. static const AVClass hls_class = {
  329. .class_name = "hls muxer",
  330. .item_name = av_default_item_name,
  331. .option = options,
  332. .version = LIBAVUTIL_VERSION_INT,
  333. };
  334. AVOutputFormat ff_hls_muxer = {
  335. .name = "hls",
  336. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  337. .extensions = "m3u8",
  338. .priv_data_size = sizeof(HLSContext),
  339. .audio_codec = AV_CODEC_ID_AAC,
  340. .video_codec = AV_CODEC_ID_H264,
  341. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  342. .write_header = hls_write_header,
  343. .write_packet = hls_write_packet,
  344. .write_trailer = hls_write_trailer,
  345. .priv_class = &hls_class,
  346. };