2 * Copyright (c) 2011, Luca Barbato
4 * This file is part of FFmpeg.
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.
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.
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
22 * @file generic segmenter
23 * M3U8 specification can be find here:
24 * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming}
35 #include "libavutil/avassert.h"
36 #include "libavutil/internal.h"
37 #include "libavutil/log.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/time.h"
43 #include "libavutil/time_internal.h"
44 #include "libavutil/timestamp.h"
46 typedef struct SegmentListEntry {
48 double start_time, end_time;
52 struct SegmentListEntry *next;
53 int64_t last_duration;
57 LIST_TYPE_UNDEFINED = -1,
61 LIST_TYPE_EXT, ///< deprecated
66 #define SEGMENT_LIST_FLAG_CACHE 1
67 #define SEGMENT_LIST_FLAG_LIVE 2
69 typedef struct SegmentContext {
70 const AVClass *class; /**< Class for private options. */
71 int segment_idx; ///< index of the segment file to write, starting from 0
72 int segment_idx_wrap; ///< number after which the index wraps
73 int segment_idx_wrap_nb; ///< number of time the index has wraped
74 int segment_count; ///< number of segment files already written
75 AVOutputFormat *oformat;
77 char *format; ///< format to use for output segment files
78 char *format_options_str; ///< format options to use for output segment files
79 AVDictionary *format_options;
80 char *list; ///< filename for the segment list file
81 int list_flags; ///< flags affecting list generation
82 int list_size; ///< number of entries for the segment list file
84 int use_clocktime; ///< flag to cut segments at regular clock time
85 int64_t last_val; ///< remember last time for wrap around detection
86 int64_t last_cut; ///< remember last cut
89 char *entry_prefix; ///< prefix to add to list entry filenames
90 int list_type; ///< set the list type
91 AVIOContext *list_pb; ///< list file put-byte context
92 char *time_str; ///< segment duration specification string
93 int64_t time; ///< segment duration
94 int use_strftime; ///< flag to expand filename with strftime
96 char *times_str; ///< segment times specification string
97 int64_t *times; ///< list of segment interval specification
98 int nb_times; ///< number of elments in the times array
100 char *frames_str; ///< segment frame numbers specification string
101 int *frames; ///< list of frame number specification
102 int nb_frames; ///< number of elments in the frames array
103 int frame_count; ///< total number of reference frames
104 int segment_frame_count; ///< number of reference frames in the segment
107 int individual_header_trailer; /**< Set by a private option. */
108 int write_header_trailer; /**< Set by a private option. */
109 char *header_filename; ///< filename to write the output header to
111 int reset_timestamps; ///< reset timestamps at the begin of each segment
112 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
113 char *reference_stream_specifier; ///< reference stream specifier
114 int reference_stream_index;
115 int break_non_keyframes;
118 char temp_list_filename[1024];
120 SegmentListEntry cur_entry;
121 SegmentListEntry *segment_list_entries;
122 SegmentListEntry *segment_list_entries_end;
125 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
127 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
132 for (; *str; str++) {
141 static int segment_mux_init(AVFormatContext *s)
143 SegmentContext *seg = s->priv_data;
148 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
153 oc->interrupt_callback = s->interrupt_callback;
154 oc->max_delay = s->max_delay;
155 av_dict_copy(&oc->metadata, s->metadata, 0);
157 for (i = 0; i < s->nb_streams; i++) {
159 AVCodecContext *icodec, *ocodec;
161 if (!(st = avformat_new_stream(oc, NULL)))
162 return AVERROR(ENOMEM);
163 icodec = s->streams[i]->codec;
165 avcodec_copy_context(ocodec, icodec);
166 if (!oc->oformat->codec_tag ||
167 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
168 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
169 ocodec->codec_tag = icodec->codec_tag;
171 ocodec->codec_tag = 0;
173 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
174 st->time_base = s->streams[i]->time_base;
175 av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
181 static int set_segment_filename(AVFormatContext *s)
183 SegmentContext *seg = s->priv_data;
184 AVFormatContext *oc = seg->avf;
187 if (seg->segment_idx_wrap)
188 seg->segment_idx %= seg->segment_idx_wrap;
189 if (seg->use_strftime) {
191 struct tm *tm, tmpbuf;
193 tm = localtime_r(&now0, &tmpbuf);
194 if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
195 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
196 return AVERROR(EINVAL);
198 } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
199 s->filename, seg->segment_idx) < 0) {
200 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
201 return AVERROR(EINVAL);
204 /* copy modified name in list entry */
205 size = strlen(av_basename(oc->filename)) + 1;
206 if (seg->entry_prefix)
207 size += strlen(seg->entry_prefix);
209 seg->cur_entry.filename = av_mallocz(size);
210 if (!seg->cur_entry.filename)
211 return AVERROR(ENOMEM);
212 snprintf(seg->cur_entry.filename, size, "%s%s",
213 seg->entry_prefix ? seg->entry_prefix : "",
214 av_basename(oc->filename));
219 static int segment_start(AVFormatContext *s, int write_header)
221 SegmentContext *seg = s->priv_data;
222 AVFormatContext *oc = seg->avf;
226 avformat_free_context(oc);
228 if ((err = segment_mux_init(s)) < 0)
234 if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
235 seg->segment_idx_wrap_nb++;
237 if ((err = set_segment_filename(s)) < 0)
240 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
241 &s->interrupt_callback, NULL)) < 0) {
242 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
245 if (!seg->individual_header_trailer)
246 oc->pb->seekable = 0;
248 if (oc->oformat->priv_class && oc->priv_data)
249 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
252 if ((err = avformat_write_header(oc, NULL)) < 0)
256 seg->segment_frame_count = 0;
260 static int segment_list_open(AVFormatContext *s)
262 SegmentContext *seg = s->priv_data;
265 snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
266 ret = avio_open2(&seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE,
267 &s->interrupt_callback, NULL);
269 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
273 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
274 SegmentListEntry *entry;
275 double max_duration = 0;
277 avio_printf(seg->list_pb, "#EXTM3U\n");
278 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
279 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
280 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
281 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
283 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
284 seg->segment_list_entries->index);
286 for (entry = seg->segment_list_entries; entry; entry = entry->next)
287 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
288 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
289 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
290 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
296 static void segment_list_print_entry(AVIOContext *list_ioctx,
298 const SegmentListEntry *list_entry,
303 avio_printf(list_ioctx, "%s\n", list_entry->filename);
307 print_csv_escaped_str(list_ioctx, list_entry->filename);
308 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
311 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
312 list_entry->end_time - list_entry->start_time, list_entry->filename);
314 case LIST_TYPE_FFCONCAT:
317 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
318 av_log(log_ctx, AV_LOG_WARNING,
319 "Error writing list entry '%s' in list file\n", list_entry->filename);
322 avio_printf(list_ioctx, "file %s\n", buf);
327 av_assert0(!"Invalid list type");
331 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
333 SegmentContext *seg = s->priv_data;
334 AVFormatContext *oc = seg->avf;
337 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
339 ret = av_write_trailer(oc);
342 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
346 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
347 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
349 ret = AVERROR(ENOMEM);
353 /* append new element */
354 memcpy(entry, &seg->cur_entry, sizeof(*entry));
355 entry->filename = av_strdup(entry->filename);
356 if (!seg->segment_list_entries)
357 seg->segment_list_entries = seg->segment_list_entries_end = entry;
359 seg->segment_list_entries_end->next = entry;
360 seg->segment_list_entries_end = entry;
362 /* drop first item */
363 if (seg->list_size && seg->segment_count >= seg->list_size) {
364 entry = seg->segment_list_entries;
365 seg->segment_list_entries = seg->segment_list_entries->next;
366 av_freep(&entry->filename);
370 if ((ret = segment_list_open(s)) < 0)
372 for (entry = seg->segment_list_entries; entry; entry = entry->next)
373 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
374 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
375 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
376 avio_closep(&seg->list_pb);
378 ff_rename(seg->temp_list_filename, seg->list, s);
380 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
381 avio_flush(seg->list_pb);
385 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
386 seg->avf->filename, seg->segment_count);
387 seg->segment_count++;
390 avio_closep(&oc->pb);
395 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
396 const char *times_str)
400 char *times_str1 = av_strdup(times_str);
401 char *saveptr = NULL;
404 return AVERROR(ENOMEM);
406 #define FAIL(err) ret = err; goto end
409 for (p = times_str1; *p; p++)
413 *times = av_malloc_array(*nb_times, sizeof(**times));
415 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
416 FAIL(AVERROR(ENOMEM));
420 for (i = 0; i < *nb_times; i++) {
422 char *tstr = av_strtok(p, ",", &saveptr);
425 if (!tstr || !tstr[0]) {
426 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
428 FAIL(AVERROR(EINVAL));
431 ret = av_parse_time(&t, tstr, 1);
433 av_log(log_ctx, AV_LOG_ERROR,
434 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
435 FAIL(AVERROR(EINVAL));
439 /* check on monotonicity */
440 if (i && (*times)[i-1] > (*times)[i]) {
441 av_log(log_ctx, AV_LOG_ERROR,
442 "Specified time %f is greater than the following time %f\n",
443 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
444 FAIL(AVERROR(EINVAL));
453 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
454 const char *frames_str)
458 char *frames_str1 = av_strdup(frames_str);
459 char *saveptr = NULL;
462 return AVERROR(ENOMEM);
464 #define FAIL(err) ret = err; goto end
467 for (p = frames_str1; *p; p++)
471 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
473 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
474 FAIL(AVERROR(ENOMEM));
478 for (i = 0; i < *nb_frames; i++) {
481 char *fstr = av_strtok(p, ",", &saveptr);
485 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
487 FAIL(AVERROR(EINVAL));
489 f = strtol(fstr, &tailptr, 10);
490 if (*tailptr || f <= 0 || f >= INT_MAX) {
491 av_log(log_ctx, AV_LOG_ERROR,
492 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
494 FAIL(AVERROR(EINVAL));
498 /* check on monotonicity */
499 if (i && (*frames)[i-1] > (*frames)[i]) {
500 av_log(log_ctx, AV_LOG_ERROR,
501 "Specified frame %d is greater than the following frame %d\n",
502 (*frames)[i], (*frames)[i-1]);
503 FAIL(AVERROR(EINVAL));
508 av_free(frames_str1);
512 static int open_null_ctx(AVIOContext **ctx)
514 int buf_size = 32768;
515 uint8_t *buf = av_malloc(buf_size);
517 return AVERROR(ENOMEM);
518 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
521 return AVERROR(ENOMEM);
526 static void close_null_ctxp(AVIOContext **pb)
528 av_freep(&(*pb)->buffer);
532 static int select_reference_stream(AVFormatContext *s)
534 SegmentContext *seg = s->priv_data;
537 seg->reference_stream_index = -1;
538 if (!strcmp(seg->reference_stream_specifier, "auto")) {
539 /* select first index of type with highest priority */
540 int type_index_map[AVMEDIA_TYPE_NB];
541 static const enum AVMediaType type_priority_list[] = {
544 AVMEDIA_TYPE_SUBTITLE,
546 AVMEDIA_TYPE_ATTACHMENT
548 enum AVMediaType type;
550 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
551 type_index_map[i] = -1;
553 /* select first index for each type */
554 for (i = 0; i < s->nb_streams; i++) {
555 type = s->streams[i]->codec->codec_type;
556 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
557 /* ignore attached pictures/cover art streams */
558 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
559 type_index_map[type] = i;
562 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
563 type = type_priority_list[i];
564 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
568 for (i = 0; i < s->nb_streams; i++) {
569 ret = avformat_match_stream_specifier(s, s->streams[i],
570 seg->reference_stream_specifier);
574 seg->reference_stream_index = i;
580 if (seg->reference_stream_index < 0) {
581 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
582 seg->reference_stream_specifier);
583 return AVERROR(EINVAL);
589 static void seg_free_context(SegmentContext *seg)
591 avio_closep(&seg->list_pb);
592 avformat_free_context(seg->avf);
596 static int seg_write_header(AVFormatContext *s)
598 SegmentContext *seg = s->priv_data;
599 AVFormatContext *oc = NULL;
600 AVDictionary *options = NULL;
604 seg->segment_count = 0;
605 if (!seg->write_header_trailer)
606 seg->individual_header_trailer = 0;
608 if (seg->header_filename) {
609 seg->write_header_trailer = 1;
610 seg->individual_header_trailer = 0;
613 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
614 av_log(s, AV_LOG_ERROR,
615 "segment_time, segment_times, and segment_frames options "
616 "are mutually exclusive, select just one of them\n");
617 return AVERROR(EINVAL);
620 if (seg->times_str) {
621 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
623 } else if (seg->frames_str) {
624 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
627 /* set default value if not specified */
629 seg->time_str = av_strdup("2");
630 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
631 av_log(s, AV_LOG_ERROR,
632 "Invalid time duration specification '%s' for segment_time option\n",
638 if (seg->format_options_str) {
639 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
641 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
642 seg->format_options_str);
648 if (seg->list_type == LIST_TYPE_UNDEFINED) {
649 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
650 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
651 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
652 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
653 else seg->list_type = LIST_TYPE_FLAT;
655 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
656 if ((ret = segment_list_open(s)) < 0)
659 const char *proto = avio_find_protocol_name(s->filename);
660 seg->use_rename = proto && !strcmp(proto, "file");
663 if (seg->list_type == LIST_TYPE_EXT)
664 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
666 if ((ret = select_reference_stream(s)) < 0)
668 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
669 seg->reference_stream_index,
670 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
672 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
675 ret = AVERROR_MUXER_NOT_FOUND;
678 if (seg->oformat->flags & AVFMT_NOFILE) {
679 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
681 ret = AVERROR(EINVAL);
685 if ((ret = segment_mux_init(s)) < 0)
689 if ((ret = set_segment_filename(s)) < 0)
692 if (seg->write_header_trailer) {
693 if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
694 &s->interrupt_callback, NULL)) < 0) {
695 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
698 if (!seg->individual_header_trailer)
699 oc->pb->seekable = 0;
701 if ((ret = open_null_ctx(&oc->pb)) < 0)
705 av_dict_copy(&options, seg->format_options, 0);
706 ret = avformat_write_header(oc, &options);
707 if (av_dict_count(options)) {
708 av_log(s, AV_LOG_ERROR,
709 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
710 ret = AVERROR(EINVAL);
715 avio_closep(&oc->pb);
718 seg->segment_frame_count = 0;
720 av_assert0(s->nb_streams == oc->nb_streams);
721 for (i = 0; i < s->nb_streams; i++) {
722 AVStream *inner_st = oc->streams[i];
723 AVStream *outer_st = s->streams[i];
724 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
727 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
728 s->avoid_negative_ts = 1;
730 if (!seg->write_header_trailer || seg->header_filename) {
731 if (seg->header_filename) {
732 av_write_frame(oc, NULL);
733 avio_closep(&oc->pb);
735 close_null_ctxp(&oc->pb);
737 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
738 &s->interrupt_callback, NULL)) < 0)
740 if (!seg->individual_header_trailer)
741 oc->pb->seekable = 0;
745 av_dict_free(&options);
747 seg_free_context(seg);
752 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
754 SegmentContext *seg = s->priv_data;
755 AVStream *st = s->streams[pkt->stream_index];
756 int64_t end_pts = INT64_MAX, offset;
757 int start_frame = INT_MAX;
764 return AVERROR(EINVAL);
767 end_pts = seg->segment_count < seg->nb_times ?
768 seg->times[seg->segment_count] : INT64_MAX;
769 } else if (seg->frames) {
770 start_frame = seg->segment_count < seg->nb_frames ?
771 seg->frames[seg->segment_count] : INT_MAX;
773 if (seg->use_clocktime) {
774 int64_t avgt = av_gettime();
775 time_t sec = avgt / 1000000;
776 localtime_r(&sec, &ti);
777 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
778 wrapped_val = usecs % seg->time;
779 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
780 seg->cut_pending = 1;
781 seg->last_cut = usecs;
783 seg->last_val = wrapped_val;
785 end_pts = seg->time * (seg->segment_count + 1);
789 ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
790 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
791 av_ts2timestr(pkt->duration, &st->time_base),
792 pkt->flags & AV_PKT_FLAG_KEY,
793 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
795 if (pkt->stream_index == seg->reference_stream_index &&
796 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
797 seg->segment_frame_count > 0 &&
798 (seg->cut_pending || seg->frame_count >= start_frame ||
799 (pkt->pts != AV_NOPTS_VALUE &&
800 av_compare_ts(pkt->pts, st->time_base,
801 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
802 /* sanitize end time in case last packet didn't have a defined duration */
803 if (seg->cur_entry.last_duration == 0)
804 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
806 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
809 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
812 seg->cut_pending = 0;
813 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
814 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
815 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
816 seg->cur_entry.end_time = seg->cur_entry.start_time +
817 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
818 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
819 seg->cur_entry.end_time =
820 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
821 seg->cur_entry.last_duration = pkt->duration;
824 if (seg->segment_frame_count == 0) {
825 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
826 seg->avf->filename, pkt->stream_index,
827 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
830 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
832 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
833 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
834 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
836 /* compute new timestamps */
837 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
838 AV_TIME_BASE_Q, st->time_base);
839 if (pkt->pts != AV_NOPTS_VALUE)
841 if (pkt->dts != AV_NOPTS_VALUE)
844 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
845 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
846 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
848 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
851 if (pkt->stream_index == seg->reference_stream_index) {
853 seg->segment_frame_count++;
857 seg_free_context(seg);
862 static int seg_write_trailer(struct AVFormatContext *s)
864 SegmentContext *seg = s->priv_data;
865 AVFormatContext *oc = seg->avf;
866 SegmentListEntry *cur, *next;
872 if (!seg->write_header_trailer) {
873 if ((ret = segment_end(s, 0, 1)) < 0)
875 if ((ret = open_null_ctx(&oc->pb)) < 0)
877 ret = av_write_trailer(oc);
878 close_null_ctxp(&oc->pb);
880 ret = segment_end(s, 1, 1);
884 avio_closep(&seg->list_pb);
886 av_dict_free(&seg->format_options);
888 av_freep(&seg->times);
889 av_freep(&seg->frames);
890 av_freep(&seg->cur_entry.filename);
892 cur = seg->segment_list_entries;
895 av_freep(&cur->filename);
900 avformat_free_context(oc);
905 #define OFFSET(x) offsetof(SegmentContext, x)
906 #define E AV_OPT_FLAG_ENCODING_PARAM
907 static const AVOption options[] = {
908 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
909 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
910 { "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 },
911 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
912 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
914 { "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"},
915 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
916 { "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"},
918 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
920 { "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" },
921 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
922 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
923 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
924 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
925 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
926 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
928 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
929 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
930 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
931 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
932 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
933 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
934 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
935 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
936 { "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 },
937 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
938 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
940 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
941 { "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 },
942 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
943 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
947 static const AVClass seg_class = {
948 .class_name = "segment muxer",
949 .item_name = av_default_item_name,
951 .version = LIBAVUTIL_VERSION_INT,
954 AVOutputFormat ff_segment_muxer = {
956 .long_name = NULL_IF_CONFIG_SMALL("segment"),
957 .priv_data_size = sizeof(SegmentContext),
958 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
959 .write_header = seg_write_header,
960 .write_packet = seg_write_packet,
961 .write_trailer = seg_write_trailer,
962 .priv_class = &seg_class,
965 static const AVClass sseg_class = {
966 .class_name = "stream_segment muxer",
967 .item_name = av_default_item_name,
969 .version = LIBAVUTIL_VERSION_INT,
972 AVOutputFormat ff_stream_segment_muxer = {
973 .name = "stream_segment,ssegment",
974 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
975 .priv_data_size = sizeof(SegmentContext),
976 .flags = AVFMT_NOFILE,
977 .write_header = seg_write_header,
978 .write_packet = seg_write_packet,
979 .write_trailer = seg_write_trailer,
980 .priv_class = &sseg_class,