Debian Codegraph @

third_party/rust/audio-mixer/src/coefficient.rs

raw
1 // The code is based from libcubeb's cubeb_mixer.cpp,
2 // which adapts the code from libswresample's rematrix.c
3
4 use crate::channel::{Channel, ChannelMap};
5
6 use std::fmt::Debug;
7
8 const CHANNELS: usize = Channel::count();
9
10 #[derive(Debug)]
11 enum Error {
12 DuplicateChannel,
13 AsymmetricChannels,
14 }
15
16 #[derive(Debug)]
17 struct ChannelLayout {
18 channels: Vec<Channel>,
19 channel_map: ChannelMap,
20 }
21
22 impl ChannelLayout {
23 fn new(channels: &[Channel]) -> Result<Self, Error> {
24 let channel_map = Self::get_channel_map(channels)?;
25 Ok(Self {
26 channels: channels.to_vec(),
27 channel_map,
28 })
29 }
30
31 // Except Silence and Discrete channels, duplicate channels aren't allowed.
32 fn get_channel_map(channels: &[Channel]) -> Result<ChannelMap, Error> {
33 let mut map = ChannelMap::empty();
34 for channel in channels {
35 let bitmask = ChannelMap::from(*channel);
36 if (channel != &Channel::Silence && channel != &Channel::Discrete)
37 && map.contains(bitmask)
38 {
39 return Err(Error::DuplicateChannel);
40 }
41 map.insert(bitmask);
42 }
43 Ok(map)
44 }
45 }
46
47 #[derive(Debug)]
48 pub struct Coefficient<T>
49 where
50 T: MixingCoefficient,
51 T::Coef: Copy,
52 {
53 input_layout: ChannelLayout,
54 output_layout: ChannelLayout,
55 matrix: Vec<Vec<T::Coef>>,
56 would_overflow_from_coefficient_value: Option<bool>, // Only used when T is i16
57 }
58
59 impl<T> Coefficient<T>
60 where
61 T: MixingCoefficient,
62 T::Coef: Copy,
63 {
64 // Given a M-channel input layout and a N-channel output layout, generate a NxM coefficients
65 // matrix m such that out_audio = m * in_audio, where in_audio, out_audio are Mx1, Nx1 matrix
66 // storing input and output audio data in their rows respectively.
67 //
68 // data in channel #1 ▸ │ Silence │ │ 0, 0, 0, 0 │ │ FrontRight │ ◂ data in channel #1
69 // data in channel #2 ▸ │ FrontRight │ = │ 1, C, 0, L │ x │ FrontCenter │ ◂ data in channel #2
70 // data in channel #3 ▸ │ FrontLeft │ │ 0, C, 1, L │ │ FrontLeft │ ◂ data in channel #3
71 // ▴ ▴ │ LowFrequency │ ◂ data in channel #4
72 // ┊ ┊ ▴
73 // ┊ ┊ ┊
74 // out_audio mixing matrix m in_audio
75 //
76 // The FrontLeft, FrontRight, ... etc label the data for front-left, front-right ... etc channel
77 // in both input and output audio data buffer.
78 //
79 // C and L are coefficients mixing input data from front-center channel and low-frequency channel
80 // to front-left and front-right.
81 //
82 // In math, the in_audio and out_audio should be a 2D-matrix with several rows containing only
83 // one column. However, the in_audio and out_audio are passed by 1-D matrix here for convenience.
84 pub fn create(input_channels: &[Channel], output_channels: &[Channel]) -> Self {
85 let input_layout = ChannelLayout::new(input_channels).expect("Invalid input layout");
86 let output_layout = ChannelLayout::new(output_channels).expect("Invalid output layout");
87
88 // Check if this is a professional audio interface rather than a sound card for playback, in
89 // which case it is expected to simply pass all the channel through without change.
90 // Those interfaces only have an explicit mapping for the stereo pair, but have lots of channels.
91 let mut only_stereo_or_discrete = true;
92 for channel in output_channels {
93 if *channel != Channel::Discrete
94 && *channel != Channel::FrontLeft
95 && *channel != Channel::FrontRight
96 {
97 only_stereo_or_discrete = false;
98 break;
99 }
100 }
101 let coefficient_matrix = if only_stereo_or_discrete && output_channels.len() > 2 {
102 let mut matrix = Vec::with_capacity(output_channels.len());
103 // Create a diagonal line of 1.0 for input channels
104 for (output_channel_index, _) in output_channels.iter().enumerate() {
105 let mut coefficients = Vec::with_capacity(input_channels.len());
106 coefficients.resize(input_channels.len(), 0.0);
107 if output_channel_index < coefficients.len() {
108 coefficients[output_channel_index] = 1.0;
109 }
110 matrix.push(coefficients);
111 }
112 matrix
113 } else {
114 let mixing_matrix =
115 Self::build_mixing_matrix(input_layout.channel_map, output_layout.channel_map)
116 .unwrap_or_else(|_| Self::get_basic_matrix());
117 Self::pick_coefficients(
118 &input_layout.channels,
119 &output_layout.channels,
120 &mixing_matrix,
121 )
122 };
123
124 let normalized_matrix = Self::normalize(T::max_coefficients_sum(), coefficient_matrix);
125
126 let would_overflow = T::would_overflow_from_coefficient_value(&normalized_matrix);
127
128 // Convert the type of the coefficients from f64 to T::Coef.
129 let matrix = normalized_matrix
130 .into_iter()
131 .map(|row| row.into_iter().map(T::coefficient_from_f64).collect())
132 .collect();
133
134 Self {
135 input_layout,
136 output_layout,
137 matrix,
138 would_overflow_from_coefficient_value: would_overflow,
139 }
140 }
141
142 // Return the coefficient for mixing input channel data into output channel.
143 pub fn get(&self, input: usize, output: usize) -> T::Coef {
144 assert!(output < self.matrix.len());
145 assert!(input < self.matrix[output].len());
146 self.matrix[output][input] // Perform copy so T::Coef must implement Copy.
147 }
148
149 pub fn would_overflow_from_coefficient_value(&self) -> Option<bool> {
150 self.would_overflow_from_coefficient_value
151 }
152
153 pub fn input_channels(&self) -> &[Channel] {
154 &self.input_layout.channels
155 }
156
157 pub fn output_channels(&self) -> &[Channel] {
158 &self.output_layout.channels
159 }
160
161 // Given audio input and output channel-maps, generate a CxC mixing coefficients matrix M,
162 // whose indice are ordered by the values defined in enum Channel, such that
163 // output_data(i) = Σ M[i][j] * input_data(j), for all j in [0, C),
164 // where i is in [0, C) and C is the number of channels defined in enum Channel,
165 // output_data and input_data are buffers containing data for channels that are also ordered
166 // by the values defined in enum Channel.
167 //
168 // │ FrontLeft │ │ 1, 0, ..., 0 │ │ FrontLeft │ ◂ data in front-left channel
169 // │ FrontRight │ │ 0, 1, ..., 0 │ │ FrontRight │ ◂ data in front-right channel
170 // │ FrontCenter │ = │ ........., 0 │ x │ FrontCenter │ ◂ data in front-center channel
171 // │ ........... │ │ ........., 0 | │ ........... │ ◂ ...
172 // │ Silence │ │ 0, 0, ..., 0 | │ Silence │ ◂ data in silence channel
173 // ▴ ▴ ▴
174 // out_audio coef matrix M in_audio
175 //
176 // ChannelMap would be used as a hash table to check the existence of channels.
177 #[allow(clippy::cognitive_complexity)]
178 fn build_mixing_matrix(
179 input_map: ChannelMap,
180 output_map: ChannelMap,
181 ) -> Result<[[f64; CHANNELS]; CHANNELS], Error> {
182 // Mixing coefficients constants.
183 use std::f64::consts::FRAC_1_SQRT_2;
184 use std::f64::consts::SQRT_2;
185 const CENTER_MIX_LEVEL: f64 = FRAC_1_SQRT_2;
186 const SURROUND_MIX_LEVEL: f64 = FRAC_1_SQRT_2;
187 const LFE_MIX_LEVEL: f64 = 1.0;
188
189 // The indices of channels in the mixing coefficients matrix.
190 const FRONT_LEFT: usize = Channel::FrontLeft.number();
191 const FRONT_RIGHT: usize = Channel::FrontRight.number();
192 const FRONT_CENTER: usize = Channel::FrontCenter.number();
193 const LOW_FREQUENCY: usize = Channel::LowFrequency.number();
194 const BACK_LEFT: usize = Channel::BackLeft.number();
195 const BACK_RIGHT: usize = Channel::BackRight.number();
196 const FRONT_LEFT_OF_CENTER: usize = Channel::FrontLeftOfCenter.number();
197 const FRONT_RIGHT_OF_CENTER: usize = Channel::FrontRightOfCenter.number();
198 const BACK_CENTER: usize = Channel::BackCenter.number();
199 const SIDE_LEFT: usize = Channel::SideLeft.number();
200 const SIDE_RIGHT: usize = Channel::SideRight.number();
201
202 // Return true if mixable channels are symmetric.
203 fn is_symmetric(map: ChannelMap) -> bool {
204 fn even(map: ChannelMap) -> bool {
205 map.bits().count_ones() % 2 == 0
206 }
207 even(map & ChannelMap::FRONT_2)
208 && even(map & ChannelMap::BACK_2)
209 && even(map & ChannelMap::FRONT_2_OF_CENTER)
210 && even(map & ChannelMap::SIDE_2)
211 }
212
213 if !is_symmetric(input_map) || !is_symmetric(output_map) {
214 return Err(Error::AsymmetricChannels);
215 }
216
217 let mut matrix = Self::get_basic_matrix();
218
219 // Get input channels that are not in the output channels.
220 let unaccounted_input_map = input_map & !output_map;
221
222 // When input has front-center but output has not, and output has front-stereo,
223 // mix input's front-center to output's front-stereo.
224 if unaccounted_input_map.contains(ChannelMap::FRONT_CENTER)
225 && output_map.contains(ChannelMap::FRONT_2)
226 {
227 let coefficient = if input_map.contains(ChannelMap::FRONT_2) {
228 CENTER_MIX_LEVEL
229 } else {
230 FRAC_1_SQRT_2
231 };
232 matrix[FRONT_LEFT][FRONT_CENTER] += coefficient;
233 matrix[FRONT_RIGHT][FRONT_CENTER] += coefficient;
234 }
235
236 // When input has front-stereo but output has not, and output has front-center,
237 // mix input's front-stereo to output's front-center.
238 if unaccounted_input_map.contains(ChannelMap::FRONT_2)
239 && output_map.contains(ChannelMap::FRONT_CENTER)
240 {
241 matrix[FRONT_CENTER][FRONT_LEFT] += FRAC_1_SQRT_2;
242 matrix[FRONT_CENTER][FRONT_RIGHT] += FRAC_1_SQRT_2;
243 if input_map.contains(ChannelMap::FRONT_CENTER) {
244 matrix[FRONT_CENTER][FRONT_CENTER] = CENTER_MIX_LEVEL * SQRT_2;
245 }
246 }
247
248 // When input has back-center but output has not,
249 if unaccounted_input_map.contains(ChannelMap::BACK_CENTER) {
250 // if output has back-stereo, mix input's back-center to output's back-stereo.
251 if output_map.contains(ChannelMap::BACK_2) {
252 matrix[BACK_LEFT][BACK_CENTER] += FRAC_1_SQRT_2;
253 matrix[BACK_RIGHT][BACK_CENTER] += FRAC_1_SQRT_2;
254 // or if output has side-stereo, mix input's back-center to output's side-stereo.
255 } else if output_map.contains(ChannelMap::SIDE_2) {
256 matrix[SIDE_LEFT][BACK_CENTER] += FRAC_1_SQRT_2;
257 matrix[SIDE_RIGHT][BACK_CENTER] += FRAC_1_SQRT_2;
258 // or if output has front-stereo, mix input's back-center to output's front-stereo.
259 } else if output_map.contains(ChannelMap::FRONT_2) {
260 matrix[FRONT_LEFT][BACK_CENTER] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
261 matrix[FRONT_RIGHT][BACK_CENTER] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
262 // or if output has front-center, mix input's back-center to output's front-center.
263 } else if output_map.contains(ChannelMap::FRONT_CENTER) {
264 matrix[FRONT_CENTER][BACK_CENTER] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
265 }
266 }
267
268 // When input has back-stereo but output has not,
269 if unaccounted_input_map.contains(ChannelMap::BACK_2) {
270 // if output has back-center, mix input's back-stereo to output's back-center.
271 if output_map.contains(ChannelMap::BACK_CENTER) {
272 matrix[BACK_CENTER][BACK_LEFT] += FRAC_1_SQRT_2;
273 matrix[BACK_CENTER][BACK_RIGHT] += FRAC_1_SQRT_2;
274 // or if output has side-stereo, mix input's back-stereo to output's side-stereo.
275 } else if output_map.contains(ChannelMap::SIDE_2) {
276 let coefficient = if input_map.contains(ChannelMap::SIDE_2) {
277 FRAC_1_SQRT_2
278 } else {
279 1.0
280 };
281 matrix[SIDE_LEFT][BACK_LEFT] += coefficient;
282 matrix[SIDE_RIGHT][BACK_RIGHT] += coefficient;
283 // or if output has front-stereo, mix input's back-stereo to output's side-stereo.
284 } else if output_map.contains(ChannelMap::FRONT_2) {
285 matrix[FRONT_LEFT][BACK_LEFT] += SURROUND_MIX_LEVEL;
286 matrix[FRONT_RIGHT][BACK_RIGHT] += SURROUND_MIX_LEVEL;
287 // or if output has front-center, mix input's back-stereo to output's front-center.
288 } else if output_map.contains(ChannelMap::FRONT_CENTER) {
289 matrix[FRONT_CENTER][BACK_LEFT] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
290 matrix[FRONT_CENTER][BACK_RIGHT] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
291 }
292 }
293
294 // When input has side-stereo but output has not,
295 if unaccounted_input_map.contains(ChannelMap::SIDE_2) {
296 // if output has back-stereo, mix input's side-stereo to output's back-stereo.
297 if output_map.contains(ChannelMap::BACK_2) {
298 let coefficient = if input_map.contains(ChannelMap::BACK_2) {
299 FRAC_1_SQRT_2
300 } else {
301 1.0
302 };
303 matrix[BACK_LEFT][SIDE_LEFT] += coefficient;
304 matrix[BACK_RIGHT][SIDE_RIGHT] += coefficient;
305 // or if output has back-center, mix input's side-stereo to output's back-center.
306 } else if output_map.contains(ChannelMap::BACK_CENTER) {
307 matrix[BACK_CENTER][SIDE_LEFT] += FRAC_1_SQRT_2;
308 matrix[BACK_CENTER][SIDE_RIGHT] += FRAC_1_SQRT_2;
309 // or if output has front-stereo, mix input's side-stereo to output's front-stereo.
310 } else if output_map.contains(ChannelMap::FRONT_2) {
311 matrix[FRONT_LEFT][SIDE_LEFT] += SURROUND_MIX_LEVEL;
312 matrix[FRONT_RIGHT][SIDE_RIGHT] += SURROUND_MIX_LEVEL;
313 // or if output has front-center, mix input's side-stereo to output's front-center.
314 } else if output_map.contains(ChannelMap::FRONT_CENTER) {
315 matrix[FRONT_CENTER][SIDE_LEFT] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
316 matrix[FRONT_CENTER][SIDE_RIGHT] += SURROUND_MIX_LEVEL * FRAC_1_SQRT_2;
317 }
318 }
319
320 // When input has front-stereo-of-center but output has not,
321 if unaccounted_input_map.contains(ChannelMap::FRONT_2_OF_CENTER) {
322 // if output has front-stereo, mix input's front-stereo-of-center to output's front-stereo.
323 if output_map.contains(ChannelMap::FRONT_2) {
324 matrix[FRONT_LEFT][FRONT_LEFT_OF_CENTER] += 1.0;
325 matrix[FRONT_RIGHT][FRONT_RIGHT_OF_CENTER] += 1.0;
326 // or if output has front-center, mix input's front-stereo-of-center to output's front-center.
327 } else if output_map.contains(ChannelMap::FRONT_CENTER) {
328 matrix[FRONT_CENTER][FRONT_LEFT_OF_CENTER] += FRAC_1_SQRT_2;
329 matrix[FRONT_CENTER][FRONT_RIGHT_OF_CENTER] += FRAC_1_SQRT_2;
330 }
331 }
332
333 // When input has low-frequency but output has not,
334 if unaccounted_input_map.contains(ChannelMap::LOW_FREQUENCY) {
335 // if output has front-center, mix input's low-frequency to output's front-center.
336 if output_map.contains(ChannelMap::FRONT_CENTER) {
337 matrix[FRONT_CENTER][LOW_FREQUENCY] += LFE_MIX_LEVEL;
338 // or if output has front-stereo, mix input's low-frequency to output's front-stereo.
339 } else if output_map.contains(ChannelMap::FRONT_2) {
340 matrix[FRONT_LEFT][LOW_FREQUENCY] += LFE_MIX_LEVEL * FRAC_1_SQRT_2;
341 matrix[FRONT_RIGHT][LOW_FREQUENCY] += LFE_MIX_LEVEL * FRAC_1_SQRT_2;
342 }
343 }
344
345 Ok(matrix)
346 }
347
348 // Return a CHANNELSxCHANNELS matrix M that is (CHANNELS-1)x(CHANNELS-1) identity matrix
349 // padding with one extra row and one column containing only zero values. The result would be:
350 //
351 // identity padding
352 // matrix column
353 // ▾ ▾
354 // ┌┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┐ i ┐
355 // │ 1, 0, 0, ..., 0 ┊, 0 │ ◂ 0 ┊ channel i
356 // │ 0, 1, 0, ..., 0 ┊, 0 │ ◂ 1 ┊ for
357 // │ 0, 0, 1, ..., 0 ┊, 0 │ ◂ 2 ┊ audio
358 // │ 0, 0, 0, ..., 0 ┊, 0 │ . ┊ output
359 // │ ............... ┊ │ . ┊
360 // │ 0, 0, 0, ..., 1 ┊, 0 │ ◂ 16 ┊
361 // ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┼┈┈┈┈┤ ◂ 17 ┊
362 // │ 0, 0, 0, ..., 0 ┊, 0 │ ◂ padding row ◂ 18 ┊
363 // ▴ ▴ ▴ .... ▴ ▴ ┘
364 // j 0 1 2 .... 17 18
365 // └┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┘
366 // channel j for audio input
367 //
368 // Given an audio input buffer, in_audio, and an output buffer, out_audio,
369 // and their channel data are both ordered by the values defined in enum Channel.
370 // The generated matrix M makes sure that:
371 //
372 // out_audio(i) = in_audio(j), if i == j and both i, j are non-silence channel
373 // = 0, if i != j or i, j are silence channel
374 //
375 // │ FrontLeft │ │ FrontLeft │ ◂ data in front-left channel
376 // │ FrontRight │ │ FrontRight │ ◂ data in front-right channel
377 // │ FrontCenter │ = M x │ FrontCenter │ ◂ data in front-center channel
378 // │ ........... │ │ ........... │ ◂ ...
379 // │ Silence │ │ Silence │ ◂ data in silence channel
380 // ▴ ▴
381 // out_audio in_audio
382 //
383 // That is,
384 // 1. If the input-channel is silence, it won't be mixed into any channel.
385 // 2. If the output-channel is silence, its output-channel data will be zero (silence).
386 // 3. If input-channel j is different from output-channel i, audio data in input channel j
387 // won't be mixed into the audio output data in channel i
388 // 4. If input-channel j is same as output-channel i, audio data in input channel j will be
389 // copied to audio output data in channel i
390 //
391 fn get_basic_matrix() -> [[f64; CHANNELS]; CHANNELS] {
392 const SILENCE: usize = Channel::Silence.number();
393 let mut matrix = [[0.0; CHANNELS]; CHANNELS];
394 for (i, row) in matrix.iter_mut().enumerate() {
395 if i != SILENCE {
396 row[i] = 1.0;
397 }
398 }
399 matrix
400 }
401
402 // Given is an CHANNELSxCHANNELS mixing matrix whose indice are ordered by the values defined
403 // in enum Channel, and the channel orders of M-channel input and N-channel output, generate a
404 // mixing matrix m such that output_data(i) = Σ m[i][j] * input_data(j), for all j in [0, M),
405 // where i is in [0, N) and {input/output}_data(k) means the data of the number k channel in
406 // the input/output buffer.
407 fn pick_coefficients(
408 input_channels: &[Channel],
409 output_channels: &[Channel],
410 source: &[[f64; CHANNELS]; CHANNELS],
411 ) -> Vec<Vec<f64>> {
412 let mut matrix = Vec::with_capacity(output_channels.len());
413 for output_channel in output_channels {
414 let output_channel_index = (*output_channel).number();
415 let mut coefficients = Vec::with_capacity(input_channels.len());
416 for input_channel in input_channels {
417 let input_channel_index = (*input_channel).number();
418 coefficients.push(source[output_channel_index][input_channel_index]);
419 }
420 matrix.push(coefficients);
421 }
422 matrix
423 }
424
425 fn normalize(max_coefficients_sum: f64, mut coefficients: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
426 let mut max_sum: f64 = 0.0;
427 for coefs in &coefficients {
428 max_sum = max_sum.max(coefs.iter().sum());
429 }
430 if max_sum != 0.0 && max_sum > max_coefficients_sum {
431 max_sum /= max_coefficients_sum;
432 for coefs in &mut coefficients {
433 for coef in coefs {
434 *coef /= max_sum;
435 }
436 }
437 }
438 coefficients
439 }
440 }
441
442 pub trait MixingCoefficient {
443 type Coef;
444
445 // TODO: These should be private.
446 fn max_coefficients_sum() -> f64; // Used for normalizing.
447 fn coefficient_from_f64(value: f64) -> Self::Coef;
448 // Precheck if overflow occurs when converting value from Self::Coef type to Self type.
449 fn would_overflow_from_coefficient_value(coefficient: &[Vec<f64>]) -> Option<bool>;
450
451 // Convert f32 (Self) -> f32 (Self::Coef) or i16 (Self) -> i32 (Self::Coef)
452 #[allow(clippy::wrong_self_convention)]
453 fn to_coefficient_value(value: Self) -> Self::Coef;
454 fn from_coefficient_value(value: Self::Coef, would_overflow: Option<bool>) -> Self;
455 }
456
457 impl MixingCoefficient for f32 {
458 type Coef = f32;
459
460 fn max_coefficients_sum() -> f64 {
461 f64::from(i32::MAX)
462 }
463
464 fn coefficient_from_f64(value: f64) -> Self::Coef {
465 value as Self::Coef
466 }
467
468 fn would_overflow_from_coefficient_value(_coefficient: &[Vec<f64>]) -> Option<bool> {
469 None
470 }
471
472 fn to_coefficient_value(value: Self) -> Self::Coef {
473 value
474 }
475
476 fn from_coefficient_value(value: Self::Coef, would_overflow: Option<bool>) -> Self {
477 assert!(would_overflow.is_none());
478 value
479 }
480 }
481
482 impl MixingCoefficient for i16 {
483 type Coef = i32;
484
485 fn max_coefficients_sum() -> f64 {
486 1.0
487 }
488
489 fn coefficient_from_f64(value: f64) -> Self::Coef {
490 (value * f64::from(1 << 15)).round() as Self::Coef
491 }
492
493 fn would_overflow_from_coefficient_value(coefficient: &[Vec<f64>]) -> Option<bool> {
494 let mut max_sum: Self::Coef = 0;
495 for row in coefficient {
496 let mut sum: Self::Coef = 0;
497 let mut rem: f64 = 0.0;
498 for coef in row {
499 let target = coef * f64::from(1 << 15) + rem;
500 let value = target.round() as Self::Coef;
501 rem += target - target.round();
502 sum += value.abs();
503 }
504 max_sum = max_sum.max(sum);
505 }
506 Some(max_sum > (1 << 15))
507 }
508
509 fn to_coefficient_value(value: Self) -> Self::Coef {
510 Self::Coef::from(value)
511 }
512
513 fn from_coefficient_value(value: Self::Coef, would_overflow: Option<bool>) -> Self {
514 use std::convert::TryFrom;
515 let would_overflow = would_overflow.expect("would_overflow must have value for i16 type");
516 let mut converted = (value + (1 << 14)) >> 15;
517 // clip the signed integer value into the -32768,32767 range.
518 if would_overflow && ((converted + 0x8000) & !0xFFFF != 0) {
519 converted = (converted >> 31) ^ 0x7FFF;
520 }
521 Self::try_from(converted).expect("Cannot convert coefficient from i32 to i16")
522 }
523 }
524
525 #[cfg(test)]
526 mod test {
527 use super::*;
528
529 #[test]
530 fn test_create_f32() {
531 test_create::<f32>(MixDirection::Downmix);
532 test_create::<f32>(MixDirection::Upmix);
533 }
534
535 #[test]
536 fn test_create_i16() {
537 test_create::<i16>(MixDirection::Downmix);
538 test_create::<i16>(MixDirection::Upmix);
539 }
540
541 fn test_create<T>(direction: MixDirection)
542 where
543 T: MixingCoefficient,
544 T::Coef: Copy + Debug,
545 {
546 let (input_channels, output_channels) = get_test_channels(direction);
547 let coefficient = Coefficient::<T>::create(&input_channels, &output_channels);
548 println!(
549 "{:?} = {:?} * {:?}",
550 output_channels, coefficient.matrix, input_channels
551 );
552 }
553
554 enum MixDirection {
555 Downmix,
556 Upmix,
557 }
558 fn get_test_channels(direction: MixDirection) -> (Vec<Channel>, Vec<Channel>) {
559 let more = vec![
560 Channel::Silence,
561 Channel::FrontRight,
562 Channel::FrontLeft,
563 Channel::LowFrequency,
564 Channel::Silence,
565 Channel::BackCenter,
566 ];
567 let less = vec![
568 Channel::FrontLeft,
569 Channel::Silence,
570 Channel::FrontRight,
571 Channel::FrontCenter,
572 ];
573 match direction {
574 MixDirection::Downmix => (more, less),
575 MixDirection::Upmix => (less, more),
576 }
577 }
578
579 #[test]
580 fn test_create_with_duplicate_silience_channels_f32() {
581 test_create_with_duplicate_channels::<f32>()
582 }
583
584 #[test]
585 fn test_create_with_duplicate_silience_channels_i16() {
586 test_create_with_duplicate_channels::<i16>()
587 }
588
589 #[test]
590 #[should_panic]
591 fn test_create_with_duplicate_input_channels_f32() {
592 test_create_with_duplicate_input_channels::<f32>()
593 }
594
595 #[test]
596 #[should_panic]
597 fn test_create_with_duplicate_input_channels_i16() {
598 test_create_with_duplicate_input_channels::<i16>()
599 }
600
601 #[test]
602 #[should_panic]
603 fn test_create_with_duplicate_output_channels_f32() {
604 test_create_with_duplicate_output_channels::<f32>()
605 }
606
607 #[test]
608 #[should_panic]
609 fn test_create_with_duplicate_output_channels_i16() {
610 test_create_with_duplicate_output_channels::<i16>()
611 }
612
613 fn test_create_with_duplicate_channels<T>()
614 where
615 T: MixingCoefficient,
616 T::Coef: Copy,
617 {
618 // Duplicate of Silence channels is allowed on both input side and output side.
619 let input_channels = [
620 Channel::FrontLeft,
621 Channel::Silence,
622 Channel::FrontRight,
623 Channel::FrontCenter,
624 Channel::Silence,
625 ];
626 let output_channels = [
627 Channel::Silence,
628 Channel::FrontRight,
629 Channel::FrontLeft,
630 Channel::BackCenter,
631 Channel::Silence,
632 ];
633 let _ = Coefficient::<T>::create(&input_channels, &output_channels);
634 }
635
636 fn test_create_with_duplicate_input_channels<T>()
637 where
638 T: MixingCoefficient,
639 T::Coef: Copy,
640 {
641 let input_channels = [
642 Channel::FrontLeft,
643 Channel::Silence,
644 Channel::FrontLeft,
645 Channel::FrontCenter,
646 ];
647 let output_channels = [
648 Channel::Silence,
649 Channel::FrontRight,
650 Channel::FrontLeft,
651 Channel::FrontCenter,
652 Channel::BackCenter,
653 ];
654 let _ = Coefficient::<T>::create(&input_channels, &output_channels);
655 }
656
657 fn test_create_with_duplicate_output_channels<T>()
658 where
659 T: MixingCoefficient,
660 T::Coef: Copy,
661 {
662 let input_channels = [
663 Channel::FrontLeft,
664 Channel::Silence,
665 Channel::FrontRight,
666 Channel::FrontCenter,
667 ];
668 let output_channels = [
669 Channel::Silence,
670 Channel::FrontRight,
671 Channel::FrontLeft,
672 Channel::FrontCenter,
673 Channel::FrontCenter,
674 Channel::BackCenter,
675 ];
676 let _ = Coefficient::<T>::create(&input_channels, &output_channels);
677 }
678
679 #[test]
680 fn test_get_discrete_mapping() {
681 test_get_discrete_mapping_matrix::<f32>();
682 test_get_discrete_mapping_matrix::<i16>();
683 }
684
685 #[test]
686 fn test_get_discrete_mapping_too_many_channels() {
687 test_get_discrete_mapping_matrix_too_many_channels::<i16>();
688 test_get_discrete_mapping_matrix_too_many_channels::<f32>();
689 }
690
691 #[test]
692 fn test_get_regular_mapping_too_many_channels() {
693 test_get_regular_mapping_matrix_too_many_channels::<i16>();
694 test_get_regular_mapping_matrix_too_many_channels::<f32>();
695 }
696
697 // Check that a matrix is diagonal (1.0 on the diagnoal, 0.0 elsewhere). It's valid to have more input or output channels
698 fn assert_is_diagonal<T>(
699 coefficients: &Coefficient<T>,
700 input_channels: usize,
701 output_channels: usize,
702 ) where
703 T: MixingCoefficient,
704 T::Coef: Copy + Debug + PartialEq,
705 {
706 for i in 0..input_channels {
707 for j in 0..output_channels {
708 if i == j {
709 assert_eq!(coefficients.get(i, j), T::coefficient_from_f64(1.0));
710 } else {
711 assert_eq!(coefficients.get(i, j), T::coefficient_from_f64(0.0));
712 }
713 }
714 }
715 println!(
716 "{:?} = {:?} * {:?}",
717 output_channels, coefficients.matrix, input_channels
718 );
719 }
720
721 fn test_get_discrete_mapping_matrix<T>()
722 where
723 T: MixingCoefficient,
724 T::Coef: Copy + Debug + PartialEq,
725 {
726 // typical 5.1
727 let input_channels = [
728 Channel::FrontLeft,
729 Channel::FrontRight,
730 Channel::FrontCenter,
731 Channel::BackLeft,
732 Channel::BackRight,
733 Channel::LowFrequency,
734 ];
735 // going into 8 channels with a tagged stereo pair and discrete channels
736 let output_channels = [
737 Channel::FrontLeft,
738 Channel::FrontRight,
739 Channel::Discrete,
740 Channel::Discrete,
741 Channel::Discrete,
742 Channel::Discrete,
743 Channel::Discrete,
744 Channel::Discrete,
745 ];
746
747 // Get a pass-through matrix in the first 6 channels
748 let coefficients = Coefficient::<T>::create(&input_channels, &output_channels);
749 assert_is_diagonal::<T>(&coefficients, input_channels.len(), output_channels.len());
750 }
751
752 fn test_get_discrete_mapping_matrix_too_many_channels<T>()
753 where
754 T: MixingCoefficient,
755 T::Coef: Copy + Debug + PartialEq,
756 {
757 // 5.1.4
758 let input_channels = [
759 Channel::FrontLeft,
760 Channel::FrontRight,
761 Channel::FrontCenter,
762 Channel::LowFrequency,
763 Channel::FrontLeftOfCenter,
764 Channel::FrontRightOfCenter,
765 Channel::TopFrontLeft,
766 Channel::TopFrontRight,
767 Channel::BackLeft,
768 Channel::BackRight,
769 ];
770 // going into 8 channels with a tagged stereo pair and discrete channels
771 let output_channels = [
772 Channel::FrontLeft,
773 Channel::FrontRight,
774 Channel::Discrete,
775 Channel::Discrete,
776 Channel::Discrete,
777 Channel::Discrete,
778 Channel::Discrete,
779 Channel::Discrete,
780 ];
781
782 // First 8 channels are to be played, last two are to be dropped.
783 let coefficients = Coefficient::<T>::create(&input_channels, &output_channels);
784 assert_is_diagonal(&coefficients, input_channels.len(), output_channels.len());
785 }
786
787 fn test_get_regular_mapping_matrix_too_many_channels<T>()
788 where
789 T: MixingCoefficient,
790 T::Coef: Copy + Debug + PartialEq,
791 {
792 // 5.1.4
793 let input_channels = [
794 Channel::FrontLeft,
795 Channel::FrontRight,
796 Channel::FrontCenter,
797 Channel::LowFrequency,
798 Channel::FrontLeftOfCenter,
799 Channel::FrontRightOfCenter,
800 Channel::TopFrontLeft,
801 Channel::TopFrontRight,
802 Channel::BackLeft,
803 Channel::BackRight,
804 ];
805 // going into a regular 5.1 sound card
806 let output_channels = [
807 Channel::FrontLeft,
808 Channel::FrontRight,
809 Channel::FrontCenter,
810 Channel::LowFrequency,
811 Channel::BackLeft,
812 Channel::BackRight,
813 ];
814
815 let coefficients = Coefficient::<T>::create(&input_channels, &output_channels);
816
817 // Non-unity gain non-silence coefficients must be present when down mixing.
818 let mut found_non_unity_non_silence = false;
819 for row in coefficients.matrix.iter() {
820 for coeff in row.iter() {
821 if T::coefficient_from_f64(1.0) != *coeff || T::coefficient_from_f64(0.0) != *coeff
822 {
823 found_non_unity_non_silence = true;
824 break;
825 }
826 }
827 }
828 assert!(found_non_unity_non_silence);
829 }
830
831 #[test]
832 fn test_normalize() {
833 use float_cmp::approx_eq;
834
835 let m = vec![
836 vec![1.0_f64, 2.0_f64, 3.0_f64],
837 vec![4.0_f64, 6.0_f64, 10.0_f64],
838 ];
839
840 let mut max_row_sum: f64 = f64::MIN;
841 for row in &m {
842 max_row_sum = max_row_sum.max(row.iter().sum());
843 }
844
845 // Type of Coefficient doesn't matter here.
846 // If the first argument of normalize >= max_row_sum, do nothing.
847 let n = Coefficient::<f32>::normalize(max_row_sum, m.clone());
848 assert_eq!(n, m);
849
850 // If the first argument of normalize < max_row_sum, do normalizing.
851 let smaller_max = max_row_sum - 0.5_f64;
852 assert!(smaller_max > 0.0_f64);
853 let n = Coefficient::<f32>::normalize(smaller_max, m);
854 let mut max_row_sum: f64 = f64::MIN;
855 for row in &n {
856 max_row_sum = max_row_sum.max(row.iter().sum());
857 assert!(row.iter().sum::<f64>() <= smaller_max);
858 }
859 assert!(approx_eq!(f64, smaller_max, max_row_sum));
860 }
861 }