voirs-sdk 0.1.0-rc.1

Unified SDK and public API for VoiRS speech synthesis
Documentation
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
//! Format plugins for audio encoding, streaming, and protocol support
//!
//! This module provides various format plugins for handling different audio
//! formats, codec integration, streaming protocols, and network formats.

use crate::{audio::AudioBuffer, error::Result, plugins::VoirsPlugin, VoirsError};
use async_trait::async_trait;
use parking_lot::RwLock;
use std::collections::HashMap;

/// Trait for format plugins that handle audio encoding/decoding
#[async_trait]
pub trait FormatPlugin: VoirsPlugin {
    /// Encode audio buffer to format-specific data
    async fn encode(&self, audio: &AudioBuffer) -> Result<Vec<u8>>;

    /// Decode format-specific data to audio buffer
    async fn decode(&self, data: &[u8]) -> Result<AudioBuffer>;

    /// Get format-specific metadata
    fn get_metadata(&self) -> HashMap<String, String>;

    /// Validate format-specific data
    fn validate_data(&self, data: &[u8]) -> bool;
}

/// Custom VoiRS audio format plugin
pub struct VoirsFormat {
    /// Compression level (0-9)
    pub compression_level: RwLock<u32>,

    /// Include metadata in format
    pub include_metadata: RwLock<bool>,

    /// Error correction level
    pub error_correction: RwLock<f32>,

    /// Format version
    pub format_version: RwLock<u32>,
}

impl VoirsFormat {
    pub fn new() -> Self {
        Self {
            compression_level: RwLock::new(5),
            include_metadata: RwLock::new(true),
            error_correction: RwLock::new(0.1),
            format_version: RwLock::new(1),
        }
    }

    /// Simple custom format: [header][metadata][compressed_audio]
    fn create_voirs_format(&self, audio: &AudioBuffer) -> Vec<u8> {
        let mut data = Vec::new();

        // Header: "VOIRS" + version + sample_rate + channels + length
        data.extend_from_slice(b"VOIRS");
        data.extend_from_slice(&(*self.format_version.read()).to_le_bytes());
        data.extend_from_slice(&audio.sample_rate().to_le_bytes());
        data.extend_from_slice(&audio.channels().to_le_bytes());
        data.extend_from_slice(&(audio.samples().len() as u32).to_le_bytes());

        // Metadata section
        if *self.include_metadata.read() {
            let metadata = format!("VoiRS Audio Format v{}", *self.format_version.read());
            let metadata_bytes = metadata.as_bytes();
            data.extend_from_slice(&(metadata_bytes.len() as u32).to_le_bytes());
            data.extend_from_slice(metadata_bytes);
        } else {
            data.extend_from_slice(&0u32.to_le_bytes()); // No metadata
        }

        // Simple compression: quantize based on compression level
        let compression = *self.compression_level.read() as f32 / 9.0;
        let quantization_factor = 1.0 + compression * 15.0; // 1x to 16x quantization

        for &sample in audio.samples() {
            let quantized = (sample * quantization_factor).round() / quantization_factor;
            let quantized_bytes = quantized.to_le_bytes();
            data.extend_from_slice(&quantized_bytes);
        }

        data
    }

    /// Parse VoiRS format data
    fn parse_voirs_format(&self, data: &[u8]) -> Result<AudioBuffer> {
        if data.len() < 25 {
            // Minimum header size
            return Err(VoirsError::internal(
                "format",
                "Invalid VoiRS format: too small",
            ));
        }

        let mut offset = 0;

        // Check header
        if &data[0..5] != b"VOIRS" {
            return Err(VoirsError::internal(
                "format",
                "Invalid VoiRS format: bad header",
            ));
        }
        offset += 5;

        // Read format info
        let _version = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;
        let sample_rate = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;
        let channels = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;
        let sample_count = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        // Skip metadata
        let metadata_len = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4 + metadata_len as usize;

        // Read samples
        let mut samples = Vec::with_capacity(sample_count as usize);
        for _ in 0..sample_count {
            if offset + 4 > data.len() {
                return Err(VoirsError::internal(
                    "format",
                    "Invalid VoiRS format: truncated",
                ));
            }
            let sample = f32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]);
            samples.push(sample);
            offset += 4;
        }

        Ok(AudioBuffer::new(samples, sample_rate, channels))
    }
}

