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.

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