oarust 0.15.1

GPU-first semantic computing engine written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=audio.json schema_version=1 generator_version=64
// schema_sha256=0acacb625934738cbac7eca8170ac18c3fb7f7dc2fb4b57552bf03ab04585d3b
//! Stateless GPU feature transforms from Audio to Matrix.

use crate::{
	Audio, AudioChannelLayout, DType, Error, Matrix, OpAttribute, Result,
	runtime::{
		AudioSemanticDispatch, AudioSemanticInput, AudioSemanticOutput, BufferBinding, ComputeDispatch,
		KernelId, PushConstant,
	},
};

use super::signal::{float_attribute, u32_extent, unsigned_attribute};

fn validate_stft(input: &Audio, config: StftConfig) -> Result<StftShape> {
	if !config.fft_size.is_power_of_two() || !(16..=1_024).contains(&config.fft_size) {
		return Err(Error::invalid_argument(
			"audio::stft fft_size must be a power of two in [16, 1024]",
		));
	}
	if config.hop_size == 0 {
		return Err(Error::invalid_argument(
			"audio::stft hop_size must be nonzero",
		));
	}
	let win_size = if config.win_size == 0 {
		config.fft_size
	} else {
		config.win_size
	};
	if win_size > config.fft_size {
		return Err(Error::invalid_argument(
			"audio::stft win_size must be zero or no larger than fft_size",
		));
	}
	let channels = u32_extent(input.channels(), "audio::stft channels")?;
	let samples = u32_extent(input.samples(), "audio::stft samples")?;
	let frames = if config.center {
		1 + samples / config.hop_size
	} else if samples < config.fft_size {
		1
	} else {
		1 + (samples - config.fft_size) / config.hop_size
	};
	let freq_bins = config.fft_size / 2 + 1;
	channels
		.checked_mul(frames)
		.and_then(|value| value.checked_mul(freq_bins))
		.ok_or_else(|| Error::out_of_range("audio::stft output exceeds u32"))?;
	Ok(StftShape {
		channels,
		samples,
		frames,
		freq_bins,
	})
}

fn validate_istft(input: &Matrix, config: IstftConfig) -> Result<IstftShape> {
	if !config.fft_size.is_power_of_two() || !(16..=1_024).contains(&config.fft_size) {
		return Err(Error::invalid_argument(
			"audio::istft fft_size must be a power of two in [16, 1024]",
		));
	}
	if config.hop_size == 0 {
		return Err(Error::invalid_argument(
			"audio::istft hop_size must be nonzero",
		));
	}
	let win_size = if config.win_size == 0 {
		config.fft_size
	} else {
		config.win_size
	};
	if win_size > config.fft_size {
		return Err(Error::invalid_argument(
			"audio::istft win_size must be zero or no larger than fft_size",
		));
	}
	if config.sample_rate == 0 {
		return Err(Error::invalid_argument(
			"audio::istft sample_rate must be nonzero",
		));
	}
	let dims = input.shape();
	if dims.len() != 4 || dims[3] != 2 {
		return Err(Error::invalid_argument(
			"audio::istft input must be [channels, frames, frequency_bins, 2]",
		));
	}
	let channels = u32_extent(dims[0], "audio::istft channels")?;
	let frames = u32_extent(dims[1], "audio::istft frames")?;
	let freq_bins = u32_extent(dims[2], "audio::istft frequency_bins")?;
	if frames == 0 || freq_bins != config.fft_size / 2 + 1 {
		return Err(Error::invalid_argument(
			"audio::istft input shape does not match fft_size",
		));
	}
	let padded_samples = frames
		.checked_sub(1)
		.and_then(|value| value.checked_mul(config.hop_size))
		.and_then(|value| value.checked_add(config.fft_size))
		.ok_or_else(|| Error::out_of_range("audio::istft output exceeds u32"))?;
	let crop_offset = if config.center {
		config.fft_size / 2
	} else {
		0
	};
	let out_samples = padded_samples
		.checked_sub(2 * crop_offset)
		.ok_or_else(|| Error::invalid_argument("audio::istft crop exceeds padded output"))?;
	channels
		.checked_mul(padded_samples)
		.ok_or_else(|| Error::out_of_range("audio::istft output exceeds u32"))?;
	Ok(IstftShape {
		channels,
		frames,
		freq_bins,
		padded_samples,
		crop_offset,
		out_samples,
	})
}