impl Default for VoirsFormat {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for VoirsFormat {
    fn name(&self) -> &str {
        "VoiRS Format"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Custom VoiRS audio format with compression and metadata"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl FormatPlugin for VoirsFormat {
    async fn encode(&self, audio: &AudioBuffer) -> Result<Vec<u8>> {
        Ok(self.create_voirs_format(audio))
    }

    async fn decode(&self, data: &[u8]) -> Result<AudioBuffer> {
        self.parse_voirs_format(data)
    }

    fn get_metadata(&self) -> HashMap<String, String> {
        let mut metadata = HashMap::new();
        metadata.insert("format".to_string(), "VoiRS".to_string());
        metadata.insert(
            "version".to_string(),
            self.format_version.read().to_string(),
        );
        metadata.insert(
            "compression".to_string(),
            self.compression_level.read().to_string(),
        );
        metadata
    }

    fn validate_data(&self, data: &[u8]) -> bool {
        data.len() >= 25 && &data[0..5] == b"VOIRS"
    }
}

/// Codec integration plugin for standard formats
pub struct CodecIntegration {
    /// Target codec type
    pub codec_type: RwLock<String>,

    /// Bitrate for lossy codecs (kbps)
    pub bitrate: RwLock<u32>,

    /// Quality setting (0.0 - 1.0)
    pub quality: RwLock<f32>,

    /// Variable bitrate mode
    pub variable_bitrate: RwLock<bool>,
}

impl CodecIntegration {
    pub fn new() -> Self {
        Self {
            codec_type: RwLock::new("PCM".to_string()),
            bitrate: RwLock::new(128),
            quality: RwLock::new(0.8),
            variable_bitrate: RwLock::new(false),
        }
    }

    /// Simulate codec encoding
    fn encode_with_codec(&self, audio: &AudioBuffer) -> Vec<u8> {
        let codec = self.codec_type.read().clone();
        let quality = *self.quality.read();

        match codec.as_str() {
            "PCM" => {
                // Uncompressed PCM
                let mut data = Vec::new();
                for &sample in audio.samples() {
                    data.extend_from_slice(&sample.to_le_bytes());
                }
                data
            }
            "MP3" => {
                // Simulate MP3 compression
                let compression_ratio = 1.0 - quality * 0.8; // Higher quality = less compression
                let mut data = Vec::new();
                data.extend_from_slice(b"MP3_SIM");
                for &sample in audio.samples() {
                    let compressed = sample * compression_ratio;
                    data.extend_from_slice(&compressed.to_le_bytes());
                }
                data
            }
            "OGG" => {
                // Simulate OGG Vorbis compression
                let compression_ratio = 1.0 - quality * 0.7;
                let mut data = Vec::new();
                data.extend_from_slice(b"OGG_SIM");
                for &sample in audio.samples() {
                    let compressed = sample * compression_ratio;
                    data.extend_from_slice(&compressed.to_le_bytes());
                }
                data
            }
            _ => {
                // Default to PCM
                let mut data = Vec::new();
                for &sample in audio.samples() {
                    data.extend_from_slice(&sample.to_le_bytes());
                }
                data
            }
        }
    }

