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.

526 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. if (write_trailer)
  172. ret = av_write_trailer(oc);
  173. if (ret < 0)
  174. av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
  175. oc->filename);
  176. if (seg->list) {
  177. if (seg->list_size && !(seg->segment_count % seg->list_size)) {
  178. segment_list_close(s);
  179. if ((ret = segment_list_open(s)) < 0)
  180. goto end;
  181. }
  182. if (seg->list_type == LIST_TYPE_FLAT) {
  183. avio_printf(seg->list_pb, "%s\n", oc->filename);
  184. } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
  185. print_csv_escaped_str(seg->list_pb, oc->filename);
  186. avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
  187. } else if (seg->list_type == LIST_TYPE_M3U8) {
  188. avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
  189. seg->end_time - seg->start_time, oc->filename);
  190. }
  191. seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
  192. avio_flush(seg->list_pb);
  193. }
  194. end:
  195. avio_close(oc->pb);
  196. return ret;
  197. }
  198. static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
  199. const char *times_str)
  200. {
  201. char *p;
  202. int i, ret = 0;
  203. char *times_str1 = av_strdup(times_str);
  204. char *saveptr = NULL;
  205. if (!times_str1)
  206. return AVERROR(ENOMEM);
  207. #define FAIL(err) ret = err; goto end
  208. *nb_times = 1;
  209. for (p = times_str1; *p; p++)
  210. if (*p == ',')
  211. (*nb_times)++;
  212. *times = av_malloc(sizeof(**times) * *nb_times);
  213. if (!*times) {
  214. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
  215. FAIL(AVERROR(ENOMEM));
  216. }
  217. p = times_str1;
  218. for (i = 0; i < *nb_times; i++) {
  219. int64_t t;
  220. char *tstr = av_strtok(p, ",", &saveptr);
  221. av_assert0(tstr);
  222. p = NULL;
  223. ret = av_parse_time(&t, tstr, 1);
  224. if (ret < 0) {
  225. av_log(log_ctx, AV_LOG_ERROR,
  226. "Invalid time duration specification in %s\n", p);
  227. FAIL(AVERROR(EINVAL));
  228. }
  229. (*times)[i] = t;
  230. /* check on monotonicity */
  231. if (i && (*times)[i-1] > (*times)[i]) {
  232. av_log(log_ctx, AV_LOG_ERROR,
  233. "Specified time %f is greater than the following time %f\n",
  234. (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
  235. FAIL(AVERROR(EINVAL));
  236. }
  237. }
  238. end:
  239. av_free(times_str1);
  240. return ret;
  241. }
  242. static int seg_write_header(AVFormatContext *s)
  243. {
  244. SegmentContext *seg = s->priv_data;
  245. AVFormatContext *oc = NULL;
  246. int ret, i;
  247. seg->segment_count = 0;
  248. if (seg->time_str && seg->times_str) {
  249. av_log(s, AV_LOG_ERROR,
  250. "segment_time and segment_times options are mutually exclusive, select just one of them\n");
  251. return AVERROR(EINVAL);
  252. }
  253. if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
  254. av_log(s, AV_LOG_ERROR,
  255. "segment_flags +live and segment_times options are mutually exclusive:"
  256. "specify -segment_time if you want a live-friendly list\n");
  257. return AVERROR(EINVAL);
  258. }
  259. if (seg->times_str) {
  260. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  261. return ret;
  262. } else {
  263. /* set default value if not specified */
  264. if (!seg->time_str)
  265. seg->time_str = av_strdup("2");
  266. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  267. av_log(s, AV_LOG_ERROR,
  268. "Invalid time duration specification '%s' for segment_time option\n",
  269. seg->time_str);
  270. return ret;
  271. }
  272. }
  273. if (seg->time_delta_str) {
  274. if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
  275. av_log(s, AV_LOG_ERROR,
  276. "Invalid time duration specification '%s' for delta option\n",
  277. seg->time_delta_str);
  278. return ret;
  279. }
  280. }
  281. if (seg->list) {
  282. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  283. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  284. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  285. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  286. else seg->list_type = LIST_TYPE_FLAT;
  287. }
  288. if ((ret = segment_list_open(s)) < 0)
  289. goto fail;
  290. }
  291. if (seg->list_type == LIST_TYPE_EXT)
  292. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  293. for (i = 0; i < s->nb_streams; i++)
  294. seg->has_video +=
  295. (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
  296. if (seg->has_video > 1)
  297. av_log(s, AV_LOG_WARNING,
  298. "More than a single video stream present, "
  299. "expect issues decoding it.\n");
  300. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  301. if (!seg->oformat) {
  302. ret = AVERROR_MUXER_NOT_FOUND;
  303. goto fail;
  304. }
  305. if (seg->oformat->flags & AVFMT_NOFILE) {
  306. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  307. oc->oformat->name);
  308. ret = AVERROR(EINVAL);
  309. goto fail;
  310. }
  311. if ((ret = segment_mux_init(s)) < 0)
  312. goto fail;
  313. oc = seg->avf;
  314. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  315. s->filename, seg->segment_idx++) < 0) {
  316. ret = AVERROR(EINVAL);
  317. goto fail;
  318. }
  319. seg->segment_count++;
  320. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  321. &s->interrupt_callback, NULL)) < 0)
  322. goto fail;
  323. if ((ret = avformat_write_header(oc, NULL)) < 0) {
  324. avio_close(oc->pb);
  325. goto fail;
  326. }
  327. fail:
  328. if (ret) {
  329. if (seg->list)
  330. segment_list_close(s);
  331. if (seg->avf)
  332. avformat_free_context(seg->avf);
  333. }
  334. return ret;
  335. }
  336. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  337. {
  338. SegmentContext *seg = s->priv_data;
  339. AVFormatContext *oc = seg->avf;
  340. AVStream *st = s->streams[pkt->stream_index];
  341. int64_t end_pts;
  342. int ret;
  343. if (seg->times) {
  344. end_pts = seg->segment_count <= seg->nb_times ?
  345. seg->times[seg->segment_count-1] : INT64_MAX;
  346. } else {
  347. end_pts = seg->time * seg->segment_count;
  348. }
  349. /* if the segment has video, start a new segment *only* with a key video frame */
  350. if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
  351. av_compare_ts(pkt->pts, st->time_base,
  352. end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
  353. pkt->flags & AV_PKT_FLAG_KEY) {
  354. av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
  355. pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
  356. ret = segment_end(s, seg->individual_header_trailer);
  357. if (!ret)
  358. ret = segment_start(s, seg->individual_header_trailer);
  359. if (ret)
  360. goto fail;
  361. oc = seg->avf;
  362. seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
  363. } else if (pkt->pts != AV_NOPTS_VALUE) {
  364. seg->end_time = FFMAX(seg->end_time,
  365. (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  366. }
  367. ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
  368. fail:
  369. if (ret < 0) {
  370. if (seg->list)
  371. avio_close(seg->list_pb);
  372. avformat_free_context(oc);
  373. }
  374. return ret;
  375. }
  376. static int seg_write_trailer(struct AVFormatContext *s)
  377. {
  378. SegmentContext *seg = s->priv_data;
  379. AVFormatContext *oc = seg->avf;
  380. int ret = segment_end(s, 1);
  381. if (seg->list)
  382. segment_list_close(s);
  383. av_opt_free(seg);
  384. av_freep(&seg->times);
  385. avformat_free_context(oc);
  386. return ret;
  387. }
  388. #define OFFSET(x) offsetof(SegmentContext, x)
  389. #define E AV_OPT_FLAG_ENCODING_PARAM
  390. static const AVOption options[] = {
  391. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  392. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  393. { "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"},
  394. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  395. { "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"},
  396. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  397. { "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" },
  398. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
  399. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
  400. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
  401. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
  402. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  403. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
  404. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  405. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  406. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  407. { NULL },
  408. };
  409. static const AVClass seg_class = {
  410. .class_name = "segment muxer",
  411. .item_name = av_default_item_name,
  412. .option = options,
  413. .version = LIBAVUTIL_VERSION_INT,
  414. };
  415. AVOutputFormat ff_segment_muxer = {
  416. .name = "segment",
  417. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  418. .priv_data_size = sizeof(SegmentContext),
  419. .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
  420. .write_header = seg_write_header,
  421. .write_packet = seg_write_packet,
  422. .write_trailer = seg_write_trailer,
  423. .priv_class = &seg_class,
  424. };
  425. static const AVClass sseg_class = {
  426. .class_name = "stream_segment muxer",
  427. .item_name = av_default_item_name,
  428. .option = options,
  429. .version = LIBAVUTIL_VERSION_INT,
  430. };
  431. AVOutputFormat ff_stream_segment_muxer = {
  432. .name = "stream_segment,ssegment",
  433. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  434. .priv_data_size = sizeof(SegmentContext),
  435. .flags = AVFMT_NOFILE,
  436. .write_header = seg_write_header,
  437. .write_packet = seg_write_packet,
  438. .write_trailer = seg_write_trailer,
  439. .priv_class = &sseg_class,
  440. };