fn validate_mel(input: &Audio, config: MelConfig) -> Result<()> {
	let nyquist = input.sample_rate() as f32 * 0.5;
	let f_max = if config.f_max > 0.0 {
		config.f_max
	} else {
		nyquist
	};
	if !config.fft_size.is_power_of_two()
		|| !(16..=1_024).contains(&config.fft_size)
		|| config.hop_size == 0
		|| !(1..=4_096).contains(&config.num_mels)
		|| !config.f_min.is_finite()
		|| !f_max.is_finite()
		|| config.f_min < 0.0
		|| config.f_min >= f_max
		|| f_max > nyquist
	{
		return Err(Error::invalid_argument(
			"audio mel configuration is invalid",
		));
	}
	Ok(())
}

fn build_mel_filterbank(input: &Audio, config: MelConfig, freq_bins: u32) -> Result<Matrix> {
	let sample_rate = input.sample_rate() as f32;
	let f_max = if config.f_max > 0.0 {
		config.f_max
	} else {
		sample_rate * 0.5
	};
	let hz_to_mel = |frequency: f32| 2_595.0 * (1.0 + frequency / 700.0).log10();
	let mel_to_hz = |mel: f32| 700.0 * (10.0_f32.powf(mel / 2_595.0) - 1.0);
	let mel_min = hz_to_mel(config.f_min);
	let mel_max = hz_to_mel(f_max);
	let point_count = config.num_mels as usize + 2;
	let mut points = Vec::new();
	points
		.try_reserve_exact(point_count)
		.map_err(|_| Error::resource_exhausted("mel point allocation failed"))?;
	for index in 0..point_count {
		let ratio = index as f32 / (config.num_mels + 1) as f32;
		points.push(mel_to_hz(mel_min + ratio * (mel_max - mel_min)));
	}
	let element_count = (config.num_mels as usize)
		.checked_mul(freq_bins as usize)
		.ok_or_else(|| Error::out_of_range("mel filterbank exceeds usize"))?;
	let mut weights = vec![0.0_f32; element_count];
	let bin_hz = sample_rate / config.fft_size as f32;
	for mel in 0..config.num_mels as usize {
		for bin in 0..freq_bins as usize {
			let frequency = bin as f32 * bin_hz;
			let (low, center, high) = (points[mel], points[mel + 1], points[mel + 2]);
			weights[mel * freq_bins as usize + bin] =
				if frequency >= low && frequency <= center && center > low {
					(frequency - low) / (center - low)
				} else if frequency > center && frequency <= high && high > center {
					(high - frequency) / (high - center)
				} else {
					0.0
				};
		}
	}
	Matrix::new_from_slice_handle(
		input.engine_handle(),
		vec![config.num_mels as usize, freq_bins as usize],
		&weights,
	)
}

/// Window function applied before each FFT frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StftWindow {
	#[default]
	Hann,
	Hamming,
	Blackman,
	Rectangular,
}

/// Short-time Fourier transform configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StftConfig {
	pub fft_size: u32,
	pub hop_size: u32,
	/// Zero selects `fft_size`.
	pub win_size: u32,
	pub window: StftWindow,
	pub center: bool,
}

impl Default for StftConfig {
	fn default() -> Self {
		Self {
			fft_size: 1_024,
			hop_size: 256,
			win_size: 0,
			window: StftWindow::Hann,
			center: true,
		}
	}
}

#[derive(Clone, Copy)]
struct StftShape {
	channels: u32,
	samples: u32,
	frames: u32,
	freq_bins: u32,
}

