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.

448 lines
14KB

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