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