sora_sdk 2026.2.0

Sora Rust SDK
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
//! テストで共有するテスト用ヘルパー型。
//!
//! 本モジュールはテストビルド (`#[cfg(test)]`) でのみコンパイルされる。
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use shiguredo_webrtc::{
    AudioCodecInfo, AudioCodecSpec, AudioCodecType, AudioDecoder, AudioDecoderHandler,
    AudioEncoder, AudioEncoderEncodedInfo, AudioEncoderFactoryOptions, AudioEncoderHandler,
    AudioSpeechType, BufferRefMut, EnvironmentRef, RawBufferWriter, SdpAudioFormat,
    SdpAudioFormatRef, SdpVideoFormat, SdpVideoFormatRef, VideoCodecType, VideoDecoder,
    VideoDecoderHandler, VideoEncoder, VideoEncoderHandler,
};

use crate::audio_codec_capability::{AudioCodecCapability, AudioCodecImplementation};
use crate::codec_direction::CodecDirection;
use crate::video_codec_capability::{VideoCodecCapability, VideoCodecImplementation};

/// `VideoEncoderHandler` を最小限に実装したテスト専用の型。
pub(crate) struct NoopVideoEncoder;
impl VideoEncoderHandler for NoopVideoEncoder {}

/// `VideoDecoderHandler` を最小限に実装したテスト専用の型。
pub(crate) struct NoopVideoDecoder;
impl VideoDecoderHandler for NoopVideoDecoder {}

/// `VideoCodecCapability` を本物のコードで実装したテスト専用の型。
pub(crate) struct TestVideoCodecCapability {
    implementation: VideoCodecImplementation,
    encoder_formats: Vec<VideoCodecType>,
    decoder_formats: Vec<VideoCodecType>,
    /// false のときは `is_supported` が true でも `resolve_sdp_format` は None を返す。
    /// コーデック固有 parameter を必須とし、コーデック名だけの入力を拒否する capability を表す。
    resolves_sdp_format: bool,
}

impl TestVideoCodecCapability {
    /// 方向ごとのコーデック種別リストを指定して生成する。
    pub(crate) fn new(
        implementation: VideoCodecImplementation,
        encoder_formats: Vec<VideoCodecType>,
        decoder_formats: Vec<VideoCodecType>,
    ) -> Self {
        Self {
            implementation,
            encoder_formats,
            decoder_formats,
            resolves_sdp_format: true,
        }
    }

    /// `resolve_sdp_format` が常に None を返す capability に変換する。
    /// コーデック固有 parameter を必須としてコーデック名だけの入力を拒否する
    /// capability の挙動をシミュレートする。
    pub(crate) fn without_sdp_format_resolution(mut self) -> Self {
        self.resolves_sdp_format = false;
        self
    }

    /// 指定した方向のコーデック種別リストを返す。
    fn formats(&self, direction: CodecDirection) -> &[VideoCodecType] {
        match direction {
            CodecDirection::Encoder => &self.encoder_formats,
            CodecDirection::Decoder => &self.decoder_formats,
        }
    }
}

impl VideoCodecCapability for TestVideoCodecCapability {
    fn get_implementation(&self) -> VideoCodecImplementation {
        self.implementation.clone()
    }

    fn get_supported_formats(&self, direction: CodecDirection) -> Vec<SdpVideoFormat> {
        self.formats(direction)
            .iter()
            .filter_map(|codec_type| codec_type.as_str().map(SdpVideoFormat::new))
            .collect()
    }

    fn is_supported(&self, direction: CodecDirection, codec_type: VideoCodecType) -> bool {
        self.formats(direction).contains(&codec_type)
    }

