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 if (!seg->segment_list_entries)
352 seg->segment_list_entries = seg->segment_list_entries_end = entry;
354 seg->segment_list_entries_end->next = entry;
355 seg->segment_list_entries_end = entry;
357 /* drop first item */
358 if (seg->list_size && seg->segment_count >= seg->list_size) {
359 entry = seg->segment_list_entries;
360 seg->segment_list_entries = seg->segment_list_entries->next;
361 av_freep(&entry->filename);
365 if ((ret = segment_list_open(s)) < 0)
367 for (entry = seg->segment_list_entries; entry; entry = entry->next)
368 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
369 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
370 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
371 avio_closep(&seg->list_pb);
373 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
374 avio_flush(seg->list_pb);
378 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
379 seg->avf->filename, seg->segment_count);
380 seg->segment_count++;
383 avio_closep(&oc->pb);
388 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
389 const char *times_str)
393 char *times_str1 = av_strdup(times_str);
394 char *saveptr = NULL;
397 return AVERROR(ENOMEM);
399 #define FAIL(err) ret = err; goto end
402 for (p = times_str1; *p; p++)
406 *times = av_malloc_array(*nb_times, sizeof(**times));
408 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
409 FAIL(AVERROR(ENOMEM));
413 for (i = 0; i < *nb_times; i++) {
415 char *tstr = av_strtok(p, ",", &saveptr);
418 if (!tstr || !tstr[0]) {
419 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
421 FAIL(AVERROR(EINVAL));
424 ret = av_parse_time(&t, tstr, 1);
426 av_log(log_ctx, AV_LOG_ERROR,
427 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
428 FAIL(AVERROR(EINVAL));
432 /* check on monotonicity */
433 if (i && (*times)[i-1] > (*times)[i]) {
434 av_log(log_ctx, AV_LOG_ERROR,
435 "Specified time %f is greater than the following time %f\n",
436 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
437 FAIL(AVERROR(EINVAL));
446 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
447 const char *frames_str)
451 char *frames_str1 = av_strdup(frames_str);
452 char *saveptr = NULL;
455 return AVERROR(ENOMEM);
457 #define FAIL(err) ret = err; goto end
460 for (p = frames_str1; *p; p++)
464 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
466 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
467 FAIL(AVERROR(ENOMEM));
471 for (i = 0; i < *nb_frames; i++) {
474 char *fstr = av_strtok(p, ",", &saveptr);
478 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
480 FAIL(AVERROR(EINVAL));
482 f = strtol(fstr, &tailptr, 10);
483 if (*tailptr || f <= 0 || f >= INT_MAX) {
484 av_log(log_ctx, AV_LOG_ERROR,
485 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
487 FAIL(AVERROR(EINVAL));
491 /* check on monotonicity */
492 if (i && (*frames)[i-1] > (*frames)[i]) {
493 av_log(log_ctx, AV_LOG_ERROR,
494 "Specified frame %d is greater than the following frame %d\n",
495 (*frames)[i], (*frames)[i-1]);
496 FAIL(AVERROR(EINVAL));
501 av_free(frames_str1);
505 static int open_null_ctx(AVIOContext **ctx)
507 int buf_size = 32768;
508 uint8_t *buf = av_malloc(buf_size);
510 return AVERROR(ENOMEM);
511 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
514 return AVERROR(ENOMEM);
519 static void close_null_ctxp(AVIOContext **pb)
521 av_freep(&(*pb)->buffer);
525 static int select_reference_stream(AVFormatContext *s)
527 SegmentContext *seg = s->priv_data;
530 seg->reference_stream_index = -1;
531 if (!strcmp(seg->reference_stream_specifier, "auto")) {
532 /* select first index of type with highest priority */
533 int type_index_map[AVMEDIA_TYPE_NB];
534 static const enum AVMediaType type_priority_list[] = {
537 AVMEDIA_TYPE_SUBTITLE,
539 AVMEDIA_TYPE_ATTACHMENT
541 enum AVMediaType type;
543 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
544 type_index_map[i] = -1;
546 /* select first index for each type */
547 for (i = 0; i < s->nb_streams; i++) {
548 type = s->streams[i]->codec->codec_type;
549 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
550 /* ignore attached pictures/cover art streams */
551 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
552 type_index_map[type] = i;
555 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
556 type = type_priority_list[i];
557 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
561 for (i = 0; i < s->nb_streams; i++) {
562 ret = avformat_match_stream_specifier(s, s->streams[i],
563 seg->reference_stream_specifier);
567 seg->reference_stream_index = i;
573 if (seg->reference_stream_index < 0) {
574 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
575 seg->reference_stream_specifier);
576 return AVERROR(EINVAL);
582 static void seg_free_context(SegmentContext *seg)
584 avio_closep(&seg->list_pb);
585 avformat_free_context(seg->avf);
589 static int seg_write_header(AVFormatContext *s)
591 SegmentContext *seg = s->priv_data;
592 AVFormatContext *oc = NULL;
593 AVDictionary *options = NULL;
597 seg->segment_count = 0;
598 if (!seg->write_header_trailer)
599 seg->individual_header_trailer = 0;
601 if (seg->header_filename) {
602 seg->write_header_trailer = 1;
603 seg->individual_header_trailer = 0;
606 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
607 av_log(s, AV_LOG_ERROR,
608 "segment_time, segment_times, and segment_frames options "
609 "are mutually exclusive, select just one of them\n");
610 return AVERROR(EINVAL);
613 if (seg->times_str) {
614 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
616 } else if (seg->frames_str) {
617 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
620 /* set default value if not specified */
622 seg->time_str = av_strdup("2");
623 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
624 av_log(s, AV_LOG_ERROR,
625 "Invalid time duration specification '%s' for segment_time option\n",
631 if (seg->format_options_str) {
632 ret = av_dict_parse_string(&seg->format_options, seg->format_options_str, "=", ":", 0);
634 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
635 seg->format_options_str);
641 if (seg->list_type == LIST_TYPE_UNDEFINED) {
642 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
643 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
644 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
645 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
646 else seg->list_type = LIST_TYPE_FLAT;
648 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8)
649 if ((ret = segment_list_open(s)) < 0)
652 if (seg->list_type == LIST_TYPE_EXT)
653 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
655 if ((ret = select_reference_stream(s)) < 0)
657 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
658 seg->reference_stream_index,
659 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
661 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
664 ret = AVERROR_MUXER_NOT_FOUND;
667 if (seg->oformat->flags & AVFMT_NOFILE) {
668 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
670 ret = AVERROR(EINVAL);
674 if ((ret = segment_mux_init(s)) < 0)
678 if ((ret = set_segment_filename(s)) < 0)
681 if (seg->write_header_trailer) {
682 if ((ret = avio_open2(&oc->pb, seg->header_filename ? seg->header_filename : oc->filename, AVIO_FLAG_WRITE,
683 &s->interrupt_callback, NULL)) < 0) {
684 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
687 if (!seg->individual_header_trailer)
688 oc->pb->seekable = 0;
690 if ((ret = open_null_ctx(&oc->pb)) < 0)
694 av_dict_copy(&options, seg->format_options, 0);
695 ret = avformat_write_header(oc, &options);
696 if (av_dict_count(options)) {
697 av_log(s, AV_LOG_ERROR,
698 "Some of the provided format options in '%s' are not recognized\n", seg->format_options_str);
699 ret = AVERROR(EINVAL);
704 avio_closep(&oc->pb);
707 seg->segment_frame_count = 0;
709 av_assert0(s->nb_streams == oc->nb_streams);
710 for (i = 0; i < s->nb_streams; i++) {
711 AVStream *inner_st = oc->streams[i];
712 AVStream *outer_st = s->streams[i];
713 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
716 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
717 s->avoid_negative_ts = 1;
719 if (!seg->write_header_trailer || seg->header_filename) {
720 if (seg->header_filename) {
721 av_write_frame(oc, NULL);
722 avio_closep(&oc->pb);
724 close_null_ctxp(&oc->pb);
726 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
727 &s->interrupt_callback, NULL)) < 0)
729 if (!seg->individual_header_trailer)
730 oc->pb->seekable = 0;
734 av_dict_free(&options);
736 seg_free_context(seg);
741 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
743 SegmentContext *seg = s->priv_data;
744 AVStream *st = s->streams[pkt->stream_index];
745 int64_t end_pts = INT64_MAX, offset;
746 int start_frame = INT_MAX;
753 return AVERROR(EINVAL);
756 end_pts = seg->segment_count < seg->nb_times ?
757 seg->times[seg->segment_count] : INT64_MAX;
758 } else if (seg->frames) {
759 start_frame = seg->segment_count < seg->nb_frames ?
760 seg->frames[seg->segment_count] : INT_MAX;
762 if (seg->use_clocktime) {
763 int64_t avgt = av_gettime();
764 time_t sec = avgt / 1000000;
765 localtime_r(&sec, &ti);
766 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
767 wrapped_val = usecs % seg->time;
768 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
769 seg->cut_pending = 1;
770 seg->last_cut = usecs;
772 seg->last_val = wrapped_val;
774 end_pts = seg->time * (seg->segment_count + 1);
778 ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
779 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
780 av_ts2timestr(pkt->duration, &st->time_base),
781 pkt->flags & AV_PKT_FLAG_KEY,
782 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
784 if (pkt->stream_index == seg->reference_stream_index &&
785 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
786 seg->segment_frame_count > 0 &&
787 (seg->cut_pending || seg->frame_count >= start_frame ||
788 (pkt->pts != AV_NOPTS_VALUE &&
789 av_compare_ts(pkt->pts, st->time_base,
790 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
791 /* sanitize end time in case last packet didn't have a defined duration */
792 if (seg->cur_entry.last_duration == 0)
793 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
795 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
798 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
801 seg->cut_pending = 0;
802 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
803 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
804 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
805 seg->cur_entry.end_time = seg->cur_entry.start_time +
806 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
807 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
808 seg->cur_entry.end_time =
809 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
810 seg->cur_entry.last_duration = pkt->duration;
813 if (seg->segment_frame_count == 0) {
814 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
815 seg->avf->filename, pkt->stream_index,
816 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
819 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
821 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
822 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
823 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
825 /* compute new timestamps */
826 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
827 AV_TIME_BASE_Q, st->time_base);
828 if (pkt->pts != AV_NOPTS_VALUE)
830 if (pkt->dts != AV_NOPTS_VALUE)
833 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
834 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
835 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
837 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
840 if (pkt->stream_index == seg->reference_stream_index) {
842 seg->segment_frame_count++;
846 seg_free_context(seg);
851 static int seg_write_trailer(struct AVFormatContext *s)
853 SegmentContext *seg = s->priv_data;
854 AVFormatContext *oc = seg->avf;
855 SegmentListEntry *cur, *next;
861 if (!seg->write_header_trailer) {
862 if ((ret = segment_end(s, 0, 1)) < 0)
864 if ((ret = open_null_ctx(&oc->pb)) < 0)
866 ret = av_write_trailer(oc);
867 close_null_ctxp(&oc->pb);
869 ret = segment_end(s, 1, 1);
873 avio_closep(&seg->list_pb);
875 av_dict_free(&seg->format_options);
877 av_freep(&seg->times);
878 av_freep(&seg->frames);
880 cur = seg->segment_list_entries;
883 av_freep(&cur->filename);
888 avformat_free_context(oc);
893 #define OFFSET(x) offsetof(SegmentContext, x)
894 #define E AV_OPT_FLAG_ENCODING_PARAM
895 static const AVOption options[] = {
896 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
897 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
898 { "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 },
899 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
900 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
902 { "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"},
903 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
904 { "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"},
906 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
908 { "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" },
909 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
910 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
911 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
912 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
913 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
914 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
916 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
917 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
918 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
919 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
920 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
921 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
922 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
923 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
924 { "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 },
925 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, E },
926 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
928 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
929 { "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 },
930 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
931 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
935 static const AVClass seg_class = {
936 .class_name = "segment muxer",
937 .item_name = av_default_item_name,
939 .version = LIBAVUTIL_VERSION_INT,
942 AVOutputFormat ff_segment_muxer = {
944 .long_name = NULL_IF_CONFIG_SMALL("segment"),
945 .priv_data_size = sizeof(SegmentContext),
946 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
947 .write_header = seg_write_header,
948 .write_packet = seg_write_packet,
949 .write_trailer = seg_write_trailer,
950 .priv_class = &seg_class,
953 static const AVClass sseg_class = {
954 .class_name = "stream_segment muxer",
955 .item_name = av_default_item_name,
957 .version = LIBAVUTIL_VERSION_INT,
960 AVOutputFormat ff_stream_segment_muxer = {
961 .name = "stream_segment,ssegment",
962 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
963 .priv_data_size = sizeof(SegmentContext),
964 .flags = AVFMT_NOFILE,
965 .write_header = seg_write_header,
966 .write_packet = seg_write_packet,
967 .write_trailer = seg_write_trailer,
968 .priv_class = &sseg_class,