FFmpeg coverage


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