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
58 char *format; ///< format to use for output segment files
59 char *list; ///< filename for the segment list file
60 int list_count; ///< list counter
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
74 double start_time, end_time;
77 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
79 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
93 static int segment_start(AVFormatContext *s)
95 SegmentContext *seg = s->priv_data;
96 AVFormatContext *oc = seg->avf;
99 if (seg->segment_idx_wrap)
100 seg->segment_idx %= seg->segment_idx_wrap;
102 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
103 s->filename, seg->segment_idx++) < 0) {
104 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
105 return AVERROR(EINVAL);
107 seg->segment_count++;
109 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
110 &s->interrupt_callback, NULL)) < 0)
113 if (!oc->priv_data && oc->oformat->priv_data_size > 0) {
114 oc->priv_data = av_mallocz(oc->oformat->priv_data_size);
115 if (!oc->priv_data) {
117 return AVERROR(ENOMEM);
119 if (oc->oformat->priv_class) {
120 *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
121 av_opt_set_defaults(oc->priv_data);
125 if ((err = oc->oformat->write_header(oc)) < 0) {
132 av_log(oc, AV_LOG_ERROR, "Failure occurred when starting segment '%s'\n",
135 av_freep(&oc->priv_data);
140 static int segment_list_open(AVFormatContext *s)
142 SegmentContext *seg = s->priv_data;
145 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
146 &s->interrupt_callback, NULL);
149 seg->list_max_segment_time = 0;
151 if (seg->list_type == LIST_TYPE_M3U8) {
152 avio_printf(seg->list_pb, "#EXTM3U\n");
153 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
154 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
155 avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
156 !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
157 if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
158 avio_printf(seg->list_pb,
159 "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
165 static void segment_list_close(AVFormatContext *s)
167 SegmentContext *seg = s->priv_data;
169 if (seg->list_type == LIST_TYPE_M3U8) {
170 if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
171 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
172 (int)ceil(seg->list_max_segment_time));
173 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
177 avio_close(seg->list_pb);
180 static int segment_end(AVFormatContext *s)
182 SegmentContext *seg = s->priv_data;
183 AVFormatContext *oc = seg->avf;
186 if (oc->oformat->write_trailer)
187 ret = oc->oformat->write_trailer(oc);
190 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
194 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
195 segment_list_close(s);
196 if ((ret = segment_list_open(s)) < 0)
200 if (seg->list_type == LIST_TYPE_FLAT) {
201 avio_printf(seg->list_pb, "%s\n", oc->filename);
202 } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
203 print_csv_escaped_str(seg->list_pb, oc->filename);
204 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
205 } else if (seg->list_type == LIST_TYPE_M3U8) {
206 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
207 seg->end_time - seg->start_time, oc->filename);
209 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
210 avio_flush(seg->list_pb);
215 if (oc->oformat->priv_class)
216 av_opt_free(oc->priv_data);
217 av_freep(&oc->priv_data);
222 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
223 const char *times_str)
227 char *times_str1 = av_strdup(times_str);
228 char *saveptr = NULL;
231 return AVERROR(ENOMEM);
233 #define FAIL(err) ret = err; goto end
236 for (p = times_str1; *p; p++)
240 *times = av_malloc(sizeof(**times) * *nb_times);
242 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
243 FAIL(AVERROR(ENOMEM));
247 for (i = 0; i < *nb_times; i++) {
249 char *tstr = av_strtok(p, ",", &saveptr);
253 ret = av_parse_time(&t, tstr, 1);
255 av_log(log_ctx, AV_LOG_ERROR,
256 "Invalid time duration specification in %s\n", p);
257 FAIL(AVERROR(EINVAL));
261 /* check on monotonicity */
262 if (i && (*times)[i-1] > (*times)[i]) {
263 av_log(log_ctx, AV_LOG_ERROR,
264 "Specified time %f is greater than the following time %f\n",
265 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
266 FAIL(AVERROR(EINVAL));
275 static int seg_write_header(AVFormatContext *s)
277 SegmentContext *seg = s->priv_data;
281 seg->segment_count = 0;
283 if (seg->time_str && seg->times_str) {
284 av_log(s, AV_LOG_ERROR,
285 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
286 return AVERROR(EINVAL);
289 if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
290 av_log(s, AV_LOG_ERROR,
291 "segment_flags +live and segment_times options are mutually exclusive:"
292 "specify -segment_time if you want a live-friendly list\n");
293 return AVERROR(EINVAL);
296 if (seg->times_str) {
297 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
300 /* set default value if not specified */
302 seg->time_str = av_strdup("2");
303 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
304 av_log(s, AV_LOG_ERROR,
305 "Invalid time duration specification '%s' for segment_time option\n",
311 if (seg->time_delta_str) {
312 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
313 av_log(s, AV_LOG_ERROR,
314 "Invalid time duration specification '%s' for delta option\n",
315 seg->time_delta_str);
320 oc = avformat_alloc_context();
323 return AVERROR(ENOMEM);
326 if (seg->list_type == LIST_TYPE_UNDEFINED) {
327 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
328 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
329 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
330 else seg->list_type = LIST_TYPE_FLAT;
332 if ((ret = segment_list_open(s)) < 0)
335 if (seg->list_type == LIST_TYPE_EXT)
336 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
338 for (i = 0; i< s->nb_streams; i++)
340 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
342 if (seg->has_video > 1)
343 av_log(s, AV_LOG_WARNING,
344 "More than a single video stream present, "
345 "expect issues decoding it.\n");
347 oc->oformat = av_guess_format(seg->format, s->filename, NULL);
350 ret = AVERROR_MUXER_NOT_FOUND;
353 if (oc->oformat->flags & AVFMT_NOFILE) {
354 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
356 ret = AVERROR(EINVAL);
362 oc->streams = s->streams;
363 oc->nb_streams = s->nb_streams;
365 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
366 s->filename, seg->segment_idx++) < 0) {
367 ret = AVERROR(EINVAL);
370 seg->segment_count++;
372 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
373 &s->interrupt_callback, NULL)) < 0)
376 if ((ret = avformat_write_header(oc, NULL)) < 0) {
386 avformat_free_context(oc);
389 segment_list_close(s);
394 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
396 SegmentContext *seg = s->priv_data;
397 AVFormatContext *oc = seg->avf;
398 AVStream *st = oc->streams[pkt->stream_index];
403 end_pts = seg->segment_count <= seg->nb_times ?
404 seg->times[seg->segment_count-1] : INT64_MAX;
406 end_pts = seg->time * seg->segment_count;
409 /* if the segment has video, start a new segment *only* with a key video frame */
410 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
411 av_compare_ts(pkt->pts, st->time_base,
412 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
413 pkt->flags & AV_PKT_FLAG_KEY) {
415 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
416 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
418 if ((ret = segment_end(s)) < 0 || (ret = segment_start(s)) < 0)
420 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
421 } else if (pkt->pts != AV_NOPTS_VALUE) {
422 seg->end_time = FFMAX(seg->end_time,
423 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
426 ret = oc->oformat->write_packet(oc, pkt);
433 avio_close(seg->list_pb);
434 avformat_free_context(oc);
440 static int seg_write_trailer(struct AVFormatContext *s)
442 SegmentContext *seg = s->priv_data;
443 AVFormatContext *oc = seg->avf;
444 int ret = segment_end(s);
446 segment_list_close(s);
449 av_freep(&seg->times);
453 avformat_free_context(oc);
457 #define OFFSET(x) offsetof(SegmentContext, x)
458 #define E AV_OPT_FLAG_ENCODING_PARAM
459 static const AVOption options[] = {
460 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
461 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
463 { "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"},
464 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
465 { "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"},
467 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
468 { "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" },
469 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
470 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
471 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
472 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
473 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
474 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
475 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
476 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
480 static const AVClass seg_class = {
481 .class_name = "segment muxer",
482 .item_name = av_default_item_name,
484 .version = LIBAVUTIL_VERSION_INT,
487 AVOutputFormat ff_segment_muxer = {
489 .long_name = NULL_IF_CONFIG_SMALL("segment"),
490 .priv_data_size = sizeof(SegmentContext),
491 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
492 .write_header = seg_write_header,
493 .write_packet = seg_write_packet,
494 .write_trailer = seg_write_trailer,
495 .priv_class = &seg_class,
498 static const AVClass sseg_class = {
499 .class_name = "stream_segment muxer",
500 .item_name = av_default_item_name,
502 .version = LIBAVUTIL_VERSION_INT,
505 AVOutputFormat ff_stream_segment_muxer = {
506 .name = "stream_segment,ssegment",
507 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
508 .priv_data_size = sizeof(SegmentContext),
509 .flags = AVFMT_NOFILE,
510 .write_header = seg_write_header,
511 .write_packet = seg_write_packet,
512 .write_trailer = seg_write_trailer,
513 .priv_class = &sseg_class,