FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/internal.h
Date: 2025-04-25 22:50:00
Exec Total Coverage
Lines: 6 6 100.0%
Functions: 3 3 100.0%
Branches: 0 0 -%

Line Branch Exec Source
1 /*
2 * copyright (c) 2001 Fabrice Bellard
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 #ifndef AVFORMAT_INTERNAL_H
22 #define AVFORMAT_INTERNAL_H
23
24 #include <stdint.h>
25
26 #include "libavcodec/packet_internal.h"
27
28 #include "avformat.h"
29
30 #define MAX_URL_SIZE 4096
31
32 /** size of probe buffer, for guessing file type from file contents */
33 #define PROBE_BUF_MIN 2048
34 #define PROBE_BUF_MAX (1 << 20)
35
36 #ifdef DEBUG
37 # define hex_dump_debug(class, buf, size) av_hex_dump_log(class, AV_LOG_DEBUG, buf, size)
38 #else
39 # define hex_dump_debug(class, buf, size) do { if (0) av_hex_dump_log(class, AV_LOG_DEBUG, buf, size); } while(0)
40 #endif
41
42 typedef struct AVCodecTag {
43 enum AVCodecID id;
44 unsigned int tag;
45 } AVCodecTag;
46
47 typedef struct CodecMime{
48 char str[32];
49 enum AVCodecID id;
50 } CodecMime;
51
52 /*************************************************/
53 /* fractional numbers for exact pts handling */
54
55 /**
56 * The exact value of the fractional number is: 'val + num / den'.
57 * num is assumed to be 0 <= num < den.
58 */
59 typedef struct FFFrac {
60 int64_t val, num, den;
61 } FFFrac;
62
63
64 typedef struct FFFormatContext {
65 /**
66 * The public context.
67 */
68 AVFormatContext pub;
69
70 /**
71 * Whether the timestamp shift offset has already been determined.
72 * -1: disabled, 0: not yet determined, 1: determined.
73 */
74 enum {
75 AVOID_NEGATIVE_TS_DISABLED = -1,
76 AVOID_NEGATIVE_TS_UNKNOWN = 0,
77 AVOID_NEGATIVE_TS_KNOWN = 1,
78 } avoid_negative_ts_status;
79 #define AVOID_NEGATIVE_TS_ENABLED(status) ((status) >= 0)
80
81 /**
82 * This buffer is only needed when packets were already buffered but
83 * not decoded, for example to get the codec parameters in MPEG
84 * streams.
85 */
86 PacketList packet_buffer;
87
88 /* av_seek_frame() support */
89 int64_t data_offset; /**< offset of the first packet */
90
91 /**
92 * The generic code uses this as a temporary packet
93 * to parse packets or for muxing, especially flushing.
94 * For demuxers, it may also be used for other means
95 * for short periods that are guaranteed not to overlap
96 * with calls to av_read_frame() (or ff_read_packet())
97 * or with each other.
98 * It may be used by demuxers as a replacement for
99 * stack packets (unless they call one of the aforementioned
100 * functions with their own AVFormatContext).
101 * Every user has to ensure that this packet is blank
102 * after using it.
103 */
104 AVPacket *parse_pkt;
105
106 /**
107 * Used to hold temporary packets for the generic demuxing code.
108 * When muxing, it may be used by muxers to hold packets (even
109 * permanent ones).
110 */
111 AVPacket *pkt;
112
113 int avoid_negative_ts_use_pts;
114
115 /**
116 * ID3v2 tag useful for MP3 demuxing
117 */
118 AVDictionary *id3v2_meta;
119
120 int missing_streams;
121 } FFFormatContext;
122
123 1114109 static av_always_inline FFFormatContext *ffformatcontext(AVFormatContext *s)
124 {
125 1114109 return (FFFormatContext*)s;
126 }
127
128 typedef struct FFStream {
129 /**
130 * The public context.
131 */
132 AVStream pub;
133
134 AVFormatContext *fmtctx;
135 /**
136 * Set to 1 if the codec allows reordering, so pts can be different
137 * from dts.
138 */
139 int reorder;
140
141 /**
142 * bitstream filter to run on stream
143 * - encoding: Set by muxer using ff_stream_add_bitstream_filter
144 * - decoding: unused
145 */
146 struct AVBSFContext *bsfc;
147
148 /**
149 * Whether or not check_bitstream should still be run on each packet
150 */
151 int bitstream_checked;
152
153 /**
154 * The codec context used by avformat_find_stream_info, the parser, etc.
155 */
156 struct AVCodecContext *avctx;
157 /**
158 * 1 if avctx has been initialized with the values from the codec parameters
159 */
160 int avctx_inited;
161
162 /* the context for extracting extradata in find_stream_info()
163 * inited=1/bsf=NULL signals that extracting is not possible (codec not
164 * supported) */
165 struct {
166 struct AVBSFContext *bsf;
167 int inited;
168 } extract_extradata;
169
170 /**
171 * Whether the internal avctx needs to be updated from codecpar (after a late change to codecpar)
172 */
173 int need_context_update;
174
175 int is_intra_only;
176
177 FFFrac priv_pts;
178
179 /**
180 * Stream information used internally by avformat_find_stream_info()
181 */
182 struct FFStreamInfo *info;
183
184 AVIndexEntry *index_entries; /**< Only used if the format does not
185 support seeking natively. */
186 int nb_index_entries;
187 unsigned int index_entries_allocated_size;
188
189 int64_t interleaver_chunk_size;
190 int64_t interleaver_chunk_duration;
191
192 /**
193 * stream probing state
194 * -1 -> probing finished
195 * 0 -> no probing requested
196 * rest -> perform probing with request_probe being the minimum score to accept.
197 */
198 int request_probe;
199 /**
200 * Indicates that everything up to the next keyframe
201 * should be discarded.
202 */
203 int skip_to_keyframe;
204
205 /**
206 * Number of samples to skip at the start of the frame decoded from the next packet.
207 */
208 int skip_samples;
209
210 /**
211 * If not 0, the number of samples that should be skipped from the start of
212 * the stream (the samples are removed from packets with pts==0, which also
213 * assumes negative timestamps do not happen).
214 * Intended for use with formats such as mp3 with ad-hoc gapless audio
215 * support.
216 */
217 int64_t start_skip_samples;
218
219 /**
220 * If not 0, the first audio sample that should be discarded from the stream.
221 * This is broken by design (needs global sample count), but can't be
222 * avoided for broken by design formats such as mp3 with ad-hoc gapless
223 * audio support.
224 */
225 int64_t first_discard_sample;
226
227 /**
228 * The sample after last sample that is intended to be discarded after
229 * first_discard_sample. Works on frame boundaries only. Used to prevent
230 * early EOF if the gapless info is broken (considered concatenated mp3s).
231 */
232 int64_t last_discard_sample;
233
234 /**
235 * Number of internally decoded frames, used internally in libavformat, do not access
236 * its lifetime differs from info which is why it is not in that structure.
237 */
238 int nb_decoded_frames;
239
240 /**
241 * Timestamp offset added to timestamps before muxing
242 */
243 int64_t mux_ts_offset;
244
245 /**
246 * This is the lowest ts allowed in this track; it may be set by the muxer
247 * during init or write_header and influences the automatic timestamp
248 * shifting code.
249 */
250 int64_t lowest_ts_allowed;
251
252 /**
253 * Internal data to check for wrapping of the time stamp
254 */
255 int64_t pts_wrap_reference;
256
257 /**
258 * Options for behavior, when a wrap is detected.
259 *
260 * Defined by AV_PTS_WRAP_ values.
261 *
262 * If correction is enabled, there are two possibilities:
263 * If the first time stamp is near the wrap point, the wrap offset
264 * will be subtracted, which will create negative time stamps.
265 * Otherwise the offset will be added.
266 */
267 int pts_wrap_behavior;
268
269 /**
270 * Internal data to prevent doing update_initial_durations() twice
271 */
272 int update_initial_durations_done;
273
274 #define MAX_REORDER_DELAY 16
275
276 /**
277 * Internal data to generate dts from pts
278 */
279 int64_t pts_reorder_error[MAX_REORDER_DELAY+1];
280 uint8_t pts_reorder_error_count[MAX_REORDER_DELAY+1];
281
282 int64_t pts_buffer[MAX_REORDER_DELAY+1];
283
284 /**
285 * Internal data to analyze DTS and detect faulty mpeg streams
286 */
287 int64_t last_dts_for_order_check;
288 uint8_t dts_ordered;
289 uint8_t dts_misordered;
290
291 /**
292 * display aspect ratio (0 if unknown)
293 * - encoding: unused
294 * - decoding: Set by libavformat to calculate sample_aspect_ratio internally
295 */
296 AVRational display_aspect_ratio;
297
298 AVProbeData probe_data;
299
300 /**
301 * last packet in packet_buffer for this stream when muxing.
302 */
303 PacketListEntry *last_in_packet_buffer;
304
305 int64_t last_IP_pts;
306 int last_IP_duration;
307
308 /**
309 * Number of packets to buffer for codec probing
310 */
311 int probe_packets;
312
313 /* av_read_frame() support */
314 enum AVStreamParseType need_parsing;
315 struct AVCodecParserContext *parser;
316
317 /**
318 * Number of frames that have been demuxed during avformat_find_stream_info()
319 */
320 int codec_info_nb_frames;
321
322 /**
323 * Stream Identifier
324 * This is the MPEG-TS stream identifier +1
325 * 0 means unknown
326 */
327 int stream_identifier;
328
329 // Timestamp generation support:
330 /**
331 * Timestamp corresponding to the last dts sync point.
332 *
333 * Initialized when AVCodecParserContext.dts_sync_point >= 0 and
334 * a DTS is received from the underlying container. Otherwise set to
335 * AV_NOPTS_VALUE by default.
336 */
337 int64_t first_dts;
338 int64_t cur_dts;
339
340 const struct AVCodecDescriptor *codec_desc;
341
342 #if FF_API_INTERNAL_TIMING
343 AVRational transferred_mux_tb;
344 #endif
345 } FFStream;
346
347 13320365 static av_always_inline FFStream *ffstream(AVStream *st)
348 {
349 13320365 return (FFStream*)st;
350 }
351
352 3164145 static av_always_inline const FFStream *cffstream(const AVStream *st)
353 {
354 3164145 return (const FFStream*)st;
355 }
356
357 #ifdef __GNUC__
358 #define dynarray_add(tab, nb_ptr, elem)\
359 do {\
360 __typeof__(tab) _tab = (tab);\
361 __typeof__(elem) _elem = (elem);\
362 (void)sizeof(**_tab == _elem); /* check that types are compatible */\
363 av_dynarray_add(_tab, nb_ptr, _elem);\
364 } while(0)
365 #else
366 #define dynarray_add(tab, nb_ptr, elem)\
367 do {\
368 av_dynarray_add((tab), nb_ptr, (elem));\
369 } while(0)
370 #endif
371
372 /**
373 * Automatically create sub-directories
374 *
375 * @param path will create sub-directories by path
376 * @return 0, or < 0 on error
377 */
378 int ff_mkdir_p(const char *path);
379
380 /**
381 * Write hexadecimal string corresponding to given binary data. The string
382 * is zero-terminated.
383 *
384 * @param buf the output string is written here;
385 * needs to be at least 2 * size + 1 bytes long.
386 * @param src the input data to be transformed.
387 * @param size the size (in byte) of src.
388 * @param lowercase determines whether to use the range [0-9a-f] or [0-9A-F].
389 * @return buf.
390 */
391 char *ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase);
392
393 /**
394 * Parse a string of hexadecimal strings. Any space between the hexadecimal
395 * digits is ignored.
396 *
397 * @param data if non-null, the parsed data is written to this pointer
398 * @param p the string to parse
399 * @return the number of bytes written (or to be written, if data is null)
400 */
401 int ff_hex_to_data(uint8_t *data, const char *p);
402
403 #define NTP_OFFSET 2208988800ULL
404 #define NTP_OFFSET_US (NTP_OFFSET * 1000000ULL)
405
406 /** Get the current time since NTP epoch in microseconds. */
407 uint64_t ff_ntp_time(void);
408
409 /**
410 * Get the NTP time stamp formatted as per the RFC-5905.
411 *
412 * @param ntp_time NTP time in micro seconds (since NTP epoch)
413 * @return the formatted NTP time stamp
414 */
415 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us);
416
417 /**
418 * Parse the NTP time in micro seconds (since NTP epoch).
419 *
420 * @param ntp_ts NTP time stamp formatted as per the RFC-5905.
421 * @return the time in micro seconds (since NTP epoch)
422 */
423 uint64_t ff_parse_ntp_time(uint64_t ntp_ts);
424
425 /**
426 * Append the media-specific SDP fragment for the media stream c
427 * to the buffer buff.
428 *
429 * Note, the buffer needs to be initialized, since it is appended to
430 * existing content.
431 *
432 * @param buff the buffer to append the SDP fragment to
433 * @param size the size of the buff buffer
434 * @param st the AVStream of the media to describe
435 * @param idx the global stream index
436 * @param dest_addr the destination address of the media stream, may be NULL
437 * @param dest_type the destination address type, may be NULL
438 * @param port the destination port of the media stream, 0 if unknown
439 * @param ttl the time to live of the stream, 0 if not multicast
440 * @param fmt the AVFormatContext, which might contain options modifying
441 * the generated SDP
442 * @return 0 on success, a negative error code on failure
443 */
444 int ff_sdp_write_media(char *buff, int size, const AVStream *st, int idx,
445 const char *dest_addr, const char *dest_type,
446 int port, int ttl, AVFormatContext *fmt);
447
448 /**
449 * Read a whole line of text from AVIOContext. Stop reading after reaching
450 * either a \\n, a \\0 or EOF. The returned string is always \\0-terminated,
451 * and may be truncated if the buffer is too small.
452 *
453 * @param s the read-only AVIOContext
454 * @param buf buffer to store the read line
455 * @param maxlen size of the buffer
456 * @return the length of the string written in the buffer, not including the
457 * final \\0
458 */
459 int ff_get_line(AVIOContext *s, char *buf, int maxlen);
460
461 /**
462 * Same as ff_get_line but strip the white-space characters in the text tail
463 *
464 * @param s the read-only AVIOContext
465 * @param buf buffer to store the read line
466 * @param maxlen size of the buffer
467 * @return the length of the string written in the buffer
468 */
469 int ff_get_chomp_line(AVIOContext *s, char *buf, int maxlen);
470
471 #define SPACE_CHARS " \t\r\n"
472
473 /**
474 * Callback function type for ff_parse_key_value.
475 *
476 * @param key a pointer to the key
477 * @param key_len the number of bytes that belong to the key, including the '='
478 * char
479 * @param dest return the destination pointer for the value in *dest, may
480 * be null to ignore the value
481 * @param dest_len the length of the *dest buffer
482 */
483 typedef void (*ff_parse_key_val_cb)(void *context, const char *key,
484 int key_len, char **dest, int *dest_len);
485 /**
486 * Parse a string with comma-separated key=value pairs. The value strings
487 * may be quoted and may contain escaped characters within quoted strings.
488 *
489 * @param str the string to parse
490 * @param callback_get_buf function that returns where to store the
491 * unescaped value string.
492 * @param context the opaque context pointer to pass to callback_get_buf
493 */
494 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
495 void *context);
496
497 enum AVCodecID ff_guess_image2_codec(const char *filename);
498
499 /**
500 * Set the time base and wrapping info for a given stream. This will be used
501 * to interpret the stream's timestamps. If the new time base is invalid
502 * (numerator or denominator are non-positive), it leaves the stream
503 * unchanged.
504 *
505 * @param st stream
506 * @param pts_wrap_bits number of bits effectively used by the pts
507 * (used for wrap control)
508 * @param pts_num time base numerator
509 * @param pts_den time base denominator
510 */
511 void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits,
512 unsigned int pts_num, unsigned int pts_den);
513
514 /**
515 * Set the timebase for each stream from the corresponding codec timebase and
516 * print it.
517 */
518 int ff_framehash_write_header(AVFormatContext *s);
519
520 /**
521 * Remove a stream from its AVFormatContext and free it.
522 * The stream must be the last stream of the AVFormatContext.
523 */
524 void ff_remove_stream(AVFormatContext *s, AVStream *st);
525
526 /**
527 * Remove a stream group from its AVFormatContext and free it.
528 * The stream group must be the last stream group of the AVFormatContext.
529 */
530 void ff_remove_stream_group(AVFormatContext *s, AVStreamGroup *stg);
531
532 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id);
533
534 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag);
535
536 /**
537 * Select a PCM codec based on the given parameters.
538 *
539 * @param bps bits-per-sample
540 * @param flt floating-point
541 * @param be big-endian
542 * @param sflags signed flags. each bit corresponds to one byte of bit depth.
543 * e.g. the 1st bit indicates if 8-bit should be signed or
544 * unsigned, the 2nd bit indicates if 16-bit should be signed or
545 * unsigned, etc... This is useful for formats such as WAVE where
546 * only 8-bit is unsigned and all other bit depths are signed.
547 * @return a PCM codec id or AV_CODEC_ID_NONE
548 */
549 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags);
550
551 /**
552 * Create a new stream and copy to it all parameters from a source stream, with
553 * the exception of the index field, which is set when the new stream is
554 * created.
555 *
556 * @param dst_ctx pointer to the context in which the new stream is created
557 * @param src pointer to source AVStream
558 * @return pointer to the new stream or NULL on error
559 */
560 AVStream *ff_stream_clone(AVFormatContext *dst_ctx, const AVStream *src);
561
562 /**
563 * Wrap ffurl_move() and log if error happens.
564 *
565 * @param url_src source path
566 * @param url_dst destination path
567 * @return 0 or AVERROR on failure
568 */
569 int ff_rename(const char *url_src, const char *url_dst, void *logctx);
570
571 /**
572 * Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end
573 * which is always set to 0.
574 *
575 * Previously allocated extradata in par will be freed.
576 *
577 * @param size size of extradata
578 * @return 0 if OK, AVERROR_xxx on error
579 */
580 int ff_alloc_extradata(AVCodecParameters *par, int size);
581
582 /**
583 * Copies the whilelists from one context to the other
584 */
585 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src);
586
587 /*
588 * A wrapper around AVFormatContext.io_close that should be used
589 * instead of calling the pointer directly.
590 *
591 * @param s AVFormatContext
592 * @param *pb the AVIOContext to be closed and freed. Can be NULL.
593 * @return >=0 on success, negative AVERROR in case of failure
594 */
595 int ff_format_io_close(AVFormatContext *s, AVIOContext **pb);
596
597 /**
598 * Utility function to check if the file uses http or https protocol
599 *
600 * @param s AVFormatContext
601 * @param filename URL or file name to open for writing
602 */
603 int ff_is_http_proto(const char *filename);
604
605 struct AVBPrint;
606 /**
607 * Finalize buf into extradata and set its size appropriately.
608 */
609 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf);
610
611 /**
612 * Set AVFormatContext url field to the provided pointer. The pointer must
613 * point to a valid string. The existing url field is freed if necessary. Also
614 * set the legacy filename field to the same string which was provided in url.
615 */
616 void ff_format_set_url(AVFormatContext *s, char *url);
617
618 /**
619 * Return a positive value if the given url has one of the given
620 * extensions, negative AVERROR on error, 0 otherwise.
621 *
622 * @param url url to check against the given extensions
623 * @param extensions a comma-separated list of filename extensions
624 */
625 int ff_match_url_ext(const char *url, const char *extensions);
626
627 /**
628 * Return in 'buf' the path with '%d' replaced by a number.
629 *
630 * Also handles the '%0nd' format where 'n' is the total number
631 * of digits and '%%'.
632 *
633 * @param buf destination buffer
634 * @param buf_size destination buffer size
635 * @param path path with substitution template
636 * @param number the number to substitute
637 * @param flags AV_FRAME_FILENAME_FLAGS_*
638 * @return 0 if OK, -1 on format error
639 */
640 int ff_get_frame_filename(char *buf, int buf_size, const char *path,
641 int64_t number, int flags);
642
643 /**
644 * Set a dictionary value to an ISO-8601 compliant timestamp string.
645 *
646 * @param dict pointer to a pointer to a dictionary struct. If *dict is NULL
647 * a dictionary struct is allocated and put in *dict.
648 * @param key metadata key
649 * @param timestamp unix timestamp in microseconds
650 * @return <0 on error
651 */
652 int ff_dict_set_timestamp(AVDictionary **dict, const char *key, int64_t timestamp);
653
654 #endif /* AVFORMAT_INTERNAL_H */
655