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