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.

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