]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
Merge commit '6e5cdf26281945ddea3aaf5eca4d127791f23ca8'
[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     AVOutputFormat *oformat;
58     AVFormatContext *avf;
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
72     int64_t time_delta;
73     int  individual_header_trailer; /**< Set by a private option. */
74     int  write_header_trailer; /**< Set by a private option. */
75     int has_video;
76     double start_time, end_time;
77 } SegmentContext;
78
79 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
80 {
81     int needs_quoting = !!str[strcspn(str, "\",\n\r")];
82
83     if (needs_quoting)
84         avio_w8(ctx, '"');
85
86     for (; *str; str++) {
87         if (*str == '"')
88             avio_w8(ctx, '"');
89         avio_w8(ctx, *str);
90     }
91     if (needs_quoting)
92         avio_w8(ctx, '"');
93 }
94
95 static int segment_mux_init(AVFormatContext *s)
96 {
97     SegmentContext *seg = s->priv_data;
98     AVFormatContext *oc;
99     int i;
100
101     seg->avf = oc = avformat_alloc_context();
102     if (!oc)
103         return AVERROR(ENOMEM);
104
105     oc->oformat            = seg->oformat;
106     oc->interrupt_callback = s->interrupt_callback;
107
108     for (i = 0; i < s->nb_streams; i++) {
109         AVStream *st;
110         AVCodecContext *icodec, *ocodec;
111
112         if (!(st = avformat_new_stream(oc, NULL)))
113             return AVERROR(ENOMEM);
114         icodec = s->streams[i]->codec;
115         ocodec = st->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;
121         } else {
122             ocodec->codec_tag = 0;
123         }
124         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
125     }
126
127     return 0;
128 }
129
130 static int segment_start(AVFormatContext *s, int write_header)
131 {
132     SegmentContext *seg = s->priv_data;
133     AVFormatContext *oc = seg->avf;
134     int err = 0;
135
136     if (write_header) {
137         avformat_free_context(oc);
138         seg->avf = NULL;
139         if ((err = segment_mux_init(s)) < 0)
140             return err;
141         oc = seg->avf;
142     }
143
144     seg->segment_idx++;
145     if (seg->segment_idx_wrap)
146         seg->segment_idx %= seg->segment_idx_wrap;
147
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);
152     }
153     seg->segment_count++;
154
155     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
156                           &s->interrupt_callback, NULL)) < 0)
157         return err;
158
159     if (oc->oformat->priv_class && oc->priv_data)
160         av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
161
162     if (write_header) {
163         if ((err = avformat_write_header(oc, NULL)) < 0)
164             return err;
165     }
166
167     return 0;
168 }
169
170 static int segment_list_open(AVFormatContext *s)
171 {
172     SegmentContext *seg = s->priv_data;
173     int ret;
174
175     ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
176                      &s->interrupt_callback, NULL);
177     if (ret < 0)
178         return ret;
179     seg->list_max_segment_time = 0;
180
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);
190     }
191
192     return ret;
193 }
194
195 static void segment_list_close(AVFormatContext *s)
196 {
197     SegmentContext *seg = s->priv_data;
198
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");
204     }
205
206     avio_close(seg->list_pb);
207 }
208
209 static int segment_end(AVFormatContext *s, int write_trailer)
210 {
211     SegmentContext *seg = s->priv_data;
212     AVFormatContext *oc = seg->avf;
213     int ret = 0;
214
215     av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
216     if (write_trailer)
217         ret = av_write_trailer(oc);
218
219     if (ret < 0)
220         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
221                oc->filename);
222
223     if (seg->list) {
224         if (seg->list_size && !(seg->segment_count % seg->list_size)) {
225             segment_list_close(s);
226             if ((ret = segment_list_open(s)) < 0)
227                 goto end;
228         }
229
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);
238         }
239         seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
240         avio_flush(seg->list_pb);
241     }
242
243 end:
244     avio_close(oc->pb);
245
246     return ret;
247 }
248
249 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
250                        const char *times_str)
251 {
252     char *p;
253     int i, ret = 0;
254     char *times_str1 = av_strdup(times_str);
255     char *saveptr = NULL;
256
257     if (!times_str1)
258         return AVERROR(ENOMEM);
259
260 #define FAIL(err) ret = err; goto end
261
262     *nb_times = 1;
263     for (p = times_str1; *p; p++)
264         if (*p == ',')
265             (*nb_times)++;
266
267     *times = av_malloc(sizeof(**times) * *nb_times);
268     if (!*times) {
269         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
270         FAIL(AVERROR(ENOMEM));
271     }
272
273     p = times_str1;
274     for (i = 0; i < *nb_times; i++) {
275         int64_t t;
276         char *tstr = av_strtok(p, ",", &saveptr);
277         av_assert0(tstr);
278         p = NULL;
279
280         ret = av_parse_time(&t, tstr, 1);
281         if (ret < 0) {
282             av_log(log_ctx, AV_LOG_ERROR,
283                    "Invalid time duration specification in %s\n", p);
284             FAIL(AVERROR(EINVAL));
285         }
286         (*times)[i] = t;
287
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));
294         }
295     }
296
297 end:
298     av_free(times_str1);
299     return ret;
300 }
301
302 static int open_null_ctx(AVIOContext **ctx)
303 {
304     int buf_size = 32768;
305     uint8_t *buf = av_malloc(buf_size);
306     if (!buf)
307         return AVERROR(ENOMEM);
308     *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
309     if (!*ctx) {
310         av_free(buf);
311         return AVERROR(ENOMEM);
312     }
313     return 0;
314 }
315
316 static void close_null_ctx(AVIOContext *pb)
317 {
318     av_free(pb->buffer);
319     av_free(pb);
320 }
321
322 static int seg_write_header(AVFormatContext *s)
323 {
324     SegmentContext *seg = s->priv_data;
325     AVFormatContext *oc = NULL;
326     int ret, i;
327
328     seg->segment_count = 0;
329     if (!seg->write_header_trailer)
330         seg->individual_header_trailer = 0;
331
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);
336     }
337
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);
343     }
344
345     if (seg->times_str) {
346         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
347             return ret;
348     } else {
349         /* set default value if not specified */
350         if (!seg->time_str)
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",
355                    seg->time_str);
356             return ret;
357         }
358     }
359
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);
365             return ret;
366         }
367     }
368
369     if (seg->list) {
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;
375         }
376         if ((ret = segment_list_open(s)) < 0)
377             goto fail;
378     }
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");
381
382     for (i = 0; i < s->nb_streams; i++)
383         seg->has_video +=
384             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
385
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");
390
391     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
392
393     if (!seg->oformat) {
394         ret = AVERROR_MUXER_NOT_FOUND;
395         goto fail;
396     }
397     if (seg->oformat->flags & AVFMT_NOFILE) {
398         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
399                seg->oformat->name);
400         ret = AVERROR(EINVAL);
401         goto fail;
402     }
403
404     if ((ret = segment_mux_init(s)) < 0)
405         goto fail;
406     oc = seg->avf;
407
408     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
409                               s->filename, seg->segment_idx) < 0) {
410         ret = AVERROR(EINVAL);
411         goto fail;
412     }
413     seg->segment_count++;
414
415     if (seg->write_header_trailer) {
416         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
417                               &s->interrupt_callback, NULL)) < 0)
418             goto fail;
419     } else {
420         if ((ret = open_null_ctx(&oc->pb)) < 0)
421             goto fail;
422     }
423
424     if ((ret = avformat_write_header(oc, NULL)) < 0) {
425         avio_close(oc->pb);
426         goto fail;
427     }
428
429     if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
430         s->avoid_negative_ts = 1;
431
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)
436             goto fail;
437     }
438
439 fail:
440     if (ret) {
441         if (seg->list)
442             segment_list_close(s);
443         if (seg->avf)
444             avformat_free_context(seg->avf);
445     }
446     return ret;
447 }
448
449 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
450 {
451     SegmentContext *seg = s->priv_data;
452     AVFormatContext *oc = seg->avf;
453     AVStream *st = s->streams[pkt->stream_index];
454     int64_t end_pts;
455     int ret;
456
457     if (seg->times) {
458         end_pts = seg->segment_count <= seg->nb_times ?
459             seg->times[seg->segment_count-1] : INT64_MAX;
460     } else {
461         end_pts = seg->time * seg->segment_count;
462     }
463
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) {
469
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));
472
473         ret = segment_end(s, seg->individual_header_trailer);
474
475         if (!ret)
476             ret = segment_start(s, seg->individual_header_trailer);
477
478         if (ret)
479             goto fail;
480
481         oc = seg->avf;
482
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));
487     }
488
489     ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
490
491 fail:
492     if (ret < 0) {
493         if (seg->list)
494             avio_close(seg->list_pb);
495         avformat_free_context(oc);
496     }
497
498     return ret;
499 }
500
501 static int seg_write_trailer(struct AVFormatContext *s)
502 {
503     SegmentContext *seg = s->priv_data;
504     AVFormatContext *oc = seg->avf;
505     int ret;
506     if (!seg->write_header_trailer) {
507         if ((ret = segment_end(s, 0)) < 0)
508             goto fail;
509         open_null_ctx(&oc->pb);
510         ret = av_write_trailer(oc);
511         close_null_ctx(oc->pb);
512     } else {
513         ret = segment_end(s, 1);
514     }
515 fail:
516     if (seg->list)
517         segment_list_close(s);
518
519     av_opt_free(seg);
520     av_freep(&seg->times);
521
522     avformat_free_context(oc);
523     return ret;
524 }
525
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 },
531
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"},
535
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 },
549     { NULL },
550 };
551
552 static const AVClass seg_class = {
553     .class_name = "segment muxer",
554     .item_name  = av_default_item_name,
555     .option     = options,
556     .version    = LIBAVUTIL_VERSION_INT,
557 };
558
559 AVOutputFormat ff_segment_muxer = {
560     .name           = "segment",
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,
568 };
569
570 static const AVClass sseg_class = {
571     .class_name = "stream_segment muxer",
572     .item_name  = av_default_item_name,
573     .option     = options,
574     .version    = LIBAVUTIL_VERSION_INT,
575 };
576
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,
586 };