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