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