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.

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