]> git.sesse.net Git - ffmpeg/blob - libavformat/segment.c
avformat: support shorten in nistshpere demuxer
[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 #include <time.h>
31
32 #include "avformat.h"
33 #include "avio_internal.h"
34 #include "internal.h"
35
36 #include "libavutil/avassert.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/log.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/avstring.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/time.h"
44 #include "libavutil/timecode.h"
45 #include "libavutil/time_internal.h"
46 #include "libavutil/timestamp.h"
47
48 typedef struct SegmentListEntry {
49     int index;
50     double start_time, end_time;
51     int64_t start_pts;
52     int64_t offset_pts;
53     char *filename;
54     struct SegmentListEntry *next;
55     int64_t last_duration;
56 } SegmentListEntry;
57
58 typedef enum {
59     LIST_TYPE_UNDEFINED = -1,
60     LIST_TYPE_FLAT = 0,
61     LIST_TYPE_CSV,
62     LIST_TYPE_M3U8,
63     LIST_TYPE_EXT, ///< deprecated
64     LIST_TYPE_FFCONCAT,
65     LIST_TYPE_NB,
66 } ListType;
67
68 #define SEGMENT_LIST_FLAG_CACHE 1
69 #define SEGMENT_LIST_FLAG_LIVE  2
70
71 typedef struct SegmentContext {
72     const AVClass *class;  /**< Class for private options. */
73     int segment_idx;       ///< index of the segment file to write, starting from 0
74     int segment_idx_wrap;  ///< number after which the index wraps
75     int segment_idx_wrap_nb;  ///< number of time the index has wraped
76     int segment_count;     ///< number of segment files already written
77     AVOutputFormat *oformat;
78     AVFormatContext *avf;
79     char *format;              ///< format to use for output segment files
80     char *format_options_str;  ///< format options to use for output segment files
81     AVDictionary *format_options;
82     char *list;            ///< filename for the segment list file
83     int   list_flags;      ///< flags affecting list generation
84     int   list_size;       ///< number of entries for the segment list file
85
86     int use_clocktime;    ///< flag to cut segments at regular clock time
87     int64_t clocktime_offset; //< clock offset for cutting the segments at regular clock time
88     int64_t clocktime_wrap_duration; //< wrapping duration considered for starting a new segment
89     int64_t last_val;      ///< remember last time for wrap around detection
90     int64_t last_cut;      ///< remember last cut
91     int cut_pending;
92
93     char *entry_prefix;    ///< prefix to add to list entry filenames
94     int list_type;         ///< set the list type
95     AVIOContext *list_pb;  ///< list file put-byte context
96     char *time_str;        ///< segment duration specification string
97     int64_t time;          ///< segment duration
98     int use_strftime;      ///< flag to expand filename with strftime
99     int increment_tc;      ///< flag to increment timecode if found
100
101     char *times_str;       ///< segment times specification string
102     int64_t *times;        ///< list of segment interval specification
103     int nb_times;          ///< number of elments in the times array
104
105     char *frames_str;      ///< segment frame numbers specification string
106     int *frames;           ///< list of frame number specification
107     int nb_frames;         ///< number of elments in the frames array
108     int frame_count;       ///< total number of reference frames
109     int segment_frame_count; ///< number of reference frames in the segment
110
111     int64_t time_delta;
112     int  individual_header_trailer; /**< Set by a private option. */
113     int  write_header_trailer; /**< Set by a private option. */
114     char *header_filename;  ///< filename to write the output header to
115
116     int reset_timestamps;  ///< reset timestamps at the begin of each segment
117     int64_t initial_offset;    ///< initial timestamps offset, expressed in microseconds
118     char *reference_stream_specifier; ///< reference stream specifier
119     int   reference_stream_index;
120     int   break_non_keyframes;
121     int   write_empty;
122
123     int use_rename;
124     char temp_list_filename[1024];
125
126     SegmentListEntry cur_entry;
127     SegmentListEntry *segment_list_entries;
128     SegmentListEntry *segment_list_entries_end;
129 } SegmentContext;
130
131 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
132 {
133     int needs_quoting = !!str[strcspn(str, "\",\n\r")];
134
135     if (needs_quoting)
136         avio_w8(ctx, '"');
137
138     for (; *str; str++) {
139         if (*str == '"')
140             avio_w8(ctx, '"');
141         avio_w8(ctx, *str);
142     }
143     if (needs_quoting)
144         avio_w8(ctx, '"');
145 }
146
147 static int segment_mux_init(AVFormatContext *s)
148 {
149     SegmentContext *seg = s->priv_data;
150     AVFormatContext *oc;
151     int i;
152     int ret;
153
154     ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
155     if (ret < 0)
156         return ret;
157     oc = seg->avf;
158
159     oc->interrupt_callback = s->interrupt_callback;
160     oc->max_delay          = s->max_delay;
161     av_dict_copy(&oc->metadata, s->metadata, 0);
162     oc->opaque             = s->opaque;
163     oc->io_close           = s->io_close;
164     oc->io_open            = s->io_open;
165
166     for (i = 0; i < s->nb_streams; i++) {
167         AVStream *st;
168         AVCodecContext *icodec, *ocodec;
169
170         if (!(st = avformat_new_stream(oc, NULL)))
171             return AVERROR(ENOMEM);
172         icodec = s->streams[i]->codec;
173         ocodec = st->codec;
174         avcodec_copy_context(ocodec, icodec);
175         if (!oc->oformat->codec_tag ||
176             av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
177             av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
178             ocodec->codec_tag = icodec->codec_tag;
179         } else {
180             ocodec->codec_tag = 0;
181         }
182         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
183         st->time_base = s->streams[i]->time_base;
184         av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
185     }
186
187     return 0;
188 }
189
190 static int set_segment_filename(AVFormatContext *s)
191 {
192     SegmentContext *seg = s->priv_data;
193     AVFormatContext *oc = seg->avf;
194     size_t size;
195     int ret;
196
197     if (seg->segment_idx_wrap)
198         seg->segment_idx %= seg->segment_idx_wrap;
199     if (seg->use_strftime) {
200         time_t now0;
201         struct tm *tm, tmpbuf;
202         time(&now0);
203         tm = localtime_r(&now0, &tmpbuf);
204         if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
205             av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
206             return AVERROR(EINVAL);
207         }
208     } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
209                                      s->filename, seg->segment_idx) < 0) {
210         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
211         return AVERROR(EINVAL);
212     }
213
214     /* copy modified name in list entry */
215     size = strlen(av_basename(oc->filename)) + 1;
216     if (seg->entry_prefix)
217         size += strlen(seg->entry_prefix);
218
219     if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
220         return ret;
221     snprintf(seg->cur_entry.filename, size, "%s%s",
222              seg->entry_prefix ? seg->entry_prefix : "",
223              av_basename(oc->filename));
224
225     return 0;
226 }
227
228 static int segment_start(AVFormatContext *s, int write_header)
229 {
230     SegmentContext *seg = s->priv_data;
231     AVFormatContext *oc = seg->avf;
232     int err = 0;
233
234     if (write_header) {
235         avformat_free_context(oc);
236         seg->avf = NULL;
237         if ((err = segment_mux_init(s)) < 0)
238             return err;
239         oc = seg->avf;
240     }
241
242     seg->segment_idx++;
243     if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
244         seg->segment_idx_wrap_nb++;
245
246     if ((err = set_segment_filename(s)) < 0)
247         return err;
248
249     if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0) {
250         av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
251         return err;
252     }
253     if (!seg->individual_header_trailer)
254         oc->pb->seekable = 0;
255
256     if (oc->oformat->priv_class && oc->priv_data)
257         av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
258
259     if (write_header) {
260         AVDictionary *options = NULL;
261         av_dict_copy(&options, seg->format_options, 0);
262         err = avformat_write_header(oc, &options);
263         av_dict_free(&options);
264         if (err < 0)
265             return err;
266     }
267
268     seg->segment_frame_count = 0;
269     return 0;
270 }
271
272 static int segment_list_open(AVFormatContext *s)
273 {
274     SegmentContext *seg = s->priv_data;
275     int ret;
276
277     snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
278     ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
279     if (ret < 0) {
280         av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
281         return ret;
282     }
283
284     if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
285         SegmentListEntry *entry;
286         double max_duration = 0;
287
288         avio_printf(seg->list_pb, "#EXTM3U\n");
289         avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
290         avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
291         avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
292                     seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
293
294         av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
295                seg->segment_list_entries->index);
296
297         for (entry = seg->segment_list_entries; entry; entry = entry->next)
298             max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
299         avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
300     } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
301         avio_printf(seg->list_pb, "ffconcat version 1.0\n");
302     }
303
304     return ret;
305 }
306
307 static void segment_list_print_entry(AVIOContext      *list_ioctx,
308                                      ListType          list_type,
309                                      const SegmentListEntry *list_entry,
310                                      void *log_ctx)
311 {
312     switch (list_type) {
313     case LIST_TYPE_FLAT:
314         avio_printf(list_ioctx, "%s\n", list_entry->filename);
315         break;
316     case LIST_TYPE_CSV:
317     case LIST_TYPE_EXT:
318         print_csv_escaped_str(list_ioctx, list_entry->filename);
319         avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
320         break;
321     case LIST_TYPE_M3U8:
322         avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
323                     list_entry->end_time - list_entry->start_time, list_entry->filename);
324         break;
325     case LIST_TYPE_FFCONCAT:
326     {
327         char *buf;
328         if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
329             av_log(log_ctx, AV_LOG_WARNING,
330                    "Error writing list entry '%s' in list file\n", list_entry->filename);
331             return;
332         }
333         avio_printf(list_ioctx, "file %s\n", buf);
334         av_free(buf);
335         break;
336     }
337     default:
338         av_assert0(!"Invalid list type");
339     }
340 }
341
342 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
343 {
344     SegmentContext *seg = s->priv_data;
345     AVFormatContext *oc = seg->avf;
346     int ret = 0;
347     AVTimecode tc;
348     AVRational rate;
349     AVDictionaryEntry *tcr;
350     char buf[AV_TIMECODE_STR_SIZE];
351     int i;
352     int err;
353
354     av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
355     if (write_trailer)
356         ret = av_write_trailer(oc);
357
358     if (ret < 0)
359         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
360                oc->filename);
361
362     if (seg->list) {
363         if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
364             SegmentListEntry *entry = av_mallocz(sizeof(*entry));
365             if (!entry) {
366                 ret = AVERROR(ENOMEM);
367                 goto end;
368             }
369
370             /* append new element */
371             memcpy(entry, &seg->cur_entry, sizeof(*entry));
372             entry->filename = av_strdup(entry->filename);
373             if (!seg->segment_list_entries)
374                 seg->segment_list_entries = seg->segment_list_entries_end = entry;
375             else
376                 seg->segment_list_entries_end->next = entry;
377             seg->segment_list_entries_end = entry;
378
379             /* drop first item */
380             if (seg->list_size && seg->segment_count >= seg->list_size) {
381                 entry = seg->segment_list_entries;
382                 seg->segment_list_entries = seg->segment_list_entries->next;
383                 av_freep(&entry->filename);
384                 av_freep(&entry);
385             }
386
387             if ((ret = segment_list_open(s)) < 0)
388                 goto end;
389             for (entry = seg->segment_list_entries; entry; entry = entry->next)
390                 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
391             if (seg->list_type == LIST_TYPE_M3U8 && is_last)
392                 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
393             ff_format_io_close(s, &seg->list_pb);
394             if (seg->use_rename)
395                 ff_rename(seg->temp_list_filename, seg->list, s);
396         } else {
397             segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
398             avio_flush(seg->list_pb);
399         }
400     }
401
402     av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
403            seg->avf->filename, seg->segment_count);
404     seg->segment_count++;
405
406     if (seg->increment_tc) {
407         tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
408         if (tcr) {
409             /* search the first video stream */
410             for (i = 0; i < s->nb_streams; i++) {
411                 if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
412                     rate = s->streams[i]->avg_frame_rate;/* Get fps from the video stream */
413                     err = av_timecode_init_from_string(&tc, rate, tcr->value, s);
414                     if (err < 0) {
415                         av_log(s, AV_LOG_WARNING, "Could not increment timecode, error occurred during timecode creation.");
416                         break;
417                     }
418                     tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(rate));/* increment timecode */
419                     av_dict_set(&s->metadata, "timecode",
420                                 av_timecode_make_string(&tc, buf, 0), 0);
421                     break;
422                 }
423             }
424         } else {
425             av_log(s, AV_LOG_WARNING, "Could not increment timecode, no timecode metadata found");
426         }
427     }
428
429 end:
430     ff_format_io_close(oc, &oc->pb);
431
432     return ret;
433 }
434
435 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
436                        const char *times_str)
437 {
438     char *p;
439     int i, ret = 0;
440     char *times_str1 = av_strdup(times_str);
441     char *saveptr = NULL;
442
443     if (!times_str1)
444         return AVERROR(ENOMEM);
445
446 #define FAIL(err) ret = err; goto end
447
448     *nb_times = 1;
449     for (p = times_str1; *p; p++)
450         if (*p == ',')
451             (*nb_times)++;
452
453     *times = av_malloc_array(*nb_times, sizeof(**times));
454     if (!*times) {
455         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
456         FAIL(AVERROR(ENOMEM));
457     }
458
459     p = times_str1;
460     for (i = 0; i < *nb_times; i++) {
461         int64_t t;
462         char *tstr = av_strtok(p, ",", &saveptr);
463         p = NULL;
464
465         if (!tstr || !tstr[0]) {
466             av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
467                    times_str);
468             FAIL(AVERROR(EINVAL));
469         }
470
471         ret = av_parse_time(&t, tstr, 1);
472         if (ret < 0) {
473             av_log(log_ctx, AV_LOG_ERROR,
474                    "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
475             FAIL(AVERROR(EINVAL));
476         }
477         (*times)[i] = t;
478
479         /* check on monotonicity */
480         if (i && (*times)[i-1] > (*times)[i]) {
481             av_log(log_ctx, AV_LOG_ERROR,
482                    "Specified time %f is greater than the following time %f\n",
483                    (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
484             FAIL(AVERROR(EINVAL));
485         }
486     }
487
488 end:
489     av_free(times_str1);
490     return ret;
491 }
492
493 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
494                         const char *frames_str)
495 {
496     char *p;
497     int i, ret = 0;
498     char *frames_str1 = av_strdup(frames_str);
499     char *saveptr = NULL;
500
501     if (!frames_str1)
502         return AVERROR(ENOMEM);
503
504 #define FAIL(err) ret = err; goto end
505
506     *nb_frames = 1;
507     for (p = frames_str1; *p; p++)
508         if (*p == ',')
509             (*nb_frames)++;
510
511     *frames = av_malloc_array(*nb_frames, sizeof(**frames));
512     if (!*frames) {
513         av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
514         FAIL(AVERROR(ENOMEM));
515     }
516
517     p = frames_str1;
518     for (i = 0; i < *nb_frames; i++) {
519         long int f;
520         char *tailptr;
521         char *fstr = av_strtok(p, ",", &saveptr);
522
523         p = NULL;
524         if (!fstr) {
525             av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
526                    frames_str);
527             FAIL(AVERROR(EINVAL));
528         }
529         f = strtol(fstr, &tailptr, 10);
530         if (*tailptr || f <= 0 || f >= INT_MAX) {
531             av_log(log_ctx, AV_LOG_ERROR,
532                    "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
533                    fstr);
534             FAIL(AVERROR(EINVAL));
535         }
536         (*frames)[i] = f;
537
538         /* check on monotonicity */
539         if (i && (*frames)[i-1] > (*frames)[i]) {
540             av_log(log_ctx, AV_LOG_ERROR,
541                    "Specified frame %d is greater than the following frame %d\n",
542                    (*frames)[i], (*frames)[i-1]);
543             FAIL(AVERROR(EINVAL));
544         }
545     }
546
547 end:
548     av_free(frames_str1);
549     return ret;
550 }
551
552 static int open_null_ctx(AVIOContext **ctx)
553 {
554     int buf_size = 32768;
555     uint8_t *buf = av_malloc(buf_size);
556     if (!buf)
557         return AVERROR(ENOMEM);
558     *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
559     if (!*ctx) {
560         av_free(buf);
561         return AVERROR(ENOMEM);
562     }
563     return 0;
564 }
565
566 static void close_null_ctxp(AVIOContext **pb)
567 {
568     av_freep(&(*pb)->buffer);
569     av_freep(pb);
570 }
571
572 static int select_reference_stream(AVFormatContext *s)
573 {
574     SegmentContext *seg = s->priv_data;
575     int ret, i;
576
577     seg->reference_stream_index = -1;
578     if (!strcmp(seg->reference_stream_specifier, "auto")) {
579         /* select first index of type with highest priority */
580         int type_index_map[AVMEDIA_TYPE_NB];
581         static const enum AVMediaType type_priority_list[] = {
582             AVMEDIA_TYPE_VIDEO,
583             AVMEDIA_TYPE_AUDIO,
584             AVMEDIA_TYPE_SUBTITLE,
585             AVMEDIA_TYPE_DATA,
586             AVMEDIA_TYPE_ATTACHMENT
587         };
588         enum AVMediaType type;
589
590         for (i = 0; i < AVMEDIA_TYPE_NB; i++)
591             type_index_map[i] = -1;
592
593         /* select first index for each type */
594         for (i = 0; i < s->nb_streams; i++) {
595             type = s->streams[i]->codec->codec_type;
596             if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
597                 /* ignore attached pictures/cover art streams */
598                 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
599                 type_index_map[type] = i;
600         }
601
602         for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
603             type = type_priority_list[i];
604             if ((seg->reference_stream_index = type_index_map[type]) >= 0)
605                 break;
606         }
607     } else {
608         for (i = 0; i < s->nb_streams; i++) {
609             ret = avformat_match_stream_specifier(s, s->streams[i],
610                                                   seg->reference_stream_specifier);
611             if (ret < 0)
612                 return ret;
613             if (ret > 0) {
614                 seg->reference_stream_index = i;
615                 break;
616             }
617         }
618     }
619
620     if (seg->reference_stream_index < 0) {
621         av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
622                seg->reference_stream_specifier);
623         return AVERROR(EINVAL);
624     }
625
626     return 0;
627 }
628
629 static void seg_free_context(SegmentContext *seg)
630 {
631     ff_format_io_close(seg->avf, &seg->list_pb);
632     avformat_free_context(seg->avf);
633     seg->avf = NULL;
634 }
635
636 static int seg_init(AVFormatContext *s)
637 {
638     SegmentContext *seg = s->priv_data;
639     AVFormatContext *oc = seg->avf;
640     AVDictionary *options = NULL;
641     int ret;
642     int i;
643
644     seg->segment_count = 0;
645     if (!seg->write_header_trailer)
646         seg->individual_header_trailer = 0;
647
648     if (seg->header_filename) {
649         seg->write_header_trailer = 1;
650         seg->individual_header_trailer = 0;
651     }
652
653     if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
654         av_log(s, AV_LOG_ERROR,
655                "segment_time, segment_times, and segment_frames options "
656                "are mutually exclusive, select just one of them\n");
657         return AVERROR(EINVAL);
658     }
659
660     if (seg->times_str) {
661         if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
662             return ret;
663     } else if (seg->frames_str) {
664         if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
665             return ret;
666     } else {
667         /* set default value if not specified */
668         if (!seg->time_str)
669             seg->time_str = av_strdup("2");
670         if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
671             av_log(s, AV_LOG_ERROR,
672                    "Invalid time duration specification '%s' for segment_time option\n",
673                    seg->time_str);
674             return ret;
675         }
676         if (seg->use_clocktime) {
677             if (seg->time <= 0) {
678                 av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
679                 return AVERROR(EINVAL);
680             }
681             seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
682         }
683     }
684
685     if (seg->format_options_str) {
686         ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
687         if (ret < 0) {
688             av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
689                    seg->format_options_str);
690             goto fail;
691         }
692     }
693
694     if (seg->list) {
695         if (seg->list_type == LIST_TYPE_UNDEFINED) {
696             if      (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
697             else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
698             else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
699             else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
700             else                                      seg->list_type = LIST_TYPE_FLAT;
701         }
702         if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
703             if ((ret = segment_list_open(s)) < 0)
704                 goto fail;
705         } else {
706             const char *proto = avio_find_protocol_name(s->filename);
707             seg->use_rename = proto && !strcmp(proto, "file");
708         }
709     }
710
711     if (seg->list_type == LIST_TYPE_EXT)
712         av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
713
714     if ((ret = select_reference_stream(s)) < 0)
715         goto fail;
716     av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
717            seg->reference_stream_index,
718            av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
719
720     seg->oformat = av_guess_format(seg->format, s->filename, NULL);
721
722     if (!seg->oformat) {
723         ret = AVERROR_MUXER_NOT_FOUND;
724         goto fail;
725     }
726     if (seg->oformat->flags & AVFMT_NOFILE) {
727         av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
728                seg->oformat->name);
729         ret = AVERROR(EINVAL);
730         goto fail;
731     }
732
733     if ((ret = segment_mux_init(s)) < 0)
734         goto fail;
735
736     if ((ret = set_segment_filename(s)) < 0)
737         goto fail;
738     oc = seg->avf;
739
740     if (seg->write_header_trailer) {
741         if ((ret = s->io_open(s, &oc->pb,
742                               seg->header_filename ? seg->header_filename : oc->filename,
743                               AVIO_FLAG_WRITE, NULL)) < 0) {
744             av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
745             goto fail;
746         }
747         if (!seg->individual_header_trailer)
748             oc->pb->seekable = 0;
749     } else {
750         if ((ret = open_null_ctx(&oc->pb)) < 0)
751             goto fail;
752     }
753
754     av_dict_copy(&options, seg->format_options, 0);
755     ret = avformat_write_header(oc, &options);
756     if (av_dict_count(options)) {
757         av_log(s, AV_LOG_ERROR,
758                "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
759         ret = AVERROR(EINVAL);
760         goto fail;
761     }
762
763     if (ret < 0) {
764         ff_format_io_close(oc, &oc->pb);
765         goto fail;
766     }
767     seg->segment_frame_count = 0;
768
769     av_assert0(s->nb_streams == oc->nb_streams);
770     for (i = 0; i < s->nb_streams; i++) {
771         AVStream *inner_st  = oc->streams[i];
772         AVStream *outer_st = s->streams[i];
773         avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
774     }
775
776     if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
777         s->avoid_negative_ts = 1;
778
779     if (!seg->write_header_trailer || seg->header_filename) {
780         if (seg->header_filename) {
781             av_write_frame(oc, NULL);
782             ff_format_io_close(oc, &oc->pb);
783         } else {
784             close_null_ctxp(&oc->pb);
785         }
786         if ((ret = oc->io_open(oc, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0)
787             goto fail;
788         if (!seg->individual_header_trailer)
789             oc->pb->seekable = 0;
790     }
791
792 fail:
793     av_dict_free(&options);
794     if (ret < 0)
795         seg_free_context(seg);
796
797     return ret;
798 }
799
800 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
801 {
802     SegmentContext *seg = s->priv_data;
803     AVStream *st = s->streams[pkt->stream_index];
804     int64_t end_pts = INT64_MAX, offset;
805     int start_frame = INT_MAX;
806     int ret;
807     struct tm ti;
808     int64_t usecs;
809     int64_t wrapped_val;
810
811     if (!seg->avf)
812         return AVERROR(EINVAL);
813
814 calc_times:
815     if (seg->times) {
816         end_pts = seg->segment_count < seg->nb_times ?
817             seg->times[seg->segment_count] : INT64_MAX;
818     } else if (seg->frames) {
819         start_frame = seg->segment_count < seg->nb_frames ?
820             seg->frames[seg->segment_count] : INT_MAX;
821     } else {
822         if (seg->use_clocktime) {
823             int64_t avgt = av_gettime();
824             time_t sec = avgt / 1000000;
825             localtime_r(&sec, &ti);
826             usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
827             wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
828             if (seg->last_cut != usecs && wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) {
829                 seg->cut_pending = 1;
830                 seg->last_cut = usecs;
831             }
832             seg->last_val = wrapped_val;
833         } else {
834             end_pts = seg->time * (seg->segment_count + 1);
835         }
836     }
837
838     ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
839             pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
840             av_ts2timestr(pkt->duration, &st->time_base),
841             pkt->flags & AV_PKT_FLAG_KEY,
842             pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
843
844     if (pkt->stream_index == seg->reference_stream_index &&
845         (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
846         (seg->segment_frame_count > 0 || seg->write_empty) &&
847         (seg->cut_pending || seg->frame_count >= start_frame ||
848          (pkt->pts != AV_NOPTS_VALUE &&
849           av_compare_ts(pkt->pts, st->time_base,
850                         end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
851         /* sanitize end time in case last packet didn't have a defined duration */
852         if (seg->cur_entry.last_duration == 0)
853             seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
854
855         if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
856             goto fail;
857
858         if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
859             goto fail;
860
861         seg->cut_pending = 0;
862         seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
863         seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
864         seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
865         seg->cur_entry.end_time = seg->cur_entry.start_time;
866
867         if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty)
868             goto calc_times;
869     }
870
871     if (pkt->stream_index == seg->reference_stream_index) {
872         if (pkt->pts != AV_NOPTS_VALUE)
873             seg->cur_entry.end_time =
874                 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
875         seg->cur_entry.last_duration = pkt->duration;
876     }
877
878     if (seg->segment_frame_count == 0) {
879         av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
880                seg->avf->filename, pkt->stream_index,
881                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
882     }
883
884     av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
885            pkt->stream_index,
886            av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
887            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
888            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
889
890     /* compute new timestamps */
891     offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
892                           AV_TIME_BASE_Q, st->time_base);
893     if (pkt->pts != AV_NOPTS_VALUE)
894         pkt->pts += offset;
895     if (pkt->dts != AV_NOPTS_VALUE)
896         pkt->dts += offset;
897
898     av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
899            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
900            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
901
902     ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
903
904 fail:
905     if (pkt->stream_index == seg->reference_stream_index) {
906         seg->frame_count++;
907         seg->segment_frame_count++;
908     }
909
910     if (ret < 0)
911         seg_free_context(seg);
912
913     return ret;
914 }
915
916 static int seg_write_trailer(struct AVFormatContext *s)
917 {
918     SegmentContext *seg = s->priv_data;
919     AVFormatContext *oc = seg->avf;
920     SegmentListEntry *cur, *next;
921     int ret = 0;
922
923     if (!oc)
924         goto fail;
925
926     if (!seg->write_header_trailer) {
927         if ((ret = segment_end(s, 0, 1)) < 0)
928             goto fail;
929         if ((ret = open_null_ctx(&oc->pb)) < 0)
930             goto fail;
931         ret = av_write_trailer(oc);
932         close_null_ctxp(&oc->pb);
933     } else {
934         ret = segment_end(s, 1, 1);
935     }
936 fail:
937     if (seg->list)
938         ff_format_io_close(s, &seg->list_pb);
939
940     av_dict_free(&seg->format_options);
941     av_opt_free(seg);
942     av_freep(&seg->times);
943     av_freep(&seg->frames);
944     av_freep(&seg->cur_entry.filename);
945
946     cur = seg->segment_list_entries;
947     while (cur) {
948         next = cur->next;
949         av_freep(&cur->filename);
950         av_free(cur);
951         cur = next;
952     }
953
954     avformat_free_context(oc);
955     seg->avf = NULL;
956     return ret;
957 }
958
959 static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
960 {
961     SegmentContext *seg = s->priv_data;
962     AVFormatContext *oc = seg->avf;
963     if (oc->oformat->check_bitstream) {
964         int ret = oc->oformat->check_bitstream(oc, pkt);
965         if (ret == 1) {
966             AVStream *st = s->streams[pkt->stream_index];
967             AVStream *ost = oc->streams[pkt->stream_index];
968             st->internal->bsfc = ost->internal->bsfc;
969             ost->internal->bsfc = NULL;
970         }
971         return ret;
972     }
973     return 1;
974 }
975
976 #define OFFSET(x) offsetof(SegmentContext, x)
977 #define E AV_OPT_FLAG_ENCODING_PARAM
978 static const AVOption options[] = {
979     { "reference_stream",  "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
980     { "segment_format",    "set container format used for the segments", OFFSET(format),  AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
981     { "segment_format_options", "set list of options for the container format used for the segments", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
982     { "segment_list",      "set the segment list filename",              OFFSET(list),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
983     { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
984
985     { "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"},
986     { "cache",             "allow list caching",                                    0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX,   E, "list_flags"},
987     { "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"},
988
989     { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT,  {.i64 = 0},     0, INT_MAX, E },
990
991     { "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" },
992     { "flat", "flat format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
993     { "csv",  "csv format",      0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV  }, INT_MIN, INT_MAX, E, "list_type" },
994     { "ext",  "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT  }, INT_MIN, INT_MAX, E, "list_type" },
995     { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
996     { "m3u8", "M3U8 format",     0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
997     { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
998
999     { "segment_atclocktime",      "set segment to be cut at clocktime",  OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
1000     { "segment_clocktime_offset", "set segment clocktime offset",        OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
1001     { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
1002     { "segment_time",      "set segment duration",                       OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E },
1003     { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
1004     { "segment_times",     "set segment split time points",              OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
1005     { "segment_frames",    "set segment split frame numbers",            OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL},  0, 0,       E },
1006     { "segment_wrap",      "set number after which the index wraps",     OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1007     { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING,  {.str = NULL}, 0, 0, E },
1008     { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1009     { "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 },
1010     { "strftime",          "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1011     { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1012     { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1013
1014     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
1015     { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
1016     { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1017     { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
1018     { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1019     { NULL },
1020 };
1021
1022 static const AVClass seg_class = {
1023     .class_name = "segment muxer",
1024     .item_name  = av_default_item_name,
1025     .option     = options,
1026     .version    = LIBAVUTIL_VERSION_INT,
1027 };
1028
1029 AVOutputFormat ff_segment_muxer = {
1030     .name           = "segment",
1031     .long_name      = NULL_IF_CONFIG_SMALL("segment"),
1032     .priv_data_size = sizeof(SegmentContext),
1033     .flags          = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
1034     .init           = seg_init,
1035     .write_packet   = seg_write_packet,
1036     .write_trailer  = seg_write_trailer,
1037     .check_bitstream = seg_check_bitstream,
1038     .priv_class     = &seg_class,
1039 };
1040
1041 static const AVClass sseg_class = {
1042     .class_name = "stream_segment muxer",
1043     .item_name  = av_default_item_name,
1044     .option     = options,
1045     .version    = LIBAVUTIL_VERSION_INT,
1046 };
1047
1048 AVOutputFormat ff_stream_segment_muxer = {
1049     .name           = "stream_segment,ssegment",
1050     .long_name      = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
1051     .priv_data_size = sizeof(SegmentContext),
1052     .flags          = AVFMT_NOFILE,
1053     .init           = seg_init,
1054     .write_packet   = seg_write_packet,
1055     .write_trailer  = seg_write_trailer,
1056     .check_bitstream = seg_check_bitstream,
1057     .priv_class     = &sseg_class,
1058 };