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.

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