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_flags; ///< flags affecting list generation
62 int list_size; ///< number of entries for the segment list file
63 double list_max_segment_time; ///< max segment time in the current list
64 ListType list_type; ///< set the list type
65 AVIOContext *list_pb; ///< list file put-byte context
66 char *time_str; ///< segment duration specification string
67 int64_t time; ///< segment duration
68 char *times_str; ///< segment times specification string
69 int64_t *times; ///< list of segment interval specification
70 int nb_times; ///< number of elments in the times array
71 char *time_delta_str; ///< approximation value duration used for the segment times
73 int individual_header_trailer; /**< Set by a private option. */
74 int write_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 AVCodecContext *icodec, *ocodec;
112 if (!(st = avformat_new_stream(oc, NULL)))
113 return AVERROR(ENOMEM);
114 icodec = s->streams[i]->codec;
116 avcodec_copy_context(ocodec, icodec);
117 if (!oc->oformat->codec_tag ||
118 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
119 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
120 ocodec->codec_tag = icodec->codec_tag;
122 ocodec->codec_tag = 0;
124 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
130 static int segment_start(AVFormatContext *s, int write_header)
132 SegmentContext *seg = s->priv_data;
133 AVFormatContext *oc = seg->avf;
137 avformat_free_context(oc);
139 if ((err = segment_mux_init(s)) < 0)
145 if (seg->segment_idx_wrap)
146 seg->segment_idx %= seg->segment_idx_wrap;
148 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
149 s->filename, seg->segment_idx) < 0) {
150 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
151 return AVERROR(EINVAL);
153 seg->segment_count++;
155 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
156 &s->interrupt_callback, NULL)) < 0)
159 if (oc->oformat->priv_class && oc->priv_data)
160 av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
163 if ((err = avformat_write_header(oc, NULL)) < 0)
170 static int segment_list_open(AVFormatContext *s)
172 SegmentContext *seg = s->priv_data;
175 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
176 &s->interrupt_callback, NULL);
179 seg->list_max_segment_time = 0;
181 if (seg->list_type == LIST_TYPE_M3U8) {
182 avio_printf(seg->list_pb, "#EXTM3U\n");
183 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
184 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_idx);
185 avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
186 !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
187 if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
188 avio_printf(seg->list_pb,
189 "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
195 static void segment_list_close(AVFormatContext *s)
197 SegmentContext *seg = s->priv_data;
199 if (seg->list_type == LIST_TYPE_M3U8) {
200 if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
201 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
202 (int)ceil(seg->list_max_segment_time));
203 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
206 avio_close(seg->list_pb);
209 static int segment_end(AVFormatContext *s, int write_trailer)
211 SegmentContext *seg = s->priv_data;
212 AVFormatContext *oc = seg->avf;
215 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
217 ret = av_write_trailer(oc);
220 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
224 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
225 segment_list_close(s);
226 if ((ret = segment_list_open(s)) < 0)
230 if (seg->list_type == LIST_TYPE_FLAT) {
231 avio_printf(seg->list_pb, "%s\n", oc->filename);
232 } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
233 print_csv_escaped_str(seg->list_pb, oc->filename);
234 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
235 } else if (seg->list_type == LIST_TYPE_M3U8) {
236 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
237 seg->end_time - seg->start_time, oc->filename);
239 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
240 avio_flush(seg->list_pb);
249 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
250 const char *times_str)
254 char *times_str1 = av_strdup(times_str);
255 char *saveptr = NULL;
258 return AVERROR(ENOMEM);
260 #define FAIL(err) ret = err; goto end
263 for (p = times_str1; *p; p++)
267 *times = av_malloc(sizeof(**times) * *nb_times);
269 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
270 FAIL(AVERROR(ENOMEM));
274 for (i = 0; i < *nb_times; i++) {
276 char *tstr = av_strtok(p, ",", &saveptr);
280 ret = av_parse_time(&t, tstr, 1);
282 av_log(log_ctx, AV_LOG_ERROR,
283 "Invalid time duration specification in %s\n", p);
284 FAIL(AVERROR(EINVAL));
288 /* check on monotonicity */
289 if (i && (*times)[i-1] > (*times)[i]) {
290 av_log(log_ctx, AV_LOG_ERROR,
291 "Specified time %f is greater than the following time %f\n",
292 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
293 FAIL(AVERROR(EINVAL));
302 static int open_null_ctx(AVIOContext **ctx)
304 int buf_size = 32768;
305 uint8_t *buf = av_malloc(buf_size);
307 return AVERROR(ENOMEM);
308 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
311 return AVERROR(ENOMEM);
316 static void close_null_ctx(AVIOContext *pb)
322 static int seg_write_header(AVFormatContext *s)
324 SegmentContext *seg = s->priv_data;
325 AVFormatContext *oc = NULL;
328 seg->segment_count = 0;
329 if (!seg->write_header_trailer)
330 seg->individual_header_trailer = 0;
332 if (seg->time_str && seg->times_str) {
333 av_log(s, AV_LOG_ERROR,
334 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
335 return AVERROR(EINVAL);
338 if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
339 av_log(s, AV_LOG_ERROR,
340 "segment_flags +live and segment_times options are mutually exclusive:"
341 "specify -segment_time if you want a live-friendly list\n");
342 return AVERROR(EINVAL);
345 if (seg->times_str) {
346 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
349 /* set default value if not specified */
351 seg->time_str = av_strdup("2");
352 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
353 av_log(s, AV_LOG_ERROR,
354 "Invalid time duration specification '%s' for segment_time option\n",
360 if (seg->time_delta_str) {
361 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
362 av_log(s, AV_LOG_ERROR,
363 "Invalid time duration specification '%s' for delta option\n",
364 seg->time_delta_str);
370 if (seg->list_type == LIST_TYPE_UNDEFINED) {
371 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
372 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
373 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
374 else seg->list_type = LIST_TYPE_FLAT;
376 if ((ret = segment_list_open(s)) < 0)
379 if (seg->list_type == LIST_TYPE_EXT)
380 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
382 for (i = 0; i < s->nb_streams; i++)
384 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
386 if (seg->has_video > 1)
387 av_log(s, AV_LOG_WARNING,
388 "More than a single video stream present, "
389 "expect issues decoding it.\n");
391 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
394 ret = AVERROR_MUXER_NOT_FOUND;
397 if (seg->oformat->flags & AVFMT_NOFILE) {
398 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
400 ret = AVERROR(EINVAL);
404 if ((ret = segment_mux_init(s)) < 0)
408 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
409 s->filename, seg->segment_idx) < 0) {
410 ret = AVERROR(EINVAL);
413 seg->segment_count++;
415 if (seg->write_header_trailer) {
416 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
417 &s->interrupt_callback, NULL)) < 0)
420 if ((ret = open_null_ctx(&oc->pb)) < 0)
424 if ((ret = avformat_write_header(oc, NULL)) < 0) {
429 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
430 s->avoid_negative_ts = 1;
432 if (!seg->write_header_trailer) {
433 close_null_ctx(oc->pb);
434 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
435 &s->interrupt_callback, NULL)) < 0)
442 segment_list_close(s);
444 avformat_free_context(seg->avf);
449 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
451 SegmentContext *seg = s->priv_data;
452 AVFormatContext *oc = seg->avf;
453 AVStream *st = s->streams[pkt->stream_index];
458 end_pts = seg->segment_count <= seg->nb_times ?
459 seg->times[seg->segment_count-1] : INT64_MAX;
461 end_pts = seg->time * seg->segment_count;
464 /* if the segment has video, start a new segment *only* with a key video frame */
465 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
466 av_compare_ts(pkt->pts, st->time_base,
467 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
468 pkt->flags & AV_PKT_FLAG_KEY) {
470 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
471 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
473 ret = segment_end(s, seg->individual_header_trailer);
476 ret = segment_start(s, seg->individual_header_trailer);
483 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
484 } else if (pkt->pts != AV_NOPTS_VALUE) {
485 seg->end_time = FFMAX(seg->end_time,
486 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
489 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
494 avio_close(seg->list_pb);
495 avformat_free_context(oc);
501 static int seg_write_trailer(struct AVFormatContext *s)
503 SegmentContext *seg = s->priv_data;
504 AVFormatContext *oc = seg->avf;
506 if (!seg->write_header_trailer) {
507 if ((ret = segment_end(s, 0)) < 0)
509 open_null_ctx(&oc->pb);
510 ret = av_write_trailer(oc);
511 close_null_ctx(oc->pb);
513 ret = segment_end(s, 1);
517 segment_list_close(s);
520 av_freep(&seg->times);
522 avformat_free_context(oc);
526 #define OFFSET(x) offsetof(SegmentContext, x)
527 #define E AV_OPT_FLAG_ENCODING_PARAM
528 static const AVOption options[] = {
529 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
530 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
532 { "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"},
533 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
534 { "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"},
536 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
537 { "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" },
538 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
539 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
540 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
541 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
542 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
543 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
544 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
545 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
546 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
547 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
548 { "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 },
552 static const AVClass seg_class = {
553 .class_name = "segment muxer",
554 .item_name = av_default_item_name,
556 .version = LIBAVUTIL_VERSION_INT,
559 AVOutputFormat ff_segment_muxer = {
561 .long_name = NULL_IF_CONFIG_SMALL("segment"),
562 .priv_data_size = sizeof(SegmentContext),
563 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
564 .write_header = seg_write_header,
565 .write_packet = seg_write_packet,
566 .write_trailer = seg_write_trailer,
567 .priv_class = &seg_class,
570 static const AVClass sseg_class = {
571 .class_name = "stream_segment muxer",
572 .item_name = av_default_item_name,
574 .version = LIBAVUTIL_VERSION_INT,
577 AVOutputFormat ff_stream_segment_muxer = {
578 .name = "stream_segment,ssegment",
579 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
580 .priv_data_size = sizeof(SegmentContext),
581 .flags = AVFMT_NOFILE,
582 .write_header = seg_write_header,
583 .write_packet = seg_write_packet,
584 .write_trailer = seg_write_trailer,
585 .priv_class = &sseg_class,