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.

362 lines
10KB

  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 "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 ListEntry {
  31. char name[1024];
  32. int duration;
  33. struct ListEntry *next;
  34. } ListEntry;
  35. typedef struct HLSContext {
  36. const AVClass *class; // Class for private options.
  37. unsigned number;
  38. int64_t sequence;
  39. int64_t start_sequence;
  40. AVOutputFormat *oformat;
  41. AVFormatContext *avf;
  42. float time; // Set by a private option.
  43. int size; // Set by a private option.
  44. int wrap; // Set by a private option.
  45. int allowcache;
  46. int64_t recording_time;
  47. int has_video;
  48. int64_t start_pts;
  49. int64_t end_pts;
  50. int64_t duration; // last segment duration computed so far, in seconds
  51. int nb_entries;
  52. ListEntry *list;
  53. ListEntry *end_list;
  54. char *basename;
  55. char *baseurl;
  56. } HLSContext;
  57. static int hls_mux_init(AVFormatContext *s)
  58. {
  59. HLSContext *hls = s->priv_data;
  60. AVFormatContext *oc;
  61. int i;
  62. hls->avf = oc = avformat_alloc_context();
  63. if (!oc)
  64. return AVERROR(ENOMEM);
  65. oc->oformat = hls->oformat;
  66. oc->interrupt_callback = s->interrupt_callback;
  67. for (i = 0; i < s->nb_streams; i++) {
  68. AVStream *st;
  69. if (!(st = avformat_new_stream(oc, NULL)))
  70. return AVERROR(ENOMEM);
  71. avcodec_copy_context(st->codec, s->streams[i]->codec);
  72. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  73. st->time_base = s->streams[i]->time_base;
  74. }
  75. return 0;
  76. }
  77. static int append_entry(HLSContext *hls, uint64_t duration)
  78. {
  79. ListEntry *en = av_malloc(sizeof(*en));
  80. if (!en)
  81. return AVERROR(ENOMEM);
  82. av_strlcpy(en->name, av_basename(hls->avf->filename), sizeof(en->name));
  83. en->duration = duration;
  84. en->next = NULL;
  85. if (!hls->list)
  86. hls->list = en;
  87. else
  88. hls->end_list->next = en;
  89. hls->end_list = en;
  90. if (hls->nb_entries >= hls->size) {
  91. en = hls->list;
  92. hls->list = en->next;
  93. av_free(en);
  94. } else
  95. hls->nb_entries++;
  96. hls->sequence++;
  97. return 0;
  98. }
  99. static void free_entries(HLSContext *hls)
  100. {
  101. ListEntry *p = hls->list, *en;
  102. while(p) {
  103. en = p;
  104. p = p->next;
  105. av_free(en);
  106. }
  107. }
  108. static int hls_window(AVFormatContext *s, int last)
  109. {
  110. HLSContext *hls = s->priv_data;
  111. ListEntry *en;
  112. int target_duration = 0;
  113. int ret = 0;
  114. AVIOContext *out = NULL;
  115. char temp_filename[1024];
  116. int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->size);
  117. snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
  118. if ((ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE,
  119. &s->interrupt_callback, NULL)) < 0)
  120. goto fail;
  121. for (en = hls->list; en; en = en->next) {
  122. if (target_duration < en->duration)
  123. target_duration = en->duration;
  124. }
  125. avio_printf(out, "#EXTM3U\n");
  126. avio_printf(out, "#EXT-X-VERSION:3\n");
  127. if (hls->allowcache == 0 || hls->allowcache == 1) {
  128. avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
  129. }
  130. avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
  131. avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
  132. av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n",
  133. sequence);
  134. for (en = hls->list; en; en = en->next) {
  135. avio_printf(out, "#EXTINF:%d,\n", en->duration);
  136. if (hls->baseurl)
  137. avio_printf(out, "%s", hls->baseurl);
  138. avio_printf(out, "%s\n", en->name);
  139. }
  140. if (last)
  141. avio_printf(out, "#EXT-X-ENDLIST\n");
  142. fail:
  143. avio_closep(&out);
  144. if (ret >= 0)
  145. ff_rename(temp_filename, s->filename);
  146. return ret;
  147. }
  148. static int hls_start(AVFormatContext *s)
  149. {
  150. HLSContext *c = s->priv_data;
  151. AVFormatContext *oc = c->avf;
  152. int err = 0;
  153. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  154. c->basename, c->wrap ? c->sequence % c->wrap : c->sequence) < 0)
  155. return AVERROR(EINVAL);
  156. c->number++;
  157. if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  158. &s->interrupt_callback, NULL)) < 0)
  159. return err;
  160. if (oc->oformat->priv_class && oc->priv_data)
  161. av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
  162. return 0;
  163. }
  164. static int hls_write_header(AVFormatContext *s)
  165. {
  166. HLSContext *hls = s->priv_data;
  167. int ret, i;
  168. char *p;
  169. const char *pattern = "%d.ts";
  170. int basename_size = strlen(s->filename) + strlen(pattern) + 1;
  171. hls->sequence = hls->start_sequence;
  172. hls->recording_time = hls->time * AV_TIME_BASE;
  173. hls->start_pts = AV_NOPTS_VALUE;
  174. for (i = 0; i < s->nb_streams; i++)
  175. hls->has_video +=
  176. s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;
  177. if (hls->has_video > 1)
  178. av_log(s, AV_LOG_WARNING,
  179. "More than a single video stream present, "
  180. "expect issues decoding it.\n");
  181. hls->oformat = av_guess_format("mpegts", NULL, NULL);
  182. if (!hls->oformat) {
  183. ret = AVERROR_MUXER_NOT_FOUND;
  184. goto fail;
  185. }
  186. hls->basename = av_malloc(basename_size);
  187. if (!hls->basename) {
  188. ret = AVERROR(ENOMEM);
  189. goto fail;
  190. }
  191. strcpy(hls->basename, s->filename);
  192. p = strrchr(hls->basename, '.');
  193. if (p)
  194. *p = '\0';
  195. av_strlcat(hls->basename, pattern, basename_size);
  196. if ((ret = hls_mux_init(s)) < 0)
  197. goto fail;
  198. if ((ret = hls_start(s)) < 0)
  199. goto fail;
  200. if ((ret = avformat_write_header(hls->avf, NULL)) < 0)
  201. return ret;
  202. fail:
  203. if (ret) {
  204. av_free(hls->basename);
  205. if (hls->avf)
  206. avformat_free_context(hls->avf);
  207. }
  208. return ret;
  209. }
  210. static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
  211. {
  212. HLSContext *hls = s->priv_data;
  213. AVFormatContext *oc = hls->avf;
  214. AVStream *st = s->streams[pkt->stream_index];
  215. int64_t end_pts = hls->recording_time * hls->number;
  216. int ret, can_split = 1;
  217. if (hls->start_pts == AV_NOPTS_VALUE) {
  218. hls->start_pts = pkt->pts;
  219. hls->end_pts = pkt->pts;
  220. }
  221. if (hls->has_video) {
  222. can_split = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  223. pkt->flags & AV_PKT_FLAG_KEY;
  224. }
  225. if (pkt->pts == AV_NOPTS_VALUE)
  226. can_split = 0;
  227. else
  228. hls->duration = av_rescale(pkt->pts - hls->end_pts,
  229. st->time_base.num, st->time_base.den);
  230. if (can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
  231. end_pts, AV_TIME_BASE_Q) >= 0) {
  232. ret = append_entry(hls, hls->duration);
  233. if (ret)
  234. return ret;
  235. hls->end_pts = pkt->pts;
  236. hls->duration = 0;
  237. av_write_frame(oc, NULL); /* Flush any buffered data */
  238. avio_close(oc->pb);
  239. ret = hls_start(s);
  240. if (ret)
  241. return ret;
  242. oc = hls->avf;
  243. if ((ret = hls_window(s, 0)) < 0)
  244. return ret;
  245. }
  246. ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
  247. return ret;
  248. }
  249. static int hls_write_trailer(struct AVFormatContext *s)
  250. {
  251. HLSContext *hls = s->priv_data;
  252. AVFormatContext *oc = hls->avf;
  253. av_write_trailer(oc);
  254. avio_closep(&oc->pb);
  255. avformat_free_context(oc);
  256. av_free(hls->basename);
  257. append_entry(hls, hls->duration);
  258. hls_window(s, 1);
  259. free_entries(hls);
  260. return 0;
  261. }
  262. #define OFFSET(x) offsetof(HLSContext, x)
  263. #define E AV_OPT_FLAG_ENCODING_PARAM
  264. static const AVOption options[] = {
  265. {"start_number", "first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
  266. {"hls_time", "segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
  267. {"hls_list_size", "maximum number of playlist entries", OFFSET(size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
  268. {"hls_wrap", "number after which the index wraps", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
  269. {"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},
  270. {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
  271. { NULL },
  272. };
  273. static const AVClass hls_class = {
  274. .class_name = "hls muxer",
  275. .item_name = av_default_item_name,
  276. .option = options,
  277. .version = LIBAVUTIL_VERSION_INT,
  278. };
  279. AVOutputFormat ff_hls_muxer = {
  280. .name = "hls",
  281. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  282. .extensions = "m3u8",
  283. .priv_data_size = sizeof(HLSContext),
  284. .audio_codec = AV_CODEC_ID_AAC,
  285. .video_codec = AV_CODEC_ID_H264,
  286. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  287. .write_header = hls_write_header,
  288. .write_packet = hls_write_packet,
  289. .write_trailer = hls_write_trailer,
  290. .priv_class = &hls_class,
  291. };