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