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.

432 lines
14KB

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