gst-plugin-threadshare 0.15.2

GStreamer Threadshare Plugin
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
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// <https://mozilla.org/MPL/2.0/>.
//
// SPDX-License-Identifier: MPL-2.0

// use futures::channel::oneshot;
use futures::prelude::*;
use gst::prelude::*;

use std::sync::{Arc, Mutex};
use std::time::Duration;

use gstthreadshare::runtime;

fn init() {
    use std::sync::Once;
    static INIT: Once = Once::new();

    INIT.call_once(|| {
        gst::init().unwrap();
        gstthreadshare::plugin_register_static().expect("gstthreadshare inter test");
    });
}

#[test]
fn nominal() {
    init();

    let pipe = gst::Pipeline::with_name("rtpdtmfsrc::nominal");
    // let src = gst::ElementFactory::make("rtpdtmfsrc")
    let src = gst::ElementFactory::make("ts-rtpdtmfsrc")
        .property("context", "rtpdtmfsrc::nominal")
        .property("context-wait", 20u32)
        .name("src::rtpdtmfsrc::nominal")
        .build()
        .unwrap();
    let mux = gst::ElementFactory::make("rtpdtmfmux").build().unwrap();
    let appsink = gst_app::AppSink::builder()
        .name("appsink::rtpdtmfsrc::nominal")
        .caps(
            &gst::Caps::builder("application/x-rtp")
                .field("media", "audio")
                .field("clock-rate", gst::List::new([8_000, 16_000]))
                .field("encoding-name", "TELEPHONE-EVENT")
                .build(),
        )
        .build();

    let elems = [&src, &mux, appsink.upcast_ref::<gst::Element>()];
    pipe.add_many(elems).unwrap();
    gst::Element::link_many(elems).unwrap();

    // Steps
    const INIT: u32 = 0;
    const SEND_EARLY_END: u32 = 1;
    const SEND_START_4: u32 = 2;
    const START_4_SENT: u32 = 3;
    const START_4_MSG_RECEIVED: u32 = 4;
    const START_4_BUFFER_RECEIVED: u32 = 5;
    const START_4_MSG_AND_BUFFER_RECEIVED: u32 = 6;
    // time interval before end
    const SEND_4_END: u32 = 9;
    const END_4_SENT: u32 = 10;
    const END_4_MSG_RECEIVED: u32 = 11;
    const END_4_BUFFER_RECEIVED: u32 = 12;
    const END_4_MSG_AND_BUFFER_RECEIVED: u32 = 13;

    const SEND_START_2: u32 = 20;
    const START_2_SENT: u32 = 21;
    const START_2_MSG_RECEIVED: u32 = 22;
    const START_2_BUFFER_RECEIVED: u32 = 23;
    const START_2_MSG_AND_BUFFER_RECEIVED: u32 = 24;
    // time interval before end
    const SEND_2_END: u32 = 27;
    const END_2_SENT: u32 = 28;
    const END_2_MSG_RECEIVED: u32 = 29;
    const END_2_BUFFER_RECEIVED: u32 = 30;
    const END_2_MSG_AND_BUFFER_RECEIVED: u32 = 31;

    const VALID_EVENT_4_DIGIT: u8 = 4;
    const VALID_EVENT_4_VOLUME: u8 = 12;
    const VALID_EVENT_2_DIGIT: u8 = 2;
    const VALID_EVENT_2_VOLUME: u8 = 18;

    const PAYLOAD_DIGIT_BYTE_INDEX: usize = 12;
    const PAYLOAD_END_VOLUME_BYTE_INDEX: usize = 13;
    const PAYLOAD_END_MASK: u8 = 0x80;
    const PAYLOAD_DURATION_BIG_BYTE_INDEX: usize = 14;
    const PAYLOAD_DURATION_SMALL_BYTE_INDEX: usize = 15;
    const PAYLOAD_DURATION_INCREMENT: u16 = 40 * 8; // 40ms @ 8kHZ

    const BUFFER_DURATION: gst::ClockTime = gst::ClockTime::from_mseconds(40);
    const BUFFER_DURATION_END: gst::ClockTime = gst::ClockTime::from_mseconds(40 * 4);

    let step = Arc::new(Mutex::new(INIT));
    appsink.set_callbacks(
        gst_app::AppSinkCallbacks::builder()
            .new_sample({
                let step = step.clone();
                let mut buffer_idx = 0;
                move |appsink| {
                    let sample = appsink.pull_sample().unwrap();
                    let buffer = sample.buffer().unwrap();
                    let buf = buffer.map_readable().unwrap();
                    let duration = (buf[PAYLOAD_DURATION_BIG_BYTE_INDEX] as u16) << 8
                        | buf[PAYLOAD_DURATION_SMALL_BYTE_INDEX] as u16;
                    let mut step = step.lock().unwrap();

                    let details = |buffer_idx| {
                        format!(
                            "idx {buffer_idx} ts {} @ step {step:02} DTMF payload: {:02x} {:02x} {:02x} {:02x}",
                            buffer.pts().display(),
                            buf[PAYLOAD_DIGIT_BYTE_INDEX],
                            buf[PAYLOAD_END_VOLUME_BYTE_INDEX],
                            buf[PAYLOAD_DURATION_BIG_BYTE_INDEX],
                            buf[PAYLOAD_DURATION_SMALL_BYTE_INDEX],
                        )
                    };

                    match *step {
                        START_4_SENT | START_4_MSG_RECEIVED => {
                            assert_eq!(buf[PAYLOAD_DIGIT_BYTE_INDEX], VALID_EVENT_4_DIGIT);
                            assert_eq!(buf[PAYLOAD_END_VOLUME_BYTE_INDEX], VALID_EVENT_4_VOLUME);
                            assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                            assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);
                            println!(
                                "rtpdtmfsrc::nominal start buffer received {}",
                                details(buffer_idx)
                            );

                            buffer_idx += 1;
                            *step = if *step == START_4_SENT {
                                START_4_BUFFER_RECEIVED
                            } else {
                                START_4_MSG_AND_BUFFER_RECEIVED
                            };
                        }
                        START_4_BUFFER_RECEIVED..END_4_SENT => {
                            assert_eq!(buf[PAYLOAD_DIGIT_BYTE_INDEX], VALID_EVENT_4_DIGIT);
                            assert_eq!(buf[PAYLOAD_END_VOLUME_BYTE_INDEX], VALID_EVENT_4_VOLUME);
                            assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                            assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);
                            println!(
                                "rtpdtmfsrc::nominal intermediate buffer received {}",
                                details(buffer_idx)
                            );

                            buffer_idx += 1;
                        }
                        END_4_SENT | END_4_MSG_RECEIVED => {
                            if buf[PAYLOAD_END_VOLUME_BYTE_INDEX] & PAYLOAD_END_MASK != 0 {
                                println!(
                                    "rtpdtmfsrc::nominal end buffer received {}",
                                    details(buffer_idx)
                                );
                                assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION_END);
                                assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);

                                buffer_idx += 1;
                                *step = if *step == END_4_SENT {
                                    END_4_BUFFER_RECEIVED
                                } else {
                                    END_4_MSG_AND_BUFFER_RECEIVED
                                };
                            } else {
                                println!(
                                    "rtpdtmfsrc::nominal late intermediate buffer received {}",
                                    details(buffer_idx)
                                );
                                assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                                assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);

                                buffer_idx += 1;
                            }
                        }
                        START_2_SENT | START_2_MSG_RECEIVED => {
                            // New digit
                            buffer_idx = 0;

                            assert_eq!(buf[PAYLOAD_DIGIT_BYTE_INDEX], VALID_EVENT_2_DIGIT);
                            assert_eq!(buf[PAYLOAD_END_VOLUME_BYTE_INDEX], VALID_EVENT_2_VOLUME);
                            assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                            assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);
                            println!(
                                "rtpdtmfsrc::nominal start buffer received {}",
                                details(buffer_idx)
                            );

                            buffer_idx += 1;
                            *step = if *step == START_2_SENT {
                                START_2_BUFFER_RECEIVED
                            } else {
                                START_2_MSG_AND_BUFFER_RECEIVED
                            };
                        }
                        START_2_SENT..END_2_SENT => {
                            assert_eq!(buf[PAYLOAD_DIGIT_BYTE_INDEX], VALID_EVENT_2_DIGIT);
                            assert_eq!(buf[PAYLOAD_END_VOLUME_BYTE_INDEX], VALID_EVENT_2_VOLUME);
                            assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                            assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);
                            println!(
                                "rtpdtmfsrc::nominal intermediate buffer received {}",
                                details(buffer_idx)
                            );

                            buffer_idx += 1;
                        }
                        END_2_SENT | END_2_MSG_RECEIVED => {
                            if buf[PAYLOAD_END_VOLUME_BYTE_INDEX] & PAYLOAD_END_MASK != 0 {
                                println!(
                                    "rtpdtmfsrc::nominal end buffer received {}",
                                    details(buffer_idx)
                                );
                                assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION_END);
                                assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);

                                buffer_idx += 1;
                                *step = if *step == END_2_SENT {
                                    END_2_BUFFER_RECEIVED
                                } else {
                                    END_2_MSG_AND_BUFFER_RECEIVED
                                };
                            } else {
                                println!(
                                    "rtpdtmfsrc::nominal late intermediate buffer received {}",
                                    details(buffer_idx)
                                );
                                assert_eq!(buffer.duration().unwrap(), BUFFER_DURATION);
                                assert_eq!(duration, (buffer_idx + 1) * PAYLOAD_DURATION_INCREMENT);

                                buffer_idx += 1;
                            }
                        }
                        _ => panic!(
                            "rtpdtmfsrc::nominal unexpected received buffer {}",
                            details(buffer_idx)
                        ),
                    }

                    Ok(gst::FlowSuccess::Ok)
                }
            })
            .build(),
    );

    pipe.set_state(gst::State::Playing).unwrap();

    runtime::executor::block_on({
        fn new_dtmf_start_event(number: u8, volume: u8) -> gst::Event {
            gst::event::CustomUpstream::builder(
                gst::Structure::builder("dtmf-event")
                    .field("type", 1i32)
                    .field("method", 1i32)
                    .field("start", true)
                    .field("number", number as i32)
                    .field("volume", volume as i32)
                    .build(),
            )
            .build()
        }

        fn new_dtmf_end_event() -> gst::Event {
            gst::event::CustomUpstream::builder(
                gst::Structure::builder("dtmf-event")
                    .field("type", 1i32)
                    .field("method", 1i32)
                    .field("start", false)
                    .build(),
            )
            .build()
        }

        let pipe = pipe.clone();
        let src = src.clone();
        let appsink = appsink.upcast::<gst::Element>();
        async move {
            use gst::MessageView::*;

            let mut timer = runtime::timer::interval(Duration::from_millis(30)).unwrap();
            let mut bus_stream = pipe.bus().unwrap().stream();

            loop {
                futures::select! {
                    _ = timer.next() => {
                        let mut step = step.lock().unwrap();
                        match *step {
                            INIT => {
                                *step = SEND_EARLY_END;
                            }
                            SEND_EARLY_END => {
                                println!("rtpdtmfsrc::nominal sending early end");
                                if appsink.send_event(new_dtmf_end_event()) {
                                    panic!("Shouldn't be able to send initial end dtmf-event");
                                }
                                *step = SEND_START_4;
                            }
                            SEND_START_4 => {
                                println!("rtpdtmfsrc::nominal sending start 4");
                                if !appsink.send_event(new_dtmf_start_event(VALID_EVENT_4_DIGIT, VALID_EVENT_4_VOLUME)) {
                                    panic!("Failed to send start dtmf-event {step}");
                                }
                                *step = START_4_SENT;
                            }
                            START_4_MSG_AND_BUFFER_RECEIVED..SEND_4_END => {
                                // give a little time interval
                                *step += 1;
                            }
                            SEND_4_END => {
                                println!("rtpdtmfsrc::nominal sending end 4");
                                if !appsink.send_event(new_dtmf_end_event()) {
                                    panic!("Failed to send start dtmf-event {step}");
                                }
                                *step = END_4_SENT;
                            }
                            END_4_MSG_AND_BUFFER_RECEIVED..SEND_START_2 => {
                                // give a little time interval
                                *step += 1;
                            }
                            SEND_START_2 => {
                                println!("rtpdtmfsrc::nominal sending start 2");
                                if !appsink.send_event(new_dtmf_start_event(VALID_EVENT_2_DIGIT, VALID_EVENT_2_VOLUME)) {
                                    panic!("Failed to send start dtmf-event {step}");
                                }
                                *step = START_2_SENT;
                            }
                            START_2_MSG_AND_BUFFER_RECEIVED..SEND_2_END => {
                                // give a little time interval
                                *step += 1;
                            }
                            SEND_2_END => {
                                println!("rtpdtmfsrc::nominal sending end 2");
                                if !appsink.send_event(new_dtmf_end_event()) {
                                    panic!("Failed to send start dtmf-event {step}");
                                }
                                *step = END_2_SENT;
                            }
                            END_2_MSG_AND_BUFFER_RECEIVED => {
                                break;
                            }
                            _ => (),
                        }
                    }
                    // _ = eos_rx => {
                    //     println!("rtpdtmfsrc::nominal");
                    // }
                    msg = bus_stream.next() => {
                        let Some(msg) = msg else { continue };
                        match msg.view() {
                            Element(_)
                                if msg.src().is_some_and(|obj| *obj == src) => {
                                    let mut step = step.lock().unwrap();
                                    match *step {
                                        START_4_SENT | START_4_BUFFER_RECEIVED => {
                                            let s = msg.structure().unwrap();
                                            assert_eq!(s.name(), "dtmf-event-processed");
                                            assert!(s.get::<bool>("start").unwrap());
                                            assert_eq!(s.get::<i32>("number").unwrap(), VALID_EVENT_4_DIGIT as i32);
                                            assert_eq!(s.get::<i32>("volume").unwrap(), VALID_EVENT_4_VOLUME as i32);
                                            println!("rtpdtmfsrc::nominal start 4 msg received");
                                            *step = if *step == START_4_SENT {
                                                START_4_MSG_RECEIVED
                                            } else {
                                                START_4_MSG_AND_BUFFER_RECEIVED
                                            };
                                        }
                                        END_4_SENT | END_4_BUFFER_RECEIVED => {
                                            let s = msg.structure().unwrap();
                                            assert_eq!(s.name(), "dtmf-event-processed");
                                            assert!(!s.get::<bool>("start").unwrap());
                                            println!("rtpdtmfsrc::nominal end 4 msg received");
                                            *step = if *step == END_4_SENT {
                                                END_4_MSG_RECEIVED
                                            } else {
                                                END_4_MSG_AND_BUFFER_RECEIVED
                                            };
                                        }
                                        START_2_SENT | START_2_BUFFER_RECEIVED => {
                                            let s = msg.structure().unwrap();
                                            assert_eq!(s.name(), "dtmf-event-processed");
                                            assert!(s.get::<bool>("start").unwrap());
                                            assert_eq!(s.get::<i32>("number").unwrap(), VALID_EVENT_2_DIGIT as i32);
                                            assert_eq!(s.get::<i32>("volume").unwrap(), VALID_EVENT_2_VOLUME as i32);
                                            println!("rtpdtmfsrc::nominal start 2 msg received");
                                            *step = if *step == START_2_SENT {
                                                START_2_MSG_RECEIVED
                                            } else {
                                                START_2_MSG_AND_BUFFER_RECEIVED
                                            };
                                        }
                                        END_2_SENT | END_2_BUFFER_RECEIVED => {
                                            let s = msg.structure().unwrap();
                                            assert_eq!(s.name(), "dtmf-event-processed");
                                            assert!(!s.get::<bool>("start").unwrap());
                                            println!("rtpdtmfsrc::nominal end 2 msg received");
                                            *step = if *step == END_2_SENT {
                                                END_2_MSG_RECEIVED
                                            } else {
                                                END_2_MSG_AND_BUFFER_RECEIVED
                                            };
                                        }
                                        _ => panic!("Unexpected ts-rtpdtmfsrc msg {msg:?}"),
                                    }
                                }
                            Latency(_) => {
                                let _ = pipe.recalculate_latency();
                            }
                            Error(err) => unreachable!("rtpdtmfsrc::nominal {err}"),
                            _ => (),
                        }
                    }
                };
            }
        }
    });

    pipe.set_state(gst::State::Null).unwrap();
}