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,
47 #define LIST_TYPE_EXT LIST_TYPE_CSV
50 const AVClass *class; /**< Class for private options. */
51 int segment_idx; ///< index of the segment file to write, starting from 0
52 int segment_idx_wrap; ///< number after which the index wraps
53 int segment_count; ///< number of segment files already written
55 char *format; ///< format to use for output segment files
56 char *list; ///< filename for the segment list file
57 int list_count; ///< list counter
58 int list_size; ///< number of entries for the segment list file
59 double list_max_segment_time; ///< max segment time in the current list
60 ListType list_type; ///< set the list type
61 AVIOContext *list_pb; ///< list file put-byte context
62 char *time_str; ///< segment duration specification string
63 int64_t time; ///< segment duration
64 char *times_str; ///< segment times specification string
65 int64_t *times; ///< list of segment interval specification
66 int nb_times; ///< number of elments in the times array
67 char *time_delta_str; ///< approximation value duration used for the segment times
70 double start_time, end_time;
73 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
78 /* check if input needs quoting */
79 for (p = str; *p; p++)
80 if (strchr("\",\n\r", *p)) {
88 for (p = str; *p; p++) {
97 static int segment_start(AVFormatContext *s)
99 SegmentContext *seg = s->priv_data;
100 AVFormatContext *oc = seg->avf;
103 if (seg->segment_idx_wrap)
104 seg->segment_idx %= seg->segment_idx_wrap;
106 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
107 s->filename, seg->segment_idx++) < 0) {
108 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
109 return AVERROR(EINVAL);
111 seg->segment_count++;
113 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
114 &s->interrupt_callback, NULL)) < 0)
117 if (!oc->priv_data && oc->oformat->priv_data_size > 0) {
118 oc->priv_data = av_mallocz(oc->oformat->priv_data_size);
119 if (!oc->priv_data) {
121 return AVERROR(ENOMEM);
123 if (oc->oformat->priv_class) {
124 *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
125 av_opt_set_defaults(oc->priv_data);
129 if ((err = oc->oformat->write_header(oc)) < 0) {
136 av_log(oc, AV_LOG_ERROR, "Failure occurred when starting segment '%s'\n",
139 av_freep(&oc->priv_data);
144 static int segment_list_open(AVFormatContext *s)
146 SegmentContext *seg = s->priv_data;
149 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
150 &s->interrupt_callback, NULL);
153 seg->list_max_segment_time = 0;
155 if (seg->list_type == LIST_TYPE_M3U8) {
156 avio_printf(seg->list_pb, "#EXTM3U\n");
157 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
158 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
164 static void segment_list_close(AVFormatContext *s)
166 SegmentContext *seg = s->priv_data;
168 if (seg->list_type == LIST_TYPE_M3U8) {
169 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
170 (int)ceil(seg->list_max_segment_time));
171 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
175 avio_close(seg->list_pb);
178 static int segment_end(AVFormatContext *s)
180 SegmentContext *seg = s->priv_data;
181 AVFormatContext *oc = seg->avf;
184 if (oc->oformat->write_trailer)
185 ret = oc->oformat->write_trailer(oc);
188 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
192 if (seg->list_size && !(seg->segment_count % seg->list_size)) {
193 segment_list_close(s);
194 if ((ret = segment_list_open(s)) < 0)
198 if (seg->list_type == LIST_TYPE_FLAT) {
199 avio_printf(seg->list_pb, "%s\n", oc->filename);
200 } else if (seg->list_type == LIST_TYPE_EXT) {
201 print_csv_escaped_str(seg->list_pb, oc->filename);
202 avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
203 } else if (seg->list_type == LIST_TYPE_M3U8) {
204 avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
205 seg->end_time - seg->start_time, oc->filename);
207 seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
208 avio_flush(seg->list_pb);
213 if (oc->oformat->priv_class)
214 av_opt_free(oc->priv_data);
215 av_freep(&oc->priv_data);
220 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
221 const char *times_str)
225 char *times_str1 = av_strdup(times_str);
226 char *saveptr = NULL;
229 return AVERROR(ENOMEM);
231 #define FAIL(err) ret = err; goto end
234 for (p = times_str1; *p; p++)
238 *times = av_malloc(sizeof(**times) * *nb_times);
240 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
241 FAIL(AVERROR(ENOMEM));
245 for (i = 0; i < *nb_times; i++) {
247 char *tstr = av_strtok(p, ",", &saveptr);
251 ret = av_parse_time(&t, tstr, 1);
253 av_log(log_ctx, AV_LOG_ERROR,
254 "Invalid time duration specification in %s\n", p);
255 FAIL(AVERROR(EINVAL));
259 /* check on monotonicity */
260 if (i && (*times)[i-1] > (*times)[i]) {
261 av_log(log_ctx, AV_LOG_ERROR,
262 "Specified time %f is greater than the following time %f\n",
263 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
264 FAIL(AVERROR(EINVAL));
273 static int seg_write_header(AVFormatContext *s)
275 SegmentContext *seg = s->priv_data;
279 seg->segment_count = 0;
281 if (seg->time_str && seg->times_str) {
282 av_log(s, AV_LOG_ERROR,
283 "segment_time and segment_times options are mutually exclusive, select just one of them\n");
284 return AVERROR(EINVAL);
287 if (seg->times_str) {
288 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
291 /* set default value if not specified */
293 seg->time_str = av_strdup("2");
294 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
295 av_log(s, AV_LOG_ERROR,
296 "Invalid time duration specification '%s' for segment_time option\n",
302 if (seg->time_delta_str) {
303 if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
304 av_log(s, AV_LOG_ERROR,
305 "Invalid time duration specification '%s' for delta option\n",
306 seg->time_delta_str);
311 oc = avformat_alloc_context();
314 return AVERROR(ENOMEM);
317 if (seg->list_type == LIST_TYPE_UNDEFINED) {
318 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
319 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
320 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
321 else seg->list_type = LIST_TYPE_FLAT;
323 if ((ret = segment_list_open(s)) < 0)
326 if (seg->list_type == LIST_TYPE_EXT)
327 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
329 for (i = 0; i< s->nb_streams; i++)
331 (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
333 if (seg->has_video > 1)
334 av_log(s, AV_LOG_WARNING,
335 "More than a single video stream present, "
336 "expect issues decoding it.\n");
338 oc->oformat = av_guess_format(seg->format, s->filename, NULL);
341 ret = AVERROR_MUXER_NOT_FOUND;
344 if (oc->oformat->flags & AVFMT_NOFILE) {
345 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
347 ret = AVERROR(EINVAL);
353 oc->streams = s->streams;
354 oc->nb_streams = s->nb_streams;
356 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
357 s->filename, seg->segment_idx++) < 0) {
358 ret = AVERROR(EINVAL);
361 seg->segment_count++;
363 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
364 &s->interrupt_callback, NULL)) < 0)
367 if ((ret = avformat_write_header(oc, NULL)) < 0) {
377 avformat_free_context(oc);
380 segment_list_close(s);
385 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
387 SegmentContext *seg = s->priv_data;
388 AVFormatContext *oc = seg->avf;
389 AVStream *st = oc->streams[pkt->stream_index];
394 end_pts = seg->segment_count <= seg->nb_times ?
395 seg->times[seg->segment_count-1] : INT64_MAX;
397 end_pts = seg->time * seg->segment_count;
400 /* if the segment has video, start a new segment *only* with a key video frame */
401 if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
402 av_compare_ts(pkt->pts, st->time_base,
403 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
404 pkt->flags & AV_PKT_FLAG_KEY) {
406 av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
407 pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
409 if ((ret = segment_end(s)) < 0 || (ret = segment_start(s)) < 0)
411 seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
412 } else if (pkt->pts != AV_NOPTS_VALUE) {
413 seg->end_time = FFMAX(seg->end_time,
414 (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
417 ret = oc->oformat->write_packet(oc, pkt);
424 avio_close(seg->list_pb);
425 avformat_free_context(oc);
431 static int seg_write_trailer(struct AVFormatContext *s)
433 SegmentContext *seg = s->priv_data;
434 AVFormatContext *oc = seg->avf;
435 int ret = segment_end(s);
437 segment_list_close(s);
440 av_freep(&seg->times);
444 avformat_free_context(oc);
448 #define OFFSET(x) offsetof(SegmentContext, x)
449 #define E AV_OPT_FLAG_ENCODING_PARAM
450 static const AVOption options[] = {
451 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
452 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
453 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
454 { "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" },
455 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
456 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, 0, "list_type" },
457 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, 0, "list_type" },
458 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
459 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
460 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
461 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
462 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
466 static const AVClass seg_class = {
467 .class_name = "segment muxer",
468 .item_name = av_default_item_name,
470 .version = LIBAVUTIL_VERSION_INT,
473 AVOutputFormat ff_segment_muxer = {
475 .long_name = NULL_IF_CONFIG_SMALL("segment"),
476 .priv_data_size = sizeof(SegmentContext),
477 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
478 .write_header = seg_write_header,
479 .write_packet = seg_write_packet,
480 .write_trailer = seg_write_trailer,
481 .priv_class = &seg_class,
484 static const AVClass sseg_class = {
485 .class_name = "stream_segment muxer",
486 .item_name = av_default_item_name,
488 .version = LIBAVUTIL_VERSION_INT,
491 AVOutputFormat ff_stream_segment_muxer = {
492 .name = "stream_segment,ssegment",
493 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
494 .priv_data_size = sizeof(SegmentContext),
495 .flags = AVFMT_NOFILE,
496 .write_header = seg_write_header,
497 .write_packet = seg_write_packet,
498 .write_trailer = seg_write_trailer,
499 .priv_class = &sseg_class,