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 ListType 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. */
109 int reset_timestamps; ///< reset timestamps at the begin of each segment
110 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
111 char *reference_stream_specifier; ///< reference stream specifier
112 int reference_stream_index;
114 SegmentListEntry cur_entry;
115 SegmentListEntry *segment_list_entries;
116 SegmentListEntry *segment_list_entries_end;
119 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
121 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
126 for (; *str; str++) {
135 static int segment_mux_init(AVFormatContext *s)
137 SegmentContext *seg = s->priv_data;
142 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
147 oc->interrupt_callback = s->interrupt_callback;
148 oc->max_delay = s->max_delay;
149 av_dict_copy(&oc->metadata, s->metadata, 0);
151 for (i = 0; i < s->nb_streams; i++) {
153 AVCodecContext *icodec, *ocodec;
155 if (!(st = avformat_new_stream(oc, NULL)))
156 return AVERROR(ENOMEM);
157 icodec = s->streams[i]->codec;
159 avcodec_copy_context(ocodec, icodec);
160 if (!oc->oformat->codec_tag ||
161 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
162 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
163 ocodec->codec_tag = icodec->codec_tag;
165 ocodec->codec_tag = 0;
167 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
168 st->time_base = s->streams[i]->time_base;
169 av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
175 static int set_segment_filename(AVFormatContext *s)
177 SegmentContext *seg = s->priv_data;
178 AVFormatContext *oc = seg->avf;
181 if (seg->segment_idx_wrap)
182 seg->segment_idx %= seg->segment_idx_wrap;
183 if (seg->use_strftime) {
185 struct tm *tm, tmpbuf;
187 tm = localtime_r(&now0, &tmpbuf);
188 if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
189 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
190 return AVERROR(EINVAL);
192 } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
193 s->filename, seg->segment_idx) < 0) {
194 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
195 return AVERROR(EINVAL);
198 /* copy modified name in list entry */
199 size = strlen(av_basename(oc->filename)) + 1;
200 if (seg->entry_prefix)
201 size += strlen(seg->entry_prefix);
203 seg->cur_entry.filename = av_mallocz(size);
204 if (!seg->cur_entry.filename)
205 return AVERROR(ENOMEM);
206 snprintf(seg->cur_entry.filename, size, "%s%s",
207 seg->entry_prefix ? seg->entry_prefix : "",
208 av_basename(oc->filename));
213 static int segment_start(AVFormatContext *s, int write_header)
215 SegmentContext *seg = s->priv_data;
216 AVFormatContext *oc = seg->avf;
220 avformat_free_context(oc);
222 if ((err = segment_mux_init(s)) < 0)
228 if ((seg->segment_idx_wrap) && (seg->segment_idx%seg->segment_idx_wrap == 0))
229 seg->segment_idx_wrap_nb++;
231 if ((err = set_segment_filename(s)) < 0)
234 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
235 &s->interrupt_callback, NULL)) < 0) {
236 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
240 if (oc->oformat->priv_class && oc->priv_data)
241 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
244 if ((err = avformat_write_header(oc, NULL)) < 0)
248 seg->segment_frame_count = 0;
252 static int segment_list_open(AVFormatContext *s)
254 SegmentContext *seg = s->priv_data;
257 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
258 &s->interrupt_callback, NULL);
260 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
264 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
265 SegmentListEntry *entry;
266 double max_duration = 0;
268 avio_printf(seg->list_pb, "#EXTM3U\n");
269 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
270 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
271 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
272 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
274 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
275 seg->segment_list_entries->index);
277 for (entry = seg->segment_list_entries; entry; entry = entry->next)
278 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
279 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
280 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
281 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
287 static void segment_list_print_entry(AVIOContext *list_ioctx,
289 const SegmentListEntry *list_entry,
294 avio_printf(list_ioctx, "%s\n", list_entry->filename);
298 print_csv_escaped_str(list_ioctx, list_entry->filename);
299 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
302 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
303 list_entry->end_time - list_entry->start_time, list_entry->filename);
305 case LIST_TYPE_FFCONCAT:
308 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
309 av_log(log_ctx, AV_LOG_WARNING,
310 "Error writing list entry '%s' in list file\n", list_entry->filename);
313 avio_printf(list_ioctx, "file %s\n", buf);
318 av_assert0(!"Invalid list type");
322 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
324 SegmentContext *seg = s->priv_data;
325 AVFormatContext *oc = seg->avf;
328 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
330 ret = av_write_trailer(oc);
333 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
337 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
338 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
340 ret = AVERROR(ENOMEM);
344 /* append new element */
345 memcpy(entry, &seg->cur_entry, sizeof(*entry));
346 if (!seg->segment_list_entries)
347 seg->segment_list_entries = seg->segment_list_entries_end = entry;
349 seg->segment_list_entries_end->next = entry;
350 seg->segment_list_entries_end = entry;
352 /* drop first item */
353 if (seg->list_size && seg->segment_count >= seg->list_size) {
354 entry = seg->segment_list_entries;
355 seg->segment_list_entries = seg->segment_list_entries->next;
356 av_freep(&entry->filename);
360 avio_closep(&seg->list_pb);
361 if ((ret = segment_list_open(s)) < 0)
363 for (entry = seg->segment_list_entries; entry; entry = entry->next)
364 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
365 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
366 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
368 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
370 avio_flush(seg->list_pb);
373 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
374 seg->avf->filename, seg->segment_count);
375 seg->segment_count++;
378 avio_closep(&oc->pb);
383 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
384 const char *times_str)
388 char *times_str1 = av_strdup(times_str);
389 char *saveptr = NULL;
392 return AVERROR(ENOMEM);
394 #define FAIL(err) ret = err; goto end
397 for (p = times_str1; *p; p++)
401 *times = av_malloc_array(*nb_times, sizeof(**times));
403 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
404 FAIL(AVERROR(ENOMEM));
408 for (i = 0; i < *nb_times; i++) {
410 char *tstr = av_strtok(p, ",", &saveptr);
413 if (!tstr || !tstr[0]) {
414 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
416 FAIL(AVERROR(EINVAL));
419 ret = av_parse_time(&t, tstr, 1);
421 av_log(log_ctx, AV_LOG_ERROR,
422 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
423 FAIL(AVERROR(EINVAL));
427 /* check on monotonicity */
428 if (i && (*times)[i-1] > (*times)[i]) {
429 av_log(log_ctx, AV_LOG_ERROR,
430 "Specified time %f is greater than the following time %f\n",
431 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
432 FAIL(AVERROR(EINVAL));
441 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
442 const char *frames_str)
446 char *frames_str1 = av_strdup(frames_str);
447 char *saveptr = NULL;
450 return AVERROR(ENOMEM);
452 #define FAIL(err) ret = err; goto end
455 for (p = frames_str1; *p; p++)
459 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
461 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
462 FAIL(AVERROR(ENOMEM));
466 for (i = 0; i < *nb_frames; i++) {
469 char *fstr = av_strtok(p, ",", &saveptr);
473 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
475 FAIL(AVERROR(EINVAL));
477 f = strtol(fstr, &tailptr, 10);
478 if (*tailptr || f <= 0 || f >= INT_MAX) {
479 av_log(log_ctx, AV_LOG_ERROR,
480 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
482 FAIL(AVERROR(EINVAL));
486 /* check on monotonicity */
487 if (i && (*frames)[i-1] > (*frames)[i]) {
488 av_log(log_ctx, AV_LOG_ERROR,
489 "Specified frame %d is greater than the following frame %d\n",
490 (*frames)[i], (*frames)[i-1]);
491 FAIL(AVERROR(EINVAL));
496 av_free(frames_str1);
500 static int open_null_ctx(AVIOContext **ctx)
502 int buf_size = 32768;
503 uint8_t *buf = av_malloc(buf_size);
505 return AVERROR(ENOMEM);
506 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
509 return AVERROR(ENOMEM);
514 static void close_null_ctxp(AVIOContext **pb)
516 av_freep(&(*pb)->buffer);
520 static int select_reference_stream(AVFormatContext *s)
522 SegmentContext *seg = s->priv_data;
525 seg->reference_stream_index = -1;
526 if (!strcmp(seg->reference_stream_specifier, "auto")) {
527 /* select first index of type with highest priority */
528 int type_index_map[AVMEDIA_TYPE_NB];
529 static const enum AVMediaType type_priority_list[] = {
532 AVMEDIA_TYPE_SUBTITLE,
534 AVMEDIA_TYPE_ATTACHMENT
536 enum AVMediaType type;
538 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
539 type_index_map[i] = -1;
541 /* select first index for each type */
542 for (i = 0; i < s->nb_streams; i++) {
543 type = s->streams[i]->codec->codec_type;
544 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
545 /* ignore attached pictures/cover art streams */
546 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
547 type_index_map[type] = i;
550 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
551 type = type_priority_list[i];
552 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
556 for (i = 0; i < s->nb_streams; i++) {
557 ret = avformat_match_stream_specifier(s, s->streams[i],
558 seg->reference_stream_specifier);
562 seg->reference_stream_index = i;
568 if (seg->reference_stream_index < 0) {
569 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
570 seg->reference_stream_specifier);
571 return AVERROR(EINVAL);
577 static void seg_free_context(SegmentContext *seg)
579 avio_closep(&seg->list_pb);
580 avformat_free_context(seg->avf);
584 static int seg_write_header(AVFormatContext *s)
586 SegmentContext *seg = s->priv_data;
587 AVFormatContext *oc = NULL;
588 AVDictionary *options = NULL;
592 seg->segment_count = 0;
593 if (!seg->write_header_trailer)
594 seg->individual_header_trailer = 0;
596 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
597 av_log(s, AV_LOG_ERROR,
598 "segment_time, segment_times, and segment_frames options "
599 "are mutually exclusive, select just one of them\n");
600 return AVERROR(EINVAL);
603 if (seg->times_str) {
604 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
606 } else if (seg->frames_str) {
607 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
610 /* set default value if not specified */
612 seg->time_str = av_strdup("2");
613 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
614 av_log(s, AV_LOG_ERROR,
615 "Invalid time duration specification '%s' for segment_time option\n",
621 if (seg->format_options_str) {
622 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
624 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
625 seg->format_options_str);
631 if (seg->list_type == LIST_TYPE_UNDEFINED) {
632 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
633 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
634 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
635 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
636 else seg->list_type = LIST_TYPE_FLAT;
638 if ((ret = segment_list_open(s)) < 0)
641 if (seg->list_type == LIST_TYPE_EXT)
642 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
644 if ((ret = select_reference_stream(s)) < 0)
646 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
647 seg->reference_stream_index,
648 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
650 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
653 ret = AVERROR_MUXER_NOT_FOUND;
656 if (seg->oformat->flags & AVFMT_NOFILE) {
657 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
659 ret = AVERROR(EINVAL);
663 if ((ret = segment_mux_init(s)) < 0)
667 if ((ret = set_segment_filename(s)) < 0)
670 if (seg->write_header_trailer) {
671 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
672 &s->interrupt_callback, NULL)) < 0) {
673 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
677 if ((ret = open_null_ctx(&oc->pb)) < 0)
681 av_dict_copy(&options, seg->format_options, 0);
682 ret = avformat_write_header(oc, &options);
683 if (av_dict_count(options)) {
684 av_log(s, AV_LOG_ERROR,
685 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
686 ret = AVERROR(EINVAL);
691 avio_closep(&oc->pb);
694 seg->segment_frame_count = 0;
696 av_assert0(s->nb_streams == oc->nb_streams);
697 for (i = 0; i < s->nb_streams; i++) {
698 AVStream *inner_st = oc->streams[i];
699 AVStream *outer_st = s->streams[i];
700 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
703 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
704 s->avoid_negative_ts = 1;
706 if (!seg->write_header_trailer) {
707 close_null_ctxp(&oc->pb);
708 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
709 &s->interrupt_callback, NULL)) < 0)
714 av_dict_free(&options);
716 seg_free_context(seg);
721 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
723 SegmentContext *seg = s->priv_data;
724 AVStream *st = s->streams[pkt->stream_index];
725 int64_t end_pts = INT64_MAX, offset;
726 int start_frame = INT_MAX;
733 return AVERROR(EINVAL);
736 end_pts = seg->segment_count < seg->nb_times ?
737 seg->times[seg->segment_count] : INT64_MAX;
738 } else if (seg->frames) {
739 start_frame = seg->segment_count < seg->nb_frames ?
740 seg->frames[seg->segment_count] : INT_MAX;
742 if (seg->use_clocktime) {
743 int64_t avgt = av_gettime();
744 time_t sec = avgt / 1000000;
745 localtime_r(&sec, &ti);
746 usecs = (int64_t)(ti.tm_hour*3600 + ti.tm_min*60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
747 wrapped_val = usecs % seg->time;
748 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
749 seg->cut_pending = 1;
750 seg->last_cut = usecs;
752 seg->last_val = wrapped_val;
754 end_pts = seg->time * (seg->segment_count+1);
758 av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
759 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
760 av_ts2timestr(pkt->duration, &st->time_base),
761 pkt->flags & AV_PKT_FLAG_KEY,
762 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
764 if (pkt->stream_index == seg->reference_stream_index &&
765 pkt->flags & AV_PKT_FLAG_KEY &&
766 seg->segment_frame_count > 0 &&
767 (seg->cut_pending || seg->frame_count >= start_frame ||
768 (pkt->pts != AV_NOPTS_VALUE &&
769 av_compare_ts(pkt->pts, st->time_base,
770 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
771 /* sanitize end time in case last packet didn't have a defined duration */
772 if (seg->cur_entry.last_duration == 0)
773 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
775 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
778 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
781 seg->cut_pending = 0;
782 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap*seg->segment_idx_wrap_nb;
783 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
784 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
785 seg->cur_entry.end_time = seg->cur_entry.start_time +
786 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
787 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
788 seg->cur_entry.end_time =
789 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
790 seg->cur_entry.last_duration = pkt->duration;
793 if (seg->segment_frame_count == 0) {
794 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
795 seg->avf->filename, pkt->stream_index,
796 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
799 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
801 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
802 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
803 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
805 /* compute new timestamps */
806 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
807 AV_TIME_BASE_Q, st->time_base);
808 if (pkt->pts != AV_NOPTS_VALUE)
810 if (pkt->dts != AV_NOPTS_VALUE)
813 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
814 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
815 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
817 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
820 if (pkt->stream_index == seg->reference_stream_index) {
822 seg->segment_frame_count++;
826 seg_free_context(seg);
831 static int seg_write_trailer(struct AVFormatContext *s)
833 SegmentContext *seg = s->priv_data;
834 AVFormatContext *oc = seg->avf;
835 SegmentListEntry *cur, *next;
841 if (!seg->write_header_trailer) {
842 if ((ret = segment_end(s, 0, 1)) < 0)
844 open_null_ctx(&oc->pb);
845 ret = av_write_trailer(oc);
846 close_null_ctxp(&oc->pb);
848 ret = segment_end(s, 1, 1);
852 avio_closep(&seg->list_pb);
854 av_dict_free(&seg->format_options);
856 av_freep(&seg->times);
857 av_freep(&seg->frames);
859 cur = seg->segment_list_entries;
862 av_freep(&cur->filename);
867 avformat_free_context(oc);
872 #define OFFSET(x) offsetof(SegmentContext, x)
873 #define E AV_OPT_FLAG_ENCODING_PARAM
874 static const AVOption options[] = {
875 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
876 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
877 { "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 },
878 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
880 { "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"},
881 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
882 { "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"},
884 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
886 { "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" },
887 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
888 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
889 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
890 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
891 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
892 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
894 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
895 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
896 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
897 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
898 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
899 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
900 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
901 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
902 { "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 },
903 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
905 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
906 { "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 },
907 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
908 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
912 static const AVClass seg_class = {
913 .class_name = "segment muxer",
914 .item_name = av_default_item_name,
916 .version = LIBAVUTIL_VERSION_INT,
919 AVOutputFormat ff_segment_muxer = {
921 .long_name = NULL_IF_CONFIG_SMALL("segment"),
922 .priv_data_size = sizeof(SegmentContext),
923 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
924 .write_header = seg_write_header,
925 .write_packet = seg_write_packet,
926 .write_trailer = seg_write_trailer,
927 .priv_class = &seg_class,
930 static const AVClass sseg_class = {
931 .class_name = "stream_segment muxer",
932 .item_name = av_default_item_name,
934 .version = LIBAVUTIL_VERSION_INT,
937 AVOutputFormat ff_stream_segment_muxer = {
938 .name = "stream_segment,ssegment",
939 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
940 .priv_data_size = sizeof(SegmentContext),
941 .flags = AVFMT_NOFILE,
942 .write_header = seg_write_header,
943 .write_packet = seg_write_packet,
944 .write_trailer = seg_write_trailer,
945 .priv_class = &sseg_class,