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/log.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/time.h"
42 #include "libavutil/time_internal.h"
43 #include "libavutil/timestamp.h"
45 typedef struct SegmentListEntry {
47 double start_time, end_time;
51 struct SegmentListEntry *next;
52 int64_t last_duration;
56 LIST_TYPE_UNDEFINED = -1,
60 LIST_TYPE_EXT, ///< deprecated
65 #define SEGMENT_LIST_FLAG_CACHE 1
66 #define SEGMENT_LIST_FLAG_LIVE 2
68 typedef struct SegmentContext {
69 const AVClass *class; /**< Class for private options. */
70 int segment_idx; ///< index of the segment file to write, starting from 0
71 int segment_idx_wrap; ///< number after which the index wraps
72 int segment_idx_wrap_nb; ///< number of time the index has wraped
73 int segment_count; ///< number of segment files already written
74 AVOutputFormat *oformat;
76 char *format; ///< format to use for output segment files
77 char *format_options_str; ///< format options to use for output segment files
78 AVDictionary *format_options;
79 char *list; ///< filename for the segment list file
80 int list_flags; ///< flags affecting list generation
81 int list_size; ///< number of entries for the segment list file
83 int use_clocktime; ///< flag to cut segments at regular clock time
84 int64_t last_val; ///< remember last time for wrap around detection
85 int64_t last_cut; ///< remember last cut
88 char *entry_prefix; ///< prefix to add to list entry filenames
89 int list_type; ///< set the list type
90 AVIOContext *list_pb; ///< list file put-byte context
91 char *time_str; ///< segment duration specification string
92 int64_t time; ///< segment duration
93 int use_strftime; ///< flag to expand filename with strftime
95 char *times_str; ///< segment times specification string
96 int64_t *times; ///< list of segment interval specification
97 int nb_times; ///< number of elments in the times array
99 char *frames_str; ///< segment frame numbers specification string
100 int *frames; ///< list of frame number specification
101 int nb_frames; ///< number of elments in the frames array
102 int frame_count; ///< total number of reference frames
103 int segment_frame_count; ///< number of reference frames in the segment
106 int individual_header_trailer; /**< Set by a private option. */
107 int write_header_trailer; /**< Set by a private option. */
108 char *header_filename; ///< filename to write the output header to
110 int reset_timestamps; ///< reset timestamps at the begin of each segment
111 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
112 char *reference_stream_specifier; ///< reference stream specifier
113 int reference_stream_index;
114 int break_non_keyframes;
116 SegmentListEntry cur_entry;
117 SegmentListEntry *segment_list_entries;
118 SegmentListEntry *segment_list_entries_end;
121 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
123 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
128 for (; *str; str++) {
137 static int segment_mux_init(AVFormatContext *s)
139 SegmentContext *seg = s->priv_data;
144 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
149 oc->interrupt_callback = s->interrupt_callback;
150 oc->max_delay = s->max_delay;
151 av_dict_copy(&oc->metadata, s->metadata, 0);
153 for (i = 0; i < s->nb_streams; i++) {
155 AVCodecContext *icodec, *ocodec;
157 if (!(st = avformat_new_stream(oc, NULL)))
158 return AVERROR(ENOMEM);
159 icodec = s->streams[i]->codec;
161 avcodec_copy_context(ocodec, icodec);
162 if (!oc->oformat->codec_tag ||
163 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
164 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
165 ocodec->codec_tag = icodec->codec_tag;
167 ocodec->codec_tag = 0;
169 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
170 st->time_base = s->streams[i]->time_base;
171 av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
177 static int set_segment_filename(AVFormatContext *s)
179 SegmentContext *seg = s->priv_data;
180 AVFormatContext *oc = seg->avf;
183 if (seg->segment_idx_wrap)
184 seg->segment_idx %= seg->segment_idx_wrap;
185 if (seg->use_strftime) {
187 struct tm *tm, tmpbuf;
189 tm = localtime_r(&now0, &tmpbuf);
190 if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
191 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
192 return AVERROR(EINVAL);
194 } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
195 s->filename, seg->segment_idx) < 0) {
196 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
197 return AVERROR(EINVAL);
200 /* copy modified name in list entry */
201 size = strlen(av_basename(oc->filename)) + 1;
202 if (seg->entry_prefix)
203 size += strlen(seg->entry_prefix);
205 seg->cur_entry.filename = av_mallocz(size);
206 if (!seg->cur_entry.filename)
207 return AVERROR(ENOMEM);
208 snprintf(seg->cur_entry.filename, size, "%s%s",
209 seg->entry_prefix ? seg->entry_prefix : "",
210 av_basename(oc->filename));
215 static int segment_start(AVFormatContext *s, int write_header)
217 SegmentContext *seg = s->priv_data;
218 AVFormatContext *oc = seg->avf;
222 avformat_free_context(oc);
224 if ((err = segment_mux_init(s)) < 0)
230 if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
231 seg->segment_idx_wrap_nb++;
233 if ((err = set_segment_filename(s)) < 0)
236 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
237 &s->interrupt_callback, NULL)) < 0) {
238 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
241 if (!seg->individual_header_trailer)
242 oc->pb->seekable = 0;
244 if (oc->oformat->priv_class && oc->priv_data)
245 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
248 if ((err = avformat_write_header(oc, NULL)) < 0)
252 seg->segment_frame_count = 0;
256 static int segment_list_open(AVFormatContext *s)
258 SegmentContext *seg = s->priv_data;
261 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
262 &s->interrupt_callback, NULL);
264 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
268 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
269 SegmentListEntry *entry;
270 double max_duration = 0;
272 avio_printf(seg->list_pb, "#EXTM3U\n");
273 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
274 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
275 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
276 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
278 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
279 seg->segment_list_entries->index);
281 for (entry = seg->segment_list_entries; entry; entry = entry->next)
282 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
283 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
284 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
285 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
291 static void segment_list_print_entry(AVIOContext *list_ioctx,
293 const SegmentListEntry *list_entry,
298 avio_printf(list_ioctx, "%s\n", list_entry->filename);
302 print_csv_escaped_str(list_ioctx, list_entry->filename);
303 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
306 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
307 list_entry->end_time - list_entry->start_time, list_entry->filename);
309 case LIST_TYPE_FFCONCAT:
312 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
313 av_log(log_ctx, AV_LOG_WARNING,
314 "Error writing list entry '%s' in list file\n", list_entry->filename);
317 avio_printf(list_ioctx, "file %s\n", buf);
322 av_assert0(!"Invalid list type");
326 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
328 SegmentContext *seg = s->priv_data;
329 AVFormatContext *oc = seg->avf;
332 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
334 ret = av_write_trailer(oc);
337 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
341 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
342 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
344 ret = AVERROR(ENOMEM);
348 /* append new element */
349 memcpy(entry, &seg->cur_entry, sizeof(*entry));
350 if (!seg->segment_list_entries)
351 seg->segment_list_entries = seg->segment_list_entries_end = entry;
353 seg->segment_list_entries_end->next = entry;
354 seg->segment_list_entries_end = entry;
356 /* drop first item */
357 if (seg->list_size && seg->segment_count >= seg->list_size) {
358 entry = seg->segment_list_entries;
359 seg->segment_list_entries = seg->segment_list_entries->next;
360 av_freep(&entry->filename);
364 if ((ret = segment_list_open(s)) < 0)
366 for (entry = seg->segment_list_entries; entry; entry = entry->next)
367 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
368 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
369 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
370 avio_closep(&seg->list_pb);
372 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
373 avio_flush(seg->list_pb);
377 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
378 seg->avf->filename, seg->segment_count);
379 seg->segment_count++;
382 avio_closep(&oc->pb);
387 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
388 const char *times_str)
392 char *times_str1 = av_strdup(times_str);
393 char *saveptr = NULL;
396 return AVERROR(ENOMEM);
398 #define FAIL(err) ret = err; goto end
401 for (p = times_str1; *p; p++)
405 *times = av_malloc_array(*nb_times, sizeof(**times));
407 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
408 FAIL(AVERROR(ENOMEM));
412 for (i = 0; i < *nb_times; i++) {
414 char *tstr = av_strtok(p, ",", &saveptr);
417 if (!tstr || !tstr[0]) {
418 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
420 FAIL(AVERROR(EINVAL));
423 ret = av_parse_time(&t, tstr, 1);
425 av_log(log_ctx, AV_LOG_ERROR,
426 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
427 FAIL(AVERROR(EINVAL));
431 /* check on monotonicity */
432 if (i && (*times)[i-1] > (*times)[i]) {
433 av_log(log_ctx, AV_LOG_ERROR,
434 "Specified time %f is greater than the following time %f\n",
435 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
436 FAIL(AVERROR(EINVAL));
445 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
446 const char *frames_str)
450 char *frames_str1 = av_strdup(frames_str);
451 char *saveptr = NULL;
454 return AVERROR(ENOMEM);
456 #define FAIL(err) ret = err; goto end
459 for (p = frames_str1; *p; p++)
463 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
465 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
466 FAIL(AVERROR(ENOMEM));
470 for (i = 0; i < *nb_frames; i++) {
473 char *fstr = av_strtok(p, ",", &saveptr);
477 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
479 FAIL(AVERROR(EINVAL));
481 f = strtol(fstr, &tailptr, 10);
482 if (*tailptr || f <= 0 || f >= INT_MAX) {
483 av_log(log_ctx, AV_LOG_ERROR,
484 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
486 FAIL(AVERROR(EINVAL));
490 /* check on monotonicity */
491 if (i && (*frames)[i-1] > (*frames)[i]) {
492 av_log(log_ctx, AV_LOG_ERROR,
493 "Specified frame %d is greater than the following frame %d\n",
494 (*frames)[i], (*frames)[i-1]);
495 FAIL(AVERROR(EINVAL));
500 av_free(frames_str1);
504 static int open_null_ctx(AVIOContext **ctx)
506 int buf_size = 32768;
507 uint8_t *buf = av_malloc(buf_size);
509 return AVERROR(ENOMEM);
510 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
513 return AVERROR(ENOMEM);
518 static void close_null_ctxp(AVIOContext **pb)
520 av_freep(&(*pb)->buffer);
524 static int select_reference_stream(AVFormatContext *s)
526 SegmentContext *seg = s->priv_data;
529 seg->reference_stream_index = -1;
530 if (!strcmp(seg->reference_stream_specifier, "auto")) {
531 /* select first index of type with highest priority */
532 int type_index_map[AVMEDIA_TYPE_NB];
533 static const enum AVMediaType type_priority_list[] = {
536 AVMEDIA_TYPE_SUBTITLE,
538 AVMEDIA_TYPE_ATTACHMENT
540 enum AVMediaType type;
542 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
543 type_index_map[i] = -1;
545 /* select first index for each type */
546 for (i = 0; i < s->nb_streams; i++) {
547 type = s->streams[i]->codec->codec_type;
548 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
549 /* ignore attached pictures/cover art streams */
550 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
551 type_index_map[type] = i;
554 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
555 type = type_priority_list[i];
556 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
560 for (i = 0; i < s->nb_streams; i++) {
561 ret = avformat_match_stream_specifier(s, s->streams[i],
562 seg->reference_stream_specifier);
566 seg->reference_stream_index = i;
572 if (seg->reference_stream_index < 0) {
573 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
574 seg->reference_stream_specifier);
575 return AVERROR(EINVAL);
581 static void seg_free_context(SegmentContext *seg)
583 avio_closep(&seg->list_pb);
584 avformat_free_context(seg->avf);
588 static int seg_write_header(AVFormatContext *s)
590 SegmentContext *seg = s->priv_data;
591 AVFormatContext *oc = NULL;
592 AVDictionary *options = NULL;
596 seg->segment_count = 0;
597 if (!seg->write_header_trailer)
598 seg->individual_header_trailer = 0;
600 if (seg->header_filename) {
601 seg->write_header_trailer = 1;
602 seg->individual_header_trailer = 0;
605 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
606 av_log(s, AV_LOG_ERROR,
607 "segment_time, segment_times, and segment_frames options "
608 "are mutually exclusive, select just one of them\n");
609 return AVERROR(EINVAL);
612 if (seg->times_str) {
613 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
615 } else if (seg->frames_str) {
616 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
619 /* set default value if not specified */
621 seg->time_str = av_strdup("2");
622 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
623 av_log(s, AV_LOG_ERROR,
624 "Invalid time duration specification '%s' for segment_time option\n",
630 if (seg->format_options_str) {
631 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
633 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
634 seg->format_options_str);
640 if (seg->list_type == LIST_TYPE_UNDEFINED) {
641 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
642 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
643 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
644 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
645 else seg->list_type = LIST_TYPE_FLAT;
647 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8)
648 if ((ret = segment_list_open(s)) < 0)
651 if (seg->list_type == LIST_TYPE_EXT)
652 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
654 if ((ret = select_reference_stream(s)) < 0)
656 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
657 seg->reference_stream_index,
658 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
660 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
663 ret = AVERROR_MUXER_NOT_FOUND;
666 if (seg->oformat->flags & AVFMT_NOFILE) {
667 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
669 ret = AVERROR(EINVAL);
673 if ((ret = segment_mux_init(s)) < 0)
677 if ((ret = set_segment_filename(s)) < 0)
680 if (seg->write_header_trailer) {
681 if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
682 &s->interrupt_callback, NULL)) < 0) {
683 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
686 if (!seg->individual_header_trailer)
687 oc->pb->seekable = 0;
689 if ((ret = open_null_ctx(&oc->pb)) < 0)
693 av_dict_copy(&options, seg->format_options, 0);
694 ret = avformat_write_header(oc, &options);
695 if (av_dict_count(options)) {
696 av_log(s, AV_LOG_ERROR,
697 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
698 ret = AVERROR(EINVAL);
703 avio_closep(&oc->pb);
706 seg->segment_frame_count = 0;
708 av_assert0(s->nb_streams == oc->nb_streams);
709 for (i = 0; i < s->nb_streams; i++) {
710 AVStream *inner_st = oc->streams[i];
711 AVStream *outer_st = s->streams[i];
712 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
715 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
716 s->avoid_negative_ts = 1;
718 if (!seg->write_header_trailer || seg->header_filename) {
719 if (seg->header_filename) {
720 av_write_frame(oc, NULL);
721 avio_closep(&oc->pb);
723 close_null_ctxp(&oc->pb);
725 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
726 &s->interrupt_callback, NULL)) < 0)
728 if (!seg->individual_header_trailer)
729 oc->pb->seekable = 0;
733 av_dict_free(&options);
735 seg_free_context(seg);
740 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
742 SegmentContext *seg = s->priv_data;
743 AVStream *st = s->streams[pkt->stream_index];
744 int64_t end_pts = INT64_MAX, offset;
745 int start_frame = INT_MAX;
752 return AVERROR(EINVAL);
755 end_pts = seg->segment_count < seg->nb_times ?
756 seg->times[seg->segment_count] : INT64_MAX;
757 } else if (seg->frames) {
758 start_frame = seg->segment_count < seg->nb_frames ?
759 seg->frames[seg->segment_count] : INT_MAX;
761 if (seg->use_clocktime) {
762 int64_t avgt = av_gettime();
763 time_t sec = avgt / 1000000;
764 localtime_r(&sec, &ti);
765 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
766 wrapped_val = usecs % seg->time;
767 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
768 seg->cut_pending = 1;
769 seg->last_cut = usecs;
771 seg->last_val = wrapped_val;
773 end_pts = seg->time * (seg->segment_count + 1);
777 av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
778 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
779 av_ts2timestr(pkt->duration, &st->time_base),
780 pkt->flags & AV_PKT_FLAG_KEY,
781 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
783 if (pkt->stream_index == seg->reference_stream_index &&
784 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
785 seg->segment_frame_count > 0 &&
786 (seg->cut_pending || seg->frame_count >= start_frame ||
787 (pkt->pts != AV_NOPTS_VALUE &&
788 av_compare_ts(pkt->pts, st->time_base,
789 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
790 /* sanitize end time in case last packet didn't have a defined duration */
791 if (seg->cur_entry.last_duration == 0)
792 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
794 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
797 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
800 seg->cut_pending = 0;
801 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
802 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
803 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
804 seg->cur_entry.end_time = seg->cur_entry.start_time +
805 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
806 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
807 seg->cur_entry.end_time =
808 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
809 seg->cur_entry.last_duration = pkt->duration;
812 if (seg->segment_frame_count == 0) {
813 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
814 seg->avf->filename, pkt->stream_index,
815 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
818 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
820 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
821 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
822 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
824 /* compute new timestamps */
825 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
826 AV_TIME_BASE_Q, st->time_base);
827 if (pkt->pts != AV_NOPTS_VALUE)
829 if (pkt->dts != AV_NOPTS_VALUE)
832 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
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 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
839 if (pkt->stream_index == seg->reference_stream_index) {
841 seg->segment_frame_count++;
845 seg_free_context(seg);
850 static int seg_write_trailer(struct AVFormatContext *s)
852 SegmentContext *seg = s->priv_data;
853 AVFormatContext *oc = seg->avf;
854 SegmentListEntry *cur, *next;
860 if (!seg->write_header_trailer) {
861 if ((ret = segment_end(s, 0, 1)) < 0)
863 if ((ret = open_null_ctx(&oc->pb)) < 0)
865 ret = av_write_trailer(oc);
866 close_null_ctxp(&oc->pb);
868 ret = segment_end(s, 1, 1);
872 avio_closep(&seg->list_pb);
874 av_dict_free(&seg->format_options);
876 av_freep(&seg->times);
877 av_freep(&seg->frames);
879 cur = seg->segment_list_entries;
882 av_freep(&cur->filename);
887 avformat_free_context(oc);
892 #define OFFSET(x) offsetof(SegmentContext, x)
893 #define E AV_OPT_FLAG_ENCODING_PARAM
894 static const AVOption options[] = {
895 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
896 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
897 { "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 },
898 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
899 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
901 { "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"},
902 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
903 { "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"},
905 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
907 { "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" },
908 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
909 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
910 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
911 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
912 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
913 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
915 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
916 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
917 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
918 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
919 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
920 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
921 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
922 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
923 { "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 },
924 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
925 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
927 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
928 { "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 },
929 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
930 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
934 static const AVClass seg_class = {
935 .class_name = "segment muxer",
936 .item_name = av_default_item_name,
938 .version = LIBAVUTIL_VERSION_INT,
941 AVOutputFormat ff_segment_muxer = {
943 .long_name = NULL_IF_CONFIG_SMALL("segment"),
944 .priv_data_size = sizeof(SegmentContext),
945 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
946 .write_header = seg_write_header,
947 .write_packet = seg_write_packet,
948 .write_trailer = seg_write_trailer,
949 .priv_class = &seg_class,
952 static const AVClass sseg_class = {
953 .class_name = "stream_segment muxer",
954 .item_name = av_default_item_name,
956 .version = LIBAVUTIL_VERSION_INT,
959 AVOutputFormat ff_stream_segment_muxer = {
960 .name = "stream_segment,ssegment",
961 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
962 .priv_data_size = sizeof(SegmentContext),
963 .flags = AVFMT_NOFILE,
964 .write_header = seg_write_header,
965 .write_packet = seg_write_packet,
966 .write_trailer = seg_write_trailer,
967 .priv_class = &sseg_class,