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;
117 SegmentListEntry cur_entry;
118 SegmentListEntry *segment_list_entries;
119 SegmentListEntry *segment_list_entries_end;
122 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
124 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
129 for (; *str; str++) {
138 static int segment_mux_init(AVFormatContext *s)
140 SegmentContext *seg = s->priv_data;
145 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
150 oc->interrupt_callback = s->interrupt_callback;
151 oc->max_delay = s->max_delay;
152 av_dict_copy(&oc->metadata, s->metadata, 0);
154 for (i = 0; i < s->nb_streams; i++) {
156 AVCodecContext *icodec, *ocodec;
158 if (!(st = avformat_new_stream(oc, NULL)))
159 return AVERROR(ENOMEM);
160 icodec = s->streams[i]->codec;
162 avcodec_copy_context(ocodec, icodec);
163 if (!oc->oformat->codec_tag ||
164 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
165 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
166 ocodec->codec_tag = icodec->codec_tag;
168 ocodec->codec_tag = 0;
170 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
171 st->time_base = s->streams[i]->time_base;
172 av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
178 static int set_segment_filename(AVFormatContext *s)
180 SegmentContext *seg = s->priv_data;
181 AVFormatContext *oc = seg->avf;
184 if (seg->segment_idx_wrap)
185 seg->segment_idx %= seg->segment_idx_wrap;
186 if (seg->use_strftime) {
188 struct tm *tm, tmpbuf;
190 tm = localtime_r(&now0, &tmpbuf);
191 if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {
192 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
193 return AVERROR(EINVAL);
195 } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
196 s->filename, seg->segment_idx) < 0) {
197 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
198 return AVERROR(EINVAL);
201 /* copy modified name in list entry */
202 size = strlen(av_basename(oc->filename)) + 1;
203 if (seg->entry_prefix)
204 size += strlen(seg->entry_prefix);
206 seg->cur_entry.filename = av_mallocz(size);
207 if (!seg->cur_entry.filename)
208 return AVERROR(ENOMEM);
209 snprintf(seg->cur_entry.filename, size, "%s%s",
210 seg->entry_prefix ? seg->entry_prefix : "",
211 av_basename(oc->filename));
216 static int segment_start(AVFormatContext *s, int write_header)
218 SegmentContext *seg = s->priv_data;
219 AVFormatContext *oc = seg->avf;
223 avformat_free_context(oc);
225 if ((err = segment_mux_init(s)) < 0)
231 if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
232 seg->segment_idx_wrap_nb++;
234 if ((err = set_segment_filename(s)) < 0)
237 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
238 &s->interrupt_callback, NULL)) < 0) {
239 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
242 if (!seg->individual_header_trailer)
243 oc->pb->seekable = 0;
245 if (oc->oformat->priv_class && oc->priv_data)
246 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
249 if ((err = avformat_write_header(oc, NULL)) < 0)
253 seg->segment_frame_count = 0;
257 static int segment_list_open(AVFormatContext *s)
259 SegmentContext *seg = s->priv_data;
262 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
263 &s->interrupt_callback, NULL);
265 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
269 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
270 SegmentListEntry *entry;
271 double max_duration = 0;
273 avio_printf(seg->list_pb, "#EXTM3U\n");
274 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
275 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
276 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
277 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
279 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
280 seg->segment_list_entries->index);
282 for (entry = seg->segment_list_entries; entry; entry = entry->next)
283 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
284 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
285 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
286 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
292 static void segment_list_print_entry(AVIOContext *list_ioctx,
294 const SegmentListEntry *list_entry,
299 avio_printf(list_ioctx, "%s\n", list_entry->filename);
303 print_csv_escaped_str(list_ioctx, list_entry->filename);
304 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
307 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
308 list_entry->end_time - list_entry->start_time, list_entry->filename);
310 case LIST_TYPE_FFCONCAT:
313 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
314 av_log(log_ctx, AV_LOG_WARNING,
315 "Error writing list entry '%s' in list file\n", list_entry->filename);
318 avio_printf(list_ioctx, "file %s\n", buf);
323 av_assert0(!"Invalid list type");
327 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
329 SegmentContext *seg = s->priv_data;
330 AVFormatContext *oc = seg->avf;
333 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
335 ret = av_write_trailer(oc);
338 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
342 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
343 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
345 ret = AVERROR(ENOMEM);
349 /* append new element */
350 memcpy(entry, &seg->cur_entry, sizeof(*entry));
351 entry->filename = av_strdup(entry->filename);
352 if (!seg->segment_list_entries)
353 seg->segment_list_entries = seg->segment_list_entries_end = entry;
355 seg->segment_list_entries_end->next = entry;
356 seg->segment_list_entries_end = entry;
358 /* drop first item */
359 if (seg->list_size && seg->segment_count >= seg->list_size) {
360 entry = seg->segment_list_entries;
361 seg->segment_list_entries = seg->segment_list_entries->next;
362 av_freep(&entry->filename);
366 if ((ret = segment_list_open(s)) < 0)
368 for (entry = seg->segment_list_entries; entry; entry = entry->next)
369 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
370 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
371 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
372 avio_closep(&seg->list_pb);
374 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
375 avio_flush(seg->list_pb);
379 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
380 seg->avf->filename, seg->segment_count);
381 seg->segment_count++;
384 avio_closep(&oc->pb);
389 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
390 const char *times_str)
394 char *times_str1 = av_strdup(times_str);
395 char *saveptr = NULL;
398 return AVERROR(ENOMEM);
400 #define FAIL(err) ret = err; goto end
403 for (p = times_str1; *p; p++)
407 *times = av_malloc_array(*nb_times, sizeof(**times));
409 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
410 FAIL(AVERROR(ENOMEM));
414 for (i = 0; i < *nb_times; i++) {
416 char *tstr = av_strtok(p, ",", &saveptr);
419 if (!tstr || !tstr[0]) {
420 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
422 FAIL(AVERROR(EINVAL));
425 ret = av_parse_time(&t, tstr, 1);
427 av_log(log_ctx, AV_LOG_ERROR,
428 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
429 FAIL(AVERROR(EINVAL));
433 /* check on monotonicity */
434 if (i && (*times)[i-1] > (*times)[i]) {
435 av_log(log_ctx, AV_LOG_ERROR,
436 "Specified time %f is greater than the following time %f\n",
437 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
438 FAIL(AVERROR(EINVAL));
447 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
448 const char *frames_str)
452 char *frames_str1 = av_strdup(frames_str);
453 char *saveptr = NULL;
456 return AVERROR(ENOMEM);
458 #define FAIL(err) ret = err; goto end
461 for (p = frames_str1; *p; p++)
465 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
467 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
468 FAIL(AVERROR(ENOMEM));
472 for (i = 0; i < *nb_frames; i++) {
475 char *fstr = av_strtok(p, ",", &saveptr);
479 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
481 FAIL(AVERROR(EINVAL));
483 f = strtol(fstr, &tailptr, 10);
484 if (*tailptr || f <= 0 || f >= INT_MAX) {
485 av_log(log_ctx, AV_LOG_ERROR,
486 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
488 FAIL(AVERROR(EINVAL));
492 /* check on monotonicity */
493 if (i && (*frames)[i-1] > (*frames)[i]) {
494 av_log(log_ctx, AV_LOG_ERROR,
495 "Specified frame %d is greater than the following frame %d\n",
496 (*frames)[i], (*frames)[i-1]);
497 FAIL(AVERROR(EINVAL));
502 av_free(frames_str1);
506 static int open_null_ctx(AVIOContext **ctx)
508 int buf_size = 32768;
509 uint8_t *buf = av_malloc(buf_size);
511 return AVERROR(ENOMEM);
512 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
515 return AVERROR(ENOMEM);
520 static void close_null_ctxp(AVIOContext **pb)
522 av_freep(&(*pb)->buffer);
526 static int select_reference_stream(AVFormatContext *s)
528 SegmentContext *seg = s->priv_data;
531 seg->reference_stream_index = -1;
532 if (!strcmp(seg->reference_stream_specifier, "auto")) {
533 /* select first index of type with highest priority */
534 int type_index_map[AVMEDIA_TYPE_NB];
535 static const enum AVMediaType type_priority_list[] = {
538 AVMEDIA_TYPE_SUBTITLE,
540 AVMEDIA_TYPE_ATTACHMENT
542 enum AVMediaType type;
544 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
545 type_index_map[i] = -1;
547 /* select first index for each type */
548 for (i = 0; i < s->nb_streams; i++) {
549 type = s->streams[i]->codec->codec_type;
550 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
551 /* ignore attached pictures/cover art streams */
552 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
553 type_index_map[type] = i;
556 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
557 type = type_priority_list[i];
558 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
562 for (i = 0; i < s->nb_streams; i++) {
563 ret = avformat_match_stream_specifier(s, s->streams[i],
564 seg->reference_stream_specifier);
568 seg->reference_stream_index = i;
574 if (seg->reference_stream_index < 0) {
575 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
576 seg->reference_stream_specifier);
577 return AVERROR(EINVAL);
583 static void seg_free_context(SegmentContext *seg)
585 avio_closep(&seg->list_pb);
586 avformat_free_context(seg->avf);
590 static int seg_write_header(AVFormatContext *s)
592 SegmentContext *seg = s->priv_data;
593 AVFormatContext *oc = NULL;
594 AVDictionary *options = NULL;
598 seg->segment_count = 0;
599 if (!seg->write_header_trailer)
600 seg->individual_header_trailer = 0;
602 if (seg->header_filename) {
603 seg->write_header_trailer = 1;
604 seg->individual_header_trailer = 0;
607 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
608 av_log(s, AV_LOG_ERROR,
609 "segment_time, segment_times, and segment_frames options "
610 "are mutually exclusive, select just one of them\n");
611 return AVERROR(EINVAL);
614 if (seg->times_str) {
615 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
617 } else if (seg->frames_str) {
618 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
621 /* set default value if not specified */
623 seg->time_str = av_strdup("2");
624 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
625 av_log(s, AV_LOG_ERROR,
626 "Invalid time duration specification '%s' for segment_time option\n",
632 if (seg->format_options_str) {
633 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
635 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
636 seg->format_options_str);
642 if (seg->list_type == LIST_TYPE_UNDEFINED) {
643 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
644 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
645 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
646 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
647 else seg->list_type = LIST_TYPE_FLAT;
649 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8)
650 if ((ret = segment_list_open(s)) < 0)
653 if (seg->list_type == LIST_TYPE_EXT)
654 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
656 if ((ret = select_reference_stream(s)) < 0)
658 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
659 seg->reference_stream_index,
660 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
662 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
665 ret = AVERROR_MUXER_NOT_FOUND;
668 if (seg->oformat->flags & AVFMT_NOFILE) {
669 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
671 ret = AVERROR(EINVAL);
675 if ((ret = segment_mux_init(s)) < 0)
679 if ((ret = set_segment_filename(s)) < 0)
682 if (seg->write_header_trailer) {
683 if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
684 &s->interrupt_callback, NULL)) < 0) {
685 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
688 if (!seg->individual_header_trailer)
689 oc->pb->seekable = 0;
691 if ((ret = open_null_ctx(&oc->pb)) < 0)
695 av_dict_copy(&options, seg->format_options, 0);
696 ret = avformat_write_header(oc, &options);
697 if (av_dict_count(options)) {
698 av_log(s, AV_LOG_ERROR,
699 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
700 ret = AVERROR(EINVAL);
705 avio_closep(&oc->pb);
708 seg->segment_frame_count = 0;
710 av_assert0(s->nb_streams == oc->nb_streams);
711 for (i = 0; i < s->nb_streams; i++) {
712 AVStream *inner_st = oc->streams[i];
713 AVStream *outer_st = s->streams[i];
714 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
717 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
718 s->avoid_negative_ts = 1;
720 if (!seg->write_header_trailer || seg->header_filename) {
721 if (seg->header_filename) {
722 av_write_frame(oc, NULL);
723 avio_closep(&oc->pb);
725 close_null_ctxp(&oc->pb);
727 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
728 &s->interrupt_callback, NULL)) < 0)
730 if (!seg->individual_header_trailer)
731 oc->pb->seekable = 0;
735 av_dict_free(&options);
737 seg_free_context(seg);
742 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
744 SegmentContext *seg = s->priv_data;
745 AVStream *st = s->streams[pkt->stream_index];
746 int64_t end_pts = INT64_MAX, offset;
747 int start_frame = INT_MAX;
754 return AVERROR(EINVAL);
757 end_pts = seg->segment_count < seg->nb_times ?
758 seg->times[seg->segment_count] : INT64_MAX;
759 } else if (seg->frames) {
760 start_frame = seg->segment_count < seg->nb_frames ?
761 seg->frames[seg->segment_count] : INT_MAX;
763 if (seg->use_clocktime) {
764 int64_t avgt = av_gettime();
765 time_t sec = avgt / 1000000;
766 localtime_r(&sec, &ti);
767 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
768 wrapped_val = usecs % seg->time;
769 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
770 seg->cut_pending = 1;
771 seg->last_cut = usecs;
773 seg->last_val = wrapped_val;
775 end_pts = seg->time * (seg->segment_count + 1);
779 ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
780 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
781 av_ts2timestr(pkt->duration, &st->time_base),
782 pkt->flags & AV_PKT_FLAG_KEY,
783 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
785 if (pkt->stream_index == seg->reference_stream_index &&
786 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
787 seg->segment_frame_count > 0 &&
788 (seg->cut_pending || seg->frame_count >= start_frame ||
789 (pkt->pts != AV_NOPTS_VALUE &&
790 av_compare_ts(pkt->pts, st->time_base,
791 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
792 /* sanitize end time in case last packet didn't have a defined duration */
793 if (seg->cur_entry.last_duration == 0)
794 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
796 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
799 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
802 seg->cut_pending = 0;
803 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
804 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
805 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
806 seg->cur_entry.end_time = seg->cur_entry.start_time +
807 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
808 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
809 seg->cur_entry.end_time =
810 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
811 seg->cur_entry.last_duration = pkt->duration;
814 if (seg->segment_frame_count == 0) {
815 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
816 seg->avf->filename, pkt->stream_index,
817 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
820 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
822 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
823 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
824 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
826 /* compute new timestamps */
827 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
828 AV_TIME_BASE_Q, st->time_base);
829 if (pkt->pts != AV_NOPTS_VALUE)
831 if (pkt->dts != AV_NOPTS_VALUE)
834 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
835 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
836 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
838 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
841 if (pkt->stream_index == seg->reference_stream_index) {
843 seg->segment_frame_count++;
847 seg_free_context(seg);
852 static int seg_write_trailer(struct AVFormatContext *s)
854 SegmentContext *seg = s->priv_data;
855 AVFormatContext *oc = seg->avf;
856 SegmentListEntry *cur, *next;
862 if (!seg->write_header_trailer) {
863 if ((ret = segment_end(s, 0, 1)) < 0)
865 if ((ret = open_null_ctx(&oc->pb)) < 0)
867 ret = av_write_trailer(oc);
868 close_null_ctxp(&oc->pb);
870 ret = segment_end(s, 1, 1);
874 avio_closep(&seg->list_pb);
876 av_dict_free(&seg->format_options);
878 av_freep(&seg->times);
879 av_freep(&seg->frames);
880 av_freep(&seg->cur_entry.filename);
882 cur = seg->segment_list_entries;
885 av_freep(&cur->filename);
890 avformat_free_context(oc);
895 #define OFFSET(x) offsetof(SegmentContext, x)
896 #define E AV_OPT_FLAG_ENCODING_PARAM
897 static const AVOption options[] = {
898 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
899 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
900 { "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 },
901 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
902 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
904 { "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"},
905 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
906 { "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"},
908 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
910 { "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" },
911 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
912 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
913 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
914 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
915 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
916 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
918 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
919 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
920 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
921 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
922 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
923 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
924 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
925 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
926 { "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 },
927 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
928 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
930 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
931 { "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 },
932 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
933 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
937 static const AVClass seg_class = {
938 .class_name = "segment muxer",
939 .item_name = av_default_item_name,
941 .version = LIBAVUTIL_VERSION_INT,
944 AVOutputFormat ff_segment_muxer = {
946 .long_name = NULL_IF_CONFIG_SMALL("segment"),
947 .priv_data_size = sizeof(SegmentContext),
948 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
949 .write_header = seg_write_header,
950 .write_packet = seg_write_packet,
951 .write_trailer = seg_write_trailer,
952 .priv_class = &seg_class,
955 static const AVClass sseg_class = {
956 .class_name = "stream_segment muxer",
957 .item_name = av_default_item_name,
959 .version = LIBAVUTIL_VERSION_INT,
962 AVOutputFormat ff_stream_segment_muxer = {
963 .name = "stream_segment,ssegment",
964 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
965 .priv_data_size = sizeof(SegmentContext),
966 .flags = AVFMT_NOFILE,
967 .write_header = seg_write_header,
968 .write_packet = seg_write_packet,
969 .write_trailer = seg_write_trailer,
970 .priv_class = &sseg_class,