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.

527 lines
18KB

  1. /*
  2. * Copyright (c) 2011, Luca Barbato
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file generic segmenter
  22. * M3U8 specification can be find here:
  23. * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming-08.txt}
  24. */
  25. #include <float.h>
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "libavutil/avassert.h"
  29. #include "libavutil/log.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/parseutils.h"
  33. #include "libavutil/mathematics.h"
  34. typedef enum {
  35. LIST_TYPE_UNDEFINED = -1,
  36. LIST_TYPE_FLAT = 0,
  37. LIST_TYPE_CSV,
  38. LIST_TYPE_M3U8,
  39. LIST_TYPE_EXT, ///< deprecated
  40. LIST_TYPE_NB,
  41. } ListType;
  42. #define SEGMENT_LIST_FLAG_CACHE 1
  43. #define SEGMENT_LIST_FLAG_LIVE 2
  44. typedef struct {
  45. const AVClass *class; /**< Class for private options. */
  46. int segment_idx; ///< index of the segment file to write, starting from 0
  47. int segment_idx_wrap; ///< number after which the index wraps
  48. int segment_count; ///< number of segment files already written
  49. AVOutputFormat *oformat;
  50. AVFormatContext *avf;
  51. char *format; ///< format to use for output segment files
  52. char *list; ///< filename for the segment list file
  53. int list_count; ///< list counter
  54. int list_flags; ///< flags affecting list generation
  55. int list_size; ///< number of entries for the segment list file
  56. double list_max_segment_time; ///< max segment time in the current list
  57. ListType list_type; ///< set the list type
  58. AVIOContext *list_pb; ///< list file put-byte context
  59. char *time_str; ///< segment duration specification string
  60. int64_t time; ///< segment duration
  61. char *times_str; ///< segment times specification string
  62. int64_t *times; ///< list of segment interval specification
  63. int nb_times; ///< number of elments in the times array
  64. char *time_delta_str; ///< approximation value duration used for the segment times
  65. int64_t time_delta;
  66. int individual_header_trailer; /**< Set by a private option. */
  67. int has_video;
  68. double start_time, end_time;
  69. } SegmentContext;
  70. static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
  71. {
  72. int needs_quoting = !!str[strcspn(str, "\",\n\r")];
  73. if (needs_quoting)
  74. avio_w8(ctx, '"');
  75. for (; *str; str++) {
  76. if (*str == '"')
  77. avio_w8(ctx, '"');
  78. avio_w8(ctx, *str);
  79. }
  80. if (needs_quoting)
  81. avio_w8(ctx, '"');
  82. }
  83. static int segment_mux_init(AVFormatContext *s)
  84. {
  85. SegmentContext *seg = s->priv_data;
  86. AVFormatContext *oc;
  87. int i;
  88. seg->avf = oc = avformat_alloc_context();
  89. if (!oc)
  90. return AVERROR(ENOMEM);
  91. oc->oformat = seg->oformat;
  92. oc->interrupt_callback = s->interrupt_callback;
  93. for (i = 0; i < s->nb_streams; i++) {
  94. AVStream *st;
  95. if (!(st = avformat_new_stream(oc, NULL)))
  96. return AVERROR(ENOMEM);
  97. avcodec_copy_context(st->codec, s->streams[i]->codec);
  98. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  99. }
  100. return 0;
  101. }
  102. static int segment_start(AVFormatContext *s, int write_header)
  103. {
  104. SegmentContext *c = s->priv_data;
  105. AVFormatContext *oc = c->avf;
  106. int err = 0;
  107. if (write_header) {
  108. avformat_free_context(oc);
  109. c->avf = NULL;
  110. if ((err = segment_mux_init(s)) < 0)
  111. return err;
  112. oc = c->avf;
  113. }
  114. if (c->segment_idx_wrap)
  115. c->segment_idx %= c->segment_idx_wrap;
  116. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  117. s->filename, c->segment_idx++) < 0) {
  118. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
  119. return AVERROR(EINVAL);
  120. }
  121. c->segment_count++;
  122. if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  123. &s->interrupt_callback, NULL)) < 0)
  124. return err;
  125. if (oc->oformat->priv_class && oc->priv_data)
  126. av_opt_set(oc->priv_data, "resend_headers", "1", 0);
  127. if (write_header) {
  128. if ((err = avformat_write_header(oc, NULL)) < 0)
  129. return err;
  130. }
  131. return 0;
  132. }
  133. static int segment_list_open(AVFormatContext *s)
  134. {
  135. SegmentContext *seg = s->priv_data;
  136. int ret;
  137. ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
  138. &s->interrupt_callback, NULL);
  139. if (ret < 0)
  140. return ret;
  141. seg->list_max_segment_time = 0;
  142. if (seg->list_type == LIST_TYPE_M3U8) {
  143. avio_printf(seg->list_pb, "#EXTM3U\n");
  144. avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
  145. avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
  146. avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
  147. !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
  148. if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
  149. avio_printf(seg->list_pb,
  150. "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
  151. }
  152. return ret;
  153. }
  154. static void segment_list_close(AVFormatContext *s)
  155. {
  156. SegmentContext *seg = s->priv_data;
  157. if (seg->list_type == LIST_TYPE_M3U8) {
  158. if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
  159. avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
  160. (int)ceil(seg->list_max_segment_time));
  161. avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
  162. }
  163. seg->list_count++;
  164. avio_close(seg->list_pb);
  165. }
  166. static int segment_end(AVFormatContext *s, int write_trailer)
  167. {
  168. SegmentContext *seg = s->priv_data;
  169. AVFormatContext *oc = seg->avf;
  170. int ret = 0;
  171. av_write_frame(oc, NULL); /* Flush any buffered data */
  172. if (write_trailer)
  173. ret = av_write_trailer(oc);
  174. if (ret < 0)
  175. av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
  176. oc->filename);
  177. if (seg->list) {
  178. if (seg->list_size && !(seg->segment_count % seg->list_size)) {
  179. segment_list_close(s);
  180. if ((ret = segment_list_open(s)) < 0)
  181. goto end;
  182. }
  183. if (seg->list_type == LIST_TYPE_FLAT) {
  184. avio_printf(seg->list_pb, "%s\n", oc->filename);
  185. } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
  186. print_csv_escaped_str(seg->list_pb, oc->filename);
  187. avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
  188. } else if (seg->list_type == LIST_TYPE_M3U8) {
  189. avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
  190. seg->end_time - seg->start_time, oc->filename);
  191. }
  192. seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
  193. avio_flush(seg->list_pb);
  194. }
  195. end:
  196. avio_close(oc->pb);
  197. return ret;
  198. }
  199. static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
  200. const char *times_str)
  201. {
  202. char *p;
  203. int i, ret = 0;
  204. char *times_str1 = av_strdup(times_str);
  205. char *saveptr = NULL;
  206. if (!times_str1)
  207. return AVERROR(ENOMEM);
  208. #define FAIL(err) ret = err; goto end
  209. *nb_times = 1;
  210. for (p = times_str1; *p; p++)
  211. if (*p == ',')
  212. (*nb_times)++;
  213. *times = av_malloc(sizeof(**times) * *nb_times);
  214. if (!*times) {
  215. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
  216. FAIL(AVERROR(ENOMEM));
  217. }
  218. p = times_str1;
  219. for (i = 0; i < *nb_times; i++) {
  220. int64_t t;
  221. char *tstr = av_strtok(p, ",", &saveptr);
  222. av_assert0(tstr);
  223. p = NULL;
  224. ret = av_parse_time(&t, tstr, 1);
  225. if (ret < 0) {
  226. av_log(log_ctx, AV_LOG_ERROR,
  227. "Invalid time duration specification in %s\n", p);
  228. FAIL(AVERROR(EINVAL));
  229. }
  230. (*times)[i] = t;
  231. /* check on monotonicity */
  232. if (i && (*times)[i-1] > (*times)[i]) {
  233. av_log(log_ctx, AV_LOG_ERROR,
  234. "Specified time %f is greater than the following time %f\n",
  235. (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
  236. FAIL(AVERROR(EINVAL));
  237. }
  238. }
  239. end:
  240. av_free(times_str1);
  241. return ret;
  242. }
  243. static int seg_write_header(AVFormatContext *s)
  244. {
  245. SegmentContext *seg = s->priv_data;
  246. AVFormatContext *oc = NULL;
  247. int ret, i;
  248. seg->segment_count = 0;
  249. if (seg->time_str && seg->times_str) {
  250. av_log(s, AV_LOG_ERROR,
  251. "segment_time and segment_times options are mutually exclusive, select just one of them\n");
  252. return AVERROR(EINVAL);
  253. }
  254. if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
  255. av_log(s, AV_LOG_ERROR,
  256. "segment_flags +live and segment_times options are mutually exclusive:"
  257. "specify -segment_time if you want a live-friendly list\n");
  258. return AVERROR(EINVAL);
  259. }
  260. if (seg->times_str) {
  261. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  262. return ret;
  263. } else {
  264. /* set default value if not specified */
  265. if (!seg->time_str)
  266. seg->time_str = av_strdup("2");
  267. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  268. av_log(s, AV_LOG_ERROR,
  269. "Invalid time duration specification '%s' for segment_time option\n",
  270. seg->time_str);
  271. return ret;
  272. }
  273. }
  274. if (seg->time_delta_str) {
  275. if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
  276. av_log(s, AV_LOG_ERROR,
  277. "Invalid time duration specification '%s' for delta option\n",
  278. seg->time_delta_str);
  279. return ret;
  280. }
  281. }
  282. if (seg->list) {
  283. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  284. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  285. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  286. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  287. else seg->list_type = LIST_TYPE_FLAT;
  288. }
  289. if ((ret = segment_list_open(s)) < 0)
  290. goto fail;
  291. }
  292. if (seg->list_type == LIST_TYPE_EXT)
  293. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  294. for (i = 0; i < s->nb_streams; i++)
  295. seg->has_video +=
  296. (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
  297. if (seg->has_video > 1)
  298. av_log(s, AV_LOG_WARNING,
  299. "More than a single video stream present, "
  300. "expect issues decoding it.\n");
  301. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  302. if (!seg->oformat) {
  303. ret = AVERROR_MUXER_NOT_FOUND;
  304. goto fail;
  305. }
  306. if (seg->oformat->flags & AVFMT_NOFILE) {
  307. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  308. oc->oformat->name);
  309. ret = AVERROR(EINVAL);
  310. goto fail;
  311. }
  312. if ((ret = segment_mux_init(s)) < 0)
  313. goto fail;
  314. oc = seg->avf;
  315. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  316. s->filename, seg->segment_idx++) < 0) {
  317. ret = AVERROR(EINVAL);
  318. goto fail;
  319. }
  320. seg->segment_count++;
  321. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  322. &s->interrupt_callback, NULL)) < 0)
  323. goto fail;
  324. if ((ret = avformat_write_header(oc, NULL)) < 0) {
  325. avio_close(oc->pb);
  326. goto fail;
  327. }
  328. fail:
  329. if (ret) {
  330. if (seg->list)
  331. segment_list_close(s);
  332. if (seg->avf)
  333. avformat_free_context(seg->avf);
  334. }
  335. return ret;
  336. }
  337. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  338. {
  339. SegmentContext *seg = s->priv_data;
  340. AVFormatContext *oc = seg->avf;
  341. AVStream *st = s->streams[pkt->stream_index];
  342. int64_t end_pts;
  343. int ret;
  344. if (seg->times) {
  345. end_pts = seg->segment_count <= seg->nb_times ?
  346. seg->times[seg->segment_count-1] : INT64_MAX;
  347. } else {
  348. end_pts = seg->time * seg->segment_count;
  349. }
  350. /* if the segment has video, start a new segment *only* with a key video frame */
  351. if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
  352. av_compare_ts(pkt->pts, st->time_base,
  353. end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
  354. pkt->flags & AV_PKT_FLAG_KEY) {
  355. av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
  356. pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
  357. ret = segment_end(s, seg->individual_header_trailer);
  358. if (!ret)
  359. ret = segment_start(s, seg->individual_header_trailer);
  360. if (ret)
  361. goto fail;
  362. oc = seg->avf;
  363. seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
  364. } else if (pkt->pts != AV_NOPTS_VALUE) {
  365. seg->end_time = FFMAX(seg->end_time,
  366. (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  367. }
  368. ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
  369. fail:
  370. if (ret < 0) {
  371. if (seg->list)
  372. avio_close(seg->list_pb);
  373. avformat_free_context(oc);
  374. }
  375. return ret;
  376. }
  377. static int seg_write_trailer(struct AVFormatContext *s)
  378. {
  379. SegmentContext *seg = s->priv_data;
  380. AVFormatContext *oc = seg->avf;
  381. int ret = segment_end(s, 1);
  382. if (seg->list)
  383. segment_list_close(s);
  384. av_opt_free(seg);
  385. av_freep(&seg->times);
  386. avformat_free_context(oc);
  387. return ret;
  388. }
  389. #define OFFSET(x) offsetof(SegmentContext, x)
  390. #define E AV_OPT_FLAG_ENCODING_PARAM
  391. static const AVOption options[] = {
  392. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  393. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  394. { "segment_list_flags","set flags affecting segment list generation", OFFSET(list_flags), AV_OPT_TYPE_FLAGS, {.i64 = SEGMENT_LIST_FLAG_CACHE }, 0, UINT_MAX, E, "list_flags"},
  395. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  396. { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, "list_flags"},
  397. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  398. { "segment_list_type", "set the segment list type", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_TYPE_UNDEFINED}, -1, LIST_TYPE_NB-1, E, "list_type" },
  399. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
  400. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
  401. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
  402. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
  403. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  404. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
  405. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  406. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  407. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  408. { NULL },
  409. };
  410. static const AVClass seg_class = {
  411. .class_name = "segment muxer",
  412. .item_name = av_default_item_name,
  413. .option = options,
  414. .version = LIBAVUTIL_VERSION_INT,
  415. };
  416. AVOutputFormat ff_segment_muxer = {
  417. .name = "segment",
  418. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  419. .priv_data_size = sizeof(SegmentContext),
  420. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
  421. .write_header = seg_write_header,
  422. .write_packet = seg_write_packet,
  423. .write_trailer = seg_write_trailer,
  424. .priv_class = &seg_class,
  425. };
  426. static const AVClass sseg_class = {
  427. .class_name = "stream_segment muxer",
  428. .item_name = av_default_item_name,
  429. .option = options,
  430. .version = LIBAVUTIL_VERSION_INT,
  431. };
  432. AVOutputFormat ff_stream_segment_muxer = {
  433. .name = "stream_segment,ssegment",
  434. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  435. .priv_data_size = sizeof(SegmentContext),
  436. .flags = AVFMT_NOFILE,
  437. .write_header = seg_write_header,
  438. .write_packet = seg_write_packet,
  439. .write_trailer = seg_write_trailer,
  440. .priv_class = &sseg_class,
  441. };