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