    /// Simulate codec decoding
    fn decode_with_codec(&self, data: &[u8]) -> Result<AudioBuffer> {
        // Detect format
        if data.len() < 8 {
            return Err(VoirsError::internal("codec", "Invalid codec data"));
        }

        let (_header, audio_data) = if data.starts_with(b"MP3_SIM") || data.starts_with(b"OGG_SIM")
        {
            (7, &data[7..])
        } else {
            (0, data) // PCM
        };

        // Decode samples
        let mut samples = Vec::new();
        for chunk in audio_data.chunks_exact(4) {
            let sample = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
            samples.push(sample);
        }

        Ok(AudioBuffer::new(samples, 44100, 1)) // Default format
    }
}

impl Default for CodecIntegration {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for CodecIntegration {
    fn name(&self) -> &str {
        "Codec Integration"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Integration with standard audio codecs (MP3, OGG, FLAC, etc.)"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl FormatPlugin for CodecIntegration {
    async fn encode(&self, audio: &AudioBuffer) -> Result<Vec<u8>> {
        Ok(self.encode_with_codec(audio))
    }

    async fn decode(&self, data: &[u8]) -> Result<AudioBuffer> {
        self.decode_with_codec(data)
    }

    fn get_metadata(&self) -> HashMap<String, String> {
        let mut metadata = HashMap::new();
        metadata.insert("codec".to_string(), self.codec_type.read().clone());
        metadata.insert("bitrate".to_string(), self.bitrate.read().to_string());
        metadata.insert("quality".to_string(), self.quality.read().to_string());
        metadata
    }

    fn validate_data(&self, data: &[u8]) -> bool {
        data.len() >= 4
            && (data.len().is_multiple_of(4)
                || data.starts_with(b"MP3_SIM")
                || data.starts_with(b"OGG_SIM"))
    }
}

/// Streaming protocol plugin for real-time audio streaming
pub struct StreamingProtocol {
    /// Protocol type (RTP, WebRTC, etc.)
    pub protocol_type: RwLock<String>,

    /// Buffer size for streaming
    pub buffer_size: RwLock<u32>,

    /// Latency target in milliseconds
    pub target_latency: RwLock<u32>,

    /// Adaptive bitrate enabled
    pub adaptive_bitrate: RwLock<bool>,

    /// Packet loss compensation
    pub loss_compensation: RwLock<f32>,
}

impl StreamingProtocol {
    pub fn new() -> Self {
        Self {
            protocol_type: RwLock::new("RTP".to_string()),
            buffer_size: RwLock::new(1024),
            target_latency: RwLock::new(50),
            adaptive_bitrate: RwLock::new(true),
            loss_compensation: RwLock::new(0.1),
        }
    }

    /// Create streaming packets
    #[allow(dead_code)]
    fn create_stream_packets(&self, audio: &AudioBuffer) -> Vec<Vec<u8>> {
        let buffer_size = *self.buffer_size.read() as usize;
        let protocol = self.protocol_type.read().clone();
        let mut packets = Vec::new();

        for chunk in audio.samples().chunks(buffer_size) {
            let mut packet = Vec::new();

            // Add protocol header
            match protocol.as_str() {
                "RTP" => {
                    packet.extend_from_slice(b"RTP");
                    packet.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
                }
                "WebRTC" => {
                    packet.extend_from_slice(b"WEBRTC");
                    packet.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
                }
                _ => {
                    packet.extend_from_slice(b"STREAM");
                    packet.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
                }
            }

            // Add audio data
            for &sample in chunk {
                packet.extend_from_slice(&sample.to_le_bytes());
            }

            packets.push(packet);
        }

        packets
    }