/// Compute magnitude STFT features in `[channels, frames, frequency_bins]` layout.
pub fn stft(input: &Audio, config: StftConfig) -> Result<Matrix> {
	let shape = validate_stft(input, config)?;
	let elements = shape.channels * shape.frames * shape.freq_bins;
	let output = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			shape.frames as usize,
			shape.freq_bins as usize,
		],
		elements as usize,
		DType::F32,
	)?;
	let buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(output.storage()),
	];
	let win_size = if config.win_size == 0 {
		config.fft_size
	} else {
		config.win_size
	};
	let window: u32 = match config.window {
		StftWindow::Hann => 0,
		StftWindow::Hamming => 1,
		StftWindow::Blackman => 2,
		StftWindow::Rectangular => 3,
	};
	let push = [
		PushConstant::U32(config.fft_size),
		PushConstant::U32(config.hop_size),
		PushConstant::U32(win_size),
		PushConstant::U32(window),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.samples),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(u32::from(config.center)),
	];
	let attributes = [
		unsigned_attribute("fftSize", u64::from(config.fft_size)),
		unsigned_attribute("hopSize", u64::from(config.hop_size)),
		unsigned_attribute("winSize", u64::from(config.win_size)),
		unsigned_attribute("window", u64::from(window)),
		OpAttribute::Boolean {
			name: "center".into(),
			value: config.center,
		},
	];
	let outputs = [AudioSemanticOutput::Matrix(&output)];
	input.engine_handle().record_audio_semantic(
		ComputeDispatch {
			kernel: KernelId::AudioStftF32,
			buffers: &buffers,
			push_constants: &push,
			workgroups: [shape.frames, 1, shape.channels],
			indirect: None,
		},
		AudioSemanticDispatch {
			contract: crate::core::operation::audio::STFT,
			inputs: &[AudioSemanticInput::Audio(input)],
			outputs: &outputs,
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Compute complex STFT coefficients in `[channels, frames, frequency_bins, 2]` interleaved real/imaginary layout.
pub fn stft_complex(input: &Audio, config: StftConfig) -> Result<Matrix> {
	let shape = validate_stft(input, config)?;
	let elements = shape.channels * shape.frames * shape.freq_bins * 2;
	let output = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			shape.frames as usize,
			shape.freq_bins as usize,
			2,
		],
		elements as usize,
		DType::F32,
	)?;
	let buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(output.storage()),
	];
	let win_size = if config.win_size == 0 {
		config.fft_size
	} else {
		config.win_size
	};
	let window: u32 = match config.window {
		StftWindow::Hann => 0,
		StftWindow::Hamming => 1,
		StftWindow::Blackman => 2,
		StftWindow::Rectangular => 3,
	};
	let push = [
		PushConstant::U32(config.fft_size),
		PushConstant::U32(config.hop_size),
		PushConstant::U32(win_size),
		PushConstant::U32(window),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.samples),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(u32::from(config.center)),
	];
	let attributes = [
		unsigned_attribute("fftSize", u64::from(config.fft_size)),
		unsigned_attribute("hopSize", u64::from(config.hop_size)),
		unsigned_attribute("winSize", u64::from(config.win_size)),
		unsigned_attribute("window", u64::from(window)),
		OpAttribute::Boolean {
			name: "center".into(),
			value: config.center,
		},
	];
	let outputs = [AudioSemanticOutput::Matrix(&output)];
	input.engine_handle().record_audio_semantic(
		ComputeDispatch {
			kernel: KernelId::AudioStftComplexF32,
			buffers: &buffers,
			push_constants: &push,
			workgroups: [shape.frames, 1, shape.channels],
			indirect: None,
		},
		AudioSemanticDispatch {
			contract: crate::core::operation::audio::STFT_COMPLEX,
			inputs: &[AudioSemanticInput::Audio(input)],
			outputs: &outputs,
			attributes: &attributes,
		},
	)?;
	crate::audio::autograd::record(crate::audio::autograd::GradNodeAudio::StftComplex {
		input: input.as_matrix().clone(),
		output_id: output.value_id(),
		fft_size: config.fft_size,
		hop_size: config.hop_size,
		win_size: config.win_size,
		window: config.window,
		center: config.center,
		sample_rate: input.sample_rate(),
	})?;
	Ok(output)
}

