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