    fn resolve_sdp_format(
        &self,
        direction: CodecDirection,
        format: SdpVideoFormatRef<'_>,
    ) -> Option<SdpVideoFormat> {
        if !self.resolves_sdp_format {
            return None;
        }
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| VideoCodecType::try_from(name.as_str()).ok())?;
        if !self.is_supported(direction, codec_type) {
            return None;
        }
        let codec_name = codec_type.as_str()?;
        let mut resolved = SdpVideoFormat::new(codec_name);
        if codec_type == VideoCodecType::H264 {
            resolved.parameters_mut().set("packetization-mode", "1");
        }
        Some(resolved)
    }

    fn create_video_encoder(
        &self,
        _env: EnvironmentRef<'_>,
        format: SdpVideoFormatRef<'_>,
    ) -> Option<VideoEncoder> {
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| VideoCodecType::try_from(name.as_str()).ok())?;
        if self.is_supported(CodecDirection::Encoder, codec_type) {
            Some(VideoEncoder::new_with_handler(Box::new(NoopVideoEncoder)))
        } else {
            None
        }
    }

    fn create_video_decoder(
        &self,
        _env: EnvironmentRef<'_>,
        format: SdpVideoFormatRef<'_>,
    ) -> Option<VideoDecoder> {
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| VideoCodecType::try_from(name.as_str()).ok())?;
        if self.is_supported(CodecDirection::Decoder, codec_type) {
            Some(VideoDecoder::new_with_handler(Box::new(NoopVideoDecoder)))
        } else {
            None
        }
    }
}

/// `AudioEncoderHandler` を実装したテスト専用の型。
///
/// `encode` は決まったバイト列 (`0x01, 0x02, 0x03`) をバッファへ追記し、
/// エンコード結果の整合 (追記バイト数 = encoded_bytes) を満たす。
pub(crate) struct TestAudioEncoder {
    payload_type: i32,
}

impl TestAudioEncoder {
    /// 指定したペイロードタイプを報告するエンコーダーを生成する。
    pub(crate) fn with_payload_type(payload_type: i32) -> Self {
        Self { payload_type }
    }
}

impl AudioEncoderHandler for TestAudioEncoder {
    fn sample_rate_hz(&mut self) -> i32 {
        48000
    }
    fn num_channels(&mut self) -> usize {
        2
    }
    fn num_10ms_frames_in_next_packet(&mut self) -> usize {
        1
    }
    fn max_10ms_frames_in_a_packet(&mut self) -> usize {
        1
    }
    fn get_target_bitrate(&mut self) -> i32 {
        32000
    }
    fn encode(
        &mut self,
        _rtp_timestamp: u32,
        _audio: &[i16],
        encoded: &mut BufferRefMut<'_>,
    ) -> AudioEncoderEncodedInfo {
        encoded.append_data(&[0x01, 0x02, 0x03]);
        let mut info = AudioEncoderEncodedInfo::new();
        info.set_encoded_bytes(encoded.size());
        info.set_payload_type(self.payload_type);
        info
    }
    fn reset(&mut self) {}
    fn get_frame_length_range(&mut self) -> Option<(i64, i64)> {
        None
    }
}

/// `AudioDecoderHandler` を実装したテスト専用の型。
///
/// `decode` は決まったサンプル列 (`0x1111` × 160) を書き込み、160 サンプルと Speech を返す。
pub(crate) struct TestAudioDecoder;
impl AudioDecoderHandler for TestAudioDecoder {
    fn sample_rate_hz(&mut self) -> i32 {
        48000
    }
    fn channels(&mut self) -> usize {
        2
    }
    fn decode(
        &mut self,
        _encoded: &[u8],
        _sample_rate_hz: i32,
        decoded: &mut RawBufferWriter<'_, i16>,
    ) -> (i32, AudioSpeechType) {
        // write は書き込み先の容量を超えないことを呼び出し側が保証する契約である。
        // このハンドラは 160 サンプルを書き込むため、呼び出し元は 160 サンプル以上の領域を渡す。
        unsafe {
            decoded.write(&[0x1111i16; 160]);
        }
        (160, AudioSpeechType::Speech)
    }
    fn reset(&mut self) {}
}

/// `TestAudioCodecCapability` が広告するテスト用のコーデック情報。
///
/// テストではビットレート等の実値に依存しないため、固定値を返す。
fn test_audio_codec_info() -> AudioCodecInfo {
    AudioCodecInfo::new(48000, 2, 32000, 6000, 510000)
}