/// Inverse STFT configuration; `sample_rate` labels the reconstructed audio.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IstftConfig {
	pub fft_size: u32,
	pub hop_size: u32,
	/// Zero selects `fft_size`.
	pub win_size: u32,
	pub window: StftWindow,
	pub center: bool,
	pub sample_rate: u32,
}

impl Default for IstftConfig {
	fn default() -> Self {
		Self {
			fft_size: 1_024,
			hop_size: 256,
			win_size: 0,
			window: StftWindow::Hann,
			center: true,
			sample_rate: 48_000,
		}
	}
}

#[derive(Clone, Copy)]
struct IstftShape {
	channels: u32,
	frames: u32,
	freq_bins: u32,
	padded_samples: u32,
	crop_offset: u32,
	out_samples: u32,
}

/// Invert a complex STFT matrix in `[channels, frames, frequency_bins, 2]` layout into planar audio using the inverse FFT and windowed overlap-add.
pub fn istft(input: &Matrix, config: IstftConfig) -> Result<Audio> {
	let shape = validate_istft(input, config)?;
	let scratch = Matrix::allocate(
		input.engine_handle(),
		vec![shape.channels as usize, shape.padded_samples as usize],
		(shape.channels * shape.padded_samples) as usize,
		DType::F32,
	)?;
	let norm = Matrix::allocate(
		input.engine_handle(),
		vec![shape.channels as usize, shape.padded_samples as usize],
		(shape.channels * shape.padded_samples) as usize,
		DType::F32,
	)?;
	let output = Matrix::allocate(
		input.engine_handle(),
		vec![shape.channels as usize, shape.out_samples as usize],
		(shape.channels * shape.out_samples) as usize,
		DType::F32,
	)?;
	let frames_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(scratch.storage()),
		BufferBinding::write(norm.storage()),
	];
	let normalize_buffers = [
		BufferBinding::read(scratch.storage()),
		BufferBinding::read(norm.storage()),
		BufferBinding::write(output.storage()),
	];
	let win_size = if config.win_size == 0 {
		config.fft_size
	} else {
		config.win_size
	};
	let window: u32 = match config.window {
		StftWindow::Hann => 0,
		StftWindow::Hamming => 1,
		StftWindow::Blackman => 2,
		StftWindow::Rectangular => 3,
	};
	let frames_push = [
		PushConstant::U32(config.fft_size),
		PushConstant::U32(config.hop_size),
		PushConstant::U32(win_size),
		PushConstant::U32(window),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(shape.padded_samples),
	];
	let normalize_push = [
		PushConstant::U32(shape.crop_offset),
		PushConstant::U32(shape.out_samples),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.padded_samples),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::AudioIstftFramesF32,
			buffers: &frames_buffers,
			push_constants: &frames_push,
			workgroups: [shape.frames, 1, shape.channels],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::AudioIstftNormalizeF32,
			buffers: &normalize_buffers,
			push_constants: &normalize_push,
			workgroups: KernelId::AudioIstftNormalizeF32
				.linear_workgroups(shape.channels * shape.out_samples),
			indirect: None,
		},
	];
	let attributes = [
		unsigned_attribute("fftSize", u64::from(config.fft_size)),
		unsigned_attribute("hopSize", u64::from(config.hop_size)),
		unsigned_attribute("winSize", u64::from(config.win_size)),
		unsigned_attribute("window", u64::from(window)),
		OpAttribute::Boolean {
			name: "center".into(),
			value: config.center,
		},
	];
	let audio = Audio::new(
		output.clone(),
		config.sample_rate,
		AudioChannelLayout::for_channel_count(shape.channels as usize),
	)?;
	let outputs = [AudioSemanticOutput::Audio(&audio)];
	input.engine_handle().record_audio_split_semantic(
		&dispatches,
		AudioSemanticDispatch {
			contract: crate::core::operation::audio::ISTFT,
			inputs: &[AudioSemanticInput::Matrix(input)],
			outputs: &outputs,
			attributes: &attributes,
		},
	)?;
	crate::audio::autograd::record(crate::audio::autograd::GradNodeAudio::Istft {
		input: input.clone(),
		output_id: audio.as_matrix().value_id(),
		fft_size: config.fft_size,
		hop_size: config.hop_size,
		win_size: config.win_size,
		window: config.window,
		center: config.center,
		sample_rate: config.sample_rate,
	})?;
	Ok(audio)
}

