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.

421 lines
13KB

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