/// `format` の持つコーデックパラメータを `BTreeMap` として収集する。
///
/// ネゴシエーションで決まったパラメータが `create_audio_encoder` まで素通しで届くことを
/// 検証するために用いる。
fn collect_audio_format_parameters(format: SdpAudioFormatRef<'_>) -> BTreeMap<String, String> {
    format.to_owned().parameters_mut().iter().collect()
}

/// `TestAudioCodecCapability` が受け取った値をテスト側から読み出すためのレコーダー。
///
/// capability は libwebrtc 側から呼ばれるため、受け取った値をテスト本体まで
/// 返す経路が必要になる。3 つのレコーダーをまとめて扱う。
#[derive(Clone)]
pub(crate) struct TestingAudioCodecRecorders {
    codec_pair_id: Arc<Mutex<Option<u64>>>,
    encoder_format_parameters: Arc<Mutex<Option<BTreeMap<String, String>>>>,
    decoder_format_parameters: Arc<Mutex<Option<BTreeMap<String, String>>>>,
}

impl TestingAudioCodecRecorders {
    /// 空のレコーダーを生成する。
    pub(crate) fn new() -> Self {
        Self {
            codec_pair_id: Arc::new(Mutex::new(None)),
            encoder_format_parameters: Arc::new(Mutex::new(None)),
            decoder_format_parameters: Arc::new(Mutex::new(None)),
        }
    }

    /// `create_audio_encoder` が最後に受け取ったコーデックペア ID を返す。
    pub(crate) fn codec_pair_id(&self) -> Option<u64> {
        *self
            .codec_pair_id
            .lock()
            .expect("codec_pair_id は poison しないはず")
    }

    /// `create_audio_encoder` が最後に受け取ったフォーマットのパラメータを返す。
    pub(crate) fn encoder_format_parameters(&self) -> BTreeMap<String, String> {
        self.encoder_format_parameters
            .lock()
            .expect("encoder_format_parameters は poison しないはず")
            .clone()
            .expect("create_audio_encoder が呼ばれたはずです")
    }

    /// `create_audio_decoder` が最後に受け取ったフォーマットのパラメータを返す。
    pub(crate) fn decoder_format_parameters(&self) -> BTreeMap<String, String> {
        self.decoder_format_parameters
            .lock()
            .expect("decoder_format_parameters は poison しないはず")
            .clone()
            .expect("create_audio_decoder が呼ばれたはずです")
    }
}

/// `AudioCodecCapability` を本物のコードで実装したテスト専用の型。
pub(crate) struct TestAudioCodecCapability {
    implementation: AudioCodecImplementation,
    encoder_formats: Vec<AudioCodecType>,
    decoder_formats: Vec<AudioCodecType>,
    /// `create_audio_encoder` が受け取った値の記録先。
    recorders: TestingAudioCodecRecorders,
}

impl TestAudioCodecCapability {
    /// 方向ごとのコーデック種別リストを指定して生成する。
    pub(crate) fn new(
        implementation: AudioCodecImplementation,
        encoder_formats: Vec<AudioCodecType>,
        decoder_formats: Vec<AudioCodecType>,
    ) -> Self {
        Self::new_with_recorders(
            implementation,
            encoder_formats,
            decoder_formats,
            TestingAudioCodecRecorders::new(),
        )
    }

    /// 記録先のレコーダーを指定して生成する。
    pub(crate) fn new_with_recorders(
        implementation: AudioCodecImplementation,
        encoder_formats: Vec<AudioCodecType>,
        decoder_formats: Vec<AudioCodecType>,
        recorders: TestingAudioCodecRecorders,
    ) -> Self {
        Self {
            implementation,
            encoder_formats,
            decoder_formats,
            recorders,
        }
    }

    /// 指定した方向のコーデック種別リストを返す。
    fn formats(&self, direction: CodecDirection) -> &[AudioCodecType] {
        match direction {
            CodecDirection::Encoder => &self.encoder_formats,
            CodecDirection::Decoder => &self.decoder_formats,
        }
    }
}

