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