]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
Merge commit 'a854362b40f0e458db5a1fb0d2612a5702ee0ace'
[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_count;      ///< list counter
62     int   list_flags;      ///< flags affecting list generation
63     int   list_size;       ///< number of entries for the segment list file
64     double list_max_segment_time; ///< max segment time in the current list
65     ListType list_type;    ///< set the list type
66     AVIOContext *list_pb;  ///< list file put-byte context
67     char *time_str;        ///< segment duration specification string
68     int64_t time;          ///< segment duration
69     char *times_str;       ///< segment times specification string
70     int64_t *times;        ///< list of segment interval specification
71     int nb_times;          ///< number of elments in the times array
72     char *time_delta_str;  ///< approximation value duration used for the segment times
73     int64_t time_delta;
74     int  individual_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         if (!(st = avformat_new_stream(oc, NULL)))
111             return AVERROR(ENOMEM);
112         avcodec_copy_context(st->codec, s->streams[i]->codec);
113         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
114     }
115
116     return 0;
117 }
118
119 static int segment_start(AVFormatContext *s, int write_header)
120 {
121     SegmentContext *c = s->priv_data;
122     AVFormatContext *oc = c->avf;
123     int err = 0;
124
125     if (write_header) {
126         avformat_free_context(oc);
127         c->avf = NULL;
128         if ((err = segment_mux_init(s)) < 0)
129             return err;
130         oc = c->avf;
131     }
132
133     if (c->segment_idx_wrap)
134         c->segment_idx %= c->segment_idx_wrap;
135
136     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
137                               s->filename, c->segment_idx++) < 0) {
138         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
139         return AVERROR(EINVAL);
140     }
141     c->segment_count++;
142
143     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
144                           &s->interrupt_callback, NULL)) < 0)
145         return err;
146
147     if (oc->oformat->priv_class && oc->priv_data)
148         av_opt_set(oc->priv_data, "resend_headers", "1", 0);
149
150     if (write_header) {
151         if ((err = avformat_write_header(oc, NULL)) < 0)
152             return err;
153     }
154
155     return 0;
156 }
157
158 static int segment_list_open(AVFormatContext *s)
159 {
160     SegmentContext *seg = s->priv_data;
161     int ret;
162
163     ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
164                      &s->interrupt_callback, NULL);
165     if (ret < 0)
166         return ret;
167     seg->list_max_segment_time = 0;
168
169     if (seg->list_type == LIST_TYPE_M3U8) {
170         avio_printf(seg->list_pb, "#EXTM3U\n");
171         avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
172         avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->list_count);
173         avio_printf(seg->list_pb, "#EXT-X-ALLOWCACHE:%d\n",
174                     !!(seg->list_flags & SEGMENT_LIST_FLAG_CACHE));
175         if (seg->list_flags & SEGMENT_LIST_FLAG_LIVE)
176             avio_printf(seg->list_pb,
177                         "#EXT-X-TARGETDURATION:%"PRId64"\n", seg->time / 1000000);
178     }
179
180     return ret;
181 }
182
183 static void segment_list_close(AVFormatContext *s)
184 {
185     SegmentContext *seg = s->priv_data;
186
187     if (seg->list_type == LIST_TYPE_M3U8) {
188         if (!(seg->list_flags & SEGMENT_LIST_FLAG_LIVE))
189             avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%d\n",
190                         (int)ceil(seg->list_max_segment_time));
191         avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
192     }
193     seg->list_count++;
194
195     avio_close(seg->list_pb);
196 }
197
198 static int segment_end(AVFormatContext *s, int write_trailer)
199 {
200     SegmentContext *seg = s->priv_data;
201     AVFormatContext *oc = seg->avf;
202     int ret = 0;
203
204     av_write_frame(oc, NULL); /* Flush any buffered data */
205     if (write_trailer)
206         ret = av_write_trailer(oc);
207
208     if (ret < 0)
209         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
210                oc->filename);
211
212     if (seg->list) {
213         if (seg->list_size && !(seg->segment_count % seg->list_size)) {
214             segment_list_close(s);
215             if ((ret = segment_list_open(s)) < 0)
216                 goto end;
217         }
218
219         if (seg->list_type == LIST_TYPE_FLAT) {
220             avio_printf(seg->list_pb, "%s\n", oc->filename);
221         } else if (seg->list_type == LIST_TYPE_CSV || seg->list_type == LIST_TYPE_EXT) {
222             print_csv_escaped_str(seg->list_pb, oc->filename);
223             avio_printf(seg->list_pb, ",%f,%f\n", seg->start_time, seg->end_time);
224         } else if (seg->list_type == LIST_TYPE_M3U8) {
225             avio_printf(seg->list_pb, "#EXTINF:%f,\n%s\n",
226                         seg->end_time - seg->start_time, oc->filename);
227         }
228         seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
229         avio_flush(seg->list_pb);
230     }
231
232 end:
233     avio_close(oc->pb);
234
235     return ret;
236 }
237
238 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
239                        const char *times_str)
240 {
241     char *p;
242     int i, ret = 0;
243     char *times_str1 = av_strdup(times_str);
244     char *saveptr = NULL;
245
246     if (!times_str1)
247         return AVERROR(ENOMEM);
248
249 #define FAIL(err) ret = err; goto end
250
251     *nb_times = 1;
252     for (p = times_str1; *p; p++)
253         if (*p == ',')
254             (*nb_times)++;
255
256     *times = av_malloc(sizeof(**times) * *nb_times);
257     if (!*times) {
258         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
259         FAIL(AVERROR(ENOMEM));
260     }
261
262     p = times_str1;
263     for (i = 0; i < *nb_times; i++) {
264         int64_t t;
265         char *tstr = av_strtok(p, ",", &saveptr);
266         av_assert0(tstr);
267         p = NULL;
268
269         ret = av_parse_time(&t, tstr, 1);
270         if (ret < 0) {
271             av_log(log_ctx, AV_LOG_ERROR,
272                    "Invalid time duration specification in %s\n", p);
273             FAIL(AVERROR(EINVAL));
274         }
275         (*times)[i] = t;
276
277         /* check on monotonicity */
278         if (i && (*times)[i-1] > (*times)[i]) {
279             av_log(log_ctx, AV_LOG_ERROR,
280                    "Specified time %f is greater than the following time %f\n",
281                    (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
282             FAIL(AVERROR(EINVAL));
283         }
284     }
285
286 end:
287     av_free(times_str1);
288     return ret;
289 }
290
291 static int seg_write_header(AVFormatContext *s)
292 {
293     SegmentContext *seg = s->priv_data;
294     AVFormatContext *oc = NULL;
295     int ret, i;
296
297     seg->segment_count = 0;
298
299     if (seg->time_str && seg->times_str) {
300         av_log(s, AV_LOG_ERROR,
301                "segment_time and segment_times options are mutually exclusive, select just one of them\n");
302         return AVERROR(EINVAL);
303     }
304
305     if ((seg->list_flags & SEGMENT_LIST_FLAG_LIVE) && seg->times_str) {
306         av_log(s, AV_LOG_ERROR,
307                "segment_flags +live and segment_times options are mutually exclusive:"
308                "specify -segment_time if you want a live-friendly list\n");
309         return AVERROR(EINVAL);
310     }
311
312     if (seg->times_str) {
313         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
314             return ret;
315     } else {
316         /* set default value if not specified */
317         if (!seg->time_str)
318             seg->time_str = av_strdup("2");
319         if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
320             av_log(s, AV_LOG_ERROR,
321                    "Invalid time duration specification '%s' for segment_time option\n",
322                    seg->time_str);
323             return ret;
324         }
325     }
326
327     if (seg->time_delta_str) {
328         if ((ret = av_parse_time(&seg->time_delta, seg->time_delta_str, 1)) < 0) {
329             av_log(s, AV_LOG_ERROR,
330                    "Invalid time duration specification '%s' for delta option\n",
331                    seg->time_delta_str);
332             return ret;
333         }
334     }
335
336     if (seg->list) {
337         if (seg->list_type == LIST_TYPE_UNDEFINED) {
338             if      (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
339             else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
340             else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
341             else                                      seg->list_type = LIST_TYPE_FLAT;
342         }
343         if ((ret = segment_list_open(s)) < 0)
344             goto fail;
345     }
346     if (seg->list_type == LIST_TYPE_EXT)
347         av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
348
349     for (i = 0; i < s->nb_streams; i++)
350         seg->has_video +=
351             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
352
353     if (seg->has_video > 1)
354         av_log(s, AV_LOG_WARNING,
355                "More than a single video stream present, "
356                "expect issues decoding it.\n");
357
358     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
359
360     if (!seg->oformat) {
361         ret = AVERROR_MUXER_NOT_FOUND;
362         goto fail;
363     }
364     if (seg->oformat->flags & AVFMT_NOFILE) {
365         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
366                oc->oformat->name);
367         ret = AVERROR(EINVAL);
368         goto fail;
369     }
370
371     if ((ret = segment_mux_init(s)) < 0)
372         goto fail;
373     oc = seg->avf;
374
375     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
376                               s->filename, seg->segment_idx++) < 0) {
377         ret = AVERROR(EINVAL);
378         goto fail;
379     }
380     seg->segment_count++;
381
382     if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
383                           &s->interrupt_callback, NULL)) < 0)
384         goto fail;
385
386     if ((ret = avformat_write_header(oc, NULL)) < 0) {
387         avio_close(oc->pb);
388         goto fail;
389     }
390
391 fail:
392     if (ret) {
393         if (seg->list)
394             segment_list_close(s);
395         if (seg->avf)
396             avformat_free_context(seg->avf);
397     }
398     return ret;
399 }
400
401 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
402 {
403     SegmentContext *seg = s->priv_data;
404     AVFormatContext *oc = seg->avf;
405     AVStream *st = s->streams[pkt->stream_index];
406     int64_t end_pts;
407     int ret;
408
409     if (seg->times) {
410         end_pts = seg->segment_count <= seg->nb_times ?
411             seg->times[seg->segment_count-1] : INT64_MAX;
412     } else {
413         end_pts = seg->time * seg->segment_count;
414     }
415
416     /* if the segment has video, start a new segment *only* with a key video frame */
417     if ((st->codec->codec_type == AVMEDIA_TYPE_VIDEO || !seg->has_video) &&
418         av_compare_ts(pkt->pts, st->time_base,
419                       end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0 &&
420         pkt->flags & AV_PKT_FLAG_KEY) {
421
422         av_log(s, AV_LOG_DEBUG, "Next segment starts with packet stream:%d pts:%"PRId64" pts_time:%f\n",
423                pkt->stream_index, pkt->pts, pkt->pts * av_q2d(st->time_base));
424
425         ret = segment_end(s, seg->individual_header_trailer);
426
427         if (!ret)
428             ret = segment_start(s, seg->individual_header_trailer);
429
430         if (ret)
431             goto fail;
432
433         oc = seg->avf;
434
435         seg->start_time = (double)pkt->pts * av_q2d(st->time_base);
436     } else if (pkt->pts != AV_NOPTS_VALUE) {
437         seg->end_time = FFMAX(seg->end_time,
438                               (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
439     }
440
441     ret = ff_write_chained(oc, pkt->stream_index, pkt, s);
442
443 fail:
444     if (ret < 0) {
445         if (seg->list)
446             avio_close(seg->list_pb);
447         avformat_free_context(oc);
448     }
449
450     return ret;
451 }
452
453 static int seg_write_trailer(struct AVFormatContext *s)
454 {
455     SegmentContext *seg = s->priv_data;
456     AVFormatContext *oc = seg->avf;
457     int ret = segment_end(s, 1);
458     if (seg->list)
459         segment_list_close(s);
460
461     av_opt_free(seg);
462     av_freep(&seg->times);
463
464     avformat_free_context(oc);
465     return ret;
466 }
467
468 #define OFFSET(x) offsetof(SegmentContext, x)
469 #define E AV_OPT_FLAG_ENCODING_PARAM
470 static const AVOption options[] = {
471     { "segment_format",    "set container format used for the segments", OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
472     { "segment_list",      "set the segment list filename",              OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
473
474     { "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"},
475     { "cache",             "allow list caching",                                    0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX,   E, "list_flags"},
476     { "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"},
477
478     { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT,  {.i64 = 0},     0, INT_MAX, E },
479     { "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" },
480     { "flat", "flat format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, 0, "list_type" },
481     { "csv",  "csv format",      0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV  }, INT_MIN, INT_MAX, 0, "list_type" },
482     { "ext",  "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT  }, INT_MIN, INT_MAX, 0, "list_type" },
483     { "m3u8", "M3U8 format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, 0, "list_type" },
484     { "segment_time",      "set segment duration",                       OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
485     { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta_str), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, E },
486     { "segment_times",     "set segment split time points",              OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
487     { "segment_wrap",      "set number after which the index wraps",     OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
488     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
489     { NULL },
490 };
491
492 static const AVClass seg_class = {
493     .class_name = "segment muxer",
494     .item_name  = av_default_item_name,
495     .option     = options,
496     .version    = LIBAVUTIL_VERSION_INT,
497 };
498
499 AVOutputFormat ff_segment_muxer = {
500     .name           = "segment",
501     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
502     .priv_data_size = sizeof(SegmentContext),
503     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE,
504     .write_header   = seg_write_header,
505     .write_packet   = seg_write_packet,
506     .write_trailer  = seg_write_trailer,
507     .priv_class     = &seg_class,
508 };
509
510 static const AVClass sseg_class = {
511     .class_name = "stream_segment muxer",
512     .item_name  = av_default_item_name,
513     .option     = options,
514     .version    = LIBAVUTIL_VERSION_INT,
515 };
516
517 AVOutputFormat ff_stream_segment_muxer = {
518     .name           = "stream_segment,ssegment",
519     .long_name      = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
520     .priv_data_size = sizeof(SegmentContext),
521     .flags          = AVFMT_NOFILE,
522     .write_header   = seg_write_header,
523     .write_packet   = seg_write_packet,
524     .write_trailer  = seg_write_trailer,
525     .priv_class     = &sseg_class,
526 };