comparison foosdk/sdk/foobar2000/SDK/audio_chunk.h @ 1:20d02a178406 default tip

*: check in everything else yay
author Paper <paper@tflc.us>
date Mon, 05 Jan 2026 02:15:46 -0500
parents
children
comparison
equal deleted inserted replaced
0:e9bb126753e7 1:20d02a178406
1 #pragma once
2
3 #include <pfc/audio_sample.h>
4 #include <pfc/memalign.h>
5 #include "exception_io.h"
6
7 #ifdef _WIN32
8 #include <MMReg.h>
9 #endif
10 //! Thrown when audio_chunk sample rate or channel mapping changes in mid-stream and the code receiving audio_chunks can't deal with that scenario.
11 PFC_DECLARE_EXCEPTION(exception_unexpected_audio_format_change, exception_io_data, "Unexpected audio format change" );
12
13 //! Interface to container of a chunk of audio data. See audio_chunk_impl for an implementation.
14 class NOVTABLE audio_chunk {
15 public:
16 struct spec_t; // forward decl
17
18 enum {
19 sample_rate_min = 1000, sample_rate_max = 20000000
20 };
21 static bool g_is_valid_sample_rate(t_uint32 p_val) {return p_val >= sample_rate_min && p_val <= sample_rate_max;}
22
23 //! Channel map flag declarations. Note that order of interleaved channel data in the stream is same as order of these flags.
24 enum
25 {
26 channel_front_left = 1<<0,
27 channel_front_right = 1<<1,
28 channel_front_center = 1<<2,
29 channel_lfe = 1<<3,
30 channel_back_left = 1<<4,
31 channel_back_right = 1<<5,
32 channel_front_center_left = 1<<6,
33 channel_front_center_right = 1<<7,
34 channel_back_center = 1<<8,
35 channel_side_left = 1<<9,
36 channel_side_right = 1<<10,
37 channel_top_center = 1<<11,
38 channel_top_front_left = 1<<12,
39 channel_top_front_center = 1<<13,
40 channel_top_front_right = 1<<14,
41 channel_top_back_left = 1<<15,
42 channel_top_back_center = 1<<16,
43 channel_top_back_right = 1<<17,
44
45 channels_back_left_right = channel_back_left | channel_back_right,
46 channels_side_left_right = channel_side_left | channel_side_right,
47
48 channel_config_mono = channel_front_center,
49 channel_config_stereo = channel_front_left | channel_front_right,
50 channel_config_2point1 = channel_config_stereo | channel_lfe,
51 channel_config_3point0 = channel_config_stereo | channel_front_center,
52 channel_config_4point0 = channel_config_stereo | channels_back_left_right,
53 channel_config_4point0_side = channel_config_stereo | channels_side_left_right,
54 channel_config_4point1 = channel_config_4point0 | channel_lfe,
55 channel_config_5point0 = channel_config_4point0 | channel_front_center,
56 channel_config_6point0 = channel_config_4point0 | channels_side_left_right,
57 channel_config_5point1 = channel_config_4point0 | channel_front_center | channel_lfe,
58 channel_config_5point1_side = channel_config_4point0_side | channel_front_center | channel_lfe,
59 channel_config_7point1 = channel_config_5point1 | channels_side_left_right,
60
61
62 defined_channel_count = 18,
63 };
64
65 //! Helper function; guesses default channel map for the specified channel count. Returns 0 on failure.
66 static unsigned g_guess_channel_config(unsigned count);
67 //! Helper function; determines channel map for the specified channel count according to Xiph specs. Throws exception_io_data on failure.
68 static unsigned g_guess_channel_config_xiph(unsigned count);
69
70 //! Helper function; translates audio_chunk channel map to WAVEFORMATEXTENSIBLE channel map.
71 static constexpr uint32_t g_channel_config_to_wfx(unsigned p_config) { return p_config;}
72 //! Helper function; translates WAVEFORMATEXTENSIBLE channel map to audio_chunk channel map.
73 static constexpr unsigned g_channel_config_from_wfx(uint32_t p_wfx) { return p_wfx;}
74
75 //! Extracts flag describing Nth channel from specified map. Usable to figure what specific channel in a stream means.
76 static unsigned g_extract_channel_flag(unsigned p_config,unsigned p_index);
77 //! Counts channels specified by channel map.
78 static constexpr unsigned g_count_channels(unsigned p_config) { return pfc::countBits32(p_config); }
79 //! Calculates index of a channel specified by p_flag in a stream where channel map is described by p_config.
80 static unsigned g_channel_index_from_flag(unsigned p_config,unsigned p_flag);
81
82 static const char * g_channel_name(unsigned p_flag);
83 static const char * g_channel_name_byidx(unsigned p_index);
84 static unsigned g_find_channel_idx(unsigned p_flag);
85 static void g_formatChannelMaskDesc(unsigned flags, pfc::string_base & out);
86 static pfc::string8 g_formatChannelMaskDesc(unsigned flags);
87 static const char* g_channelMaskName(unsigned flags);
88
89
90
91 //! Retrieves audio data buffer pointer (non-const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \n
92 //! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible.
93 virtual audio_sample * get_data() = 0;
94 //! Retrieves audio data buffer pointer (const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \n
95 //! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible.
96 virtual const audio_sample * get_data() const = 0;
97 //! Retrieves size of allocated buffer space, in audio_samples.
98 virtual t_size get_data_size() const = 0;
99 //! Resizes audio data buffer to specified size. Throws std::bad_alloc on failure.
100 virtual void set_data_size(t_size p_new_size) = 0;
101 //! Sanity helper, same as set_data_size.
102 //! @param bQuicker Avoid memory allocation, permit up to 2x memory used
103 void allocate(size_t size, bool bQuicker = false);
104
105 //! Retrieves sample rate of contained audio data.
106 virtual unsigned get_srate() const = 0;
107 //! Sets sample rate of contained audio data.
108 virtual void set_srate(unsigned val) = 0;
109 //! Retrieves channel count of contained audio data.
110 virtual unsigned get_channels() const = 0;
111 //! Helper - for consistency - same as get_channels().
112 inline unsigned get_channel_count() const {return get_channels();}
113 //! Retrieves channel map of contained audio data. Conditions where number of channels specified by channel map don't match get_channels() return value should not be possible.
114 virtual unsigned get_channel_config() const = 0;
115 //! Sets channel count / channel map.
116 virtual void set_channels(unsigned p_count,unsigned p_config) = 0;
117
118 //! Retrieves number of valid samples in the buffer. \n
119 //! Note that a "sample" means a unit of interleaved PCM data representing states of each channel at given point of time, not a single PCM value. \n
120 //! For an example, duration of contained audio data is equal to sample count / sample rate, while actual size of contained data is equal to sample count * channel count.
121 virtual t_size get_sample_count() const = 0;
122
123 //! Sets number of valid samples in the buffer. WARNING: sample count * channel count should never be above allocated buffer size.
124 virtual void set_sample_count(t_size val) = 0;
125
126 //! Helper, same as get_srate().
127 inline unsigned get_sample_rate() const {return get_srate();}
128 //! Helper, same as set_srate().
129 inline void set_sample_rate(unsigned val) {set_srate(val);}
130
131 //! Helper; sets channel count to specified value and uses default channel map for this channel count.
132 void set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));}
133
134
135 //! Helper; resizes audio data buffer when its current size is smaller than requested.
136 inline void grow_data_size(t_size p_requested) {if (p_requested > get_data_size()) set_data_size(p_requested);}
137
138
139 //! Retrieves duration of contained audio data, in seconds.
140 inline double get_duration() const
141 {
142 double rv = 0;
143 t_size srate = get_srate (), samples = get_sample_count();
144 if (srate>0 && samples>0) rv = (double)samples/(double)srate;
145 return rv;
146 }
147
148 //! Returns whether the chunk is empty (contains no audio data).
149 inline bool is_empty() const {return get_channels()==0 || get_srate()==0 || get_sample_count()==0;}
150
151 //! Returns whether the chunk contents are valid (for bug check purposes).
152 bool is_valid() const;
153
154 void debugChunkSpec() const;
155 pfc::string8 formatChunkSpec() const;
156 #if PFC_DEBUG
157 void assert_valid(const char * ctx) const;
158 #else
159 void assert_valid(const char* ctx) const { (void)ctx; }
160 #endif
161
162
163 //! Returns whether the chunk contains valid sample rate & channel info (but allows an empty chunk).
164 bool is_spec_valid() const;
165
166 //! Returns actual amount of audio data contained in the buffer (sample count * channel count). Must not be greater than data size (see get_data_size()).
167 size_t get_used_size() const {return get_sample_count() * get_channels();}
168 //! Same as get_used_size(); old confusingly named version.
169 size_t get_data_length() const {return get_sample_count() * get_channels();}
170
171 //! Resets all audio_chunk data.
172 inline void reset() {
173 set_sample_count(0);
174 set_srate(0);
175 set_channels(0,0);
176 set_data_size(0);
177 }
178
179 //! Helper, sets chunk data to contents of specified buffer, with specified number of channels / sample rate / channel map.
180 void set_data(const audio_sample * src,size_t samples,unsigned nch,unsigned srate,unsigned channel_config);
181 void set_data(const audio_sample* src, size_t samples, spec_t const& spec, bool bQucker = false);
182 void set_data(const audio_sample* src, t_size samples, unsigned nch, unsigned srate);
183
184 void set_data_int16(const int16_t * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config);
185
186 //! Helper, sets chunk data to contents of specified buffer, using default win32/wav conventions for signed/unsigned switch.
187 inline void set_data_fixedpoint(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config) {
188 this->set_data_fixedpoint_ms(ptr, bytes, srate, nch, bps, channel_config);
189 }
190
191 void set_data_fixedpoint_signed(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config);
192
193 enum
194 {
195 FLAG_LITTLE_ENDIAN = 1,
196 FLAG_BIG_ENDIAN = 2,
197 FLAG_SIGNED = 4,
198 FLAG_UNSIGNED = 8,
199 };
200
201 inline static unsigned flags_autoendian() {
202 return pfc::byte_order_is_big_endian ? FLAG_BIG_ENDIAN : FLAG_LITTLE_ENDIAN;
203 }
204
205 void set_data_fixedpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//p_flags - see FLAG_* above
206
207 void set_data_fixedpoint_ms(const void * ptr, size_t bytes, unsigned sampleRate, unsigned channels, unsigned bps, unsigned channelConfig);
208
209 void set_data_floatingpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//signed/unsigned flags dont apply
210 static bool is_supported_floatingpoint(unsigned bps) { return bps == 32 || bps == 64 || bps == 16 || bps == 24; }
211
212 void set_data_32(const float* src, t_size samples, unsigned nch, unsigned srate);
213 void set_data_32(const float* src, t_size samples, spec_t const & spec );
214
215 //! Appends silent samples at the end of the chunk. \n
216 //! The chunk may be empty prior to this call, its sample rate & channel count will be set to the specified values then. \n
217 //! The chunk may have different sample rate than requested; silent sample count will be recalculated to the used sample rate retaining actual duration.
218 //! @param samples Number of silent samples to append.
219 //! @param hint_nch If no channel count is set on this chunk, it will be set to this value.
220 //! @param hint_srate The sample rate of silent samples being inserted. If no sampler ate is set on this chunk, it will be set to this value.\n
221 //! Otherwise if chunk's sample rate doesn't match hint_srate, sample count will be recalculated to chunk's actual sample rate.
222 void pad_with_silence_ex(t_size samples,unsigned hint_nch,unsigned hint_srate);
223 //! Appends silent samples at the end of the chunk. \n
224 //! The chunk must have valid sample rate & channel count prior to this call.
225 //! @param samples Number of silent samples to append.
226 void pad_with_silence(t_size samples);
227 //! Inserts silence at the beginning of the audio chunk.
228 //! @param samples Number of silent samples to insert.
229 void insert_silence_fromstart(t_size samples);
230 //! Helper; removes N first samples from the chunk. \n
231 //! If the chunk contains fewer samples than requested, it becomes empty.
232 //! @returns Number of samples actually removed.
233 t_size skip_first_samples(t_size samples);
234 //! Produces a chunk of silence, with the specified duration. \n
235 //! Any existing audio sdata will be discarded. \n
236 //! Expects sample rate and channel count to be set first. \n
237 //! Also allocates memory for the requested amount of data see: set_data_size().
238 //! @param samples Desired number of samples.
239 void set_silence(t_size samples);
240 //! Produces a chunk of silence, with the specified duration. \n
241 //! Any existing audio sdata will be discarded. \n
242 //! Expects sample rate and channel count to be set first. \n
243 //! Also allocates memory for the requested amount of data see: set_data_size().
244 //! @param seconds Desired duration in seconds.
245 void set_silence_seconds( double seconds );
246
247 //! Helper; skips first samples of the chunk updating a remaining to-skip counter.
248 //! @param skipDuration Reference to the duration of audio remining to be skipped, in seconds. Updated by each call.
249 //! @returns False if the chunk became empty, true otherwise.
250 bool process_skip(double & skipDuration);
251
252 //! Simple function to get original PCM stream back. Assumes host's endianness, integers are signed - including the 8bit mode; 32bit mode assumed to be float.
253 //! @returns false when the conversion could not be performed because of unsupported bit depth etc.
254 bool to_raw_data(class mem_block_container & out, t_uint32 bps, bool useUpperBits = true, audio_sample scale = 1.0) const;
255
256 //! Convert audio_chunk contents to fixed-point PCM format.
257 //! @param useUpperBits relevant if bps != bpsValid, signals whether upper or lower bits of each sample should be used.
258 bool toFixedPoint(class mem_block_container & out, uint32_t bps, uint32_t bpsValid, bool useUpperBits = true, audio_sample scale = 1.0) const;
259
260 //! Convert a buffer of audio_samples to fixed-point PCM format.
261 //! @param useUpperBits relevant if bps != bpsValid, signals whether upper or lower bits of each sample should be used.
262 static bool g_toFixedPoint(const audio_sample * in, void * out, size_t count, uint32_t bps, uint32_t bpsValid, bool useUpperBits = true, audio_sample scale = 1.0);
263
264
265 //! Helper, calculates peak value of data in the chunk. The optional parameter specifies initial peak value, to simplify calling code.
266 audio_sample get_peak(audio_sample p_peak) const;
267 audio_sample get_peak() const;
268
269 //! Helper function; scales entire chunk content by specified value.
270 void scale(audio_sample p_value);
271
272 //! Helper; copies content of another audio chunk to this chunk.
273 //! @param bQuicker Avoid memory allocation, permit up to 2x memory used
274 void copy(const audio_chunk & p_source, bool bQuicker = false) {
275 set_data(p_source.get_data(),p_source.get_sample_count(),p_source.get_spec(), bQuicker);
276 }
277
278 const audio_chunk & operator=(const audio_chunk & p_source) {
279 copy(p_source);
280 return *this;
281 }
282
283 struct spec_t {
284 uint32_t sampleRate = 0;
285 uint32_t chanCount = 0, chanMask = 0;
286
287 static bool equals( const spec_t & v1, const spec_t & v2 );
288 bool operator==(const spec_t & other) const { return equals(*this, other);}
289 bool operator!=(const spec_t & other) const { return !equals(*this, other);}
290 bool is_valid() const;
291 void clear() { sampleRate = 0; chanCount = 0; chanMask = 0; }
292
293 #ifdef _WIN32
294 //! Creates WAVE_FORMAT_IEEE_FLOAT WAVEFORMATEX structure
295 WAVEFORMATEX toWFX() const;
296 //! Creates WAVE_FORMAT_IEEE_FLOAT WAVEFORMATEXTENSIBLE structure
297 WAVEFORMATEXTENSIBLE toWFXEX() const;
298 //! Creates WAVE_FORMAT_PCM WAVEFORMATEX structure
299 WAVEFORMATEX toWFXWithBPS(uint32_t bps) const;
300 //! Creates WAVE_FORMAT_PCM WAVEFORMATEXTENSIBLE structure
301 WAVEFORMATEXTENSIBLE toWFXEXWithBPS(uint32_t bps) const;
302 #endif
303
304 pfc::string8 toString( const char * delim = " " ) const;
305 };
306 static spec_t makeSpec(uint32_t rate, uint32_t channels);
307 static spec_t makeSpec(uint32_t rate, uint32_t channels, uint32_t chanMask);
308 static spec_t emptySpec() { return makeSpec(0, 0, 0); }
309
310 spec_t get_spec() const;
311 void set_spec(const spec_t &);
312
313 void append(const audio_chunk& other);
314 protected:
315 audio_chunk() {}
316 ~audio_chunk() {}
317 };
318
319 //! Implementation of audio_chunk. Takes pfc allocator template as template parameter.
320 template<typename container_t = pfc::mem_block_aligned_t<audio_sample, 16> >
321 class audio_chunk_impl_t : public audio_chunk {
322 typedef audio_chunk_impl_t<container_t> t_self;
323 container_t m_data;
324 unsigned m_srate = 0, m_nch = 0, m_setup = 0;
325 t_size m_samples = 0;
326
327 public:
328 audio_chunk_impl_t() {}
329 audio_chunk_impl_t(const audio_sample * src,unsigned samples,unsigned nch,unsigned srate) {set_data(src,samples,nch,srate);}
330 audio_chunk_impl_t(const audio_chunk & p_source) {copy(p_source);}
331
332
333 virtual audio_sample * get_data() {return m_data.get_ptr();}
334 virtual const audio_sample * get_data() const {return m_data.get_ptr();}
335 virtual t_size get_data_size() const {return m_data.get_size();}
336 virtual void set_data_size(t_size new_size) {m_data.set_size(new_size);}
337
338 virtual unsigned get_srate() const {return m_srate;}
339 virtual void set_srate(unsigned val) {m_srate=val;}
340 virtual unsigned get_channels() const {return m_nch;}
341 virtual unsigned get_channel_config() const {return m_setup;}
342 virtual void set_channels(unsigned val,unsigned setup) {m_nch = val;m_setup = setup;}
343 void set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));}
344
345 virtual t_size get_sample_count() const {return m_samples;}
346 virtual void set_sample_count(t_size val) {m_samples = val;}
347
348 const t_self & operator=(const audio_chunk & p_source) {copy(p_source);return *this;}
349 };
350
351 typedef audio_chunk_impl_t<> audio_chunk_impl;
352 typedef audio_chunk_impl_t<pfc::mem_block_aligned_incremental_t<audio_sample, 16> > audio_chunk_fast_impl;
353
354 //! Implements const methods of audio_chunk only, referring to an external buffer. For temporary use only (does not maintain own storage), e.g.: somefunc( audio_chunk_temp_impl(mybuffer,....) );
355 class audio_chunk_memref_impl : public audio_chunk {
356 public:
357 audio_chunk_memref_impl(const audio_sample * p_data,t_size p_samples,t_uint32 p_sample_rate,t_uint32 p_channels,t_uint32 p_channel_config) :
358 m_samples(p_samples), m_sample_rate(p_sample_rate), m_channels(p_channels), m_channel_config(p_channel_config), m_data(p_data)
359 {
360 #if PFC_DEBUG
361 assert_valid(__FUNCTION__);
362 #endif
363 }
364
365 audio_sample * get_data() {throw pfc::exception_not_implemented();}
366 const audio_sample * get_data() const {return m_data;}
367 t_size get_data_size() const {return m_samples * m_channels;}
368 void set_data_size(t_size) {throw pfc::exception_not_implemented();}
369
370 unsigned get_srate() const {return m_sample_rate;}
371 void set_srate(unsigned) {throw pfc::exception_not_implemented();}
372 unsigned get_channels() const {return m_channels;}
373 unsigned get_channel_config() const {return m_channel_config;}
374 void set_channels(unsigned,unsigned) {throw pfc::exception_not_implemented();}
375
376 t_size get_sample_count() const {return m_samples;}
377
378 void set_sample_count(t_size) {throw pfc::exception_not_implemented();}
379
380 private:
381 t_size m_samples;
382 t_uint32 m_sample_rate,m_channels,m_channel_config;
383 const audio_sample * m_data;
384 };
385
386
387 // Compatibility typedefs.
388 typedef audio_chunk_fast_impl audio_chunk_impl_temporary;
389 typedef audio_chunk_impl audio_chunk_i;
390 typedef audio_chunk_memref_impl audio_chunk_temp_impl;
391
392 class audio_chunk_partial_ref : public audio_chunk_temp_impl {
393 public:
394 audio_chunk_partial_ref(const audio_chunk & chunk, t_size base, t_size count) : audio_chunk_temp_impl(chunk.get_data() + base * chunk.get_channels(), count, chunk.get_sample_rate(), chunk.get_channels(), chunk.get_channel_config()) {}
395 };