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/log.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/timestamp.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 int reset_timestamps; ///< reset timestamps at the begin of each segment
78 double start_time, end_time;
79 int64_t start_pts, start_dts;
82 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
84 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
98 static int segment_mux_init(AVFormatContext *s)
100 SegmentContext *seg = s->priv_data;
104 seg->avf = oc = avformat_alloc_context();
106 return AVERROR(ENOMEM);
108 oc->oformat = seg->oformat;
109 oc->interrupt_callback = s->interrupt_callback;
111 for (i = 0; i < s->nb_streams; i++) {
113 AVCodecContext *icodec, *ocodec;
115 if (!(st = avformat_new_stream(oc, NULL)))
116 return AVERROR(ENOMEM);
117 icodec = s->streams[i]->codec;
119 avcodec_copy_context(ocodec, icodec);
120 if (!oc->oformat->codec_tag ||
121 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
122 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
123 ocodec->codec_tag = icodec->codec_tag;
125 ocodec->codec_tag = 0;
127 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
133 static int set_segment_filename(AVFormatContext *s)
135 SegmentContext *seg = s->priv_data;
136 AVFormatContext *oc = seg->avf;
138 if (seg->segment_idx_wrap)
139 seg->segment_idx %= seg->segment_idx_wrap;
140 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
141 s->filename, seg->segment_idx) < 0) {
142 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
143 return AVERROR(EINVAL);
148 static int segment_start(AVFormatContext *s, int write_header)
150 SegmentContext *seg = s->priv_data;
151 AVFormatContext *oc = seg->avf;
155 avformat_free_context(oc);
157 if ((err = segment_mux_init(s)) < 0)
163 if ((err = set_segment_filename(s)) < 0)
165 seg->segment_count++;
167 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
168 &s->interrupt_callback, NULL)) < 0)
171 if (oc->oformat->priv_class && oc->priv_data)
172 av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
175 if ((err = avformat_write_header(oc, NULL)) < 0)
182 static int segment_list_open(AVFormatContext *s)
184 SegmentContext *seg = s->priv_data;
187 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
188 &s->interrupt_callback, NULL);
191 seg->list_max_segment_time = 0;
193 if (seg->list_type == LIST_TYPE_M3U8) {
194 avio_printf(seg->list_pb, "#EXTM3U\n");
195 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
196 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_idx);
197 avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
198 !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
199 if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
200 avio_printf(seg->list_pb,
201 "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
207 static void segment_list_close(AVFormatContext *s)
209 SegmentContext *seg = s->priv_data;
211 if (seg->list_type == LIST_TYPE_M3U8) {
212 if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
213 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
214 (int)ceil(seg->list_max_segment_time));
215 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
218 avio_close(seg->list_pb);
221 static int segment_end(AVFormatContext *s, int write_trailer)
223 SegmentContext *seg = s->priv_data;
224 AVFormatContext *oc = seg->avf;
227 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
229 ret = av_write_trailer(oc);
232 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
236 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
237 segment_list_close(s);
238 if ((ret = segment_list_open(s)) < 0)
242 if (seg->list_type == LIST_TYPE_FLAT) {
243 avio_printf(seg->list_pb, "%s\n", oc->filename);
244 } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
245 print_csv_escaped_str(seg->list_pb, oc->filename);
246 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
247 } else if (seg->list_type == LIST_TYPE_M3U8) {
248 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
249 seg->end_time - seg->start_time, oc->filename);
251 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
252 avio_flush(seg->list_pb);
261 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
262 const char *times_str)
266 char *times_str1 = av_strdup(times_str);
267 char *saveptr = NULL;
270 return AVERROR(ENOMEM);
272 #define FAIL(err) ret = err; goto end
275 for (p = times_str1; *p; p++)
279 *times = av_malloc(sizeof(**times) * *nb_times);
281 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
282 FAIL(AVERROR(ENOMEM));
286 for (i = 0; i < *nb_times; i++) {
288 char *tstr = av_strtok(p, ",", &saveptr);
291 if (!tstr || !tstr[0]) {
292 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
294 FAIL(AVERROR(EINVAL));
297 ret = av_parse_time(&t, tstr, 1);
299 av_log(log_ctx, AV_LOG_ERROR,
300 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
301 FAIL(AVERROR(EINVAL));
305 /* check on monotonicity */
306 if (i && (*times)[i-1] > (*times)[i]) {
307 av_log(log_ctx, AV_LOG_ERROR,
308 "Specified time %f is greater than the following time %f\n",
309 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
310 FAIL(AVERROR(EINVAL));
319 static int open_null_ctx(AVIOContext **ctx)
321 int buf_size = 32768;
322 uint8_t *buf = av_malloc(buf_size);
324 return AVERROR(ENOMEM);
325 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
328 return AVERROR(ENOMEM);
333 static void close_null_ctx(AVIOContext *pb)
339 static int seg_write_header(AVFormatContext *s)
341 SegmentContext *seg = s->priv_data;
342 AVFormatContext *oc = NULL;
345 seg->segment_count = 0;
346 if (!seg->write_header_trailer)
347 seg->individual_header_trailer = 0;
349 if (seg->time_str && seg->times_str) {
350 av_log(s, AV_LOG_ERROR,
351 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
352 return AVERROR(EINVAL);
355 if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
356 av_log(s, AV_LOG_ERROR,
357 "segment_flags +live and segment_times options are mutually exclusive:"
358 "specify -segment_time if you want a live-friendly list\n");
359 return AVERROR(EINVAL);
362 if (seg->times_str) {
363 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
366 /* set default value if not specified */
368 seg->time_str = av_strdup("2");
369 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
370 av_log(s, AV_LOG_ERROR,
371 "Invalid time duration specification '%s' for segment_time option\n",
377 if (seg->time_delta_str) {
378 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
379 av_log(s, AV_LOG_ERROR,
380 "Invalid time duration specification '%s' for delta option\n",
381 seg->time_delta_str);
387 if (seg->list_type == LIST_TYPE_UNDEFINED) {
388 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
389 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
390 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
391 else seg->list_type = LIST_TYPE_FLAT;
393 if ((ret = segment_list_open(s)) < 0)
396 if (seg->list_type == LIST_TYPE_EXT)
397 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
399 for (i = 0; i < s->nb_streams; i++)
401 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
403 if (seg->has_video > 1)
404 av_log(s, AV_LOG_WARNING,
405 "More than a single video stream present, "
406 "expect issues decoding it.\n");
408 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
411 ret = AVERROR_MUXER_NOT_FOUND;
414 if (seg->oformat->flags & AVFMT_NOFILE) {
415 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
417 ret = AVERROR(EINVAL);
421 if ((ret = segment_mux_init(s)) < 0)
425 if ((ret = set_segment_filename(s)) < 0)
427 seg->segment_count++;
429 if (seg->write_header_trailer) {
430 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
431 &s->interrupt_callback, NULL)) < 0)
434 if ((ret = open_null_ctx(&oc->pb)) < 0)
438 if ((ret = avformat_write_header(oc, NULL)) < 0) {
443 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
444 s->avoid_negative_ts = 1;
446 if (!seg->write_header_trailer) {
447 close_null_ctx(oc->pb);
448 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
449 &s->interrupt_callback, NULL)) < 0)
456 segment_list_close(s);
458 avformat_free_context(seg->avf);
463 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
465 SegmentContext *seg = s->priv_data;
466 AVFormatContext *oc = seg->avf;
467 AVStream *st = s->streams[pkt->stream_index];
472 end_pts = seg->segment_count <= seg->nb_times ?
473 seg->times[seg->segment_count-1] : INT64_MAX;
475 end_pts = seg->time * seg->segment_count;
478 /* if the segment has video, start a new segment *only* with a key video frame */
479 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
480 pkt->pts != AV_NOPTS_VALUE &&
481 av_compare_ts(pkt->pts, st->time_base,
482 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
483 pkt->flags & AV_PKT_FLAG_KEY) {
485 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
486 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
488 ret = segment_end(s, seg->individual_header_trailer);
491 ret = segment_start(s, seg->individual_header_trailer);
498 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
499 seg->start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
500 seg->start_dts = pkt->dts != AV_NOPTS_VALUE ?
501 av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q) : seg->start_pts;
502 } else if (pkt->pts != AV_NOPTS_VALUE) {
503 seg->end_time = FFMAX(seg->end_time,
504 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
507 if (seg->reset_timestamps) {
508 av_log(s, AV_LOG_DEBUG, "start_pts:%s pts:%s start_dts:%s dts:%s",
509 av_ts2timestr(seg->start_pts, &AV_TIME_BASE_Q), av_ts2timestr(pkt->pts, &st->time_base),
510 av_ts2timestr(seg->start_dts, &AV_TIME_BASE_Q), av_ts2timestr(pkt->dts, &st->time_base));
512 /* compute new timestamps */
513 if (pkt->pts != AV_NOPTS_VALUE)
514 pkt->pts -= av_rescale_q(seg->start_pts, AV_TIME_BASE_Q, st->time_base);
515 if (pkt->dts != AV_NOPTS_VALUE)
516 pkt->dts -= av_rescale_q(seg->start_dts, AV_TIME_BASE_Q, st->time_base);
518 av_log(s, AV_LOG_DEBUG, " -> pts:%s dts:%s\n",
519 av_ts2timestr(pkt->pts, &st->time_base), av_ts2timestr(pkt->dts, &st->time_base));
522 ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
527 avio_close(seg->list_pb);
528 avformat_free_context(oc);
534 static int seg_write_trailer(struct AVFormatContext *s)
536 SegmentContext *seg = s->priv_data;
537 AVFormatContext *oc = seg->avf;
539 if (!seg->write_header_trailer) {
540 if ((ret = segment_end(s, 0)) < 0)
542 open_null_ctx(&oc->pb);
543 ret = av_write_trailer(oc);
544 close_null_ctx(oc->pb);
546 ret = segment_end(s, 1);
550 segment_list_close(s);
553 av_freep(&seg->times);
555 avformat_free_context(oc);
559 #define OFFSET(x) offsetof(SegmentContext, x)
560 #define E AV_OPT_FLAG_ENCODING_PARAM
561 static const AVOption options[] = {
562 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
563 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
565 { "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"},
566 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
567 { "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"},
569 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
570 { "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" },
571 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
572 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
573 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
574 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
575 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
576 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
577 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
578 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
579 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
580 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
582 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
583 { "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 },
584 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
588 static const AVClass seg_class = {
589 .class_name = "segment muxer",
590 .item_name = av_default_item_name,
592 .version = LIBAVUTIL_VERSION_INT,
595 AVOutputFormat ff_segment_muxer = {
597 .long_name = NULL_IF_CONFIG_SMALL("segment"),
598 .priv_data_size = sizeof(SegmentContext),
599 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
600 .write_header = seg_write_header,
601 .write_packet = seg_write_packet,
602 .write_trailer = seg_write_trailer,
603 .priv_class = &seg_class,
606 static const AVClass sseg_class = {
607 .class_name = "stream_segment muxer",
608 .item_name = av_default_item_name,
610 .version = LIBAVUTIL_VERSION_INT,
613 AVOutputFormat ff_stream_segment_muxer = {
614 .name = "stream_segment,ssegment",
615 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
616 .priv_data_size = sizeof(SegmentContext),
617 .flags = AVFMT_NOFILE,
618 .write_header = seg_write_header,
619 .write_packet = seg_write_packet,
620 .write_trailer = seg_write_trailer,
621 .priv_class = &sseg_class,