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.

490 lines
17KB

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