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/timestamp.h"
44 typedef struct SegmentListEntry {
46 double start_time, end_time;
50 struct SegmentListEntry *next;
51 int64_t last_duration;
55 LIST_TYPE_UNDEFINED = -1,
59 LIST_TYPE_EXT, ///< deprecated
64 #define SEGMENT_LIST_FLAG_CACHE 1
65 #define SEGMENT_LIST_FLAG_LIVE 2
68 const AVClass *class; /**< Class for private options. */
69 int segment_idx; ///< index of the segment file to write, starting from 0
70 int segment_idx_wrap; ///< number after which the index wraps
71 int segment_idx_wrap_nb; ///< number of time the index has wraped
72 int segment_count; ///< number of segment files already written
73 AVOutputFormat *oformat;
75 char *format; ///< format to use for output segment files
76 char *list; ///< filename for the segment list file
77 int list_flags; ///< flags affecting list generation
78 int list_size; ///< number of entries for the segment list file
80 int use_clocktime; ///< flag to cut segments at regular clock time
81 int64_t last_val; ///< remember last time for wrap around detection
82 int64_t last_cut; ///< remember last cut
85 char *entry_prefix; ///< prefix to add to list entry filenames
86 ListType list_type; ///< set the list type
87 AVIOContext *list_pb; ///< list file put-byte context
88 char *time_str; ///< segment duration specification string
89 int64_t time; ///< segment duration
91 char *times_str; ///< segment times specification string
92 int64_t *times; ///< list of segment interval specification
93 int nb_times; ///< number of elments in the times array
95 char *frames_str; ///< segment frame numbers specification string
96 int *frames; ///< list of frame number specification
97 int nb_frames; ///< number of elments in the frames array
98 int frame_count; ///< total number of reference frames
99 int segment_frame_count; ///< number of reference frames in the segment
102 int individual_header_trailer; /**< Set by a private option. */
103 int write_header_trailer; /**< Set by a private option. */
105 int reset_timestamps; ///< reset timestamps at the begin of each segment
106 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
107 char *reference_stream_specifier; ///< reference stream specifier
108 int reference_stream_index;
110 SegmentListEntry cur_entry;
111 SegmentListEntry *segment_list_entries;
112 SegmentListEntry *segment_list_entries_end;
115 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
117 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
122 for (; *str; str++) {
131 static int segment_mux_init(AVFormatContext *s)
133 SegmentContext *seg = s->priv_data;
137 seg->avf = oc = avformat_alloc_context();
139 return AVERROR(ENOMEM);
141 oc->oformat = seg->oformat;
142 oc->interrupt_callback = s->interrupt_callback;
143 av_dict_copy(&oc->metadata, s->metadata, 0);
145 for (i = 0; i < s->nb_streams; i++) {
147 AVCodecContext *icodec, *ocodec;
149 if (!(st = avformat_new_stream(oc, NULL)))
150 return AVERROR(ENOMEM);
151 icodec = s->streams[i]->codec;
153 avcodec_copy_context(ocodec, icodec);
154 if (!oc->oformat->codec_tag ||
155 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == ocodec->codec_id ||
156 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0) {
157 ocodec->codec_tag = icodec->codec_tag;
159 ocodec->codec_tag = 0;
161 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
167 static int set_segment_filename(AVFormatContext *s)
169 SegmentContext *seg = s->priv_data;
170 AVFormatContext *oc = seg->avf;
173 if (seg->segment_idx_wrap)
174 seg->segment_idx %= seg->segment_idx_wrap;
175 if (av_get_frame_filename(oc->filename, sizeof(oc->filename),
176 s->filename, seg->segment_idx) < 0) {
177 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);
178 return AVERROR(EINVAL);
181 /* copy modified name in list entry */
182 size = strlen(av_basename(oc->filename)) + 1;
183 if (seg->entry_prefix)
184 size += strlen(seg->entry_prefix);
186 seg->cur_entry.filename = av_mallocz(size);
187 if (!seg->cur_entry.filename)
188 return AVERROR(ENOMEM);
189 snprintf(seg->cur_entry.filename, size, "%s%s",
190 seg->entry_prefix ? seg->entry_prefix : "",
191 av_basename(oc->filename));
196 static int segment_start(AVFormatContext *s, int write_header)
198 SegmentContext *seg = s->priv_data;
199 AVFormatContext *oc = seg->avf;
203 avformat_free_context(oc);
205 if ((err = segment_mux_init(s)) < 0)
211 if ((seg->segment_idx_wrap) && (seg->segment_idx%seg->segment_idx_wrap == 0))
212 seg->segment_idx_wrap_nb++;
214 if ((err = set_segment_filename(s)) < 0)
217 if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
218 &s->interrupt_callback, NULL)) < 0) {
219 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
223 if (oc->oformat->priv_class && oc->priv_data)
224 av_opt_set(oc->priv_data, "resend_headers", "1", 0); /* mpegts specific */
227 if ((err = avformat_write_header(oc, NULL)) < 0)
231 seg->segment_frame_count = 0;
235 static int segment_list_open(AVFormatContext *s)
237 SegmentContext *seg = s->priv_data;
240 ret = avio_open2(&seg->list_pb, seg->list, AVIO_FLAG_WRITE,
241 &s->interrupt_callback, NULL);
243 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
247 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
248 SegmentListEntry *entry;
249 double max_duration = 0;
251 avio_printf(seg->list_pb, "#EXTM3U\n");
252 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
253 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
254 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
255 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
257 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
258 seg->segment_list_entries->index);
260 for (entry = seg->segment_list_entries; entry; entry = entry->next)
261 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
262 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
263 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
264 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
270 static void segment_list_print_entry(AVIOContext *list_ioctx,
272 const SegmentListEntry *list_entry,
277 avio_printf(list_ioctx, "%s\n", list_entry->filename);
281 print_csv_escaped_str(list_ioctx, list_entry->filename);
282 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
285 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
286 list_entry->end_time - list_entry->start_time, list_entry->filename);
288 case LIST_TYPE_FFCONCAT:
291 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
292 av_log(log_ctx, AV_LOG_WARNING,
293 "Error writing list entry '%s' in list file\n", list_entry->filename);
296 avio_printf(list_ioctx, "file %s\n", buf);
301 av_assert0(!"Invalid list type");
305 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
307 SegmentContext *seg = s->priv_data;
308 AVFormatContext *oc = seg->avf;
311 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
313 ret = av_write_trailer(oc);
316 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
320 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
321 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
323 ret = AVERROR(ENOMEM);
327 /* append new element */
328 memcpy(entry, &seg->cur_entry, sizeof(*entry));
329 if (!seg->segment_list_entries)
330 seg->segment_list_entries = seg->segment_list_entries_end = entry;
332 seg->segment_list_entries_end->next = entry;
333 seg->segment_list_entries_end = entry;
335 /* drop first item */
336 if (seg->list_size && seg->segment_count >= seg->list_size) {
337 entry = seg->segment_list_entries;
338 seg->segment_list_entries = seg->segment_list_entries->next;
339 av_free(entry->filename);
343 avio_close(seg->list_pb);
344 if ((ret = segment_list_open(s)) < 0)
346 for (entry = seg->segment_list_entries; entry; entry = entry->next)
347 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
348 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
349 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
351 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
353 avio_flush(seg->list_pb);
356 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
357 seg->avf->filename, seg->segment_count);
358 seg->segment_count++;
366 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
367 const char *times_str)
371 char *times_str1 = av_strdup(times_str);
372 char *saveptr = NULL;
375 return AVERROR(ENOMEM);
377 #define FAIL(err) ret = err; goto end
380 for (p = times_str1; *p; p++)
384 *times = av_malloc_array(*nb_times, sizeof(**times));
386 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
387 FAIL(AVERROR(ENOMEM));
391 for (i = 0; i < *nb_times; i++) {
393 char *tstr = av_strtok(p, ",", &saveptr);
396 if (!tstr || !tstr[0]) {
397 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
399 FAIL(AVERROR(EINVAL));
402 ret = av_parse_time(&t, tstr, 1);
404 av_log(log_ctx, AV_LOG_ERROR,
405 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
406 FAIL(AVERROR(EINVAL));
410 /* check on monotonicity */
411 if (i && (*times)[i-1] > (*times)[i]) {
412 av_log(log_ctx, AV_LOG_ERROR,
413 "Specified time %f is greater than the following time %f\n",
414 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
415 FAIL(AVERROR(EINVAL));
424 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
425 const char *frames_str)
429 char *frames_str1 = av_strdup(frames_str);
430 char *saveptr = NULL;
433 return AVERROR(ENOMEM);
435 #define FAIL(err) ret = err; goto end
438 for (p = frames_str1; *p; p++)
442 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
444 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
445 FAIL(AVERROR(ENOMEM));
449 for (i = 0; i < *nb_frames; i++) {
452 char *fstr = av_strtok(p, ",", &saveptr);
456 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
458 FAIL(AVERROR(EINVAL));
460 f = strtol(fstr, &tailptr, 10);
461 if (*tailptr || f <= 0 || f >= INT_MAX) {
462 av_log(log_ctx, AV_LOG_ERROR,
463 "Invalid argument '%s', must be a positive integer <= INT64_MAX\n",
465 FAIL(AVERROR(EINVAL));
469 /* check on monotonicity */
470 if (i && (*frames)[i-1] > (*frames)[i]) {
471 av_log(log_ctx, AV_LOG_ERROR,
472 "Specified frame %d is greater than the following frame %d\n",
473 (*frames)[i], (*frames)[i-1]);
474 FAIL(AVERROR(EINVAL));
479 av_free(frames_str1);
483 static int open_null_ctx(AVIOContext **ctx)
485 int buf_size = 32768;
486 uint8_t *buf = av_malloc(buf_size);
488 return AVERROR(ENOMEM);
489 *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL);
492 return AVERROR(ENOMEM);
497 static void close_null_ctx(AVIOContext *pb)
503 static int select_reference_stream(AVFormatContext *s)
505 SegmentContext *seg = s->priv_data;
508 seg->reference_stream_index = -1;
509 if (!strcmp(seg->reference_stream_specifier, "auto")) {
510 /* select first index of type with highest priority */
511 int type_index_map[AVMEDIA_TYPE_NB];
512 static const enum AVMediaType type_priority_list[] = {
515 AVMEDIA_TYPE_SUBTITLE,
517 AVMEDIA_TYPE_ATTACHMENT
519 enum AVMediaType type;
521 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
522 type_index_map[i] = -1;
524 /* select first index for each type */
525 for (i = 0; i < s->nb_streams; i++) {
526 type = s->streams[i]->codec->codec_type;
527 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
528 /* ignore attached pictures/cover art streams */
529 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
530 type_index_map[type] = i;
533 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
534 type = type_priority_list[i];
535 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
539 for (i = 0; i < s->nb_streams; i++) {
540 ret = avformat_match_stream_specifier(s, s->streams[i],
541 seg->reference_stream_specifier);
545 seg->reference_stream_index = i;
551 if (seg->reference_stream_index < 0) {
552 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
553 seg->reference_stream_specifier);
554 return AVERROR(EINVAL);
560 static int seg_write_header(AVFormatContext *s)
562 SegmentContext *seg = s->priv_data;
563 AVFormatContext *oc = NULL;
566 seg->segment_count = 0;
567 if (!seg->write_header_trailer)
568 seg->individual_header_trailer = 0;
570 if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) {
571 av_log(s, AV_LOG_ERROR,
572 "segment_time, segment_times, and segment_frames options "
573 "are mutually exclusive, select just one of them\n");
574 return AVERROR(EINVAL);
577 if (seg->times_str) {
578 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
580 } else if (seg->frames_str) {
581 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
584 /* set default value if not specified */
586 seg->time_str = av_strdup("2");
587 if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) {
588 av_log(s, AV_LOG_ERROR,
589 "Invalid time duration specification '%s' for segment_time option\n",
596 if (seg->list_type == LIST_TYPE_UNDEFINED) {
597 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
598 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
599 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
600 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
601 else seg->list_type = LIST_TYPE_FLAT;
603 if ((ret = segment_list_open(s)) < 0)
606 if (seg->list_type == LIST_TYPE_EXT)
607 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
609 if ((ret = select_reference_stream(s)) < 0)
611 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
612 seg->reference_stream_index,
613 av_get_media_type_string(s->streams[seg->reference_stream_index]->codec->codec_type));
615 seg->oformat = av_guess_format(seg->format, s->filename, NULL);
618 ret = AVERROR_MUXER_NOT_FOUND;
621 if (seg->oformat->flags & AVFMT_NOFILE) {
622 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
624 ret = AVERROR(EINVAL);
628 if ((ret = segment_mux_init(s)) < 0)
632 if ((ret = set_segment_filename(s)) < 0)
635 if (seg->write_header_trailer) {
636 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
637 &s->interrupt_callback, NULL)) < 0) {
638 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->filename);
642 if ((ret = open_null_ctx(&oc->pb)) < 0)
646 if ((ret = avformat_write_header(oc, NULL)) < 0) {
650 seg->segment_frame_count = 0;
652 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
653 s->avoid_negative_ts = 1;
655 if (!seg->write_header_trailer) {
656 close_null_ctx(oc->pb);
657 if ((ret = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
658 &s->interrupt_callback, NULL)) < 0)
665 avio_close(seg->list_pb);
667 avformat_free_context(seg->avf);
672 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
674 SegmentContext *seg = s->priv_data;
675 AVStream *st = s->streams[pkt->stream_index];
676 int64_t end_pts = INT64_MAX, offset;
677 int start_frame = INT_MAX;
684 end_pts = seg->segment_count < seg->nb_times ?
685 seg->times[seg->segment_count] : INT64_MAX;
686 } else if (seg->frames) {
687 start_frame = seg->segment_count <= seg->nb_frames ?
688 seg->frames[seg->segment_count] : INT_MAX;
690 if (seg->use_clocktime) {
691 int64_t avgt = av_gettime();
692 time_t sec = avgt / 1000000;
694 localtime_r(&sec, &ti);
696 ti = *localtime(&sec);
698 usecs = (int64_t)(ti.tm_hour*3600 + ti.tm_min*60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
699 wrapped_val = usecs % seg->time;
700 if (seg->last_cut != usecs && wrapped_val < seg->last_val) {
701 seg->cut_pending = 1;
702 seg->last_cut = usecs;
704 seg->last_val = wrapped_val;
706 end_pts = seg->time * (seg->segment_count+1);
710 av_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
711 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
712 av_ts2timestr(pkt->duration, &st->time_base),
713 pkt->flags & AV_PKT_FLAG_KEY,
714 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
716 if (pkt->stream_index == seg->reference_stream_index &&
717 pkt->flags & AV_PKT_FLAG_KEY &&
718 seg->segment_frame_count > 0 &&
719 (seg->cut_pending || seg->frame_count >= start_frame ||
720 (pkt->pts != AV_NOPTS_VALUE &&
721 av_compare_ts(pkt->pts, st->time_base,
722 end_pts-seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
723 /* sanitize end time in case last packet didn't have a defined duration */
724 if (seg->cur_entry.last_duration == 0)
725 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
727 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
730 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
733 seg->cut_pending = 0;
734 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap*seg->segment_idx_wrap_nb;
735 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
736 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
737 seg->cur_entry.end_time = seg->cur_entry.start_time +
738 pkt->pts != AV_NOPTS_VALUE ? (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base) : 0;
739 } else if (pkt->pts != AV_NOPTS_VALUE && pkt->stream_index == seg->reference_stream_index) {
740 seg->cur_entry.end_time =
741 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
742 seg->cur_entry.last_duration = pkt->duration;
745 if (seg->segment_frame_count == 0) {
746 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
747 seg->avf->filename, pkt->stream_index,
748 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
751 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
753 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
754 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
755 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
757 /* compute new timestamps */
758 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
759 AV_TIME_BASE_Q, st->time_base);
760 if (pkt->pts != AV_NOPTS_VALUE)
762 if (pkt->dts != AV_NOPTS_VALUE)
765 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
766 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
767 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
769 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);
772 if (pkt->stream_index == seg->reference_stream_index) {
774 seg->segment_frame_count++;
780 static int seg_write_trailer(struct AVFormatContext *s)
782 SegmentContext *seg = s->priv_data;
783 AVFormatContext *oc = seg->avf;
784 SegmentListEntry *cur, *next;
787 if (!seg->write_header_trailer) {
788 if ((ret = segment_end(s, 0, 1)) < 0)
790 open_null_ctx(&oc->pb);
791 ret = av_write_trailer(oc);
792 close_null_ctx(oc->pb);
794 ret = segment_end(s, 1, 1);
798 avio_close(seg->list_pb);
801 av_freep(&seg->times);
802 av_freep(&seg->frames);
804 cur = seg->segment_list_entries;
807 av_free(cur->filename);
812 avformat_free_context(oc);
816 #define OFFSET(x) offsetof(SegmentContext, x)
817 #define E AV_OPT_FLAG_ENCODING_PARAM
818 static const AVOption options[] = {
819 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, CHAR_MIN, CHAR_MAX, E },
820 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
821 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
823 { "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"},
824 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"},
825 { "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"},
827 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
829 { "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" },
830 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" },
831 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" },
832 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" },
833 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" },
834 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
835 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" },
837 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E},
838 { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
839 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 0, E },
840 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
841 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
842 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
843 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
844 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
845 { "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 },
847 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
848 { "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 },
849 { "reset_timestamps", "reset timestamps at the begin of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
850 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
854 static const AVClass seg_class = {
855 .class_name = "segment muxer",
856 .item_name = av_default_item_name,
858 .version = LIBAVUTIL_VERSION_INT,
861 AVOutputFormat ff_segment_muxer = {
863 .long_name = NULL_IF_CONFIG_SMALL("segment"),
864 .priv_data_size = sizeof(SegmentContext),
865 .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
866 .write_header = seg_write_header,
867 .write_packet = seg_write_packet,
868 .write_trailer = seg_write_trailer,
869 .priv_class = &seg_class,
872 static const AVClass sseg_class = {
873 .class_name = "stream_segment muxer",
874 .item_name = av_default_item_name,
876 .version = LIBAVUTIL_VERSION_INT,
879 AVOutputFormat ff_stream_segment_muxer = {
880 .name = "stream_segment,ssegment",
881 .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
882 .priv_data_size = sizeof(SegmentContext),
883 .flags = AVFMT_NOFILE,
884 .write_header = seg_write_header,
885 .write_packet = seg_write_packet,
886 .write_trailer = seg_write_trailer,
887 .priv_class = &sseg_class,