2 * Copyright (c) 2011, Luca Barbato
4 * This file is part of Libav.
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.
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.
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
22 * @file generic segmenter
23 * M3U8 specification can be find here:
24 * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming-08.txt}
32 #include "libavutil/avassert.h"
33 #include "libavutil/log.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/mathematics.h"
40 LIST_TYPE_UNDEFINED = -1,
44 LIST_TYPE_EXT, ///< deprecated
49 #define SEGMENT_LIST_FLAG_CACHE 1
50 #define SEGMENT_LIST_FLAG_LIVE 2
53 const AVClass *class; /**< Class for private options. */
54 int segment_idx; ///< index of the segment file to write, starting from 0
55 int segment_idx_wrap; ///< number after which the index wraps
56 int segment_count; ///< number of segment files already written
57 AVOutputFormat *oformat;
59 char *format; ///< format to use for output segment files
60 char *list; ///< filename for the segment list file
61 int list_count; ///< list counter
62 int list_flags; ///< flags affecting list generation
63 int list_size; ///< number of entries for the segment list file
64 double list_max_segment_time; ///< max segment time in the current list
65 ListType list_type; ///< set the list type
66 AVIOContext *list_pb; ///< list file put-byte context
67 char *time_str; ///< segment duration specification string
68 int64_t time; ///< segment duration
69 char *times_str; ///< segment times specification string
70 int64_t *times; ///< list of segment interval specification
71 int nb_times; ///< number of elments in the times array
72 char *time_delta_str; ///< approximation value duration used for the segment times
74 int individual_header_trailer; /**< Set by a private option. */
76 double start_time, end_time;
79 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
81 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
95 static int segment_mux_init(AVFormatContext *s)
97 SegmentContext *seg = s->priv_data;
101 seg->avf = oc = avformat_alloc_context();
103 return AVERROR(ENOMEM);
105 oc->oformat = seg->oformat;
106 oc->interrupt_callback = s->interrupt_callback;
108 for (i = 0; i < s->nb_streams; i++) {
110 if (!(st = avformat_new_stream(oc, NULL)))
111 return AVERROR(ENOMEM);
112 avcodec_copy_context(st->codec, s->streams[i]->codec);
113 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
119 static int segment_start(AVFormatContext *s, int write_header)
121 SegmentContext *c = s->priv_data;
122 AVFormatContext *oc = c->avf;
126 avformat_free_context(oc);
128 if ((err = segment_mux_init(s)) < 0)
133 if (c->segment_idx_wrap)
134 c->segment_idx %= c->segment_idx_wrap;
136 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
137 s->filename, c->segment_idx++) < 0) {
138 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
139 return AVERROR(EINVAL);
143 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
144 &s->interrupt_callback, NULL)) < 0)
147 if (oc->oformat->priv_class && oc->priv_data)
148 av_opt_set(oc->priv_data, "resend_headers", "1", 0);
151 if ((err = avformat_write_header(oc, NULL)) < 0)
158 static int segment_list_open(AVFormatContext *s)
160 SegmentContext *seg = s->priv_data;
163 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
164 &s->interrupt_callback, NULL);
167 seg->list_max_segment_time = 0;
169 if (seg->list_type == LIST_TYPE_M3U8) {
170 avio_printf(seg->list_pb, "#EXTM3U\n");
171 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
172 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
173 avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
174 !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
175 if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
176 avio_printf(seg->list_pb,
177 "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
183 static void segment_list_close(AVFormatContext *s)
185 SegmentContext *seg = s->priv_data;
187 if (seg->list_type == LIST_TYPE_M3U8) {
188 if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
189 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
190 (int)ceil(seg->list_max_segment_time));
191 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
195 avio_close(seg->list_pb);
198 static int segment_end(AVFormatContext *s, int write_trailer)
200 SegmentContext *seg = s->priv_data;
201 AVFormatContext *oc = seg->avf;
204 av_write_frame(oc, NULL); /* Flush any buffered data */
206 ret = av_write_trailer(oc);
209 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
213 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
214 segment_list_close(s);
215 if ((ret = segment_list_open(s)) < 0)
219 if (seg->list_type == LIST_TYPE_FLAT) {
220 avio_printf(seg->list_pb, "%s\n", oc->filename);
221 } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
222 print_csv_escaped_str(seg->list_pb, oc->filename);
223 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
224 } else if (seg->list_type == LIST_TYPE_M3U8) {
225 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
226 seg->end_time - seg->start_time, oc->filename);
228 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
229 avio_flush(seg->list_pb);
238 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
239 const char *times_str)
243 char *times_str1 = av_strdup(times_str);
244 char *saveptr = NULL;
247 return AVERROR(ENOMEM);
249 #define FAIL(err) ret = err; goto end
252 for (p = times_str1; *p; p++)
256 *times = av_malloc(sizeof(**times) * *nb_times);
258 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
259 FAIL(AVERROR(ENOMEM));
263 for (i = 0; i < *nb_times; i++) {
265 char *tstr = av_strtok(p, ",", &saveptr);
269 ret = av_parse_time(&t, tstr, 1);
271 av_log(log_ctx, AV_LOG_ERROR,
272 "Invalid time duration specification in %s\n", p);
273 FAIL(AVERROR(EINVAL));
277 /* check on monotonicity */
278 if (i && (*times)[i-1] > (*times)[i]) {
279 av_log(log_ctx, AV_LOG_ERROR,
280 "Specified time %f is greater than the following time %f\n",
281 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
282 FAIL(AVERROR(EINVAL));
291 static int seg_write_header(AVFormatContext *s)
293 SegmentContext *seg = s->priv_data;
294 AVFormatContext *oc = NULL;
297 seg->segment_count = 0;
299 if (seg->time_str && seg->times_str) {
300 av_log(s, AV_LOG_ERROR,
301 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
302 return AVERROR(EINVAL);
305 if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
306 av_log(s, AV_LOG_ERROR,
307 "segment_flags +live and segment_times options are mutually exclusive:"
308 "specify -segment_time if you want a live-friendly list\n");
309 return AVERROR(EINVAL);
312 if (seg->times_str) {
313 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
316 /* set default value if not specified */
318 seg->time_str = av_strdup("2");
319 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
320 av_log(s, AV_LOG_ERROR,
321 "Invalid time duration specification '%s' for segment_time option\n",
327 if (seg->time_delta_str) {
328 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
329 av_log(s, AV_LOG_ERROR,
330 "Invalid time duration specification '%s' for delta option\n",
331 seg->time_delta_str);
337 if (seg->list_type == LIST_TYPE_UNDEFINED) {
338 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
339 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
340 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
341 else seg->list_type = LIST_TYPE_FLAT;
343 if ((ret = segment_list_open(s)) < 0)
346 if (seg->list_type == LIST_TYPE_EXT)
347 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
349 for (i = 0; i < s->nb_streams; i++)
351 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
353 if (seg->has_video > 1)
354 av_log(s, AV_LOG_WARNING,
355 "More than a single video stream present, "
356 "expect issues decoding it.\n");
358 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
361 ret = AVERROR_MUXER_NOT_FOUND;
364 if (seg->oformat->flags & AVFMT_NOFILE) {
365 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
367 ret = AVERROR(EINVAL);
371 if ((ret = segment_mux_init(s)) < 0)
375 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
376 s->filename, seg->segment_idx++) < 0) {
377 ret = AVERROR(EINVAL);
380 seg->segment_count++;
382 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
383 &s->interrupt_callback, NULL)) < 0)
386 if ((ret = avformat_write_header(oc, NULL)) < 0) {
394 segment_list_close(s);
396 avformat_free_context(seg->avf);
401 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
403 SegmentContext *seg = s->priv_data;
404 AVFormatContext *oc = seg->avf;
405 AVStream *st = s->streams[pkt->stream_index];
410 end_pts = seg->segment_count <= seg->nb_times ?
411 seg->times[seg->segment_count-1] : INT64_MAX;
413 end_pts = seg->time * seg->segment_count;
416 /* if the segment has video, start a new segment *only* with a key video frame */
417 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
418 av_compare_ts(pkt->pts, st->time_base,
419 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
420 pkt->flags & AV_PKT_FLAG_KEY) {
422 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
423 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
425 ret = segment_end(s, seg->individual_header_trailer);
428 ret = segment_start(s, seg->individual_header_trailer);
435 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
436 } else if (pkt->pts != AV_NOPTS_VALUE) {
437 seg->end_time = FFMAX(seg->end_time,
438 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
441 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
446 avio_close(seg->list_pb);
447 avformat_free_context(oc);
453 static int seg_write_trailer(struct AVFormatContext *s)
455 SegmentContext *seg = s->priv_data;
456 AVFormatContext *oc = seg->avf;
457 int ret = segment_end(s, 1);
459 segment_list_close(s);
462 av_freep(&seg->times);
464 avformat_free_context(oc);
468 #define OFFSET(x) offsetof(SegmentContext, x)
469 #define E AV_OPT_FLAG_ENCODING_PARAM
470 static const AVOption options[] = {
471 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
472 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
474 { "segment_list_flags","set flags affecting segment list generation", OFFSET(list_flags), AV_OPT_TYPE_FLAGS, {.i64 = SEGMENT_LIST_FLAG_CACHE }, 0, UINT_MAX, E, "list_flags"},
475 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
476 { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, "list_flags"},
478 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
479 { "segment_list_type", "set the segment list type", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_TYPE_UNDEFINED}, -1, LIST_TYPE_NB-1, E, "list_type" },
480 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
481 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
482 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
483 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
484 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
485 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
486 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
487 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
488 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
492 static const AVClass seg_class = {
493 .class_name = "segment muxer",
494 .item_name = av_default_item_name,
496 .version = LIBAVUTIL_VERSION_INT,
499 AVOutputFormat ff_segment_muxer = {
501 .long_name = NULL_IF_CONFIG_SMALL("segment"),
502 .priv_data_size = sizeof(SegmentContext),
503 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
504 .write_header = seg_write_header,
505 .write_packet = seg_write_packet,
506 .write_trailer = seg_write_trailer,
507 .priv_class = &seg_class,
510 static const AVClass sseg_class = {
511 .class_name = "stream_segment muxer",
512 .item_name = av_default_item_name,
514 .version = LIBAVUTIL_VERSION_INT,
517 AVOutputFormat ff_stream_segment_muxer = {
518 .name = "stream_segment,ssegment",
519 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
520 .priv_data_size = sizeof(SegmentContext),
521 .flags = AVFMT_NOFILE,
522 .write_header = seg_write_header,
523 .write_packet = seg_write_packet,
524 .write_trailer = seg_write_trailer,
525 .priv_class = &sseg_class,