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.

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