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}
33 #include "avio_internal.h"
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/time_internal.h"
45 #include "libavutil/timestamp.h"
47 typedef struct SegmentListEntry {
49 double start_time, end_time;
53 struct SegmentListEntry *next;
54 int64_t last_duration;
58 LIST_TYPE_UNDEFINED = -1,
62 LIST_TYPE_EXT, ///< deprecated
67 #define SEGMENT_LIST_FLAG_CACHE 1
68 #define SEGMENT_LIST_FLAG_LIVE 2
70 typedef struct SegmentContext {
71 const AVClass *class; /**< Class for private options. */
72 int segment_idx; ///< index of the segment file to write, starting from 0
73 int segment_idx_wrap; ///< number after which the index wraps
74 int segment_idx_wrap_nb; ///< number of time the index has wraped
75 int segment_count; ///< number of segment files already written
76 AVOutputFormat *oformat;
78 char *format; ///< format to use for output segment files
79 char *format_options_str; ///< format options to use for output segment files
80 AVDictionary *format_options;
81 char *list; ///< filename for the segment list file
82 int list_flags; ///< flags affecting list generation
83 int list_size; ///< number of entries for the segment list file
85 int use_clocktime; ///< flag to cut segments at regular clock time
86 int64_t clocktime_offset; //< clock offset for cutting the segments at regular clock time
87 int64_t clocktime_wrap_duration; //< wrapping duration considered for starting a new segment
88 int64_t last_val; ///< remember last time for wrap around detection
89 int64_t last_cut; ///< remember last cut
92 char *entry_prefix; ///< prefix to add to list entry filenames
93 int list_type; ///< set the list type
94 AVIOContext *list_pb; ///< list file put-byte context
95 char *time_str; ///< segment duration specification string
96 int64_t time; ///< segment duration
97 int use_strftime; ///< flag to expand filename with strftime
99 char *times_str; ///< segment times specification string
100 int64_t *times; ///< list of segment interval specification
101 int nb_times; ///< number of elments in the times array
103 char *frames_str; ///< segment frame numbers specification string
104 int *frames; ///< list of frame number specification
105 int nb_frames; ///< number of elments in the frames array
106 int frame_count; ///< total number of reference frames
107 int segment_frame_count; ///< number of reference frames in the segment
110 int individual_header_trailer; /**< Set by a private option. */
111 int write_header_trailer; /**< Set by a private option. */
112 char *header_filename; ///< filename to write the output header to
114 int reset_timestamps; ///< reset timestamps at the begin of each segment
115 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
116 char *reference_stream_specifier; ///< reference stream specifier
117 int reference_stream_index;
118 int break_non_keyframes;
121 char temp_list_filename[1024];
123 SegmentListEntry cur_entry;
124 SegmentListEntry *segment_list_entries;
125 SegmentListEntry *segment_list_entries_end;
128 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
130 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
135 for (; *str; str++) {
144 static int segment_mux_init(AVFormatContext *s)
146 SegmentContext *seg = s->priv_data;
151 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
156 oc->interrupt_callback = s->interrupt_callback;
157 oc->max_delay = s->max_delay;
158 av_dict_copy(&oc->metadata, s->metadata, 0);
159 oc->opaque = s->opaque;
160 oc->io_close = s->io_close;
161 oc->io_open = s->io_open;
163 for (i = 0; i < s->nb_streams; i++) {
165 AVCodecContext *icodec, *ocodec;
167 if (!(st = avformat_new_stream(oc, NULL)))
168 return AVERROR(ENOMEM);
169 icodec = s->streams[i]->codec;
171 avcodec_copy_context(ocodec, icodec);
172 if (!oc->oformat->codec_tag ||
173 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
174 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
175 ocodec->codec_tag = icodec->codec_tag;
177 ocodec->codec_tag = 0;
179 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
180 st->time_base = s->streams[i]->time_base;
181 av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
187 static int set_segment_filename(AVFormatContext *s)
189 SegmentContext *seg = s->priv_data;
190 AVFormatContext *oc = seg->avf;
194 if (seg->segment_idx_wrap)
195 seg->segment_idx %= seg->segment_idx_wrap;
196 if (seg->use_strftime) {
198 struct tm *tm, tmpbuf;
200 tm = localtime_r(&now0, &tmpbuf);
201 if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
202 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
203 return AVERROR(EINVAL);
205 } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
206 s->filename, seg->segment_idx) < 0) {
207 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
208 return AVERROR(EINVAL);
211 /* copy modified name in list entry */
212 size = strlen(av_basename(oc->filename)) + 1;
213 if (seg->entry_prefix)
214 size += strlen(seg->entry_prefix);
216 if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
218 snprintf(seg->cur_entry.filename, size, "%s%s",
219 seg->entry_prefix ? seg->entry_prefix : "",
220 av_basename(oc->filename));
225 static int segment_start(AVFormatContext *s, int write_header)
227 SegmentContext *seg = s->priv_data;
228 AVFormatContext *oc = seg->avf;
232 avformat_free_context(oc);
234 if ((err = segment_mux_init(s)) < 0)
240 if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
241 seg->segment_idx_wrap_nb++;
243 if ((err = set_segment_filename(s)) < 0)
246 if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0) {
247 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
250 if (!seg->individual_header_trailer)
251 oc->pb->seekable = 0;
253 if (oc->oformat->priv_class && oc->priv_data)
254 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
257 if ((err = avformat_write_header(oc, NULL)) < 0)
261 seg->segment_frame_count = 0;
265 static int segment_list_open(AVFormatContext *s)
267 SegmentContext *seg = s->priv_data;
270 snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list);
271 ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
273 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
277 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
278 SegmentListEntry *entry;
279 double max_duration = 0;
281 avio_printf(seg->list_pb, "#EXTM3U\n");
282 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
283 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
284 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
285 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
287 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
288 seg->segment_list_entries->index);
290 for (entry = seg->segment_list_entries; entry; entry = entry->next)
291 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
292 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
293 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
294 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
300 static void segment_list_print_entry(AVIOContext *list_ioctx,
302 const SegmentListEntry *list_entry,
307 avio_printf(list_ioctx, "%s\n", list_entry->filename);
311 print_csv_escaped_str(list_ioctx, list_entry->filename);
312 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
315 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
316 list_entry->end_time - list_entry->start_time, list_entry->filename);
318 case LIST_TYPE_FFCONCAT:
321 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
322 av_log(log_ctx, AV_LOG_WARNING,
323 "Error writing list entry '%s' in list file\n", list_entry->filename);
326 avio_printf(list_ioctx, "file %s\n", buf);
331 av_assert0(!"Invalid list type");
335 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
337 SegmentContext *seg = s->priv_data;
338 AVFormatContext *oc = seg->avf;
341 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
343 ret = av_write_trailer(oc);
346 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
350 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
351 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
353 ret = AVERROR(ENOMEM);
357 /* append new element */
358 memcpy(entry, &seg->cur_entry, sizeof(*entry));
359 entry->filename = av_strdup(entry->filename);
360 if (!seg->segment_list_entries)
361 seg->segment_list_entries = seg->segment_list_entries_end = entry;
363 seg->segment_list_entries_end->next = entry;
364 seg->segment_list_entries_end = entry;
366 /* drop first item */
367 if (seg->list_size && seg->segment_count >= seg->list_size) {
368 entry = seg->segment_list_entries;
369 seg->segment_list_entries = seg->segment_list_entries->next;
370 av_freep(&entry->filename);
374 if ((ret = segment_list_open(s)) < 0)
376 for (entry = seg->segment_list_entries; entry; entry = entry->next)
377 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
378 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
379 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
380 ff_format_io_close(s, &seg->list_pb);
382 ff_rename(seg->temp_list_filename, seg->list, s);
384 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
385 avio_flush(seg->list_pb);
389 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
390 seg->avf->filename, seg->segment_count);
391 seg->segment_count++;
394 ff_format_io_close(oc, &oc->pb);
399 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
400 const char *times_str)
404 char *times_str1 = av_strdup(times_str);
405 char *saveptr = NULL;
408 return AVERROR(ENOMEM);
410 #define FAIL(err) ret = err; goto end
413 for (p = times_str1; *p; p++)
417 *times = av_malloc_array(*nb_times, sizeof(**times));
419 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
420 FAIL(AVERROR(ENOMEM));
424 for (i = 0; i < *nb_times; i++) {
426 char *tstr = av_strtok(p, ",", &saveptr);
429 if (!tstr || !tstr[0]) {
430 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
432 FAIL(AVERROR(EINVAL));
435 ret = av_parse_time(&t, tstr, 1);
437 av_log(log_ctx, AV_LOG_ERROR,
438 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
439 FAIL(AVERROR(EINVAL));
443 /* check on monotonicity */
444 if (i && (*times)[i-1] > (*times)[i]) {
445 av_log(log_ctx, AV_LOG_ERROR,
446 "Specified time %f is greater than the following time %f\n",
447 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
448 FAIL(AVERROR(EINVAL));
457 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
458 const char *frames_str)
462 char *frames_str1 = av_strdup(frames_str);
463 char *saveptr = NULL;
466 return AVERROR(ENOMEM);
468 #define FAIL(err) ret = err; goto end
471 for (p = frames_str1; *p; p++)
475 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
477 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
478 FAIL(AVERROR(ENOMEM));
482 for (i = 0; i < *nb_frames; i++) {
485 char *fstr = av_strtok(p, ",", &saveptr);
489 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
491 FAIL(AVERROR(EINVAL));
493 f = strtol(fstr, &tailptr, 10);
494 if (*tailptr || f <= 0 || f >= INT_MAX) {
495 av_log(log_ctx, AV_LOG_ERROR,
496 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
498 FAIL(AVERROR(EINVAL));
502 /* check on monotonicity */
503 if (i && (*frames)[i-1] > (*frames)[i]) {
504 av_log(log_ctx, AV_LOG_ERROR,
505 "Specified frame %d is greater than the following frame %d\n",
506 (*frames)[i], (*frames)[i-1]);
507 FAIL(AVERROR(EINVAL));
512 av_free(frames_str1);
516 static int open_null_ctx(AVIOContext **ctx)
518 int buf_size = 32768;
519 uint8_t *buf = av_malloc(buf_size);
521 return AVERROR(ENOMEM);
522 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
525 return AVERROR(ENOMEM);
530 static void close_null_ctxp(AVIOContext **pb)
532 av_freep(&(*pb)->buffer);
536 static int select_reference_stream(AVFormatContext *s)
538 SegmentContext *seg = s->priv_data;
541 seg->reference_stream_index = -1;
542 if (!strcmp(seg->reference_stream_specifier, "auto")) {
543 /* select first index of type with highest priority */
544 int type_index_map[AVMEDIA_TYPE_NB];
545 static const enum AVMediaType type_priority_list[] = {
548 AVMEDIA_TYPE_SUBTITLE,
550 AVMEDIA_TYPE_ATTACHMENT
552 enum AVMediaType type;
554 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
555 type_index_map[i] = -1;
557 /* select first index for each type */
558 for (i = 0; i < s->nb_streams; i++) {
559 type = s->streams[i]->codec->codec_type;
560 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
561 /* ignore attached pictures/cover art streams */
562 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
563 type_index_map[type] = i;
566 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
567 type = type_priority_list[i];
568 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
572 for (i = 0; i < s->nb_streams; i++) {
573 ret = avformat_match_stream_specifier(s, s->streams[i],
574 seg->reference_stream_specifier);
578 seg->reference_stream_index = i;
584 if (seg->reference_stream_index < 0) {
585 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
586 seg->reference_stream_specifier);
587 return AVERROR(EINVAL);
593 static void seg_free_context(SegmentContext *seg)
595 ff_format_io_close(seg->avf, &seg->list_pb);
596 avformat_free_context(seg->avf);
600 static int seg_write_header(AVFormatContext *s)
602 SegmentContext *seg = s->priv_data;
603 AVFormatContext *oc = NULL;
604 AVDictionary *options = NULL;
608 seg->segment_count = 0;
609 if (!seg->write_header_trailer)
610 seg->individual_header_trailer = 0;
612 if (seg->header_filename) {
613 seg->write_header_trailer = 1;
614 seg->individual_header_trailer = 0;
617 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
618 av_log(s, AV_LOG_ERROR,
619 "segment_time, segment_times, and segment_frames options "
620 "are mutually exclusive, select just one of them\n");
621 return AVERROR(EINVAL);
624 if (seg->times_str) {
625 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
627 } else if (seg->frames_str) {
628 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
631 /* set default value if not specified */
633 seg->time_str = av_strdup("2");
634 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
635 av_log(s, AV_LOG_ERROR,
636 "Invalid time duration specification '%s' for segment_time option\n",
640 if (seg->use_clocktime) {
641 if (seg->time <= 0) {
642 av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
643 return AVERROR(EINVAL);
645 seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
649 if (seg->format_options_str) {
650 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
652 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
653 seg->format_options_str);
659 if (seg->list_type == LIST_TYPE_UNDEFINED) {
660 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
661 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
662 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
663 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
664 else seg->list_type = LIST_TYPE_FLAT;
666 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
667 if ((ret = segment_list_open(s)) < 0)
670 const char *proto = avio_find_protocol_name(s->filename);
671 seg->use_rename = proto && !strcmp(proto, "file");
674 if (seg->list_type == LIST_TYPE_EXT)
675 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
677 if ((ret = select_reference_stream(s)) < 0)
679 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
680 seg->reference_stream_index,
681 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
683 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
686 ret = AVERROR_MUXER_NOT_FOUND;
689 if (seg->oformat->flags & AVFMT_NOFILE) {
690 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
692 ret = AVERROR(EINVAL);
696 if ((ret = segment_mux_init(s)) < 0)
700 if ((ret = set_segment_filename(s)) < 0)
703 if (seg->write_header_trailer) {
704 if ((ret = s->io_open(s, &oc->pb,
705 seg->header_filename ? seg->header_filename : oc->filename,
706 AVIO_FLAG_WRITE, NULL)) < 0) {
707 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
710 if (!seg->individual_header_trailer)
711 oc->pb->seekable = 0;
713 if ((ret = open_null_ctx(&oc->pb)) < 0)
717 av_dict_copy(&options, seg->format_options, 0);
718 ret = avformat_write_header(oc, &options);
719 if (av_dict_count(options)) {
720 av_log(s, AV_LOG_ERROR,
721 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
722 ret = AVERROR(EINVAL);
727 ff_format_io_close(oc, &oc->pb);
730 seg->segment_frame_count = 0;
732 av_assert0(s->nb_streams == oc->nb_streams);
733 for (i = 0; i < s->nb_streams; i++) {
734 AVStream *inner_st = oc->streams[i];
735 AVStream *outer_st = s->streams[i];
736 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
739 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
740 s->avoid_negative_ts = 1;
742 if (!seg->write_header_trailer || seg->header_filename) {
743 if (seg->header_filename) {
744 av_write_frame(oc, NULL);
745 ff_format_io_close(oc, &oc->pb);
747 close_null_ctxp(&oc->pb);
749 if ((ret = oc->io_open(oc, &oc->pb, oc->filename, AVIO_FLAG_WRITE, NULL)) < 0)
751 if (!seg->individual_header_trailer)
752 oc->pb->seekable = 0;
756 av_dict_free(&options);
758 seg_free_context(seg);
763 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
765 SegmentContext *seg = s->priv_data;
766 AVStream *st = s->streams[pkt->stream_index];
767 int64_t end_pts = INT64_MAX, offset;
768 int start_frame = INT_MAX;
775 return AVERROR(EINVAL);
778 end_pts = seg->segment_count < seg->nb_times ?
779 seg->times[seg->segment_count] : INT64_MAX;
780 } else if (seg->frames) {
781 start_frame = seg->segment_count < seg->nb_frames ?
782 seg->frames[seg->segment_count] : INT_MAX;
784 if (seg->use_clocktime) {
785 int64_t avgt = av_gettime();
786 time_t sec = avgt / 1000000;
787 localtime_r(&sec, &ti);
788 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
789 wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
790 if (seg->last_cut != usecs && wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) {
791 seg->cut_pending = 1;
792 seg->last_cut = usecs;
794 seg->last_val = wrapped_val;
796 end_pts = seg->time * (seg->segment_count + 1);
800 ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
801 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
802 av_ts2timestr(pkt->duration, &st->time_base),
803 pkt->flags & AV_PKT_FLAG_KEY,
804 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
806 if (pkt->stream_index == seg->reference_stream_index &&
807 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
808 seg->segment_frame_count > 0 &&
809 (seg->cut_pending || seg->frame_count >= start_frame ||
810 (pkt->pts != AV_NOPTS_VALUE &&
811 av_compare_ts(pkt->pts, st->time_base,
812 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
813 /* sanitize end time in case last packet didn't have a defined duration */
814 if (seg->cur_entry.last_duration == 0)
815 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
817 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
820 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
823 seg->cut_pending = 0;
824 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
825 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
826 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
827 seg->cur_entry.end_time = seg->cur_entry.start_time +
828 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
829 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
830 seg->cur_entry.end_time =
831 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
832 seg->cur_entry.last_duration = pkt->duration;
835 if (seg->segment_frame_count == 0) {
836 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
837 seg->avf->filename, pkt->stream_index,
838 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
841 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
843 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
844 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
845 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
847 /* compute new timestamps */
848 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
849 AV_TIME_BASE_Q, st->time_base);
850 if (pkt->pts != AV_NOPTS_VALUE)
852 if (pkt->dts != AV_NOPTS_VALUE)
855 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
856 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
857 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
859 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
862 if (pkt->stream_index == seg->reference_stream_index) {
864 seg->segment_frame_count++;
868 seg_free_context(seg);
873 static int seg_write_trailer(struct AVFormatContext *s)
875 SegmentContext *seg = s->priv_data;
876 AVFormatContext *oc = seg->avf;
877 SegmentListEntry *cur, *next;
883 if (!seg->write_header_trailer) {
884 if ((ret = segment_end(s, 0, 1)) < 0)
886 if ((ret = open_null_ctx(&oc->pb)) < 0)
888 ret = av_write_trailer(oc);
889 close_null_ctxp(&oc->pb);
891 ret = segment_end(s, 1, 1);
895 ff_format_io_close(s, &seg->list_pb);
897 av_dict_free(&seg->format_options);
899 av_freep(&seg->times);
900 av_freep(&seg->frames);
901 av_freep(&seg->cur_entry.filename);
903 cur = seg->segment_list_entries;
906 av_freep(&cur->filename);
911 avformat_free_context(oc);
916 #define OFFSET(x) offsetof(SegmentContext, x)
917 #define E AV_OPT_FLAG_ENCODING_PARAM
918 static const AVOption options[] = {
919 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
920 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
921 { "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 },
922 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
923 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
925 { "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"},
926 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
927 { "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"},
929 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
931 { "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" },
932 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
933 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
934 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
935 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
936 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
937 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
939 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
940 { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
941 { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
942 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
943 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
944 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
945 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
946 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
947 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
948 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
949 { "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 },
950 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
951 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
953 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
954 { "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 },
955 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
956 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
960 static const AVClass seg_class = {
961 .class_name = "segment muxer",
962 .item_name = av_default_item_name,
964 .version = LIBAVUTIL_VERSION_INT,
967 AVOutputFormat ff_segment_muxer = {
969 .long_name = NULL_IF_CONFIG_SMALL("segment"),
970 .priv_data_size = sizeof(SegmentContext),
971 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
972 .write_header = seg_write_header,
973 .write_packet = seg_write_packet,
974 .write_trailer = seg_write_trailer,
975 .priv_class = &seg_class,
978 static const AVClass sseg_class = {
979 .class_name = "stream_segment muxer",
980 .item_name = av_default_item_name,
982 .version = LIBAVUTIL_VERSION_INT,
985 AVOutputFormat ff_stream_segment_muxer = {
986 .name = "stream_segment,ssegment",
987 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
988 .priv_data_size = sizeof(SegmentContext),
989 .flags = AVFMT_NOFILE,
990 .write_header = seg_write_header,
991 .write_packet = seg_write_packet,
992 .write_trailer = seg_write_trailer,
993 .priv_class = &sseg_class,