]> 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_NB,
45 } ListType;
46
47 #define LIST_TYPE_EXT LIST_TYPE_CSV
48
49 typedef struct {
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
54     AVFormatContext *avf;
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
68     int64_t time_delta;
69     int has_video;
70     double start_time, end_time;
71 } SegmentContext;
72
73 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
74 {
75     const char *p;
76     int quote = 0;
77
78     /* check if input needs quoting */
79     for (p = str; *p; p++)
80         if (strchr("\",\n\r", *p)) {
81             quote = 1;
82             break;
83         }
84
85     if (quote)
86         avio_w8(ctx, '"');
87
88     for (p = str; *p; p++) {
89         if (*p == '"')
90             avio_w8(ctx, '"');
91         avio_w8(ctx, *p);
92     }
93     if (quote)
94         avio_w8(ctx, '"');
95 }
96
97 static int segment_start(AVFormatContext *s)
98 {
99     SegmentContext *seg = s->priv_data;
100     AVFormatContext *oc = seg->avf;
101     int err = 0;
102
103     if (seg->segment_idx_wrap)
104         seg->segment_idx %= seg->segment_idx_wrap;
105
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);
110     }
111     seg->segment_count++;
112
113     if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
114                           &s->interrupt_callback, NULL)) < 0)
115         return err;
116
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) {
120             avio_close(oc->pb);
121             return AVERROR(ENOMEM);
122         }
123         if (oc->oformat->priv_class) {
124             *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
125             av_opt_set_defaults(oc->priv_data);
126         }
127     }
128
129     if ((err = oc->oformat->write_header(oc)) < 0) {
130         goto fail;
131     }
132
133     return 0;
134
135 fail:
136     av_log(oc, AV_LOG_ERROR, "Failure occurred when starting segment '%s'\n",
137            oc->filename);
138     avio_close(oc->pb);
139     av_freep(&oc->priv_data);
140
141     return err;
142 }
143
144 static int segment_list_open(AVFormatContext *s)
145 {
146     SegmentContext *seg = s->priv_data;
147     int ret;
148
149     ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
150                      &s->interrupt_callback, NULL);
151     if (ret < 0)
152         return ret;
153     seg->list_max_segment_time = 0;
154
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);
159     }
160
161     return ret;
162 }
163
164 static void segment_list_close(AVFormatContext *s)
165 {
166     SegmentContext *seg = s->priv_data;
167
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");
172     }
173     seg->list_count++;
174
175     avio_close(seg->list_pb);
176 }
177
178 static int segment_end(AVFormatContext *s)
179 {
180     SegmentContext *seg = s->priv_data;
181     AVFormatContext *oc = seg->avf;
182     int ret = 0;
183
184     if (oc->oformat->write_trailer)
185         ret = oc->oformat->write_trailer(oc);
186
187     if (ret < 0)
188         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
189                oc->filename);
190
191     if (seg->list) {
192         if (seg->list_size && !(seg->segment_count % seg->list_size)) {
193             segment_list_close(s);
194             if ((ret = segment_list_open(s)) < 0)
195                 goto end;
196         }
197
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);
206         }
207         seg->list_max_segment_time = FFMAX(seg->end_time - seg->start_time, seg->list_max_segment_time);
208         avio_flush(seg->list_pb);
209     }
210
211 end:
212     avio_close(oc->pb);
213     if (oc->oformat->priv_class)
214         av_opt_free(oc->priv_data);
215     av_freep(&oc->priv_data);
216
217     return ret;
218 }
219
220 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
221                        const char *times_str)
222 {
223     char *p;
224     int i, ret = 0;
225     char *times_str1 = av_strdup(times_str);
226     char *saveptr = NULL;
227
228     if (!times_str1)
229         return AVERROR(ENOMEM);
230
231 #define FAIL(err) ret = err; goto end
232
233     *nb_times = 1;
234     for (p = times_str1; *p; p++)
235         if (*p == ',')
236             (*nb_times)++;
237
238     *times = av_malloc(sizeof(**times) * *nb_times);
239     if (!*times) {
240         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
241         FAIL(AVERROR(ENOMEM));
242     }
243
244     p = times_str1;
245     for (i = 0; i < *nb_times; i++) {
246         int64_t t;
247         char *tstr = av_strtok(p, ",", &saveptr);
248         av_assert0(tstr);
249         p = NULL;
250
251         ret = av_parse_time(&t, tstr, 1);
252         if (ret < 0) {
253             av_log(log_ctx, AV_LOG_ERROR,
254                    "Invalid time duration specification in %s\n", p);
255             FAIL(AVERROR(EINVAL));
256         }
257         (*times)[i] = t;
258
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));
265         }
266     }
267
268 end:
269     av_free(times_str1);
270     return ret;
271 }
272
273 static int seg_write_header(AVFormatContext *s)
274 {
275     SegmentContext *seg = s->priv_data;
276     AVFormatContext *oc;
277     int ret, i;
278
279     seg->segment_count = 0;
280
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);
285     }
286
287     if (seg->times_str) {
288         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
289             return ret;
290     } else {
291         /* set default value if not specified */
292         if (!seg->time_str)
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",
297                    seg->time_str);
298             return ret;
299         }
300     }
301
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);
307             return ret;
308         }
309     }
310
311     oc = avformat_alloc_context();
312
313     if (!oc)
314         return AVERROR(ENOMEM);
315
316     if (seg->list) {
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;
322         }
323         if ((ret = segment_list_open(s)) < 0)
324             goto fail;
325     }
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");
328
329     for (i = 0; i< s->nb_streams; i++)
330         seg->has_video +=
331             (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO);
332
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");
337
338     oc->oformat = av_guess_format(seg->format, s->filename, NULL);
339
340     if (!oc->oformat) {
341         ret = AVERROR_MUXER_NOT_FOUND;
342         goto fail;
343     }
344     if (oc->oformat->flags & AVFMT_NOFILE) {
345         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
346                oc->oformat->name);
347         ret = AVERROR(EINVAL);
348         goto fail;
349     }
350
351     seg->avf = oc;
352
353     oc->streams = s->streams;
354     oc->nb_streams = s->nb_streams;
355
356     if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
357                               s->filename, seg->segment_idx++) < 0) {
358         ret = AVERROR(EINVAL);
359         goto fail;
360     }
361     seg->segment_count++;
362
363     if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
364                           &s->interrupt_callback, NULL)) < 0)
365         goto fail;
366
367     if ((ret = avformat_write_header(oc, NULL)) < 0) {
368         avio_close(oc->pb);
369         goto fail;
370     }
371
372 fail:
373     if (ret) {
374         if (oc) {
375             oc->streams = NULL;
376             oc->nb_streams = 0;
377             avformat_free_context(oc);
378         }
379         if (seg->list)
380             segment_list_close(s);
381     }
382     return ret;
383 }
384
385 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
386 {
387     SegmentContext *seg = s->priv_data;
388     AVFormatContext *oc = seg->avf;
389     AVStream *st = oc->streams[pkt->stream_index];
390     int64_t end_pts;
391     int ret;
392
393     if (seg->times) {
394         end_pts = seg->segment_count <= seg->nb_times ?
395             seg->times[seg->segment_count-1] : INT64_MAX;
396     } else {
397         end_pts = seg->time * seg->segment_count;
398     }
399
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) {
405
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));
408
409         if ((ret = segment_end(s)) < 0 || (ret = segment_start(s)) < 0)
410             goto fail;
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));
415     }
416
417     ret = oc->oformat->write_packet(oc, pkt);
418
419 fail:
420     if (ret < 0) {
421         oc->streams = NULL;
422         oc->nb_streams = 0;
423         if (seg->list)
424             avio_close(seg->list_pb);
425         avformat_free_context(oc);
426     }
427
428     return ret;
429 }
430
431 static int seg_write_trailer(struct AVFormatContext *s)
432 {
433     SegmentContext *seg = s->priv_data;
434     AVFormatContext *oc = seg->avf;
435     int ret = segment_end(s);
436     if (seg->list)
437         segment_list_close(s);
438
439     av_opt_free(seg);
440     av_freep(&seg->times);
441
442     oc->streams = NULL;
443     oc->nb_streams = 0;
444     avformat_free_context(oc);
445     return ret;
446 }
447
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 },
463     { NULL },
464 };
465
466 static const AVClass seg_class = {
467     .class_name = "segment muxer",
468     .item_name  = av_default_item_name,
469     .option     = options,
470     .version    = LIBAVUTIL_VERSION_INT,
471 };
472
473 AVOutputFormat ff_segment_muxer = {
474     .name           = "segment",
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,
482 };
483
484 static const AVClass sseg_class = {
485     .class_name = "stream_segment muxer",
486     .item_name  = av_default_item_name,
487     .option     = options,
488     .version    = LIBAVUTIL_VERSION_INT,
489 };
490
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,
500 };