/// Mel-spectrogram configuration.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MelConfig {
	pub fft_size: u32,
	pub hop_size: u32,
	pub num_mels: u32,
	pub f_min: f32,
	/// Zero selects the Nyquist frequency.
	pub f_max: f32,
	pub log_scale: bool,
	pub normalize: bool,
}

impl Default for MelConfig {
	fn default() -> Self {
		Self {
			fft_size: 1_024,
			hop_size: 256,
			num_mels: 80,
			f_min: 0.0,
			f_max: 0.0,
			log_scale: true,
			normalize: false,
		}
	}
}

/// Compute HTK triangular-filter mel features in `[channels, mels, frames]` layout.
pub fn mel_spectrogram(input: &Audio, config: MelConfig) -> Result<Matrix> {
	validate_mel(input, config)?;
	let stft_config = StftConfig {
		fft_size: config.fft_size,
		hop_size: config.hop_size,
		win_size: config.fft_size,
		..StftConfig::default()
	};
	let shape = validate_stft(input, stft_config)?;
	let elements = shape.channels * shape.frames * shape.freq_bins;
	let spectrum = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			shape.frames as usize,
			shape.freq_bins as usize,
		],
		elements as usize,
		DType::F32,
	)?;
	let filterbank = build_mel_filterbank(input, config, shape.freq_bins)?;
	let values_per_channel = config
		.num_mels
		.checked_mul(shape.frames)
		.ok_or_else(|| Error::out_of_range("audio::mel_spectrogram channel extent exceeds u32"))?;
	let output_elements = shape
		.channels
		.checked_mul(values_per_channel)
		.ok_or_else(|| Error::out_of_range("audio::mel_spectrogram output exceeds u32"))?;

	let spectrum_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(spectrum.storage()),
	];
	let win_size = if stft_config.win_size == 0 {
		stft_config.fft_size
	} else {
		stft_config.win_size
	};
	let window: u32 = match stft_config.window {
		StftWindow::Hann => 0,
		StftWindow::Hamming => 1,
		StftWindow::Blackman => 2,
		StftWindow::Rectangular => 3,
	};
	let spectrum_push = [
		PushConstant::U32(stft_config.fft_size),
		PushConstant::U32(stft_config.hop_size),
		PushConstant::U32(win_size),
		PushConstant::U32(window),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.samples),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(u32::from(stft_config.center)),
	];
	let mel_push = [
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(config.num_mels),
		PushConstant::U32(u32::from(config.log_scale)),
	];
	let attributes = [
		unsigned_attribute("fftSize", u64::from(config.fft_size)),
		unsigned_attribute("hopSize", u64::from(config.hop_size)),
		unsigned_attribute("numMels", u64::from(config.num_mels)),
		float_attribute("fMin", config.f_min),
		float_attribute("fMax", config.f_max),
		OpAttribute::Boolean {
			name: "logScale".into(),
			value: config.log_scale,
		},
		OpAttribute::Boolean {
			name: "normalize".into(),
			value: config.normalize,
		},
	];

	let output = if config.normalize {
		let raw = Matrix::allocate(
			input.engine_handle(),
			vec![
				shape.channels as usize,
				config.num_mels as usize,
				shape.frames as usize,
			],
			output_elements as usize,
			DType::F32,
		)?;
		let output = Matrix::allocate(
			input.engine_handle(),
			raw.shape().to_vec(),
			raw.num_elements(),
			DType::F32,
		)?;
		let mel_buffers = [
			BufferBinding::read(spectrum.storage()),
			BufferBinding::write(raw.storage()),
			BufferBinding::read(filterbank.storage()),
		];
		let normalize_buffers = [
			BufferBinding::read(raw.storage()),
			BufferBinding::write(output.storage()),
		];
		let normalize_push = [
			PushConstant::U32(shape.channels),
			PushConstant::U32(values_per_channel),
		];
		let dispatches = [
			ComputeDispatch {
				kernel: KernelId::AudioStftF32,
				buffers: &spectrum_buffers,
				push_constants: &spectrum_push,
				workgroups: [shape.frames, 1, shape.channels],
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::AudioMelFilterbankF32,
				buffers: &mel_buffers,
				push_constants: &mel_push,
				workgroups: [config.num_mels.div_ceil(32), shape.frames, shape.channels],
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::AudioMelNormalizeF32,
				buffers: &normalize_buffers,
				push_constants: &normalize_push,
				workgroups: [shape.channels, 1, 1],
				indirect: None,
			},
		];
		let outputs = [AudioSemanticOutput::Matrix(&output)];
		input.engine_handle().record_audio_split_semantic(
			&dispatches,
			AudioSemanticDispatch {
				contract: crate::core::operation::audio::MEL_SPECTROGRAM,
				inputs: &[AudioSemanticInput::Audio(input)],
				outputs: &outputs,
				attributes: &attributes,
			},
		)?;
		output
	} else {
		let output = Matrix::allocate(
			input.engine_handle(),
			vec![
				shape.channels as usize,
				config.num_mels as usize,
				shape.frames as usize,
			],
			output_elements as usize,
			DType::F32,
		)?;
		let mel_buffers = [
			BufferBinding::read(spectrum.storage()),
			BufferBinding::write(output.storage()),
			BufferBinding::read(filterbank.storage()),
		];
		let dispatches = [
			ComputeDispatch {
				kernel: KernelId::AudioStftF32,
				buffers: &spectrum_buffers,
				push_constants: &spectrum_push,
				workgroups: [shape.frames, 1, shape.channels],
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::AudioMelFilterbankF32,
				buffers: &mel_buffers,
				push_constants: &mel_push,
				workgroups: [config.num_mels.div_ceil(32), shape.frames, shape.channels],
				indirect: None,
			},
		];
		let outputs = [AudioSemanticOutput::Matrix(&output)];
		input.engine_handle().record_audio_split_semantic(
			&dispatches,
			AudioSemanticDispatch {
				contract: crate::core::operation::audio::MEL_SPECTROGRAM,
				inputs: &[AudioSemanticInput::Audio(input)],
				outputs: &outputs,
				attributes: &attributes,
			},
		)?;
		output
	};
	Ok(output)
}

