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. */
75 int write_header_trailer; /**< Set by a private option. */
77 double start_time, end_time;
80 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
82 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
96 static int segment_mux_init(AVFormatContext *s)
98 SegmentContext *seg = s->priv_data;
102 seg->avf = oc = avformat_alloc_context();
104 return AVERROR(ENOMEM);
106 oc->oformat = seg->oformat;
107 oc->interrupt_callback = s->interrupt_callback;
109 for (i = 0; i < s->nb_streams; i++) {
111 if (!(st = avformat_new_stream(oc, NULL)))
112 return AVERROR(ENOMEM);
113 avcodec_copy_context(st->codec, s->streams[i]->codec);
114 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
120 static int segment_start(AVFormatContext *s, int write_header)
122 SegmentContext *c = s->priv_data;
123 AVFormatContext *oc = c->avf;
127 avformat_free_context(oc);
129 if ((err = segment_mux_init(s)) < 0)
134 if (c->segment_idx_wrap)
135 c->segment_idx %= c->segment_idx_wrap;
137 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
138 s->filename, c->segment_idx++) < 0) {
139 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
140 return AVERROR(EINVAL);
144 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
145 &s->interrupt_callback, NULL)) < 0)
148 if (oc->oformat->priv_class && oc->priv_data)
149 av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
152 if ((err = avformat_write_header(oc, NULL)) < 0)
159 static int segment_list_open(AVFormatContext *s)
161 SegmentContext *seg = s->priv_data;
164 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
165 &s->interrupt_callback, NULL);
168 seg->list_max_segment_time = 0;
170 if (seg->list_type == LIST_TYPE_M3U8) {
171 avio_printf(seg->list_pb, "#EXTM3U\n");
172 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
173 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
174 avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
175 !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
176 if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
177 avio_printf(seg->list_pb,
178 "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
184 static void segment_list_close(AVFormatContext *s)
186 SegmentContext *seg = s->priv_data;
188 if (seg->list_type == LIST_TYPE_M3U8) {
189 if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
190 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
191 (int)ceil(seg->list_max_segment_time));
192 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
196 avio_close(seg->list_pb);
199 static int segment_end(AVFormatContext *s, int write_trailer)
201 SegmentContext *seg = s->priv_data;
202 AVFormatContext *oc = seg->avf;
205 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
207 ret = av_write_trailer(oc);
210 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
214 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
215 segment_list_close(s);
216 if ((ret = segment_list_open(s)) < 0)
220 if (seg->list_type == LIST_TYPE_FLAT) {
221 avio_printf(seg->list_pb, "%s\n", oc->filename);
222 } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
223 print_csv_escaped_str(seg->list_pb, oc->filename);
224 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
225 } else if (seg->list_type == LIST_TYPE_M3U8) {
226 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
227 seg->end_time - seg->start_time, oc->filename);
229 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
230 avio_flush(seg->list_pb);
239 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
240 const char *times_str)
244 char *times_str1 = av_strdup(times_str);
245 char *saveptr = NULL;
248 return AVERROR(ENOMEM);
250 #define FAIL(err) ret = err; goto end
253 for (p = times_str1; *p; p++)
257 *times = av_malloc(sizeof(**times) * *nb_times);
259 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
260 FAIL(AVERROR(ENOMEM));
264 for (i = 0; i < *nb_times; i++) {
266 char *tstr = av_strtok(p, ",", &saveptr);
270 ret = av_parse_time(&t, tstr, 1);
272 av_log(log_ctx, AV_LOG_ERROR,
273 "Invalid time duration specification in %s\n", p);
274 FAIL(AVERROR(EINVAL));
278 /* check on monotonicity */
279 if (i && (*times)[i-1] > (*times)[i]) {
280 av_log(log_ctx, AV_LOG_ERROR,
281 "Specified time %f is greater than the following time %f\n",
282 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
283 FAIL(AVERROR(EINVAL));
292 static int open_null_ctx(AVIOContext **ctx)
294 int buf_size = 32768;
295 uint8_t *buf = av_malloc(buf_size);
297 return AVERROR(ENOMEM);
298 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
301 return AVERROR(ENOMEM);
306 static void close_null_ctx(AVIOContext *pb)
312 static int seg_write_header(AVFormatContext *s)
314 SegmentContext *seg = s->priv_data;
315 AVFormatContext *oc = NULL;
318 seg->segment_count = 0;
319 if (!seg->write_header_trailer)
320 seg->individual_header_trailer = 0;
322 if (seg->time_str && seg->times_str) {
323 av_log(s, AV_LOG_ERROR,
324 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
325 return AVERROR(EINVAL);
328 if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
329 av_log(s, AV_LOG_ERROR,
330 "segment_flags +live and segment_times options are mutually exclusive:"
331 "specify -segment_time if you want a live-friendly list\n");
332 return AVERROR(EINVAL);
335 if (seg->times_str) {
336 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
339 /* set default value if not specified */
341 seg->time_str = av_strdup("2");
342 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
343 av_log(s, AV_LOG_ERROR,
344 "Invalid time duration specification '%s' for segment_time option\n",
350 if (seg->time_delta_str) {
351 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
352 av_log(s, AV_LOG_ERROR,
353 "Invalid time duration specification '%s' for delta option\n",
354 seg->time_delta_str);
360 if (seg->list_type == LIST_TYPE_UNDEFINED) {
361 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
362 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
363 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
364 else seg->list_type = LIST_TYPE_FLAT;
366 if ((ret = segment_list_open(s)) < 0)
369 if (seg->list_type == LIST_TYPE_EXT)
370 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
372 for (i = 0; i < s->nb_streams; i++)
374 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
376 if (seg->has_video > 1)
377 av_log(s, AV_LOG_WARNING,
378 "More than a single video stream present, "
379 "expect issues decoding it.\n");
381 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
384 ret = AVERROR_MUXER_NOT_FOUND;
387 if (seg->oformat->flags & AVFMT_NOFILE) {
388 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
390 ret = AVERROR(EINVAL);
394 if ((ret = segment_mux_init(s)) < 0)
398 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
399 s->filename, seg->segment_idx++) < 0) {
400 ret = AVERROR(EINVAL);
403 seg->segment_count++;
405 if (seg->write_header_trailer) {
406 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
407 &s->interrupt_callback, NULL)) < 0)
410 if ((ret = open_null_ctx(&oc->pb)) < 0)
414 if ((ret = avformat_write_header(oc, NULL)) < 0) {
419 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
420 s->avoid_negative_ts = 1;
422 if (!seg->write_header_trailer) {
423 close_null_ctx(oc->pb);
424 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
425 &s->interrupt_callback, NULL)) < 0)
432 segment_list_close(s);
434 avformat_free_context(seg->avf);
439 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
441 SegmentContext *seg = s->priv_data;
442 AVFormatContext *oc = seg->avf;
443 AVStream *st = s->streams[pkt->stream_index];
448 end_pts = seg->segment_count <= seg->nb_times ?
449 seg->times[seg->segment_count-1] : INT64_MAX;
451 end_pts = seg->time * seg->segment_count;
454 /* if the segment has video, start a new segment *only* with a key video frame */
455 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
456 av_compare_ts(pkt->pts, st->time_base,
457 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
458 pkt->flags & AV_PKT_FLAG_KEY) {
460 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
461 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
463 ret = segment_end(s, seg->individual_header_trailer);
466 ret = segment_start(s, seg->individual_header_trailer);
473 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
474 } else if (pkt->pts != AV_NOPTS_VALUE) {
475 seg->end_time = FFMAX(seg->end_time,
476 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
479 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
484 avio_close(seg->list_pb);
485 avformat_free_context(oc);
491 static int seg_write_trailer(struct AVFormatContext *s)
493 SegmentContext *seg = s->priv_data;
494 AVFormatContext *oc = seg->avf;
496 if (!seg->write_header_trailer) {
497 if ((ret = segment_end(s, 0)) < 0)
499 open_null_ctx(&oc->pb);
500 ret = av_write_trailer(oc);
501 close_null_ctx(oc->pb);
503 ret = segment_end(s, 1);
507 segment_list_close(s);
510 av_freep(&seg->times);
512 avformat_free_context(oc);
516 #define OFFSET(x) offsetof(SegmentContext, x)
517 #define E AV_OPT_FLAG_ENCODING_PARAM
518 static const AVOption options[] = {
519 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
520 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
522 { "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"},
523 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
524 { "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"},
526 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
527 { "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" },
528 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
529 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
530 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
531 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
532 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
533 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
534 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
535 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
536 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
537 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
538 { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
542 static const AVClass seg_class = {
543 .class_name = "segment muxer",
544 .item_name = av_default_item_name,
546 .version = LIBAVUTIL_VERSION_INT,
549 AVOutputFormat ff_segment_muxer = {
551 .long_name = NULL_IF_CONFIG_SMALL("segment"),
552 .priv_data_size = sizeof(SegmentContext),
553 .flags = AVFMT_NOFILE,
554 .write_header = seg_write_header,
555 .write_packet = seg_write_packet,
556 .write_trailer = seg_write_trailer,
557 .priv_class = &seg_class,
560 static const AVClass sseg_class = {
561 .class_name = "stream_segment muxer",
562 .item_name = av_default_item_name,
564 .version = LIBAVUTIL_VERSION_INT,
567 AVOutputFormat ff_stream_segment_muxer = {
568 .name = "stream_segment,ssegment",
569 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
570 .priv_data_size = sizeof(SegmentContext),
571 .flags = AVFMT_NOFILE,
572 .write_header = seg_write_header,
573 .write_packet = seg_write_packet,
574 .write_trailer = seg_write_trailer,
575 .priv_class = &sseg_class,