]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
avformat/hls: fix potential integer overflow
[ffmpeg] / libavformat / segment.c
1 /*
2  * Copyright (c) 2011, Luca Barbato
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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}
25  */
26
27 /* #define DEBUG */
28
29 #include <float.h>
30 #include <time.h>
31
32 #include "avformat.h"
33 #include "avio_internal.h"
34 #include "internal.h"
35
36 #include "libavutil/avassert.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/log.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/avstring.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/time.h"
44 #include "libavutil/time_internal.h"
45 #include "libavutil/timestamp.h"
46
47 typedef struct SegmentListEntry {
48     int index;
49     double start_time, end_time;
50     int64_t start_pts;
51     int64_t offset_pts;
52     char *filename;
53     struct SegmentListEntry *next;
54     int64_t last_duration;
55 } SegmentListEntry;
56
57 typedef enum {
58     LIST_TYPE_UNDEFINED = -1,
59     LIST_TYPE_FLAT = 0,
60     LIST_TYPE_CSV,
61     LIST_TYPE_M3U8,
62     LIST_TYPE_EXT, ///< deprecated
63     LIST_TYPE_FFCONCAT,
64     LIST_TYPE_NB,
65 } ListType;
66
67 #define SEGMENT_LIST_FLAG_CACHE 1
68 #define SEGMENT_LIST_FLAG_LIVE  2
69
70 typedef struct SegmentContext {
71     const AVClass *class;  /**< Class for private options. */
72     int segment_idx;       ///< index of the segment file to write, starting from 0
73     int segment_idx_wrap;  ///< number after which the index wraps
74     int segment_idx_wrap_nb;  ///< number of time the index has wraped
75     int segment_count;     ///< number of segment files already written
76     AVOutputFormat *oformat;
77     AVFormatContext *avf;
78     char *format;              ///< format to use for output segment files
79     char *format_options_str;  ///< format options to use for output segment files
80     AVDictionary *format_options;
81     char *list;            ///< filename for the segment list file
82     int   list_flags;      ///< flags affecting list generation
83     int   list_size;       ///< number of entries for the segment list file
84
85     int use_clocktime;    ///< flag to cut segments at regular clock time
86     int64_t clocktime_offset; //< clock offset for cutting the segments at regular clock time
87     int64_t clocktime_wrap_duration; //< wrapping duration considered for starting a new segment
88     int64_t last_val;      ///< remember last time for wrap around detection
89     int64_t last_cut;      ///< remember last cut
90     int cut_pending;
91
92     char *entry_prefix;    ///< prefix to add to list entry filenames
93     int list_type;         ///< set the list type
94     AVIOContext *list_pb;  ///< list file put-byte context
95     char *time_str;        ///< segment duration specification string
96     int64_t time;          ///< segment duration
97     int use_strftime;      ///< flag to expand filename with strftime
98
99     char *times_str;       ///< segment times specification string
100     int64_t *times;        ///< list of segment interval specification
101     int nb_times;          ///< number of elments in the times array
102
103     char *frames_str;      ///< segment frame numbers specification string
104     int *frames;           ///< list of frame number specification
105     int nb_frames;         ///< number of elments in the frames array
106     int frame_count;       ///< total number of reference frames
107     int segment_frame_count; ///< number of reference frames in the segment
108
109     int64_t time_delta;
110     int  individual_header_trailer; /**< Set by a private option. */
111     int  write_header_trailer; /**< Set by a private option. */
112     char *header_filename;  ///< filename to write the output header to
113
114     int reset_timestamps;  ///< reset timestamps at the begin of each segment
115     int64_t initial_offset;    ///< initial timestamps offset, expressed in microseconds
116     char *reference_stream_specifier; ///< reference stream specifier
117     int   reference_stream_index;
118     int   break_non_keyframes;
119
120     int use_rename;
121     char temp_list_filename[1024];
122
123     SegmentListEntry cur_entry;
124     SegmentListEntry *segment_list_entries;
125     SegmentListEntry *segment_list_entries_end;
126 } SegmentContext;
127
128 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
129 {
130     int needs_quoting = !!str[strcspn(str, "\",\n\r")];
131
132     if (needs_quoting)
133         avio_w8(ctx, '"');
134
135     for (; *str; str++) {
136         if (*str == '"')
137             avio_w8(ctx, '"');
138         avio_w8(ctx, *str);
139     }
140     if (needs_quoting)
141         avio_w8(ctx, '"');
142 }
143
144 static int segment_mux_init(AVFormatContext *s)
145 {
146     SegmentContext *seg = s->priv_data;
147     AVFormatContext *oc;
148     int i;
149     int ret;
150
151     ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
152     if (ret < 0)
153         return ret;
154     oc = seg->avf;
155
156     oc->interrupt_callback = s->interrupt_callback;
157     oc->max_delay          = s->max_delay;
158     av_dict_copy(&oc->metadata, s->metadata, 0);
159     oc->opaque             = s->opaque;
160     oc->io_close           = s->io_close;
161     oc->io_open            = s->io_open;
162
163     for (i = 0; i < s->nb_streams; i++) {
164         AVStream *st;
165         AVCodecContext *icodec, *ocodec;
166
167         if (!(st = avformat_new_stream(oc, NULL)))
168             return AVERROR(ENOMEM);
169         icodec = s->streams[i]->codec;
170         ocodec = st->codec;
171         avcodec_copy_context(ocodec, icodec);
172         if (!oc->oformat->codec_tag ||
173             av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
174             av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
175             ocodec->codec_tag = icodec->codec_tag;
176         } else {
177             ocodec->codec_tag = 0;
178         }
179         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
180         st->time_base = s->streams[i]->time_base;
181         av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
182     }
183
184     return 0;
185 }
186
187 static int set_segment_filename(AVFormatContext *s)
188 {
189     SegmentContext *seg = s->priv_data;
190     AVFormatContext *oc = seg->avf;
191     size_t size;
192     int ret;
193
194     if (seg->segment_idx_wrap)
195         seg->segment_idx %= seg->segment_idx_wrap;
196     if (seg->use_strftime) {
197         time_t now0;
198         struct tm *tm, tmpbuf;
199         time(&now0);
200         tm = localtime_r(&now0, &tmpbuf);
201         if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
202             av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
203             return AVERROR(EINVAL);
204         }
205     } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
206                                      s->filename, seg->segment_idx) < 0) {
207         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
208         return AVERROR(EINVAL);
209     }
210
211     /* copy modified name in list entry */
212     size = strlen(av_basename(oc->filename)) + 1;
213     if (seg->entry_prefix)
214         size += strlen(seg->entry_prefix);
215
216     if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
217         return ret;
218     snprintf(seg->cur_entry.filename, size, "%s%s",
219              seg->entry_prefix ? seg->entry_prefix : "",
220              av_basename(oc->filename));
221
222     return 0;
223 }
224
225 static int segment_start(AVFormatContext *s, int write_header)
226 {
227     SegmentContext *seg = s->priv_data;
228     AVFormatContext *oc = seg->avf;
229     int err = 0;
230
231     if (write_header) {
232         avformat_free_context(oc);
233         seg->avf = NULL;
234         if ((err = segment_mux_init(s)) < 0)
235             return err;
236         oc = seg->avf;
237     }
238
239     seg->segment_idx++;
240     if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
241         seg->segment_idx_wrap_nb++;
242
243     if ((err = set_segment_filename(s)) < 0)
244         return err;
245
246     if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0) {
247         av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
248         return err;
249     }
250     if (!seg->individual_header_trailer)
251         oc->pb->seekable = 0;
252
253     if (oc->oformat->priv_class && oc->priv_data)
254         av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
255
256     if (write_header) {
257         if ((err = avformat_write_header(oc, NULL)) < 0)
258             return err;
259     }
260
261     seg->segment_frame_count = 0;
262     return 0;
263 }
264
265 static int segment_list_open(AVFormatContext *s)
266 {
267     SegmentContext *seg = s->priv_data;
268     int ret;
269
270     snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
271     ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
272     if (ret < 0) {
273         av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
274         return ret;
275     }
276
277     if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
278         SegmentListEntry *entry;
279         double max_duration = 0;
280
281         avio_printf(seg->list_pb, "#EXTM3U\n");
282         avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
283         avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
284         avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
285                     seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
286
287         av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
288                seg->segment_list_entries->index);
289
290         for (entry = seg->segment_list_entries; entry; entry = entry->next)
291             max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
292         avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
293     } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
294         avio_printf(seg->list_pb, "ffconcat version 1.0\n");
295     }
296
297     return ret;
298 }
299
300 static void segment_list_print_entry(AVIOContext      *list_ioctx,
301                                      ListType          list_type,
302                                      const SegmentListEntry *list_entry,
303                                      void *log_ctx)
304 {
305     switch (list_type) {
306     case LIST_TYPE_FLAT:
307         avio_printf(list_ioctx, "%s\n", list_entry->filename);
308         break;
309     case LIST_TYPE_CSV:
310     case LIST_TYPE_EXT:
311         print_csv_escaped_str(list_ioctx, list_entry->filename);
312         avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
313         break;
314     case LIST_TYPE_M3U8:
315         avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
316                     list_entry->end_time - list_entry->start_time, list_entry->filename);
317         break;
318     case LIST_TYPE_FFCONCAT:
319     {
320         char *buf;
321         if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
322             av_log(log_ctx, AV_LOG_WARNING,
323                    "Error writing list entry '%s' in list file\n", list_entry->filename);
324             return;
325         }
326         avio_printf(list_ioctx, "file %s\n", buf);
327         av_free(buf);
328         break;
329     }
330     default:
331         av_assert0(!"Invalid list type");
332     }
333 }
334
335 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
336 {
337     SegmentContext *seg = s->priv_data;
338     AVFormatContext *oc = seg->avf;
339     int ret = 0;
340
341     av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
342     if (write_trailer)
343         ret = av_write_trailer(oc);
344
345     if (ret < 0)
346         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
347                oc->filename);
348
349     if (seg->list) {
350         if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
351             SegmentListEntry *entry = av_mallocz(sizeof(*entry));
352             if (!entry) {
353                 ret = AVERROR(ENOMEM);
354                 goto end;
355             }
356
357             /* append new element */
358             memcpy(entry, &seg->cur_entry, sizeof(*entry));
359             entry->filename = av_strdup(entry->filename);
360             if (!seg->segment_list_entries)
361                 seg->segment_list_entries = seg->segment_list_entries_end = entry;
362             else
363                 seg->segment_list_entries_end->next = entry;
364             seg->segment_list_entries_end = entry;
365
366             /* drop first item */
367             if (seg->list_size && seg->segment_count >= seg->list_size) {
368                 entry = seg->segment_list_entries;
369                 seg->segment_list_entries = seg->segment_list_entries->next;
370                 av_freep(&entry->filename);
371                 av_freep(&entry);
372             }
373
374             if ((ret = segment_list_open(s)) < 0)
375                 goto end;
376             for (entry = seg->segment_list_entries; entry; entry = entry->next)
377                 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
378             if (seg->list_type == LIST_TYPE_M3U8 && is_last)
379                 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
380             ff_format_io_close(s, &seg->list_pb);
381             if (seg->use_rename)
382                 ff_rename(seg->temp_list_filename, seg->list, s);
383         } else {
384             segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
385             avio_flush(seg->list_pb);
386         }
387     }
388
389     av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
390            seg->avf->filename, seg->segment_count);
391     seg->segment_count++;
392
393 end:
394     ff_format_io_close(oc, &oc->pb);
395
396     return ret;
397 }
398
399 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
400                        const char *times_str)
401 {
402     char *p;
403     int i, ret = 0;
404     char *times_str1 = av_strdup(times_str);
405     char *saveptr = NULL;
406
407     if (!times_str1)
408         return AVERROR(ENOMEM);
409
410 #define FAIL(err) ret = err; goto end
411
412     *nb_times = 1;
413     for (p = times_str1; *p; p++)
414         if (*p == ',')
415             (*nb_times)++;
416
417     *times = av_malloc_array(*nb_times, sizeof(**times));
418     if (!*times) {
419         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
420         FAIL(AVERROR(ENOMEM));
421     }
422
423     p = times_str1;
424     for (i = 0; i < *nb_times; i++) {
425         int64_t t;
426         char *tstr = av_strtok(p, ",", &saveptr);
427         p = NULL;
428
429         if (!tstr || !tstr[0]) {
430             av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
431                    times_str);
432             FAIL(AVERROR(EINVAL));
433         }
434
435         ret = av_parse_time(&t, tstr, 1);
436         if (ret < 0) {
437             av_log(log_ctx, AV_LOG_ERROR,
438                    "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
439             FAIL(AVERROR(EINVAL));
440         }
441         (*times)[i] = t;
442
443         /* check on monotonicity */
444         if (i && (*times)[i-1] > (*times)[i]) {
445             av_log(log_ctx, AV_LOG_ERROR,
446                    "Specified time %f is greater than the following time %f\n",
447                    (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
448             FAIL(AVERROR(EINVAL));
449         }
450     }
451
452 end:
453     av_free(times_str1);
454     return ret;
455 }
456
457 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
458                         const char *frames_str)
459 {
460     char *p;
461     int i, ret = 0;
462     char *frames_str1 = av_strdup(frames_str);
463     char *saveptr = NULL;
464
465     if (!frames_str1)
466         return AVERROR(ENOMEM);
467
468 #define FAIL(err) ret = err; goto end
469
470     *nb_frames = 1;
471     for (p = frames_str1; *p; p++)
472         if (*p == ',')
473             (*nb_frames)++;
474
475     *frames = av_malloc_array(*nb_frames, sizeof(**frames));
476     if (!*frames) {
477         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
478         FAIL(AVERROR(ENOMEM));
479     }
480
481     p = frames_str1;
482     for (i = 0; i < *nb_frames; i++) {
483         long int f;
484         char *tailptr;
485         char *fstr = av_strtok(p, ",", &saveptr);
486
487         p = NULL;
488         if (!fstr) {
489             av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
490                    frames_str);
491             FAIL(AVERROR(EINVAL));
492         }
493         f = strtol(fstr, &tailptr, 10);
494         if (*tailptr || f <= 0 || f >= INT_MAX) {
495             av_log(log_ctx, AV_LOG_ERROR,
496                    "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
497                    fstr);
498             FAIL(AVERROR(EINVAL));
499         }
500         (*frames)[i] = f;
501
502         /* check on monotonicity */
503         if (i && (*frames)[i-1] > (*frames)[i]) {
504             av_log(log_ctx, AV_LOG_ERROR,
505                    "Specified frame %d is greater than the following frame %d\n",
506                    (*frames)[i], (*frames)[i-1]);
507             FAIL(AVERROR(EINVAL));
508         }
509     }
510
511 end:
512     av_free(frames_str1);
513     return ret;
514 }
515
516 static int open_null_ctx(AVIOContext **ctx)
517 {
518     int buf_size = 32768;
519     uint8_t *buf = av_malloc(buf_size);
520     if (!buf)
521         return AVERROR(ENOMEM);
522     *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
523     if (!*ctx) {
524         av_free(buf);
525         return AVERROR(ENOMEM);
526     }
527     return 0;
528 }
529
530 static void close_null_ctxp(AVIOContext **pb)
531 {
532     av_freep(&(*pb)->buffer);
533     av_freep(pb);
534 }
535
536 static int select_reference_stream(AVFormatContext *s)
537 {
538     SegmentContext *seg = s->priv_data;
539     int ret, i;
540
541     seg->reference_stream_index = -1;
542     if (!strcmp(seg->reference_stream_specifier, "auto")) {
543         /* select first index of type with highest priority */
544         int type_index_map[AVMEDIA_TYPE_NB];
545         static const enum AVMediaType type_priority_list[] = {
546             AVMEDIA_TYPE_VIDEO,
547             AVMEDIA_TYPE_AUDIO,
548             AVMEDIA_TYPE_SUBTITLE,
549             AVMEDIA_TYPE_DATA,
550             AVMEDIA_TYPE_ATTACHMENT
551         };
552         enum AVMediaType type;
553
554         for (i = 0; i < AVMEDIA_TYPE_NB; i++)
555             type_index_map[i] = -1;
556
557         /* select first index for each type */
558         for (i = 0; i < s->nb_streams; i++) {
559             type = s->streams[i]->codec->codec_type;
560             if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
561                 /* ignore attached pictures/cover art streams */
562                 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
563                 type_index_map[type] = i;
564         }
565
566         for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
567             type = type_priority_list[i];
568             if ((seg->reference_stream_index = type_index_map[type]) >= 0)
569                 break;
570         }
571     } else {
572         for (i = 0; i < s->nb_streams; i++) {
573             ret = avformat_match_stream_specifier(s, s->streams[i],
574                                                   seg->reference_stream_specifier);
575             if (ret < 0)
576                 return ret;
577             if (ret > 0) {
578                 seg->reference_stream_index = i;
579                 break;
580             }
581         }
582     }
583
584     if (seg->reference_stream_index < 0) {
585         av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
586                seg->reference_stream_specifier);
587         return AVERROR(EINVAL);
588     }
589
590     return 0;
591 }
592
593 static void seg_free_context(SegmentContext *seg)
594 {
595     ff_format_io_close(seg->avf, &seg->list_pb);
596     avformat_free_context(seg->avf);
597     seg->avf = NULL;
598 }
599
600 static int seg_write_header(AVFormatContext *s)
601 {
602     SegmentContext *seg = s->priv_data;
603     AVFormatContext *oc = NULL;
604     AVDictionary *options = NULL;
605     int ret;
606     int i;
607
608     seg->segment_count = 0;
609     if (!seg->write_header_trailer)
610         seg->individual_header_trailer = 0;
611
612     if (seg->header_filename) {
613         seg->write_header_trailer = 1;
614         seg->individual_header_trailer = 0;
615     }
616
617     if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
618         av_log(s, AV_LOG_ERROR,
619                "segment_time, segment_times, and segment_frames options "
620                "are mutually exclusive, select just one of them\n");
621         return AVERROR(EINVAL);
622     }
623
624     if (seg->times_str) {
625         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
626             return ret;
627     } else if (seg->frames_str) {
628         if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
629             return ret;
630     } else {
631         /* set default value if not specified */
632         if (!seg->time_str)
633             seg->time_str = av_strdup("2");
634         if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
635             av_log(s, AV_LOG_ERROR,
636                    "Invalid time duration specification '%s' for segment_time option\n",
637                    seg->time_str);
638             return ret;
639         }
640         if (seg->use_clocktime) {
641             if (seg->time <= 0) {
642                 av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
643                 return AVERROR(EINVAL);
644             }
645             seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
646         }
647     }
648
649     if (seg->format_options_str) {
650         ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
651         if (ret < 0) {
652             av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
653                    seg->format_options_str);
654             goto fail;
655         }
656     }
657
658     if (seg->list) {
659         if (seg->list_type == LIST_TYPE_UNDEFINED) {
660             if      (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
661             else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
662             else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
663             else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
664             else                                      seg->list_type = LIST_TYPE_FLAT;
665         }
666         if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
667             if ((ret = segment_list_open(s)) < 0)
668                 goto fail;
669         } else {
670             const char *proto = avio_find_protocol_name(s->filename);
671             seg->use_rename = proto && !strcmp(proto, "file");
672         }
673     }
674     if (seg->list_type == LIST_TYPE_EXT)
675         av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
676
677     if ((ret = select_reference_stream(s)) < 0)
678         goto fail;
679     av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
680            seg->reference_stream_index,
681            av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
682
683     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
684
685     if (!seg->oformat) {
686         ret = AVERROR_MUXER_NOT_FOUND;
687         goto fail;
688     }
689     if (seg->oformat->flags & AVFMT_NOFILE) {
690         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
691                seg->oformat->name);
692         ret = AVERROR(EINVAL);
693         goto fail;
694     }
695
696     if ((ret = segment_mux_init(s)) < 0)
697         goto fail;
698     oc = seg->avf;
699
700     if ((ret = set_segment_filename(s)) < 0)
701         goto fail;
702
703     if (seg->write_header_trailer) {
704         if ((ret = s->io_open(s, &oc->pb,
705                               seg->header_filename ? seg->header_filename : oc->filename,
706                               AVIO_FLAG_WRITE, NULL)) < 0) {
707             av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
708             goto fail;
709         }
710         if (!seg->individual_header_trailer)
711             oc->pb->seekable = 0;
712     } else {
713         if ((ret = open_null_ctx(&oc->pb)) < 0)
714             goto fail;
715     }
716
717     av_dict_copy(&options, seg->format_options, 0);
718     ret = avformat_write_header(oc, &options);
719     if (av_dict_count(options)) {
720         av_log(s, AV_LOG_ERROR,
721                "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
722         ret = AVERROR(EINVAL);
723         goto fail;
724     }
725
726     if (ret < 0) {
727         ff_format_io_close(oc, &oc->pb);
728         goto fail;
729     }
730     seg->segment_frame_count = 0;
731
732     av_assert0(s->nb_streams == oc->nb_streams);
733     for (i = 0; i < s->nb_streams; i++) {
734         AVStream *inner_st  = oc->streams[i];
735         AVStream *outer_st = s->streams[i];
736         avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
737     }
738
739     if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
740         s->avoid_negative_ts = 1;
741
742     if (!seg->write_header_trailer || seg->header_filename) {
743         if (seg->header_filename) {
744             av_write_frame(oc, NULL);
745             ff_format_io_close(oc, &oc->pb);
746         } else {
747             close_null_ctxp(&oc->pb);
748         }
749         if ((ret = oc->io_open(oc, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0)
750             goto fail;
751         if (!seg->individual_header_trailer)
752             oc->pb->seekable = 0;
753     }
754
755 fail:
756     av_dict_free(&options);
757     if (ret < 0)
758         seg_free_context(seg);
759
760     return ret;
761 }
762
763 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
764 {
765     SegmentContext *seg = s->priv_data;
766     AVStream *st = s->streams[pkt->stream_index];
767     int64_t end_pts = INT64_MAX, offset;
768     int start_frame = INT_MAX;
769     int ret;
770     struct tm ti;
771     int64_t usecs;
772     int64_t wrapped_val;
773
774     if (!seg->avf)
775         return AVERROR(EINVAL);
776
777     if (seg->times) {
778         end_pts = seg->segment_count < seg->nb_times ?
779             seg->times[seg->segment_count] : INT64_MAX;
780     } else if (seg->frames) {
781         start_frame = seg->segment_count < seg->nb_frames ?
782             seg->frames[seg->segment_count] : INT_MAX;
783     } else {
784         if (seg->use_clocktime) {
785             int64_t avgt = av_gettime();
786             time_t sec = avgt / 1000000;
787             localtime_r(&sec, &ti);
788             usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
789             wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
790             if (seg->last_cut != usecs && wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) {
791                 seg->cut_pending = 1;
792                 seg->last_cut = usecs;
793             }
794             seg->last_val = wrapped_val;
795         } else {
796             end_pts = seg->time * (seg->segment_count + 1);
797         }
798     }
799
800     ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
801             pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
802             av_ts2timestr(pkt->duration, &st->time_base),
803             pkt->flags & AV_PKT_FLAG_KEY,
804             pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
805
806     if (pkt->stream_index == seg->reference_stream_index &&
807         (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
808         seg->segment_frame_count > 0 &&
809         (seg->cut_pending || seg->frame_count >= start_frame ||
810          (pkt->pts != AV_NOPTS_VALUE &&
811           av_compare_ts(pkt->pts, st->time_base,
812                         end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
813         /* sanitize end time in case last packet didn't have a defined duration */
814         if (seg->cur_entry.last_duration == 0)
815             seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
816
817         if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
818             goto fail;
819
820         if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
821             goto fail;
822
823         seg->cut_pending = 0;
824         seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
825         seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
826         seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
827         seg->cur_entry.end_time = seg->cur_entry.start_time +
828             pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
829     } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
830         seg->cur_entry.end_time =
831             FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
832         seg->cur_entry.last_duration = pkt->duration;
833     }
834
835     if (seg->segment_frame_count == 0) {
836         av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
837                seg->avf->filename, pkt->stream_index,
838                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
839     }
840
841     av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
842            pkt->stream_index,
843            av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
844            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
845            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
846
847     /* compute new timestamps */
848     offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
849                           AV_TIME_BASE_Q, st->time_base);
850     if (pkt->pts != AV_NOPTS_VALUE)
851         pkt->pts += offset;
852     if (pkt->dts != AV_NOPTS_VALUE)
853         pkt->dts += offset;
854
855     av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
856            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
857            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
858
859     ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
860
861 fail:
862     if (pkt->stream_index == seg->reference_stream_index) {
863         seg->frame_count++;
864         seg->segment_frame_count++;
865     }
866
867     if (ret < 0)
868         seg_free_context(seg);
869
870     return ret;
871 }
872
873 static int seg_write_trailer(struct AVFormatContext *s)
874 {
875     SegmentContext *seg = s->priv_data;
876     AVFormatContext *oc = seg->avf;
877     SegmentListEntry *cur, *next;
878     int ret = 0;
879
880     if (!oc)
881         goto fail;
882
883     if (!seg->write_header_trailer) {
884         if ((ret = segment_end(s, 0, 1)) < 0)
885             goto fail;
886         if ((ret = open_null_ctx(&oc->pb)) < 0)
887             goto fail;
888         ret = av_write_trailer(oc);
889         close_null_ctxp(&oc->pb);
890     } else {
891         ret = segment_end(s, 1, 1);
892     }
893 fail:
894     if (seg->list)
895         ff_format_io_close(s, &seg->list_pb);
896
897     av_dict_free(&seg->format_options);
898     av_opt_free(seg);
899     av_freep(&seg->times);
900     av_freep(&seg->frames);
901     av_freep(&seg->cur_entry.filename);
902
903     cur = seg->segment_list_entries;
904     while (cur) {
905         next = cur->next;
906         av_freep(&cur->filename);
907         av_free(cur);
908         cur = next;
909     }
910
911     avformat_free_context(oc);
912     seg->avf = NULL;
913     return ret;
914 }
915
916 #define OFFSET(x) offsetof(SegmentContext, x)
917 #define E AV_OPT_FLAG_ENCODING_PARAM
918 static const AVOption options[] = {
919     { "reference_stream",  "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
920     { "segment_format",    "set container format used for the segments", OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
921     { "segment_format_options", "set list of options for the container format used for the segments", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
922     { "segment_list",      "set the segment list filename",              OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
923     { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
924
925     { "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"},
926     { "cache",             "allow list caching",                                    0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX,   E, "list_flags"},
927     { "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"},
928
929     { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT,  {.i64 = 0},     0, INT_MAX, E },
930
931     { "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" },
932     { "flat", "flat format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
933     { "csv",  "csv format",      0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV  }, INT_MIN, INT_MAX, E, "list_type" },
934     { "ext",  "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT  }, INT_MIN, INT_MAX, E, "list_type" },
935     { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
936     { "m3u8", "M3U8 format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
937     { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
938
939     { "segment_atclocktime",      "set segment to be cut at clocktime",  OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
940     { "segment_clocktime_offset", "set segment clocktime offset",        OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
941     { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
942     { "segment_time",      "set segment duration",                       OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
943     { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
944     { "segment_times",     "set segment split time points",              OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
945     { "segment_frames",    "set segment split frame numbers",            OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
946     { "segment_wrap",      "set number after which the index wraps",     OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
947     { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING,  {.str = NULL}, 0, 0, E },
948     { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
949     { "segment_wrap_number", "set the number of wrap before the first segment", OFFSET(segment_idx_wrap_nb), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
950     { "strftime",          "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
951     { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
952
953     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
954     { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
955     { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
956     { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
957     { NULL },
958 };
959
960 static const AVClass seg_class = {
961     .class_name = "segment muxer",
962     .item_name  = av_default_item_name,
963     .option     = options,
964     .version    = LIBAVUTIL_VERSION_INT,
965 };
966
967 AVOutputFormat ff_segment_muxer = {
968     .name           = "segment",
969     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
970     .priv_data_size = sizeof(SegmentContext),
971     .flags          = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
972     .write_header   = seg_write_header,
973     .write_packet   = seg_write_packet,
974     .write_trailer  = seg_write_trailer,
975     .priv_class     = &seg_class,
976 };
977
978 static const AVClass sseg_class = {
979     .class_name = "stream_segment muxer",
980     .item_name  = av_default_item_name,
981     .option     = options,
982     .version    = LIBAVUTIL_VERSION_INT,
983 };
984
985 AVOutputFormat ff_stream_segment_muxer = {
986     .name           = "stream_segment,ssegment",
987     .long_name      = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
988     .priv_data_size = sizeof(SegmentContext),
989     .flags          = AVFMT_NOFILE,
990     .write_header   = seg_write_header,
991     .write_packet   = seg_write_packet,
992     .write_trailer  = seg_write_trailer,
993     .priv_class     = &sseg_class,
994 };