/// Mel-frequency cepstral coefficient configuration.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MfccConfig {
	pub num_coeffs: u32,
	pub mel: MelConfig,
}

impl Default for MfccConfig {
	fn default() -> Self {
		Self {
			num_coeffs: 13,
			mel: MelConfig::default(),
		}
	}
}

/// Compute orthonormal DCT-II coefficients in `[channels, coefficients, frames]` layout.
pub fn mfcc(input: &Audio, config: MfccConfig) -> Result<Matrix> {
	if config.num_coeffs == 0 || config.num_coeffs > config.mel.num_mels {
		return Err(Error::invalid_argument(
			"audio::mfcc num_coeffs must be in [1, num_mels]",
		));
	}
	validate_mel(input, config.mel)?;
	let stft_config = StftConfig {
		fft_size: config.mel.fft_size,
		hop_size: config.mel.hop_size,
		win_size: config.mel.fft_size,
		..StftConfig::default()
	};
	let shape = validate_stft(input, stft_config)?;
	let elements = shape.channels * shape.frames * shape.freq_bins;
	let spectrum = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			shape.frames as usize,
			shape.freq_bins as usize,
		],
		elements as usize,
		DType::F32,
	)?;
	let filterbank = build_mel_filterbank(input, config.mel, shape.freq_bins)?;
	let mel_elements = shape
		.channels
		.checked_mul(config.mel.num_mels)
		.and_then(|value| value.checked_mul(shape.frames))
		.ok_or_else(|| Error::out_of_range("audio::mfcc mel workspace exceeds u32"))?;
	let mel = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			config.mel.num_mels as usize,
			shape.frames as usize,
		],
		mel_elements as usize,
		DType::F32,
	)?;
	let output_elements = shape
		.channels
		.checked_mul(config.num_coeffs)
		.and_then(|value| value.checked_mul(shape.frames))
		.ok_or_else(|| Error::out_of_range("audio::mfcc output exceeds u32"))?;
	let output = Matrix::allocate(
		input.engine_handle(),
		vec![
			shape.channels as usize,
			config.num_coeffs as usize,
			shape.frames as usize,
		],
		output_elements as usize,
		DType::F32,
	)?;
	let spectrum_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(spectrum.storage()),
	];
	let win_size = if stft_config.win_size == 0 {
		stft_config.fft_size
	} else {
		stft_config.win_size
	};
	let window: u32 = match stft_config.window {
		StftWindow::Hann => 0,
		StftWindow::Hamming => 1,
		StftWindow::Blackman => 2,
		StftWindow::Rectangular => 3,
	};
	let spectrum_push = [
		PushConstant::U32(stft_config.fft_size),
		PushConstant::U32(stft_config.hop_size),
		PushConstant::U32(win_size),
		PushConstant::U32(window),
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.samples),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(u32::from(stft_config.center)),
	];
	let mel_buffers = [
		BufferBinding::read(spectrum.storage()),
		BufferBinding::write(mel.storage()),
		BufferBinding::read(filterbank.storage()),
	];
	let mut mel_config = config.mel;
	mel_config.log_scale = true;
	mel_config.normalize = false;
	let mel_push = [
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.frames),
		PushConstant::U32(shape.freq_bins),
		PushConstant::U32(mel_config.num_mels),
		PushConstant::U32(u32::from(mel_config.log_scale)),
	];
	let dct_buffers = [
		BufferBinding::read(mel.storage()),
		BufferBinding::write(output.storage()),
	];
	let dct_push = [
		PushConstant::U32(shape.channels),
		PushConstant::U32(shape.frames),
		PushConstant::U32(config.mel.num_mels),
		PushConstant::U32(config.num_coeffs),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::AudioStftF32,
			buffers: &spectrum_buffers,
			push_constants: &spectrum_push,
			workgroups: [shape.frames, 1, shape.channels],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::AudioMelFilterbankF32,
			buffers: &mel_buffers,
			push_constants: &mel_push,
			workgroups: [
				mel_config.num_mels.div_ceil(32),
				shape.frames,
				shape.channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::AudioMfccDctF32,
			buffers: &dct_buffers,
			push_constants: &dct_push,
			workgroups: [config.num_coeffs.div_ceil(32), shape.frames, shape.channels],
			indirect: None,
		},
	];
	let attributes = [
		unsigned_attribute("numCoeffs", u64::from(config.num_coeffs)),
		unsigned_attribute("fftSize", u64::from(config.mel.fft_size)),
		unsigned_attribute("hopSize", u64::from(config.mel.hop_size)),
		unsigned_attribute("numMels", u64::from(config.mel.num_mels)),
		float_attribute("fMin", config.mel.f_min),
		float_attribute("fMax", config.mel.f_max),
		OpAttribute::Boolean {
			name: "logScale".into(),
			value: config.mel.log_scale,
		},
		OpAttribute::Boolean {
			name: "normalize".into(),
			value: config.mel.normalize,
		},
	];
	let outputs = [AudioSemanticOutput::Matrix(&output)];
	input.engine_handle().record_audio_split_semantic(
		&dispatches,
		AudioSemanticDispatch {
			contract: crate::core::operation::audio::MFCC,
			inputs: &[AudioSemanticInput::Audio(input)],
			outputs: &outputs,
			attributes: &attributes,
		},
	)?;
	Ok(output)
}