]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
Merge commit 'db158f0dd217cf839be8af195d66cf49a76537a8'
[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     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_closep(&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_closep(&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 void seg_free_context(SegmentContext *seg)
578 {
579     avio_closep(&seg->list_pb);
580     avformat_free_context(seg->avf);
581     seg->avf = NULL;
582 }
583
584 static int seg_write_header(AVFormatContext *s)
585 {
586     SegmentContext *seg = s->priv_data;
587     AVFormatContext *oc = NULL;
588     AVDictionary *options = NULL;
589     int ret;
590     int i;
591
592     seg->segment_count = 0;
593     if (!seg->write_header_trailer)
594         seg->individual_header_trailer = 0;
595
596     if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
597         av_log(s, AV_LOG_ERROR,
598                "segment_time, segment_times, and segment_frames options "
599                "are mutually exclusive, select just one of them\n");
600         return AVERROR(EINVAL);
601     }
602
603     if (seg->times_str) {
604         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
605             return ret;
606     } else if (seg->frames_str) {
607         if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
608             return ret;
609     } else {
610         /* set default value if not specified */
611         if (!seg->time_str)
612             seg->time_str = av_strdup("2");
613         if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
614             av_log(s, AV_LOG_ERROR,
615                    "Invalid time duration specification '%s' for segment_time option\n",
616                    seg->time_str);
617             return ret;
618         }
619     }
620
621     if (seg->format_options_str) {
622         ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
623         if (ret < 0) {
624             av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
625                    seg->format_options_str);
626             goto fail;
627         }
628     }
629
630     if (seg->list) {
631         if (seg->list_type == LIST_TYPE_UNDEFINED) {
632             if      (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
633             else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
634             else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
635             else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
636             else                                      seg->list_type = LIST_TYPE_FLAT;
637         }
638         if ((ret = segment_list_open(s)) < 0)
639             goto fail;
640     }
641     if (seg->list_type == LIST_TYPE_EXT)
642         av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
643
644     if ((ret = select_reference_stream(s)) < 0)
645         goto fail;
646     av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
647            seg->reference_stream_index,
648            av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
649
650     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
651
652     if (!seg->oformat) {
653         ret = AVERROR_MUXER_NOT_FOUND;
654         goto fail;
655     }
656     if (seg->oformat->flags & AVFMT_NOFILE) {
657         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
658                seg->oformat->name);
659         ret = AVERROR(EINVAL);
660         goto fail;
661     }
662
663     if ((ret = segment_mux_init(s)) < 0)
664         goto fail;
665     oc = seg->avf;
666
667     if ((ret = set_segment_filename(s)) < 0)
668         goto fail;
669
670     if (seg->write_header_trailer) {
671         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
672                               &s->interrupt_callback, NULL)) < 0) {
673             av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
674             goto fail;
675         }
676     } else {
677         if ((ret = open_null_ctx(&oc->pb)) < 0)
678             goto fail;
679     }
680
681     av_dict_copy(&options, seg->format_options, 0);
682     ret = avformat_write_header(oc, &options);
683     if (av_dict_count(options)) {
684         av_log(s, AV_LOG_ERROR,
685                "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
686         ret = AVERROR(EINVAL);
687         goto fail;
688     }
689
690     if (ret < 0) {
691         avio_closep(&oc->pb);
692         goto fail;
693     }
694     seg->segment_frame_count = 0;
695
696     av_assert0(s->nb_streams == oc->nb_streams);
697     for (i = 0; i < s->nb_streams; i++) {
698         AVStream *inner_st  = oc->streams[i];
699         AVStream *outer_st = s->streams[i];
700         avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
701     }
702
703     if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
704         s->avoid_negative_ts = 1;
705
706     if (!seg->write_header_trailer) {
707         close_null_ctxp(&oc->pb);
708         if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
709                               &s->interrupt_callback, NULL)) < 0)
710             goto fail;
711     }
712
713 fail:
714     av_dict_free(&options);
715     if (ret < 0)
716         seg_free_context(seg);
717
718     return ret;
719 }
720
721 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
722 {
723     SegmentContext *seg = s->priv_data;
724     AVStream *st = s->streams[pkt->stream_index];
725     int64_t end_pts = INT64_MAX, offset;
726     int start_frame = INT_MAX;
727     int ret;
728     struct tm ti;
729     int64_t usecs;
730     int64_t wrapped_val;
731
732     if (!seg->avf)
733         return AVERROR(EINVAL);
734
735     if (seg->times) {
736         end_pts = seg->segment_count < seg->nb_times ?
737             seg->times[seg->segment_count] : INT64_MAX;
738     } else if (seg->frames) {
739         start_frame = seg->segment_count < seg->nb_frames ?
740             seg->frames[seg->segment_count] : INT_MAX;
741     } else {
742         if (seg->use_clocktime) {
743             int64_t avgt = av_gettime();
744             time_t sec = avgt / 1000000;
745             localtime_r(&sec, &ti);
746             usecs = (int64_t)(ti.tm_hour*3600 + ti.tm_min*60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
747             wrapped_val = usecs % seg->time;
748             if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
749                 seg->cut_pending = 1;
750                 seg->last_cut = usecs;
751             }
752             seg->last_val = wrapped_val;
753         } else {
754             end_pts = seg->time * (seg->segment_count+1);
755         }
756     }
757
758     av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
759             pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
760             av_ts2timestr(pkt->duration, &st->time_base),
761             pkt->flags & AV_PKT_FLAG_KEY,
762             pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
763
764     if (pkt->stream_index == seg->reference_stream_index &&
765         pkt->flags & AV_PKT_FLAG_KEY &&
766         seg->segment_frame_count > 0 &&
767         (seg->cut_pending || seg->frame_count >= start_frame ||
768          (pkt->pts != AV_NOPTS_VALUE &&
769           av_compare_ts(pkt->pts, st->time_base,
770                         end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
771         /* sanitize end time in case last packet didn't have a defined duration */
772         if (seg->cur_entry.last_duration == 0)
773             seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
774
775         if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
776             goto fail;
777
778         if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
779             goto fail;
780
781         seg->cut_pending = 0;
782         seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap*seg->segment_idx_wrap_nb;
783         seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
784         seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
785         seg->cur_entry.end_time = seg->cur_entry.start_time +
786             pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
787     } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
788         seg->cur_entry.end_time =
789             FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
790         seg->cur_entry.last_duration = pkt->duration;
791     }
792
793     if (seg->segment_frame_count == 0) {
794         av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
795                seg->avf->filename, pkt->stream_index,
796                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
797     }
798
799     av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
800            pkt->stream_index,
801            av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
802            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
803            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
804
805     /* compute new timestamps */
806     offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
807                           AV_TIME_BASE_Q, st->time_base);
808     if (pkt->pts != AV_NOPTS_VALUE)
809         pkt->pts += offset;
810     if (pkt->dts != AV_NOPTS_VALUE)
811         pkt->dts += offset;
812
813     av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
814            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
815            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
816
817     ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
818
819 fail:
820     if (pkt->stream_index == seg->reference_stream_index) {
821         seg->frame_count++;
822         seg->segment_frame_count++;
823     }
824
825     if (ret < 0)
826         seg_free_context(seg);
827
828     return ret;
829 }
830
831 static int seg_write_trailer(struct AVFormatContext *s)
832 {
833     SegmentContext *seg = s->priv_data;
834     AVFormatContext *oc = seg->avf;
835     SegmentListEntry *cur, *next;
836     int ret = 0;
837
838     if (!oc)
839         goto fail;
840
841     if (!seg->write_header_trailer) {
842         if ((ret = segment_end(s, 0, 1)) < 0)
843             goto fail;
844         open_null_ctx(&oc->pb);
845         ret = av_write_trailer(oc);
846         close_null_ctxp(&oc->pb);
847     } else {
848         ret = segment_end(s, 1, 1);
849     }
850 fail:
851     if (seg->list)
852         avio_closep(&seg->list_pb);
853
854     av_dict_free(&seg->format_options);
855     av_opt_free(seg);
856     av_freep(&seg->times);
857     av_freep(&seg->frames);
858
859     cur = seg->segment_list_entries;
860     while (cur) {
861         next = cur->next;
862         av_freep(&cur->filename);
863         av_free(cur);
864         cur = next;
865     }
866
867     avformat_free_context(oc);
868     seg->avf = NULL;
869     return ret;
870 }
871
872 #define OFFSET(x) offsetof(SegmentContext, x)
873 #define E AV_OPT_FLAG_ENCODING_PARAM
874 static const AVOption options[] = {
875     { "reference_stream",  "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
876     { "segment_format",    "set container format used for the segments", OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
877     { "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 },
878     { "segment_list",      "set the segment list filename",              OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
879
880     { "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"},
881     { "cache",             "allow list caching",                                    0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX,   E, "list_flags"},
882     { "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"},
883
884     { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT,  {.i64 = 0},     0, INT_MAX, E },
885
886     { "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" },
887     { "flat", "flat format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
888     { "csv",  "csv format",      0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV  }, INT_MIN, INT_MAX, E, "list_type" },
889     { "ext",  "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT  }, INT_MIN, INT_MAX, E, "list_type" },
890     { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
891     { "m3u8", "M3U8 format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
892     { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
893
894     { "segment_atclocktime",      "set segment to be cut at clocktime",  OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
895     { "segment_time",      "set segment duration",                       OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
896     { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
897     { "segment_times",     "set segment split time points",              OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
898     { "segment_frames",    "set segment split frame numbers",            OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
899     { "segment_wrap",      "set number after which the index wraps",     OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
900     { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING,  {.str = NULL}, 0, 0, E },
901     { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
902     { "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 },
903     { "strftime",          "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
904
905     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
906     { "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 },
907     { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
908     { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
909     { NULL },
910 };
911
912 static const AVClass seg_class = {
913     .class_name = "segment muxer",
914     .item_name  = av_default_item_name,
915     .option     = options,
916     .version    = LIBAVUTIL_VERSION_INT,
917 };
918
919 AVOutputFormat ff_segment_muxer = {
920     .name           = "segment",
921     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
922     .priv_data_size = sizeof(SegmentContext),
923     .flags          = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
924     .write_header   = seg_write_header,
925     .write_packet   = seg_write_packet,
926     .write_trailer  = seg_write_trailer,
927     .priv_class     = &seg_class,
928 };
929
930 static const AVClass sseg_class = {
931     .class_name = "stream_segment muxer",
932     .item_name  = av_default_item_name,
933     .option     = options,
934     .version    = LIBAVUTIL_VERSION_INT,
935 };
936
937 AVOutputFormat ff_stream_segment_muxer = {
938     .name           = "stream_segment,ssegment",
939     .long_name      = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
940     .priv_data_size = sizeof(SegmentContext),
941     .flags          = AVFMT_NOFILE,
942     .write_header   = seg_write_header,
943     .write_packet   = seg_write_packet,
944     .write_trailer  = seg_write_trailer,
945     .priv_class     = &sseg_class,
946 };