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