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.

577 lines
19KB

  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 write_header_trailer; /**< Set by a private option. */
  68. int has_video;
  69. double start_time, end_time;
  70. } SegmentContext;
  71. static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
  72. {
  73. int needs_quoting = !!str[strcspn(str, "\",\n\r")];
  74. if (needs_quoting)
  75. avio_w8(ctx, '"');
  76. for (; *str; str++) {
  77. if (*str == '"')
  78. avio_w8(ctx, '"');
  79. avio_w8(ctx, *str);
  80. }
  81. if (needs_quoting)
  82. avio_w8(ctx, '"');
  83. }
  84. static int segment_mux_init(AVFormatContext *s)
  85. {
  86. SegmentContext *seg = s->priv_data;
  87. AVFormatContext *oc;
  88. int i;
  89. seg->avf = oc = avformat_alloc_context();
  90. if (!oc)
  91. return AVERROR(ENOMEM);
  92. oc->oformat = seg->oformat;
  93. oc->interrupt_callback = s->interrupt_callback;
  94. for (i = 0; i < s->nb_streams; i++) {
  95. AVStream *st;
  96. if (!(st = avformat_new_stream(oc, NULL)))
  97. return AVERROR(ENOMEM);
  98. avcodec_copy_context(st->codec, s->streams[i]->codec);
  99. st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
  100. }
  101. return 0;
  102. }
  103. static int segment_start(AVFormatContext *s, int write_header)
  104. {
  105. SegmentContext *c = s->priv_data;
  106. AVFormatContext *oc = c->avf;
  107. int err = 0;
  108. if (write_header) {
  109. avformat_free_context(oc);
  110. c->avf = NULL;
  111. if ((err = segment_mux_init(s)) < 0)
  112. return err;
  113. oc = c->avf;
  114. }
  115. if (c->segment_idx_wrap)
  116. c->segment_idx %= c->segment_idx_wrap;
  117. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  118. s->filename, c->segment_idx++) < 0) {
  119. av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
  120. return AVERROR(EINVAL);
  121. }
  122. c->segment_count++;
  123. if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  124. &s->interrupt_callback, NULL)) < 0)
  125. return err;
  126. if (oc->oformat->priv_class && oc->priv_data)
  127. av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
  128. if (write_header) {
  129. if ((err = avformat_write_header(oc, NULL)) < 0)
  130. return err;
  131. }
  132. return 0;
  133. }
  134. static int segment_list_open(AVFormatContext *s)
  135. {
  136. SegmentContext *seg = s->priv_data;
  137. int ret;
  138. ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
  139. &s->interrupt_callback, NULL);
  140. if (ret < 0)
  141. return ret;
  142. seg->list_max_segment_time = 0;
  143. if (seg->list_type == LIST_TYPE_M3U8) {
  144. avio_printf(seg->list_pb, "#EXTM3U\n");
  145. avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
  146. avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
  147. avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
  148. !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
  149. if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
  150. avio_printf(seg->list_pb,
  151. "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
  152. }
  153. return ret;
  154. }
  155. static void segment_list_close(AVFormatContext *s)
  156. {
  157. SegmentContext *seg = s->priv_data;
  158. if (seg->list_type == LIST_TYPE_M3U8) {
  159. if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
  160. avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
  161. (int)ceil(seg->list_max_segment_time));
  162. avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
  163. }
  164. seg->list_count++;
  165. avio_close(seg->list_pb);
  166. }
  167. static int segment_end(AVFormatContext *s, int write_trailer)
  168. {
  169. SegmentContext *seg = s->priv_data;
  170. AVFormatContext *oc = seg->avf;
  171. int ret = 0;
  172. av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
  173. if (write_trailer)
  174. ret = av_write_trailer(oc);
  175. if (ret < 0)
  176. av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
  177. oc->filename);
  178. if (seg->list) {
  179. if (seg->list_size && !(seg->segment_count % seg->list_size)) {
  180. segment_list_close(s);
  181. if ((ret = segment_list_open(s)) < 0)
  182. goto end;
  183. }
  184. if (seg->list_type == LIST_TYPE_FLAT) {
  185. avio_printf(seg->list_pb, "%s\n", oc->filename);
  186. } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
  187. print_csv_escaped_str(seg->list_pb, oc->filename);
  188. avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
  189. } else if (seg->list_type == LIST_TYPE_M3U8) {
  190. avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
  191. seg->end_time - seg->start_time, oc->filename);
  192. }
  193. seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
  194. avio_flush(seg->list_pb);
  195. }
  196. end:
  197. avio_close(oc->pb);
  198. return ret;
  199. }
  200. static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
  201. const char *times_str)
  202. {
  203. char *p;
  204. int i, ret = 0;
  205. char *times_str1 = av_strdup(times_str);
  206. char *saveptr = NULL;
  207. if (!times_str1)
  208. return AVERROR(ENOMEM);
  209. #define FAIL(err) ret = err; goto end
  210. *nb_times = 1;
  211. for (p = times_str1; *p; p++)
  212. if (*p == ',')
  213. (*nb_times)++;
  214. *times = av_malloc(sizeof(**times) * *nb_times);
  215. if (!*times) {
  216. av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
  217. FAIL(AVERROR(ENOMEM));
  218. }
  219. p = times_str1;
  220. for (i = 0; i < *nb_times; i++) {
  221. int64_t t;
  222. char *tstr = av_strtok(p, ",", &saveptr);
  223. av_assert0(tstr);
  224. p = NULL;
  225. ret = av_parse_time(&t, tstr, 1);
  226. if (ret < 0) {
  227. av_log(log_ctx, AV_LOG_ERROR,
  228. "Invalid time duration specification in %s\n", p);
  229. FAIL(AVERROR(EINVAL));
  230. }
  231. (*times)[i] = t;
  232. /* check on monotonicity */
  233. if (i && (*times)[i-1] > (*times)[i]) {
  234. av_log(log_ctx, AV_LOG_ERROR,
  235. "Specified time %f is greater than the following time %f\n",
  236. (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
  237. FAIL(AVERROR(EINVAL));
  238. }
  239. }
  240. end:
  241. av_free(times_str1);
  242. return ret;
  243. }
  244. static int open_null_ctx(AVIOContext **ctx)
  245. {
  246. int buf_size = 32768;
  247. uint8_t *buf = av_malloc(buf_size);
  248. if (!buf)
  249. return AVERROR(ENOMEM);
  250. *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
  251. if (!*ctx) {
  252. av_free(buf);
  253. return AVERROR(ENOMEM);
  254. }
  255. return 0;
  256. }
  257. static void close_null_ctx(AVIOContext *pb)
  258. {
  259. av_free(pb->buffer);
  260. av_free(pb);
  261. }
  262. static int seg_write_header(AVFormatContext *s)
  263. {
  264. SegmentContext *seg = s->priv_data;
  265. AVFormatContext *oc = NULL;
  266. int ret, i;
  267. seg->segment_count = 0;
  268. if (!seg->write_header_trailer)
  269. seg->individual_header_trailer = 0;
  270. if (seg->time_str && seg->times_str) {
  271. av_log(s, AV_LOG_ERROR,
  272. "segment_time and segment_times options are mutually exclusive, select just one of them\n");
  273. return AVERROR(EINVAL);
  274. }
  275. if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
  276. av_log(s, AV_LOG_ERROR,
  277. "segment_flags +live and segment_times options are mutually exclusive:"
  278. "specify -segment_time if you want a live-friendly list\n");
  279. return AVERROR(EINVAL);
  280. }
  281. if (seg->times_str) {
  282. if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
  283. return ret;
  284. } else {
  285. /* set default value if not specified */
  286. if (!seg->time_str)
  287. seg->time_str = av_strdup("2");
  288. if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
  289. av_log(s, AV_LOG_ERROR,
  290. "Invalid time duration specification '%s' for segment_time option\n",
  291. seg->time_str);
  292. return ret;
  293. }
  294. }
  295. if (seg->time_delta_str) {
  296. if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
  297. av_log(s, AV_LOG_ERROR,
  298. "Invalid time duration specification '%s' for delta option\n",
  299. seg->time_delta_str);
  300. return ret;
  301. }
  302. }
  303. if (seg->list) {
  304. if (seg->list_type == LIST_TYPE_UNDEFINED) {
  305. if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
  306. else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
  307. else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
  308. else seg->list_type = LIST_TYPE_FLAT;
  309. }
  310. if ((ret = segment_list_open(s)) < 0)
  311. goto fail;
  312. }
  313. if (seg->list_type == LIST_TYPE_EXT)
  314. av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
  315. for (i = 0; i < s->nb_streams; i++)
  316. seg->has_video +=
  317. (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
  318. if (seg->has_video > 1)
  319. av_log(s, AV_LOG_WARNING,
  320. "More than a single video stream present, "
  321. "expect issues decoding it.\n");
  322. seg->oformat = av_guess_format(seg->format, s->filename, NULL);
  323. if (!seg->oformat) {
  324. ret = AVERROR_MUXER_NOT_FOUND;
  325. goto fail;
  326. }
  327. if (seg->oformat->flags & AVFMT_NOFILE) {
  328. av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
  329. seg->oformat->name);
  330. ret = AVERROR(EINVAL);
  331. goto fail;
  332. }
  333. if ((ret = segment_mux_init(s)) < 0)
  334. goto fail;
  335. oc = seg->avf;
  336. if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
  337. s->filename, seg->segment_idx++) < 0) {
  338. ret = AVERROR(EINVAL);
  339. goto fail;
  340. }
  341. seg->segment_count++;
  342. if (seg->write_header_trailer) {
  343. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  344. &s->interrupt_callback, NULL)) < 0)
  345. goto fail;
  346. } else {
  347. if ((ret = open_null_ctx(&oc->pb)) < 0)
  348. goto fail;
  349. }
  350. if ((ret = avformat_write_header(oc, NULL)) < 0) {
  351. avio_close(oc->pb);
  352. goto fail;
  353. }
  354. if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
  355. s->avoid_negative_ts = 1;
  356. if (!seg->write_header_trailer) {
  357. close_null_ctx(oc->pb);
  358. if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
  359. &s->interrupt_callback, NULL)) < 0)
  360. goto fail;
  361. }
  362. fail:
  363. if (ret) {
  364. if (seg->list)
  365. segment_list_close(s);
  366. if (seg->avf)
  367. avformat_free_context(seg->avf);
  368. }
  369. return ret;
  370. }
  371. static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
  372. {
  373. SegmentContext *seg = s->priv_data;
  374. AVFormatContext *oc = seg->avf;
  375. AVStream *st = s->streams[pkt->stream_index];
  376. int64_t end_pts;
  377. int ret;
  378. if (seg->times) {
  379. end_pts = seg->segment_count <= seg->nb_times ?
  380. seg->times[seg->segment_count-1] : INT64_MAX;
  381. } else {
  382. end_pts = seg->time * seg->segment_count;
  383. }
  384. /* if the segment has video, start a new segment *only* with a key video frame */
  385. if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
  386. av_compare_ts(pkt->pts, st->time_base,
  387. end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
  388. pkt->flags & AV_PKT_FLAG_KEY) {
  389. av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
  390. pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
  391. ret = segment_end(s, seg->individual_header_trailer);
  392. if (!ret)
  393. ret = segment_start(s, seg->individual_header_trailer);
  394. if (ret)
  395. goto fail;
  396. oc = seg->avf;
  397. seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
  398. } else if (pkt->pts != AV_NOPTS_VALUE) {
  399. seg->end_time = FFMAX(seg->end_time,
  400. (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
  401. }
  402. ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
  403. fail:
  404. if (ret < 0) {
  405. if (seg->list)
  406. avio_close(seg->list_pb);
  407. avformat_free_context(oc);
  408. }
  409. return ret;
  410. }
  411. static int seg_write_trailer(struct AVFormatContext *s)
  412. {
  413. SegmentContext *seg = s->priv_data;
  414. AVFormatContext *oc = seg->avf;
  415. int ret;
  416. if (!seg->write_header_trailer) {
  417. if ((ret = segment_end(s, 0)) < 0)
  418. goto fail;
  419. open_null_ctx(&oc->pb);
  420. ret = av_write_trailer(oc);
  421. close_null_ctx(oc->pb);
  422. } else {
  423. ret = segment_end(s, 1);
  424. }
  425. fail:
  426. if (seg->list)
  427. segment_list_close(s);
  428. av_opt_free(seg);
  429. av_freep(&seg->times);
  430. avformat_free_context(oc);
  431. return ret;
  432. }
  433. #define OFFSET(x) offsetof(SegmentContext, x)
  434. #define E AV_OPT_FLAG_ENCODING_PARAM
  435. static const AVOption options[] = {
  436. { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  437. { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  438. { "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"},
  439. { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
  440. { "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"},
  441. { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  442. { "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" },
  443. { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
  444. { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
  445. { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
  446. { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
  447. { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
  448. { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  449. { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
  450. { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
  451. { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  452. { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  453. { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  454. { NULL },
  455. };
  456. static const AVClass seg_class = {
  457. .class_name = "segment muxer",
  458. .item_name = av_default_item_name,
  459. .option = options,
  460. .version = LIBAVUTIL_VERSION_INT,
  461. };
  462. AVOutputFormat ff_segment_muxer = {
  463. .name = "segment",
  464. .long_name = NULL_IF_CONFIG_SMALL("segment"),
  465. .priv_data_size = sizeof(SegmentContext),
  466. .flags = AVFMT_NOFILE,
  467. .write_header = seg_write_header,
  468. .write_packet = seg_write_packet,
  469. .write_trailer = seg_write_trailer,
  470. .priv_class = &seg_class,
  471. };
  472. static const AVClass sseg_class = {
  473. .class_name = "stream_segment muxer",
  474. .item_name = av_default_item_name,
  475. .option = options,
  476. .version = LIBAVUTIL_VERSION_INT,
  477. };
  478. AVOutputFormat ff_stream_segment_muxer = {
  479. .name = "stream_segment,ssegment",
  480. .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
  481. .priv_data_size = sizeof(SegmentContext),
  482. .flags = AVFMT_NOFILE,
  483. .write_header = seg_write_header,
  484. .write_packet = seg_write_packet,
  485. .write_trailer = seg_write_trailer,
  486. .priv_class = &sseg_class,
  487. };