FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/segment.c
Date: 2025-10-10 03:51:19
Exec Total Coverage
Lines: 324 572 56.6%
Functions: 13 18 72.2%
Branches: 176 417 42.2%

Line Branch Exec Source
1 /*
2 * Copyright (c) 2011, Luca Barbato
3 *
4 * This file is part of FFmpeg.
5 *
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.
10 *
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.
15 *
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
19 */
20
21 /**
22 * @file generic segmenter
23 * M3U8 specification can be find here:
24 * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming}
25 */
26
27 #include "config_components.h"
28
29 #include <time.h>
30
31 #include "avformat.h"
32 #include "internal.h"
33 #include "mux.h"
34
35 #include "libavutil/avassert.h"
36 #include "libavutil/internal.h"
37 #include "libavutil/log.h"
38 #include "libavutil/mem.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/avstring.h"
41 #include "libavutil/bprint.h"
42 #include "libavutil/parseutils.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/time.h"
45 #include "libavutil/timecode.h"
46 #include "libavutil/time_internal.h"
47 #include "libavutil/timestamp.h"
48
49 typedef struct SegmentListEntry {
50 int index;
51 double start_time, end_time;
52 int64_t start_pts;
53 int64_t offset_pts;
54 char *filename;
55 struct SegmentListEntry *next;
56 int64_t last_duration;
57 } SegmentListEntry;
58
59 typedef enum {
60 LIST_TYPE_UNDEFINED = -1,
61 LIST_TYPE_FLAT = 0,
62 LIST_TYPE_CSV,
63 LIST_TYPE_M3U8,
64 LIST_TYPE_EXT, ///< deprecated
65 LIST_TYPE_FFCONCAT,
66 LIST_TYPE_NB,
67 } ListType;
68
69 #define SEGMENT_LIST_FLAG_CACHE 1
70 #define SEGMENT_LIST_FLAG_LIVE 2
71
72 typedef struct SegmentContext {
73 const AVClass *class; /**< Class for private options. */
74 int segment_idx; ///< index of the segment file to write, starting from 0
75 int segment_idx_wrap; ///< number after which the index wraps
76 int segment_idx_wrap_nb; ///< number of time the index has wrapped
77 int segment_count; ///< number of segment files already written
78 const AVOutputFormat *oformat;
79 AVFormatContext *avf;
80 char *format; ///< format to use for output segment files
81 AVDictionary *format_options;
82 char *list; ///< filename for the segment list file
83 int list_flags; ///< flags affecting list generation
84 int list_size; ///< number of entries for the segment list file
85
86 int is_nullctx; ///< whether avf->pb is a nullctx
87 int use_clocktime; ///< flag to cut segments at regular clock time
88 int64_t clocktime_offset; //< clock offset for cutting the segments at regular clock time
89 int64_t clocktime_wrap_duration; //< wrapping duration considered for starting a new segment
90 int64_t last_val; ///< remember last time for wrap around detection
91 int cut_pending;
92 int header_written; ///< whether we've already called avformat_write_header
93
94 char *entry_prefix; ///< prefix to add to list entry filenames
95 int list_type; ///< set the list type
96 AVIOContext *list_pb; ///< list file put-byte context
97 int64_t time; ///< segment duration
98 int64_t min_seg_duration; ///< minimum segment duration
99 int use_strftime; ///< flag to expand filename with strftime
100 int increment_tc; ///< flag to increment timecode if found
101
102 char *times_str; ///< segment times specification string
103 int64_t *times; ///< list of segment interval specification
104 int nb_times; ///< number of elements in the times array
105
106 char *frames_str; ///< segment frame numbers specification string
107 int *frames; ///< list of frame number specification
108 int nb_frames; ///< number of elements in the frames array
109 int frame_count; ///< total number of reference frames
110 int segment_frame_count; ///< number of reference frames in the segment
111
112 int64_t time_delta;
113 int individual_header_trailer; /**< Set by a private option. */
114 int write_header_trailer; /**< Set by a private option. */
115 char *header_filename; ///< filename to write the output header to
116
117 int reset_timestamps; ///< reset timestamps at the beginning of each segment
118 int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds
119 char *reference_stream_specifier; ///< reference stream specifier
120 int reference_stream_index;
121 int64_t reference_stream_first_pts; ///< initial timestamp, expressed in microseconds
122 int break_non_keyframes;
123 int write_empty;
124
125 int use_rename;
126 char *temp_list_filename;
127
128 SegmentListEntry cur_entry;
129 SegmentListEntry *segment_list_entries;
130 SegmentListEntry *segment_list_entries_end;
131 } SegmentContext;
132
133 static void print_csv_escaped_str(AVIOContext *ctx, const char *str)
134 {
135 int needs_quoting = !!str[strcspn(str, "\",\n\r")];
136
137 if (needs_quoting)
138 avio_w8(ctx, '"');
139
140 for (; *str; str++) {
141 if (*str == '"')
142 avio_w8(ctx, '"');
143 avio_w8(ctx, *str);
144 }
145 if (needs_quoting)
146 avio_w8(ctx, '"');
147 }
148
149 13 static int segment_mux_init(AVFormatContext *s)
150 {
151 13 SegmentContext *seg = s->priv_data;
152 AVFormatContext *oc;
153 int i;
154 int ret;
155
156 13 ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL);
157
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 13 times.
13 if (ret < 0)
158 return ret;
159 13 oc = seg->avf;
160
161 13 oc->interrupt_callback = s->interrupt_callback;
162 13 oc->max_delay = s->max_delay;
163 13 av_dict_copy(&oc->metadata, s->metadata, 0);
164 13 oc->opaque = s->opaque;
165 13 oc->io_close2 = s->io_close2;
166 13 oc->io_open = s->io_open;
167 13 oc->flags = s->flags;
168
169
2/2
✓ Branch 0 taken 13 times.
✓ Branch 1 taken 13 times.
26 for (i = 0; i < s->nb_streams; i++) {
170 13 AVStream *st, *ist = s->streams[i];
171 13 AVCodecParameters *ipar = ist->codecpar, *opar;
172
173 13 st = ff_stream_clone(oc, ist);
174
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 13 times.
13 if (!st)
175 return AVERROR(ENOMEM);
176 13 opar = st->codecpar;
177
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 9 times.
13 if (!oc->oformat->codec_tag ||
178
2/4
✓ Branch 1 taken 4 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 4 times.
8 av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == opar->codec_id ||
179 4 av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) {
180 9 opar->codec_tag = ipar->codec_tag;
181 } else {
182 4 opar->codec_tag = 0;
183 }
184 }
185
186 13 return 0;
187 }
188
189 15 static int set_segment_filename(AVFormatContext *s)
190 {
191 15 SegmentContext *seg = s->priv_data;
192 15 AVFormatContext *oc = seg->avf;
193 size_t size;
194 int ret;
195 AVBPrint filename;
196 char *new_name;
197
198 15 av_bprint_init(&filename, 0, AV_BPRINT_SIZE_UNLIMITED);
199
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (seg->segment_idx_wrap)
200 seg->segment_idx %= seg->segment_idx_wrap;
201
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (seg->use_strftime) {
202 time_t now0;
203 struct tm *tm, tmpbuf;
204 time(&now0);
205 tm = localtime_r(&now0, &tmpbuf);
206 av_bprint_strftime(&filename, s->url, tm);
207 if (!av_bprint_is_complete(&filename)) {
208 av_bprint_finalize(&filename, NULL);
209 return AVERROR(ENOMEM);
210 }
211 } else {
212 15 ret = ff_bprint_get_frame_filename(&filename, s->url, seg->segment_idx, 0);
213
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (ret < 0) {
214 av_bprint_finalize(&filename, NULL);
215 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->url);
216 return ret;
217 }
218 }
219 15 ret = av_bprint_finalize(&filename, &new_name);
220
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (ret < 0)
221 return ret;
222 15 ff_format_set_url(oc, new_name);
223
224 /* copy modified name in list entry */
225 15 size = strlen(av_basename(oc->url)) + 1;
226
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (seg->entry_prefix)
227 size += strlen(seg->entry_prefix);
228
229
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 15 times.
15 if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0)
230 return ret;
231 15 snprintf(seg->cur_entry.filename, size, "%s%s",
232
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 seg->entry_prefix ? seg->entry_prefix : "",
233 15 av_basename(oc->url));
234
235 15 return 0;
236 }
237
238 10 static int segment_start(AVFormatContext *s, int write_header)
239 {
240 10 SegmentContext *seg = s->priv_data;
241 10 AVFormatContext *oc = seg->avf;
242 10 int err = 0;
243
244
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 2 times.
10 if (write_header) {
245 8 avformat_free_context(oc);
246 8 seg->avf = NULL;
247
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
8 if ((err = segment_mux_init(s)) < 0)
248 return err;
249 8 oc = seg->avf;
250 }
251
252 10 seg->segment_idx++;
253
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
10 if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
254 seg->segment_idx_wrap_nb++;
255
256
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if ((err = set_segment_filename(s)) < 0)
257 return err;
258
259
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if ((err = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0) {
260 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url);
261 return err;
262 }
263
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 8 times.
10 if (!seg->individual_header_trailer)
264 2 oc->pb->seekable = 0;
265
266
2/4
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
✗ Branch 3 not taken.
10 if (oc->oformat->priv_class && oc->priv_data)
267 10 av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0);
268
269
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 2 times.
10 if (write_header) {
270 8 AVDictionary *options = NULL;
271 8 av_dict_copy(&options, seg->format_options, 0);
272 8 av_dict_set(&options, "fflags", "-autobsf", 0);
273 8 err = avformat_write_header(oc, &options);
274 8 av_dict_free(&options);
275
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8 times.
8 if (err < 0)
276 return err;
277 }
278
279 10 seg->segment_frame_count = 0;
280 10 return 0;
281 }
282
283 12 static int segment_list_open(AVFormatContext *s)
284 {
285 12 SegmentContext *seg = s->priv_data;
286 int ret;
287
288 12 av_freep(&seg->temp_list_filename);
289
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 seg->temp_list_filename = av_asprintf(seg->use_rename ? "%s.tmp" : "%s", seg->list);
290
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 12 times.
12 if (!seg->temp_list_filename)
291 return AVERROR(ENOMEM);
292 12 ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL);
293
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 12 times.
12 if (ret < 0) {
294 av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list);
295 return ret;
296 }
297
298
2/4
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 12 times.
✗ Branch 3 not taken.
24 if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) {
299 SegmentListEntry *entry;
300 12 double max_duration = 0;
301
302 12 avio_printf(seg->list_pb, "#EXTM3U\n");
303 12 avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n");
304 12 avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index);
305 12 avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n",
306
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO");
307
308 12 av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n",
309 12 seg->segment_list_entries->index);
310
311
2/2
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 12 times.
39 for (entry = seg->segment_list_entries; entry; entry = entry->next)
312
2/2
✓ Branch 0 taken 13 times.
✓ Branch 1 taken 14 times.
27 max_duration = FFMAX(max_duration, entry->end_time - entry->start_time);
313 12 avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration));
314 } else if (seg->list_type == LIST_TYPE_FFCONCAT) {
315 avio_printf(seg->list_pb, "ffconcat version 1.0\n");
316 }
317
318 12 return ret;
319 }
320
321 27 static void segment_list_print_entry(AVIOContext *list_ioctx,
322 ListType list_type,
323 const SegmentListEntry *list_entry,
324 void *log_ctx)
325 {
326
1/5
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✓ Branch 2 taken 27 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
27 switch (list_type) {
327 case LIST_TYPE_FLAT:
328 avio_printf(list_ioctx, "%s\n", list_entry->filename);
329 break;
330 case LIST_TYPE_CSV:
331 case LIST_TYPE_EXT:
332 print_csv_escaped_str(list_ioctx, list_entry->filename);
333 avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time);
334 break;
335 27 case LIST_TYPE_M3U8:
336 27 avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n",
337 27 list_entry->end_time - list_entry->start_time, list_entry->filename);
338 27 break;
339 case LIST_TYPE_FFCONCAT:
340 {
341 char *buf;
342 if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) {
343 av_log(log_ctx, AV_LOG_WARNING,
344 "Error writing list entry '%s' in list file\n", list_entry->filename);
345 return;
346 }
347 avio_printf(list_ioctx, "file %s\n", buf);
348 av_free(buf);
349 break;
350 }
351 default:
352 av_assert0(!"Invalid list type");
353 }
354 }
355
356 15 static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
357 {
358 15 SegmentContext *seg = s->priv_data;
359 15 AVFormatContext *oc = seg->avf;
360 15 int ret = 0;
361 AVTimecode tc;
362 AVRational rate;
363 AVDictionaryEntry *tcr;
364 char buf[AV_TIMECODE_STR_SIZE];
365 int i;
366 int err;
367
368
2/4
✓ Branch 0 taken 15 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 15 times.
15 if (!oc || !oc->pb)
369 return AVERROR(EINVAL);
370
371 15 av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */
372
2/2
✓ Branch 0 taken 13 times.
✓ Branch 1 taken 2 times.
15 if (write_trailer)
373 13 ret = av_write_trailer(oc);
374
375
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (ret < 0)
376 av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
377 oc->url);
378
379
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 3 times.
15 if (seg->list) {
380
2/4
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 12 times.
✗ Branch 3 not taken.
24 if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
381 12 SegmentListEntry *entry = av_mallocz(sizeof(*entry));
382
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 12 times.
12 if (!entry) {
383 ret = AVERROR(ENOMEM);
384 goto end;
385 }
386
387 /* append new element */
388 12 memcpy(entry, &seg->cur_entry, sizeof(*entry));
389 12 entry->filename = av_strdup(entry->filename);
390
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 8 times.
12 if (!seg->segment_list_entries)
391 4 seg->segment_list_entries = seg->segment_list_entries_end = entry;
392 else
393 8 seg->segment_list_entries_end->next = entry;
394 12 seg->segment_list_entries_end = entry;
395
396 /* drop first item */
397
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 12 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
12 if (seg->list_size && seg->segment_count >= seg->list_size) {
398 entry = seg->segment_list_entries;
399 seg->segment_list_entries = seg->segment_list_entries->next;
400 av_freep(&entry->filename);
401 av_freep(&entry);
402 }
403
404
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 12 times.
12 if ((ret = segment_list_open(s)) < 0)
405 goto end;
406
2/2
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 12 times.
39 for (entry = seg->segment_list_entries; entry; entry = entry->next)
407 27 segment_list_print_entry(seg->list_pb, seg->list_type, entry, s);
408
3/4
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✓ Branch 3 taken 8 times.
12 if (seg->list_type == LIST_TYPE_M3U8 && is_last)
409 4 avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n");
410 12 ff_format_io_close(s, &seg->list_pb);
411
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 if (seg->use_rename)
412 12 ff_rename(seg->temp_list_filename, seg->list, s);
413 } else {
414 segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s);
415 avio_flush(seg->list_pb);
416 }
417 }
418
419 15 av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n",
420 15 seg->avf->url, seg->segment_count);
421 15 seg->segment_count++;
422
423
1/2
✓ Branch 0 taken 15 times.
✗ Branch 1 not taken.
15 if (seg->increment_tc) {
424 tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
425 if (tcr) {
426 /* search the first video stream */
427 for (i = 0; i < s->nb_streams; i++) {
428 if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
429 rate = s->streams[i]->avg_frame_rate;/* Get fps from the video stream */
430 err = av_timecode_init_from_string(&tc, rate, tcr->value, s);
431 if (err < 0) {
432 av_log(s, AV_LOG_WARNING, "Could not increment global timecode, error occurred during timecode creation.\n");
433 break;
434 }
435 tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(rate));/* increment timecode */
436 av_dict_set(&s->metadata, "timecode",
437 av_timecode_make_string(&tc, buf, 0), 0);
438 break;
439 }
440 }
441 } else {
442 av_log(s, AV_LOG_WARNING, "Could not increment global timecode, no global timecode metadata found.\n");
443 }
444 for (i = 0; i < s->nb_streams; i++) {
445 if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
446 char st_buf[AV_TIMECODE_STR_SIZE];
447 AVTimecode st_tc;
448 AVRational st_rate = s->streams[i]->avg_frame_rate;
449 AVDictionaryEntry *st_tcr = av_dict_get(s->streams[i]->metadata, "timecode", NULL, 0);
450 if (st_tcr) {
451 if ((av_timecode_init_from_string(&st_tc, st_rate, st_tcr->value, s) < 0)) {
452 av_log(s, AV_LOG_WARNING, "Could not increment stream %d timecode, error occurred during timecode creation.\n", i);
453 continue;
454 }
455 st_tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(st_rate)); // increment timecode
456 av_dict_set(&s->streams[i]->metadata, "timecode", av_timecode_make_string(&st_tc, st_buf, 0), 0);
457 }
458 }
459 }
460 }
461
462 15 end:
463 15 ff_format_io_close(oc, &oc->pb);
464
465 15 return ret;
466 }
467
468 static int parse_times(void *log_ctx, int64_t **times, int *nb_times,
469 const char *times_str)
470 {
471 char *p;
472 int i, ret = 0;
473 char *times_str1 = av_strdup(times_str);
474 char *saveptr = NULL;
475
476 if (!times_str1)
477 return AVERROR(ENOMEM);
478
479 #define FAIL(err) ret = err; goto end
480
481 *nb_times = 1;
482 for (p = times_str1; *p; p++)
483 if (*p == ',')
484 (*nb_times)++;
485
486 *times = av_malloc_array(*nb_times, sizeof(**times));
487 if (!*times) {
488 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n");
489 FAIL(AVERROR(ENOMEM));
490 }
491
492 p = times_str1;
493 for (i = 0; i < *nb_times; i++) {
494 int64_t t;
495 char *tstr = av_strtok(p, ",", &saveptr);
496 p = NULL;
497
498 if (!tstr || !tstr[0]) {
499 av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n",
500 times_str);
501 FAIL(AVERROR(EINVAL));
502 }
503
504 ret = av_parse_time(&t, tstr, 1);
505 if (ret < 0) {
506 av_log(log_ctx, AV_LOG_ERROR,
507 "Invalid time duration specification '%s' in times list %s\n", tstr, times_str);
508 FAIL(AVERROR(EINVAL));
509 }
510 (*times)[i] = t;
511
512 /* check on monotonicity */
513 if (i && (*times)[i-1] > (*times)[i]) {
514 av_log(log_ctx, AV_LOG_ERROR,
515 "Specified time %f is smaller than the last time %f\n",
516 (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000);
517 FAIL(AVERROR(EINVAL));
518 }
519 }
520
521 end:
522 av_free(times_str1);
523 return ret;
524 }
525
526 static int parse_frames(void *log_ctx, int **frames, int *nb_frames,
527 const char *frames_str)
528 {
529 const char *p;
530 int i;
531
532 *nb_frames = 1;
533 for (p = frames_str; *p; p++)
534 if (*p == ',')
535 (*nb_frames)++;
536
537 *frames = av_malloc_array(*nb_frames, sizeof(**frames));
538 if (!*frames) {
539 av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n");
540 return AVERROR(ENOMEM);
541 }
542
543 p = frames_str;
544 for (i = 0; i < *nb_frames; i++) {
545 long int f;
546 char *tailptr;
547
548 if (*p == '\0' || *p == ',') {
549 av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n",
550 frames_str);
551 return AVERROR(EINVAL);
552 }
553 f = strtol(p, &tailptr, 10);
554 if (*tailptr != '\0' && *tailptr != ',' || f <= 0 || f >= INT_MAX) {
555 av_log(log_ctx, AV_LOG_ERROR,
556 "Invalid argument '%s', must be a positive integer < INT_MAX\n",
557 p);
558 return AVERROR(EINVAL);
559 }
560 if (*tailptr == ',')
561 tailptr++;
562 p = tailptr;
563 (*frames)[i] = f;
564
565 /* check on monotonicity */
566 if (i && (*frames)[i-1] > (*frames)[i]) {
567 av_log(log_ctx, AV_LOG_ERROR,
568 "Specified frame %d is smaller than the last frame %d\n",
569 (*frames)[i], (*frames)[i-1]);
570 return AVERROR(EINVAL);
571 }
572 }
573
574 return 0;
575 }
576
577 static int open_null_ctx(AVIOContext **ctx)
578 {
579 int buf_size = 32768;
580 uint8_t *buf = av_malloc(buf_size);
581 if (!buf)
582 return AVERROR(ENOMEM);
583 *ctx = avio_alloc_context(buf, buf_size, 1, NULL, NULL, NULL, NULL);
584 if (!*ctx) {
585 av_free(buf);
586 return AVERROR(ENOMEM);
587 }
588 return 0;
589 }
590
591 static void close_null_ctxp(AVIOContext **pb)
592 {
593 av_freep(&(*pb)->buffer);
594 avio_context_free(pb);
595 }
596
597 5 static int select_reference_stream(AVFormatContext *s)
598 {
599 5 SegmentContext *seg = s->priv_data;
600 int ret, i;
601
602 5 seg->reference_stream_index = -1;
603
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (!strcmp(seg->reference_stream_specifier, "auto")) {
604 /* select first index of type with highest priority */
605 int type_index_map[AVMEDIA_TYPE_NB];
606 static const enum AVMediaType type_priority_list[] = {
607 AVMEDIA_TYPE_VIDEO,
608 AVMEDIA_TYPE_AUDIO,
609 AVMEDIA_TYPE_SUBTITLE,
610 AVMEDIA_TYPE_DATA,
611 AVMEDIA_TYPE_ATTACHMENT
612 };
613 enum AVMediaType type;
614
615
2/2
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 5 times.
30 for (i = 0; i < AVMEDIA_TYPE_NB; i++)
616 25 type_index_map[i] = -1;
617
618 /* select first index for each type */
619
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 5 times.
10 for (i = 0; i < s->nb_streams; i++) {
620 5 type = s->streams[i]->codecpar->codec_type;
621
2/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
5 if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1
622 /* ignore attached pictures/cover art streams */
623
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC))
624 5 type_index_map[type] = i;
625 }
626
627
1/2
✓ Branch 0 taken 9 times.
✗ Branch 1 not taken.
9 for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) {
628 9 type = type_priority_list[i];
629
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 4 times.
9 if ((seg->reference_stream_index = type_index_map[type]) >= 0)
630 5 break;
631 }
632 } else {
633 for (i = 0; i < s->nb_streams; i++) {
634 ret = avformat_match_stream_specifier(s, s->streams[i],
635 seg->reference_stream_specifier);
636 if (ret < 0)
637 return ret;
638 if (ret > 0) {
639 seg->reference_stream_index = i;
640 break;
641 }
642 }
643 }
644
645
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->reference_stream_index < 0) {
646 av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n",
647 seg->reference_stream_specifier);
648 return AVERROR(EINVAL);
649 }
650
651 5 return 0;
652 }
653
654 5 static void seg_free(AVFormatContext *s)
655 {
656 5 SegmentContext *seg = s->priv_data;
657 SegmentListEntry *cur;
658
659 5 ff_format_io_close(s, &seg->list_pb);
660
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (seg->avf) {
661
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->is_nullctx)
662 close_null_ctxp(&seg->avf->pb);
663 else
664 5 ff_format_io_close(s, &seg->avf->pb);
665 5 avformat_free_context(seg->avf);
666 5 seg->avf = NULL;
667 }
668 5 av_freep(&seg->times);
669 5 av_freep(&seg->frames);
670 5 av_freep(&seg->cur_entry.filename);
671 5 av_freep(&seg->temp_list_filename);
672
673 5 cur = seg->segment_list_entries;
674
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 5 times.
17 while (cur) {
675 12 SegmentListEntry *next = cur->next;
676 12 av_freep(&cur->filename);
677 12 av_free(cur);
678 12 cur = next;
679 }
680 5 }
681
682 5 static int seg_init(AVFormatContext *s)
683 {
684 5 SegmentContext *seg = s->priv_data;
685 5 AVFormatContext *oc = seg->avf;
686 5 AVDictionary *options = NULL;
687 int ret;
688 int i;
689
690 5 seg->segment_count = 0;
691
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (!seg->write_header_trailer)
692 seg->individual_header_trailer = 0;
693
694
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 4 times.
5 if (seg->header_filename) {
695 1 seg->write_header_trailer = 1;
696 1 seg->individual_header_trailer = 0;
697 }
698
699
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->initial_offset > 0) {
700 av_log(s, AV_LOG_WARNING, "NOTE: the option initial_offset is deprecated,"
701 "you can use output_ts_offset instead of it\n");
702 }
703
704
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if ((seg->time != 2000000) + !!seg->times_str + !!seg->frames_str > 1) {
705 av_log(s, AV_LOG_ERROR,
706 "segment_time, segment_times, and segment_frames options "
707 "are mutually exclusive, select just one of them\n");
708 return AVERROR(EINVAL);
709 }
710
711
2/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 5 times.
5 if (seg->times_str || seg->frames_str)
712 seg->min_seg_duration = 0;
713
714
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->times_str) {
715 if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0)
716 return ret;
717
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 } else if (seg->frames_str) {
718 if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0)
719 return ret;
720 } else {
721
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->use_clocktime) {
722 if (seg->time <= 0) {
723 av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n");
724 return AVERROR(EINVAL);
725 }
726 seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time);
727 }
728
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->min_seg_duration > seg->time) {
729 av_log(s, AV_LOG_ERROR, "min_seg_duration cannot be greater than segment_time\n");
730 return AVERROR(EINVAL);
731 }
732 }
733
734
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 1 times.
5 if (seg->list) {
735
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 if (seg->list_type == LIST_TYPE_UNDEFINED) {
736
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
4 if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV;
737
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
4 else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT;
738
1/2
✓ Branch 1 taken 4 times.
✗ Branch 2 not taken.
4 else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8;
739 else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT;
740 else seg->list_type = LIST_TYPE_FLAT;
741 }
742
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 4 times.
4 if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) {
743 if ((ret = segment_list_open(s)) < 0)
744 return ret;
745 } else {
746 4 const char *proto = avio_find_protocol_name(seg->list);
747
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 seg->use_rename = proto && !strcmp(proto, "file");
748 }
749 }
750
751
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->list_type == LIST_TYPE_EXT)
752 av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n");
753
754
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
5 if ((ret = select_reference_stream(s)) < 0)
755 return ret;
756 5 av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n",
757 seg->reference_stream_index,
758 5 av_get_media_type_string(s->streams[seg->reference_stream_index]->codecpar->codec_type));
759
760 5 seg->reference_stream_first_pts = AV_NOPTS_VALUE;
761
762 5 seg->oformat = av_guess_format(seg->format, s->url, NULL);
763
764
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (!seg->oformat)
765 return AVERROR_MUXER_NOT_FOUND;
766
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (seg->oformat->flags & AVFMT_NOFILE) {
767 av_log(s, AV_LOG_ERROR, "format %s not supported.\n",
768 seg->oformat->name);
769 return AVERROR(EINVAL);
770 }
771
772
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
5 if ((ret = segment_mux_init(s)) < 0)
773 return ret;
774
775
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
5 if ((ret = set_segment_filename(s)) < 0)
776 return ret;
777 5 oc = seg->avf;
778
779
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (seg->write_header_trailer) {
780
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
5 if ((ret = s->io_open(s, &oc->pb,
781
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 4 times.
5 seg->header_filename ? seg->header_filename : oc->url,
782 AVIO_FLAG_WRITE, NULL)) < 0) {
783 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url);
784 return ret;
785 }
786
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 4 times.
5 if (!seg->individual_header_trailer)
787 1 oc->pb->seekable = 0;
788 } else {
789 if ((ret = open_null_ctx(&oc->pb)) < 0)
790 return ret;
791 seg->is_nullctx = 1;
792 }
793
794 5 av_dict_copy(&options, seg->format_options, 0);
795 5 av_dict_set(&options, "fflags", "-autobsf", 0);
796 5 ret = avformat_init_output(oc, &options);
797
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
5 if (av_dict_count(options)) {
798 av_log(s, AV_LOG_ERROR,
799 "Some of the provided format options are not recognized\n");
800 av_dict_free(&options);
801 return AVERROR(EINVAL);
802 }
803 5 av_dict_free(&options);
804
805
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (ret < 0) {
806 return ret;
807 }
808 5 seg->segment_frame_count = 0;
809
810
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 av_assert0(s->nb_streams == oc->nb_streams);
811
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (ret == AVSTREAM_INIT_IN_WRITE_HEADER) {
812 ret = avformat_write_header(oc, NULL);
813 if (ret < 0)
814 return ret;
815 seg->header_written = 1;
816 }
817
818
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 5 times.
10 for (i = 0; i < s->nb_streams; i++) {
819 5 AVStream *inner_st = oc->streams[i];
820 5 AVStream *outer_st = s->streams[i];
821 5 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
822 }
823
824
2/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
5 if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0)
825 5 s->avoid_negative_ts = 1;
826
827 5 return ret;
828 }
829
830 5 static int seg_write_header(AVFormatContext *s)
831 {
832 5 SegmentContext *seg = s->priv_data;
833 5 AVFormatContext *oc = seg->avf;
834 int ret;
835
836
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (!seg->header_written) {
837 5 ret = avformat_write_header(oc, NULL);
838
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (ret < 0)
839 return ret;
840 }
841
842
3/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 4 times.
5 if (!seg->write_header_trailer || seg->header_filename) {
843
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (seg->header_filename) {
844 1 av_write_frame(oc, NULL);
845 1 ff_format_io_close(oc, &oc->pb);
846 } else {
847 close_null_ctxp(&oc->pb);
848 seg->is_nullctx = 0;
849 }
850
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
1 if ((ret = oc->io_open(oc, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0)
851 return ret;
852
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (!seg->individual_header_trailer)
853 1 oc->pb->seekable = 0;
854 }
855
856 5 return 0;
857 }
858
859 1726 static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
860 {
861 1726 SegmentContext *seg = s->priv_data;
862 1726 AVStream *st = s->streams[pkt->stream_index];
863 1726 int64_t end_pts = INT64_MAX, offset, pkt_pts_avtb;
864 1726 int start_frame = INT_MAX;
865 int ret;
866 struct tm ti;
867 int64_t usecs;
868 int64_t wrapped_val;
869
870
2/4
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1726 times.
1726 if (!seg->avf || !seg->avf->pb)
871 return AVERROR(EINVAL);
872
873
2/2
✓ Branch 0 taken 194 times.
✓ Branch 1 taken 1532 times.
1726 if (!st->codecpar->extradata_size) {
874 size_t pkt_extradata_size;
875 1532 uint8_t *pkt_extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &pkt_extradata_size);
876
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 1532 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
1532 if (pkt_extradata && pkt_extradata_size > 0) {
877 ret = ff_alloc_extradata(st->codecpar, pkt_extradata_size);
878 if (ret < 0) {
879 av_log(s, AV_LOG_WARNING, "Unable to add extradata to stream. Output segments may be invalid.\n");
880 goto calc_times;
881 }
882 memcpy(st->codecpar->extradata, pkt_extradata, pkt_extradata_size);
883 }
884 }
885
886 1726 calc_times:
887
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1726 times.
1726 if (seg->times) {
888 end_pts = seg->segment_count < seg->nb_times ?
889 seg->times[seg->segment_count] : INT64_MAX;
890
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1726 times.
1726 } else if (seg->frames) {
891 start_frame = seg->segment_count < seg->nb_frames ?
892 seg->frames[seg->segment_count] : INT_MAX;
893 } else {
894
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1726 times.
1726 if (seg->use_clocktime) {
895 int64_t avgt = av_gettime();
896 time_t sec = avgt / 1000000;
897 localtime_r(&sec, &ti);
898 usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);
899 wrapped_val = (usecs + seg->clocktime_offset) % seg->time;
900 if (wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration)
901 seg->cut_pending = 1;
902 seg->last_val = wrapped_val;
903 } else {
904 1726 end_pts = seg->time * (seg->segment_count + 1);
905 }
906 }
907
908 ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",
909 pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
910 av_ts2timestr(pkt->duration, &st->time_base),
911 pkt->flags & AV_PKT_FLAG_KEY,
912 pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);
913
914
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 1721 times.
1726 if (seg->reference_stream_first_pts == AV_NOPTS_VALUE &&
915
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 pkt->stream_index == seg->reference_stream_index &&
916
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 pkt->pts != AV_NOPTS_VALUE) {
917 5 seg->reference_stream_first_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
918 }
919
920
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (seg->reference_stream_first_pts != AV_NOPTS_VALUE) {
921 1726 end_pts += (INT64_MAX - end_pts >= seg->reference_stream_first_pts) ?
922 1726 seg->reference_stream_first_pts :
923 INT64_MAX - end_pts;
924 }
925
926
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->pts != AV_NOPTS_VALUE)
927 1726 pkt_pts_avtb = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
928
929
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->stream_index == seg->reference_stream_index &&
930
3/4
✓ Branch 0 taken 120 times.
✓ Branch 1 taken 1606 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 120 times.
1726 (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&
931
3/4
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 1601 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 5 times.
1606 (seg->segment_frame_count > 0 || seg->write_empty) &&
932
2/4
✓ Branch 0 taken 1601 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1601 times.
✗ Branch 3 not taken.
1601 (seg->cut_pending || seg->frame_count >= start_frame ||
933
1/2
✓ Branch 0 taken 1601 times.
✗ Branch 1 not taken.
1601 (pkt->pts != AV_NOPTS_VALUE &&
934
3/4
✓ Branch 0 taken 1601 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
✓ Branch 3 taken 1591 times.
3202 pkt_pts_avtb - seg->cur_entry.start_pts >= seg->min_seg_duration &&
935 1601 av_compare_ts(pkt->pts, st->time_base,
936 1601 end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) {
937 /* sanitize end time in case last packet didn't have a defined duration */
938
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (seg->cur_entry.last_duration == 0)
939 seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);
940
941
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)
942 goto fail;
943
944
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)
945 goto fail;
946
947 10 seg->cut_pending = 0;
948 10 seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;
949 10 seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);
950 10 seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
951 10 seg->cur_entry.end_time = seg->cur_entry.start_time;
952
953
4/8
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 10 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 10 times.
10 if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty)
954 goto calc_times;
955 }
956
957
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->stream_index == seg->reference_stream_index) {
958
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->pts != AV_NOPTS_VALUE)
959 1726 seg->cur_entry.end_time =
960
2/2
✓ Branch 1 taken 91 times.
✓ Branch 2 taken 1635 times.
1726 FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));
961 1726 seg->cur_entry.last_duration = pkt->duration;
962 }
963
964
2/2
✓ Branch 0 taken 15 times.
✓ Branch 1 taken 1711 times.
1726 if (seg->segment_frame_count == 0) {
965 45 av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",
966 15 seg->avf->url, pkt->stream_index,
967 15 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);
968 }
969
970 1726 av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",
971 pkt->stream_index,
972 1726 av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),
973 1726 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
974 1726 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
975
976 /* compute new timestamps */
977 1726 offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),
978
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1726 times.
1726 AV_TIME_BASE_Q, st->time_base);
979
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->pts != AV_NOPTS_VALUE)
980 1726 pkt->pts += offset;
981
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (pkt->dts != AV_NOPTS_VALUE)
982 1726 pkt->dts += offset;
983
984 1726 av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
985 1726 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
986 1726 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
987
988 1726 ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s,
989
2/4
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1726 times.
✗ Branch 3 not taken.
1726 seg->initial_offset || seg->reset_timestamps ||
990
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1726 times.
1726 ffofmt(seg->avf->oformat)->interleave_packet);
991
992 1726 fail:
993 /* Use st->index here as the packet returned from ff_write_chained()
994 * is blank if interleaving has been used. */
995
1/2
✓ Branch 0 taken 1726 times.
✗ Branch 1 not taken.
1726 if (st->index == seg->reference_stream_index) {
996 1726 seg->frame_count++;
997 1726 seg->segment_frame_count++;
998 }
999
1000 1726 return ret;
1001 }
1002
1003 5 static int seg_write_trailer(struct AVFormatContext *s)
1004 {
1005 5 SegmentContext *seg = s->priv_data;
1006 5 AVFormatContext *oc = seg->avf;
1007 int ret;
1008
1009
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (!oc)
1010 return 0;
1011
1012
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (!seg->write_header_trailer) {
1013 if ((ret = segment_end(s, 0, 1)) < 0)
1014 return ret;
1015 if ((ret = open_null_ctx(&oc->pb)) < 0)
1016 return ret;
1017 seg->is_nullctx = 1;
1018 ret = av_write_trailer(oc);
1019 } else {
1020 5 ret = segment_end(s, 1, 1);
1021 }
1022 5 return ret;
1023 }
1024
1025 5 static int seg_check_bitstream(AVFormatContext *s, AVStream *st,
1026 const AVPacket *pkt)
1027 {
1028 5 SegmentContext *seg = s->priv_data;
1029 5 AVFormatContext *oc = seg->avf;
1030
1/2
✓ Branch 1 taken 5 times.
✗ Branch 2 not taken.
5 if (ffofmt(oc->oformat)->check_bitstream) {
1031 5 AVStream *const ost = oc->streams[st->index];
1032 5 int ret = ffofmt(oc->oformat)->check_bitstream(oc, ost, pkt);
1033
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (ret == 1) {
1034 5 FFStream *const sti = ffstream(st);
1035 5 FFStream *const osti = ffstream(ost);
1036 5 sti->bsfc = osti->bsfc;
1037 5 osti->bsfc = NULL;
1038 }
1039 5 return ret;
1040 }
1041 return 1;
1042 }
1043
1044 #define OFFSET(x) offsetof(SegmentContext, x)
1045 #define E AV_OPT_FLAG_ENCODING_PARAM
1046 static const AVOption options[] = {
1047 { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, 0, 0, E },
1048 { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1049 { "segment_format_options", "set list of options for the container format used for the segments", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, E },
1050 { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1051 { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1052
1053 { "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, .unit = "list_flags"},
1054 { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, .unit = "list_flags"},
1055 { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, .unit = "list_flags"},
1056
1057 { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1058
1059 { "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, .unit = "list_type" },
1060 { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1061 { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1062 { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1063 { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1064 { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1065 { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, .unit = "list_type" },
1066
1067 { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
1068 { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E},
1069 { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E},
1070 { "segment_time", "set segment duration", OFFSET(time),AV_OPT_TYPE_DURATION, {.i64 = 2000000}, INT64_MIN, INT64_MAX, E },
1071 { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E },
1072 { "min_seg_duration", "set minimum segment duration", OFFSET(min_seg_duration), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E },
1073 { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
1074 { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E },
1075 { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1076 { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1077 { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1078 { "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 },
1079 { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1080 { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1081 { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1082
1083 { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
1084 { "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 },
1085 { "reset_timestamps", "reset timestamps at the beginning of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1086 { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E },
1087 { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
1088 { NULL },
1089 };
1090
1091 static const AVClass seg_class = {
1092 .class_name = "(stream) segment muxer",
1093 .item_name = av_default_item_name,
1094 .option = options,
1095 .version = LIBAVUTIL_VERSION_INT,
1096 };
1097
1098 #if CONFIG_SEGMENT_MUXER
1099 const FFOutputFormat ff_segment_muxer = {
1100 .p.name = "segment",
1101 .p.long_name = NULL_IF_CONFIG_SMALL("segment"),
1102 .p.flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER,
1103 .p.priv_class = &seg_class,
1104 .priv_data_size = sizeof(SegmentContext),
1105 .init = seg_init,
1106 .write_header = seg_write_header,
1107 .write_packet = seg_write_packet,
1108 .write_trailer = seg_write_trailer,
1109 .deinit = seg_free,
1110 .check_bitstream = seg_check_bitstream,
1111 };
1112 #endif
1113
1114 #if CONFIG_STREAM_SEGMENT_MUXER
1115 const FFOutputFormat ff_stream_segment_muxer = {
1116 .p.name = "stream_segment,ssegment",
1117 .p.long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"),
1118 .p.flags = AVFMT_NOFILE,
1119 .p.priv_class = &seg_class,
1120 .priv_data_size = sizeof(SegmentContext),
1121 .init = seg_init,
1122 .write_header = seg_write_header,
1123 .write_packet = seg_write_packet,
1124 .write_trailer = seg_write_trailer,
1125 .deinit = seg_free,
1126 .check_bitstream = seg_check_bitstream,
1127 };
1128 #endif
1129