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