    /// Reconstruct audio from stream packets
    #[allow(dead_code)]
    fn reconstruct_from_packets(&self, packets: &[Vec<u8>]) -> Result<AudioBuffer> {
        let mut samples = Vec::new();

        for packet in packets {
            if packet.len() < 7 {
                continue; // Skip invalid packets
            }

            let (header_size, data_start) = if packet.starts_with(b"RTP") {
                (7, 7)
            } else if packet.starts_with(b"WEBRTC") || packet.starts_with(b"STREAM") {
                (10, 10)
            } else {
                continue; // Unknown packet format
            };

            let sample_count = u32::from_le_bytes([
                packet[header_size - 4],
                packet[header_size - 3],
                packet[header_size - 2],
                packet[header_size - 1],
            ]) as usize;

            for i in 0..sample_count {
                let offset = data_start + i * 4;
                if offset + 4 <= packet.len() {
                    let sample = f32::from_le_bytes([
                        packet[offset],
                        packet[offset + 1],
                        packet[offset + 2],
                        packet[offset + 3],
                    ]);
                    samples.push(sample);
                }
            }
        }

        Ok(AudioBuffer::new(samples, 44100, 1))
    }
}

impl Default for StreamingProtocol {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for StreamingProtocol {
    fn name(&self) -> &str {
        "Streaming Protocol"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Real-time audio streaming with RTP, WebRTC, and custom protocols"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Network format plugin for distributed audio processing
pub struct NetworkFormat {
    /// Network compression enabled
    pub compression_enabled: RwLock<bool>,

    /// Encryption level (0-3)
    pub encryption_level: RwLock<u32>,

    /// Checksum verification
    pub checksum_enabled: RwLock<bool>,

    /// Fragment size for large transfers
    pub fragment_size: RwLock<u32>,
}

impl NetworkFormat {
    pub fn new() -> Self {
        Self {
            compression_enabled: RwLock::new(true),
            encryption_level: RwLock::new(1),
            checksum_enabled: RwLock::new(true),
            fragment_size: RwLock::new(8192),
        }
    }

    /// Create network-optimized format
    fn create_network_format(&self, audio: &AudioBuffer) -> Vec<u8> {
        let mut data = Vec::new();

        // Network header
        data.extend_from_slice(b"VOINET");
        data.extend_from_slice(&audio.sample_rate().to_le_bytes());
        data.extend_from_slice(&audio.channels().to_le_bytes());

        // Flags
        let mut flags = 0u8;
        if *self.compression_enabled.read() {
            flags |= 0x01;
        }
        if *self.checksum_enabled.read() {
            flags |= 0x02;
        }
        flags |= (*self.encryption_level.read() as u8) << 2;
        data.push(flags);

        // Audio data with optional compression
        let audio_data: Vec<u8> = if *self.compression_enabled.read() {
            // Simple compression: delta encoding
            let mut compressed = Vec::new();
            let mut prev_sample = 0.0f32;
            for &sample in audio.samples() {
                let delta = sample - prev_sample;
                compressed.extend_from_slice(&delta.to_le_bytes());
                prev_sample = sample;
            }
            compressed
        } else {
            // Uncompressed
            let mut uncompressed = Vec::new();
            for &sample in audio.samples() {
                uncompressed.extend_from_slice(&sample.to_le_bytes());
            }
            uncompressed
        };

        // Add data size
        data.extend_from_slice(&(audio_data.len() as u32).to_le_bytes());

        // Add audio data
        data.extend_from_slice(&audio_data);

        // Add checksum if enabled
        if *self.checksum_enabled.read() {
            let checksum = audio_data
                .iter()
                .fold(0u32, |acc, &b| acc.wrapping_add(b as u32));
            data.extend_from_slice(&checksum.to_le_bytes());
        }

        data
    }

    /// Parse network format
    fn parse_network_format(&self, data: &[u8]) -> Result<AudioBuffer> {
        if data.len() < 15 {
            return Err(VoirsError::internal("network", "Invalid network format"));
        }

        if &data[0..6] != b"VOINET" {
            return Err(VoirsError::internal(
                "network",
                "Invalid network format header",
            ));
        }

        let mut offset = 6;
        let sample_rate = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;
        let channels = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let flags = data[offset];
        offset += 1;
        let compression_enabled = (flags & 0x01) != 0;
        let checksum_enabled = (flags & 0x02) != 0;

        let data_size = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        if offset + data_size as usize > data.len() {
            return Err(VoirsError::internal("network", "Truncated network format"));
        }

        let audio_data = &data[offset..offset + data_size as usize];
        offset += data_size as usize;

        // Verify checksum if enabled
        if checksum_enabled {
            if offset + 4 > data.len() {
                return Err(VoirsError::internal("network", "Missing checksum"));
            }
            let expected_checksum = u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]);
            let actual_checksum = audio_data
                .iter()
                .fold(0u32, |acc, &b| acc.wrapping_add(b as u32));
            if expected_checksum != actual_checksum {
                return Err(VoirsError::internal("network", "Checksum mismatch"));
            }
        }

        // Decode audio data
        let samples = if compression_enabled {
            // Delta decoding
            let mut samples = Vec::new();
            let mut current_sample = 0.0f32;
            for chunk in audio_data.chunks_exact(4) {
                let delta = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                current_sample += delta;
                samples.push(current_sample);
            }
            samples
        } else {
            // Direct decoding
            let mut samples = Vec::new();
            for chunk in audio_data.chunks_exact(4) {
                let sample = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                samples.push(sample);
            }
            samples
        };

        Ok(AudioBuffer::new(samples, sample_rate, channels))
    }
}

impl Default for NetworkFormat {
    fn default() -> Self {
        Self::new()
    }
}

impl VoirsPlugin for NetworkFormat {
    fn name(&self) -> &str {
        "Network Format"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn description(&self) -> &str {
        "Network-optimized format with compression and error checking"
    }

    fn author(&self) -> &str {
        "VoiRS Team"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl FormatPlugin for NetworkFormat {
    async fn encode(&self, audio: &AudioBuffer) -> Result<Vec<u8>> {
        Ok(self.create_network_format(audio))
    }

    async fn decode(&self, data: &[u8]) -> Result<AudioBuffer> {
        self.parse_network_format(data)
    }

    fn get_metadata(&self) -> HashMap<String, String> {
        let mut metadata = HashMap::new();
        metadata.insert(
            "compression".to_string(),
            self.compression_enabled.read().to_string(),
        );
        metadata.insert(
            "encryption".to_string(),
            self.encryption_level.read().to_string(),
        );
        metadata.insert(
            "checksum".to_string(),
            self.checksum_enabled.read().to_string(),
        );
        metadata
    }

    fn validate_data(&self, data: &[u8]) -> bool {
        data.len() >= 15 && &data[0..6] == b"VOINET"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_voirs_format() {
        let format = VoirsFormat::new();
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.5, 44100, 0.5);

        // Test encoding
        let encoded = format.encode(&audio).await.unwrap();
        assert!(!encoded.is_empty());
        assert!(format.validate_data(&encoded));

        // Test decoding
        let decoded = format.decode(&encoded).await.unwrap();
        assert_eq!(decoded.sample_rate(), audio.sample_rate());
        assert_eq!(decoded.channels(), audio.channels());
    }

    #[tokio::test]
    async fn test_codec_integration() {
        let codec = CodecIntegration::new();
        let audio = crate::AudioBuffer::sine_wave(1000.0, 0.3, 22050, 0.7);

        // Test PCM encoding/decoding
        let encoded = codec.encode(&audio).await.unwrap();
        let decoded = codec.decode(&encoded).await.unwrap();
        assert_eq!(decoded.len(), audio.len());

        // Test metadata
        let metadata = codec.get_metadata();
        assert!(metadata.contains_key("codec"));
    }

    #[tokio::test]
    async fn test_streaming_protocol() {
        let stream = StreamingProtocol::new();
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.1, 44100, 0.5);

        // Test packet creation
        let packets = stream.create_stream_packets(&audio);
        assert!(!packets.is_empty());

        // Test reconstruction
        let reconstructed = stream.reconstruct_from_packets(&packets).unwrap();
        assert!(!reconstructed.is_empty());
    }

    #[tokio::test]
    async fn test_network_format() {
        let network = NetworkFormat::new();
        let audio = crate::AudioBuffer::sine_wave(440.0, 0.2, 48000, 0.8);

        // Test encoding
        let encoded = network.encode(&audio).await.unwrap();
        assert!(!encoded.is_empty());
        assert!(network.validate_data(&encoded));

        // Test decoding
        let decoded = network.decode(&encoded).await.unwrap();
        assert_eq!(decoded.sample_rate(), audio.sample_rate());
        assert_eq!(decoded.channels(), audio.channels());

        // Test metadata
        let metadata = network.get_metadata();
        assert!(metadata.contains_key("compression"));
        assert!(metadata.contains_key("checksum"));
    }

    #[test]
    fn test_format_plugin_metadata() {
        let voirs_format = VoirsFormat::new();
        assert_eq!(voirs_format.name(), "VoiRS Format");
        assert_eq!(voirs_format.version(), "1.0.0");
        assert_eq!(voirs_format.author(), "VoiRS Team");

        let codec = CodecIntegration::new();
        assert_eq!(codec.name(), "Codec Integration");

        let network = NetworkFormat::new();
        assert_eq!(network.name(), "Network Format");
    }
}