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.

501 lines
16KB

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