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