summaryrefslogtreecommitdiffstats
path: root/src/state.rs
blob: dfccd9ad0bf675abae385a11f9d6d9e7f6058a8b (plain) (blame)
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
use std::error::Error;
use std::process::{Command, Stdio};
use std::sync::Arc;

use futures::{
    compat::Future01CompatExt,
    future::{FutureExt, TryFutureExt},
};
use futures01::{future::Future, sink::Sink};

use futures_util::stream::StreamExt;
use tsclientlib::{Connection, MessageTarget, DisconnectOptions};

use gst::prelude::*;
use gstreamer as gst;
use gstreamer_app as gst_app;
use gstreamer_audio as gst_audio;

use byte_slice_cast::*;

#[derive(Clone)]
pub struct State {
    conn: Arc<Connection>,
    pipeline: Arc<gst::Pipeline>,
}

impl State {
    pub fn new(conn: Connection) -> Self {
        let conn_arc = Arc::new(conn);

        gst::init().unwrap();
        let pipeline = gst::Pipeline::new(Some("Ts Audio Player"));
        let http_dl = gst::ElementFactory::make("souphttpsrc", Some("http-source")).unwrap();
        let decoder = gst::ElementFactory::make("decodebin", Some("video-decoder")).unwrap();
        pipeline.add_many(&[&http_dl, &decoder]).unwrap();

        http_dl
            .link(&decoder)
            .expect("Can link https_dl to decoder");

        let pipeline_weak = pipeline.downgrade();

        let inner_conn = conn_arc.clone();
        decoder.connect_pad_added(move |_, decoder_src| {
            let pipeline = match pipeline_weak.upgrade() {
                Some(pipeline) => pipeline,
                None => return,
            };

            let is_audio = {
                let media_type = decoder_src.get_current_caps().and_then(|caps| {
                    caps.get_structure(0).map(|s| {
                        let name = s.get_name();
                        name.starts_with("audio/")
                    })
                });

                match media_type {
                    None => {
                        eprintln!(
                            "Failed to get media type from pad {}",
                            decoder_src.get_name()
                        );
                        return;
                    }
                    Some(media_type) => media_type,
                }
            };

            if is_audio {
                let names = [
                    "audio-converter",
                    "volume",
                    "audio-resampler",
                    "opus-encoder",
                    "app-sink",
                ];
                for element in pipeline.iterate_elements() {
                    if let Ok(element) = element {
                        if names.contains(&&*element.get_name()) {
                            element.set_state(gst::State::Null);
                            pipeline.remove_many(&[&element]);
                        }
                    }
                }

                let convert =
                    gst::ElementFactory::make("audioconvert", Some("audio-converter")).unwrap();
                let volume = gst::ElementFactory::make("volume", Some("volume")).unwrap();
                let resample =
                    gst::ElementFactory::make("audioresample", Some("audio-resampler")).unwrap();
                let opus_enc = gst::ElementFactory::make("opusenc", Some("opus-encoder")).unwrap();
                let sink = gst::ElementFactory::make("appsink", Some("app-sink")).unwrap();

                sink.set_property("async", &false);

                volume.set_property("volume", &0.2);

                {
                    let elements = &[&convert, &volume, &resample, &opus_enc, &sink];
                    pipeline.add_many(elements).expect("Can add audio elements");
                    gst::Element::link_many(elements).expect("Can link audio elements");

                    for e in elements {
                        e.sync_state_with_parent()
                            .expect("Can sync state with parent");
                    }
                }

                let appsink = sink
                    .dynamic_cast::<gst_app::AppSink>()
                    .expect("Sink element is expected to be an appsink!");

                appsink.set_caps(Some(&gst::Caps::new_simple("audio/x-opus", &[])));

                let inner_conn = inner_conn.clone();
                appsink.set_callbacks(
                    gst_app::AppSinkCallbacks::new()
                        // Add a handler to the "new-sample" signal.
                        .new_sample(move |appsink| {
                            // Pull the sample in question out of the appsink's buffer.
                            let sample = appsink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
                            let buffer = sample
                                .get_buffer()
                                .expect("Failed to get buffer from appsink");

                            let map = buffer
                                .map_readable()
                                .expect("Failed to map buffer readable");

                            let samples = map
                                .as_slice_of::<u8>()
                                .expect("Failed to interprete buffer as S16 PCM");

                            let packet = tsproto_packets::packets::OutAudio::new(
                                &tsproto_packets::packets::AudioData::C2S {
                                    id: 0,
                                    codec: tsproto_packets::packets::CodecType::OpusMusic,
                                    data: &samples,
                                },
                            );

                            let send_packet = inner_conn
                                .get_packet_sink()
                                .send(packet)
                                .map(|_| ())
                                .map_err(|e| println!("Failed to send voice packet"));

                            tokio::run(send_packet);

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

                let convert_sink = convert
                    .get_static_pad("sink")
                    .expect("queue has no sinkpad");
                decoder_src
                    .link(&convert_sink)
                    .expect("Can link decoder src to convert sink");
            }
        });

        Self {
            conn: conn_arc,
            pipeline: Arc::new(pipeline),
        }
    }

    pub fn add_audio<'a>(&self, uri: String) {
        let ytdl_args = [
            "--no-playlist",
            "-f",
            "bestaudio/best",
            "-g",
            &uri,
            "-o",
            "-",
        ];

        let ytdl_output = Command::new("youtube-dl")
            .args(&ytdl_args)
            .stdin(Stdio::null())
            .output()
            .unwrap();

        if ytdl_output.status.success() == false {
            tokio::spawn(
                self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot")
                .map_err(|_| println!("Failed to change name")),
            );
            tokio::spawn(
                self.conn
                .lock()
                .to_mut()
                .send_message(MessageTarget::Channel, "Failed to load url")
                .map_err(|_| println!("Failed to change name")),
            );
            return;
        }
        let dl_url: &str = &String::from_utf8(ytdl_output.stderr).unwrap();

        self.pipeline
            .set_state(gst::State::Ready)
            .expect("Can set state to ready");

        let http_src = self
            .pipeline
            .get_by_name("http-source")
            .expect("Http source should be registered");
        http_src
            .set_property("location", &dl_url)
            .expect("Can set location on http_dl");

        self.pipeline
            .set_state(gst::State::Playing)
            .expect("Can set state to playing");

        tokio::spawn(
            self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot - Playing")
                .map_err(|_| println!("Failed to change name")),
        );
    }

    pub async fn poll(&self) {
        let bus = self
            .pipeline
            .get_bus()
            .expect("Pipeline without bus. Shouldn't happen!");

        let mut messages = gst::BusStream::new(&bus);
        while let Some(msg) = messages.next().await {
            use gst::MessageView;

            // Determine whether we want to quit: on EOS or error message
            // we quit, otherwise simply continue.
            match msg.view() {
                MessageView::Eos(..) => break,
                MessageView::Error(err) => {
                    println!(
                        "Error from {:?}: {} ({:?})",
                        err.get_src().map(|s| s.get_path_string()),
                        err.get_error(),
                        err.get_debug()
                    );
                    break;
                }
                _ => (),
            };
        }

        tokio::spawn(
            self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot")
                .map_err(|_| println!("Failed to change name")),
        );

        self.pipeline
            .set_state(gst::State::Null)
            .expect("Can set state to null");
    }

    pub fn volume(&self, volume: f64) {
        self.pipeline
            .get_by_name("volume")
            .expect("Volume filter should be registered")
            .set_property("volume", &volume)
            .expect("can change volume");
    }

    pub fn play(&self) {
        self.pipeline
            .set_state(gst::State::Playing)
            .expect("can play");

        tokio::spawn(
            self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot - Playing")
                .map_err(|_| println!("Failed to change name")),
        );
    }

    pub fn pause(&self) {
        self.pipeline
            .set_state(gst::State::Paused)
            .expect("can pause");

        tokio::spawn(
            self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot - Paused")
                .map_err(|_| println!("Failed to change name")),
        );
    }

    pub fn stop(&self) {
        self.pipeline
            .set_state(gst::State::Ready)
            .expect("can stop");

        tokio::spawn(
            self.conn
                .lock()
                .to_mut()
                .set_name("PokeBot - Stopped")
                .map_err(|_| println!("Failed to change name")),
        );
    }

    pub async fn disconnect(&self) {
        self.conn
            .disconnect(DisconnectOptions::new())
            .compat()
            .await;
    }
}