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.

467 lines
15KB

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