impl AudioCodecCapability for TestAudioCodecCapability {
    fn get_implementation(&self) -> AudioCodecImplementation {
        self.implementation.clone()
    }

    fn get_supported_codec_specs(&self, direction: CodecDirection) -> Vec<AudioCodecSpec> {
        self.formats(direction)
            .iter()
            .filter_map(|codec_type| {
                let name = codec_type.as_str()?;
                Some(AudioCodecSpec::new(
                    SdpAudioFormat::new(name, 48000, 2),
                    test_audio_codec_info(),
                ))
            })
            .collect()
    }

    fn is_supported(&self, direction: CodecDirection, codec_type: AudioCodecType) -> bool {
        self.formats(direction).contains(&codec_type)
    }

    fn query(
        &self,
        direction: CodecDirection,
        format: SdpAudioFormatRef<'_>,
    ) -> Option<AudioCodecInfo> {
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| AudioCodecType::try_from(name.as_str()).ok())?;
        if self.is_supported(direction, codec_type) {
            Some(test_audio_codec_info())
        } else {
            None
        }
    }

    fn create_audio_encoder(
        &self,
        _env: EnvironmentRef<'_>,
        format: SdpAudioFormatRef<'_>,
        options: &AudioEncoderFactoryOptions,
    ) -> Option<AudioEncoder> {
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| AudioCodecType::try_from(name.as_str()).ok())?;
        if self.is_supported(CodecDirection::Encoder, codec_type) {
            *self
                .recorders
                .codec_pair_id
                .lock()
                .expect("codec_pair_id は poison しないはず") = options
                .codec_pair_id()
                .map(|id| id.numeric_representation());
            *self
                .recorders
                .encoder_format_parameters
                .lock()
                .expect("encoder_format_parameters は poison しないはず") =
                Some(collect_audio_format_parameters(format));
            Some(AudioEncoder::new_with_handler(Box::new(
                TestAudioEncoder::with_payload_type(options.payload_type()),
            )))
        } else {
            None
        }
    }

    fn create_audio_decoder(
        &self,
        _env: EnvironmentRef<'_>,
        format: SdpAudioFormatRef<'_>,
    ) -> Option<AudioDecoder> {
        let codec_type = format
            .name()
            .ok()
            .and_then(|name| AudioCodecType::try_from(name.as_str()).ok())?;
        if self.is_supported(CodecDirection::Decoder, codec_type) {
            *self
                .recorders
                .decoder_format_parameters
                .lock()
                .expect("decoder_format_parameters は poison しないはず") =
                Some(collect_audio_format_parameters(format));
            Some(AudioDecoder::new_with_handler(Box::new(TestAudioDecoder)))
        } else {
            None
        }
    }
}

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

    #[test]
    fn capability_methods_share_the_same_format_list() {
        let capability = TestVideoCodecCapability::new(
            VideoCodecImplementation::new("test", "Test Codec"),
            vec![VideoCodecType::Vp9, VideoCodecType::H264],
            Vec::new(),
        );
        // 公開フォーマットのリストが is_supported / resolve_sdp_format /
        // create_video_encoder にも効くことを確認する。
        assert!(
            capability.is_supported(CodecDirection::Encoder, VideoCodecType::Vp9),
            "公開フォーマットに含まれる VP9 は is_supported で true になるべきです"
        );
        let vp9 = SdpVideoFormat::new("VP9");
        assert!(
            capability
                .resolve_sdp_format(CodecDirection::Encoder, vp9.as_ref())
                .is_some(),
            "公開フォーマットに含まれる VP9 は resolve_sdp_format で解決できるべきです"
        );
        assert!(
            capability
                .create_video_encoder(shiguredo_webrtc::Environment::new().as_ref(), vp9.as_ref())
                .is_some(),
            "公開フォーマットに含まれる VP9 はエンコーダーを生成できるべきです"
        );
    }
}