]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
lavf/segment: Use distinct IDs for list type ext & csv
[ffmpeg] / libavformat / segment.c
1 /*
2  * Copyright (c) 2011, Luca Barbato
3  *
4  * This file is part of Libav.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /**
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}
25  */
26
27 #include <float.h>
28
29 #include "avformat.h"
30 #include "internal.h"
31
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"
38
39 typedef enum {
40     LIST_TYPE_UNDEFINED = -1,
41     LIST_TYPE_FLAT = 0,
42     LIST_TYPE_CSV,
43     LIST_TYPE_M3U8,
44     LIST_TYPE_EXT, ///< deprecated
45     LIST_TYPE_NB,
46 } ListType;
47
48
49 #define SEGMENT_LIST_FLAG_CACHE 1
50 #define SEGMENT_LIST_FLAG_LIVE  2
51
52 typedef struct {
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     AVFormatContext *avf;
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
72     int64_t time_delta;
73     int has_video;
74     double start_time, end_time;
75 } SegmentContext;
76
77 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
78 {
79     int needs_quoting = !!str[strcspn(str, "\",\n\r")];
80
81     if (needs_quoting)
82         avio_w8(ctx, '"');
83
84     for (; *str; str++) {
85         if (*str == '"')
86             avio_w8(ctx, '"');
87         avio_w8(ctx, *str);
88     }
89     if (needs_quoting)
90         avio_w8(ctx, '"');
91 }
92
93 static int segment_start(AVFormatContext *s)
94 {
95     SegmentContext *seg = s->priv_data;
96     AVFormatContext *oc = seg->avf;
97     int err = 0;
98
99     if (seg->segment_idx_wrap)
100         seg->segment_idx %= seg->segment_idx_wrap;
101
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);
106     }
107     seg->segment_count++;
108
109     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
110                           &s->interrupt_callback, NULL)) < 0)
111         return err;
112
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) {
116             avio_close(oc->pb);
117             return AVERROR(ENOMEM);
118         }
119         if (oc->oformat->priv_class) {
120             *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
121             av_opt_set_defaults(oc->priv_data);
122         }
123     }
124
125     if ((err = oc->oformat->write_header(oc)) < 0) {
126         goto fail;
127     }
128
129     return 0;
130
131 fail:
132     av_log(oc, AV_LOG_ERROR, "Failure occurred when starting segment '%s'\n",
133            oc->filename);
134     avio_close(oc->pb);
135     av_freep(&oc->priv_data);
136
137     return err;
138 }
139
140 static int segment_list_open(AVFormatContext *s)
141 {
142     SegmentContext *seg = s->priv_data;
143     int ret;
144
145     ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
146                      &s->interrupt_callback, NULL);
147     if (ret < 0)
148         return ret;
149     seg->list_max_segment_time = 0;
150
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);
160     }
161
162     return ret;
163 }
164
165 static void segment_list_close(AVFormatContext *s)
166 {
167     SegmentContext *seg = s->priv_data;
168
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");
174     }
175     seg->list_count++;
176
177     avio_close(seg->list_pb);
178 }
179
180 static int segment_end(AVFormatContext *s)
181 {
182     SegmentContext *seg = s->priv_data;
183     AVFormatContext *oc = seg->avf;
184     int ret = 0;
185
186     if (oc->oformat->write_trailer)
187         ret = oc->oformat->write_trailer(oc);
188
189     if (ret < 0)
190         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
191                oc->filename);
192
193     if (seg->list) {
194         if (seg->list_size && !(seg->segment_count % seg->list_size)) {
195             segment_list_close(s);
196             if ((ret = segment_list_open(s)) < 0)
197                 goto end;
198         }
199
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);
208         }
209         seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
210         avio_flush(seg->list_pb);
211     }
212
213 end:
214     avio_close(oc->pb);
215     if (oc->oformat->priv_class)
216         av_opt_free(oc->priv_data);
217     av_freep(&oc->priv_data);
218
219     return ret;
220 }
221
222 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
223                        const char *times_str)
224 {
225     char *p;
226     int i, ret = 0;
227     char *times_str1 = av_strdup(times_str);
228     char *saveptr = NULL;
229
230     if (!times_str1)
231         return AVERROR(ENOMEM);
232
233 #define FAIL(err) ret = err; goto end
234
235     *nb_times = 1;
236     for (p = times_str1; *p; p++)
237         if (*p == ',')
238             (*nb_times)++;
239
240     *times = av_malloc(sizeof(**times) * *nb_times);
241     if (!*times) {
242         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
243         FAIL(AVERROR(ENOMEM));
244     }
245
246     p = times_str1;
247     for (i = 0; i < *nb_times; i++) {
248         int64_t t;
249         char *tstr = av_strtok(p, ",", &saveptr);
250         av_assert0(tstr);
251         p = NULL;
252
253         ret = av_parse_time(&t, tstr, 1);
254         if (ret < 0) {
255             av_log(log_ctx, AV_LOG_ERROR,
256                    "Invalid time duration specification in %s\n", p);
257             FAIL(AVERROR(EINVAL));
258         }
259         (*times)[i] = t;
260
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));
267         }
268     }
269
270 end:
271     av_free(times_str1);
272     return ret;
273 }
274
275 static int seg_write_header(AVFormatContext *s)
276 {
277     SegmentContext *seg = s->priv_data;
278     AVFormatContext *oc;
279     int ret, i;
280
281     seg->segment_count = 0;
282
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);
287     }
288
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);
294     }
295
296     if (seg->times_str) {
297         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
298             return ret;
299     } else {
300         /* set default value if not specified */
301         if (!seg->time_str)
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",
306                    seg->time_str);
307             return ret;
308         }
309     }
310
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);
316             return ret;
317         }
318     }
319
320     oc = avformat_alloc_context();
321
322     if (!oc)
323         return AVERROR(ENOMEM);
324
325     if (seg->list) {
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;
331         }
332         if ((ret = segment_list_open(s)) < 0)
333             goto fail;
334     }
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");
337
338     for (i = 0; i< s->nb_streams; i++)
339         seg->has_video +=
340             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
341
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");
346
347     oc->oformat = av_guess_format(seg->format, s->filename, NULL);
348
349     if (!oc->oformat) {
350         ret = AVERROR_MUXER_NOT_FOUND;
351         goto fail;
352     }
353     if (oc->oformat->flags & AVFMT_NOFILE) {
354         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
355                oc->oformat->name);
356         ret = AVERROR(EINVAL);
357         goto fail;
358     }
359
360     seg->avf = oc;
361
362     oc->streams = s->streams;
363     oc->nb_streams = s->nb_streams;
364
365     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
366                               s->filename, seg->segment_idx++) < 0) {
367         ret = AVERROR(EINVAL);
368         goto fail;
369     }
370     seg->segment_count++;
371
372     if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
373                           &s->interrupt_callback, NULL)) < 0)
374         goto fail;
375
376     if ((ret = avformat_write_header(oc, NULL)) < 0) {
377         avio_close(oc->pb);
378         goto fail;
379     }
380
381 fail:
382     if (ret) {
383         if (oc) {
384             oc->streams = NULL;
385             oc->nb_streams = 0;
386             avformat_free_context(oc);
387         }
388         if (seg->list)
389             segment_list_close(s);
390     }
391     return ret;
392 }
393
394 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
395 {
396     SegmentContext *seg = s->priv_data;
397     AVFormatContext *oc = seg->avf;
398     AVStream *st = oc->streams[pkt->stream_index];
399     int64_t end_pts;
400     int ret;
401
402     if (seg->times) {
403         end_pts = seg->segment_count <= seg->nb_times ?
404             seg->times[seg->segment_count-1] : INT64_MAX;
405     } else {
406         end_pts = seg->time * seg->segment_count;
407     }
408
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) {
414
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));
417
418         if ((ret = segment_end(s)) < 0 || (ret = segment_start(s)) < 0)
419             goto fail;
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));
424     }
425
426     ret = oc->oformat->write_packet(oc, pkt);
427
428 fail:
429     if (ret < 0) {
430         oc->streams = NULL;
431         oc->nb_streams = 0;
432         if (seg->list)
433             avio_close(seg->list_pb);
434         avformat_free_context(oc);
435     }
436
437     return ret;
438 }
439
440 static int seg_write_trailer(struct AVFormatContext *s)
441 {
442     SegmentContext *seg = s->priv_data;
443     AVFormatContext *oc = seg->avf;
444     int ret = segment_end(s);
445     if (seg->list)
446         segment_list_close(s);
447
448     av_opt_free(seg);
449     av_freep(&seg->times);
450
451     oc->streams = NULL;
452     oc->nb_streams = 0;
453     avformat_free_context(oc);
454     return ret;
455 }
456
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 },
462
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"},
466
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 },
477     { NULL },
478 };
479
480 static const AVClass seg_class = {
481     .class_name = "segment muxer",
482     .item_name  = av_default_item_name,
483     .option     = options,
484     .version    = LIBAVUTIL_VERSION_INT,
485 };
486
487 AVOutputFormat ff_segment_muxer = {
488     .name           = "segment",
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,
496 };
497
498 static const AVClass sseg_class = {
499     .class_name = "stream_segment muxer",
500     .item_name  = av_default_item_name,
501     .option     = options,
502     .version    = LIBAVUTIL_VERSION_INT,
503 };
504
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,
514 };