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.

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