-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathspirc.rs
More file actions
493 lines (406 loc) · 14.9 KB
/
spirc.rs
File metadata and controls
493 lines (406 loc) · 14.9 KB
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
use futures::future;
use futures::sink::BoxSink;
use futures::stream::BoxStream;
use futures::sync::{oneshot, mpsc};
use futures::{Future, Stream, Sink, Async, Poll, BoxFuture};
use protobuf::{self, Message};
use mercury::MercuryError;
use player::Player;
use mixer::Mixer;
use session::Session;
use util::{now_ms, SpotifyId, SeqGenerator};
use version;
use protocol;
use protocol::spirc::{PlayStatus, State, MessageType, Frame, DeviceState};
pub struct SpircTask {
player: Player,
mixer: Box<Mixer>,
fixed_volume: bool,
sequence: SeqGenerator<u32>,
ident: String,
device: DeviceState,
state: State,
subscription: BoxStream<Frame, MercuryError>,
sender: BoxSink<Frame, MercuryError>,
commands: mpsc::UnboundedReceiver<SpircCommand>,
end_of_track: BoxFuture<(), oneshot::Canceled>,
shutdown: bool,
session: Session,
}
pub enum SpircCommand {
Shutdown
}
pub struct Spirc {
commands: mpsc::UnboundedSender<SpircCommand>,
}
fn initial_state() -> State {
protobuf_init!(protocol::spirc::State::new(), {
repeat: false,
shuffle: false,
status: PlayStatus::kPlayStatusStop,
position_ms: 0,
position_measured_at: 0,
})
}
fn initial_device_state(name: String, volume: u16) -> DeviceState {
protobuf_init!(DeviceState::new(), {
sw_version: version::version_string(),
is_active: false,
can_play: true,
volume: volume as u32,
name: name,
capabilities => [
@{
typ: protocol::spirc::CapabilityType::kCanBePlayer,
intValue => [1]
},
@{
typ: protocol::spirc::CapabilityType::kDeviceType,
intValue => [5]
},
@{
typ: protocol::spirc::CapabilityType::kGaiaEqConnectId,
intValue => [1]
},
@{
typ: protocol::spirc::CapabilityType::kSupportsLogout,
intValue => [0]
},
@{
typ: protocol::spirc::CapabilityType::kIsObservable,
intValue => [1]
},
@{
typ: protocol::spirc::CapabilityType::kVolumeSteps,
intValue => [64]
},
@{
typ: protocol::spirc::CapabilityType::kSupportedContexts,
stringValue => [
"album",
"playlist",
"search",
"inbox",
"toplist",
"starred",
"publishedstarred",
"track",
]
},
@{
typ: protocol::spirc::CapabilityType::kSupportedTypes,
stringValue => [
"audio/local",
"audio/track",
"local",
"track",
]
}
],
})
}
impl Spirc {
pub fn new(session: Session, player: Player, mixer: Box<Mixer>, fixed_volume: bool)
-> (Spirc, SpircTask)
{
debug!("new Spirc[{}]", session.session_id());
let ident = session.device_id().to_owned();
let name = session.config().name.clone();
let uri = format!("hm://remote/user/{}", session.username());
let subscription = session.mercury().subscribe(&uri as &str);
let subscription = subscription.map(|stream| stream.map_err(|_| MercuryError)).flatten_stream();
let subscription = subscription.map(|response| -> Frame {
let data = response.payload.first().unwrap();
protobuf::parse_from_bytes(data).unwrap()
}).boxed();
let sender = Box::new(session.mercury().sender(uri).with(|frame: Frame| {
Ok(frame.write_to_bytes().unwrap())
}));
let (cmd_tx, cmd_rx) = mpsc::unbounded();
let volume = 0xFFFF;
let device = initial_device_state(name, volume);
mixer.set_volume(volume);
let mut task = SpircTask {
player: player,
mixer: mixer,
fixed_volume: fixed_volume,
sequence: SeqGenerator::new(1),
ident: ident,
device: device,
state: initial_state(),
subscription: subscription,
sender: sender,
commands: cmd_rx,
end_of_track: future::empty().boxed(),
shutdown: false,
session: session.clone(),
};
let spirc = Spirc {
commands: cmd_tx,
};
task.hello();
(spirc, task)
}
pub fn shutdown(&self) {
let _ = mpsc::UnboundedSender::send(&self.commands, SpircCommand::Shutdown);
}
}
impl Future for SpircTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
loop {
let mut progress = false;
if !self.shutdown {
match self.subscription.poll().unwrap() {
Async::Ready(Some(frame)) => {
progress = true;
self.handle_frame(frame);
}
Async::Ready(None) => panic!("subscription terminated"),
Async::NotReady => (),
}
match self.commands.poll().unwrap() {
Async::Ready(Some(command)) => {
progress = true;
self.handle_command(command);
}
Async::Ready(None) => (),
Async::NotReady => (),
}
match self.end_of_track.poll() {
Ok(Async::Ready(())) => {
progress = true;
self.handle_end_of_track();
}
Ok(Async::NotReady) => (),
Err(oneshot::Canceled) => {
self.end_of_track = future::empty().boxed()
}
}
}
let poll_sender = self.sender.poll_complete().unwrap();
// Only shutdown once we've flushed out all our messages
if self.shutdown && poll_sender.is_ready() {
return Ok(Async::Ready(()));
}
if !progress {
return Ok(Async::NotReady);
}
}
}
}
impl SpircTask {
fn handle_command(&mut self, cmd: SpircCommand) {
match cmd {
SpircCommand::Shutdown => {
CommandSender::new(self, MessageType::kMessageTypeGoodbye).send();
self.shutdown = true;
self.commands.close();
}
}
}
fn handle_frame(&mut self, frame: Frame) {
debug!("{:?} {:?} {} {} {}",
frame.get_typ(),
frame.get_device_state().get_name(),
frame.get_ident(),
frame.get_seq_nr(),
frame.get_state_update_id());
if frame.get_ident() == self.ident ||
(frame.get_recipient().len() > 0 && !frame.get_recipient().contains(&self.ident)) {
return;
}
match frame.get_typ() {
MessageType::kMessageTypeHello => {
self.notify(Some(frame.get_ident()));
}
MessageType::kMessageTypeLoad => {
if !self.device.get_is_active() {
self.device.set_is_active(true);
self.device.set_became_active_at(now_ms());
}
self.update_tracks(&frame);
if self.state.get_track().len() > 0 {
self.state.set_position_ms(frame.get_state().get_position_ms());
self.state.set_position_measured_at(now_ms() as u64);
let play = frame.get_state().get_status() == PlayStatus::kPlayStatusPlay;
self.load_track(play);
} else {
self.state.set_status(PlayStatus::kPlayStatusStop);
}
self.notify(None);
}
MessageType::kMessageTypePlay => {
if self.state.get_status() == PlayStatus::kPlayStatusPause {
self.mixer.start();
self.player.play();
self.state.set_status(PlayStatus::kPlayStatusPlay);
self.state.set_position_measured_at(now_ms() as u64);
}
self.notify(None);
}
MessageType::kMessageTypePause => {
if self.state.get_status() == PlayStatus::kPlayStatusPlay {
self.player.pause();
self.mixer.stop();
self.state.set_status(PlayStatus::kPlayStatusPause);
let now = now_ms() as u64;
let position = self.state.get_position_ms();
let diff = now - self.state.get_position_measured_at();
self.state.set_position_ms(position + diff as u32);
self.state.set_position_measured_at(now);
}
self.notify(None);
}
MessageType::kMessageTypeNext => {
let current_index = self.state.get_playing_track_index();
let new_index = (current_index + 1) % (self.state.get_track().len() as u32);
self.state.set_playing_track_index(new_index);
self.state.set_position_ms(0);
self.state.set_position_measured_at(now_ms() as u64);
self.load_track(true);
self.notify(None);
}
MessageType::kMessageTypePrev => {
// Previous behaves differently based on the position
// Under 3s it goes to the previous song
// Over 3s it seeks to zero
if self.position() < 3000 {
let current_index = self.state.get_playing_track_index();
let new_index = if current_index == 0 {
self.state.get_track().len() as u32 - 1
} else {
current_index - 1
};
self.state.set_playing_track_index(new_index);
self.state.set_position_ms(0);
self.state.set_position_measured_at(now_ms() as u64);
self.load_track(true);
} else {
self.state.set_position_ms(0);
self.state.set_position_measured_at(now_ms() as u64);
self.player.seek(0);
}
self.notify(None);
}
MessageType::kMessageTypeSeek => {
let position = frame.get_position();
self.state.set_position_ms(position);
self.state.set_position_measured_at(now_ms() as u64);
self.player.seek(position);
self.notify(None);
}
MessageType::kMessageTypeReplace => {
self.update_tracks(&frame);
self.notify(None);
}
MessageType::kMessageTypeVolume => {
let volume = frame.get_volume();
self.device.set_volume(volume);
if !self.fixed_volume {
self.mixer.set_volume(frame.get_volume() as u16);
}
debug!("volume {}", volume);
self.notify(None);
}
MessageType::kMessageTypeNotify => {
if self.device.get_is_active() &&
frame.get_device_state().get_is_active()
{
self.device.set_is_active(false);
self.state.set_status(PlayStatus::kPlayStatusStop);
self.player.stop();
self.mixer.stop();
}
}
_ => (),
}
}
fn handle_end_of_track(&mut self) {
let current_index = self.state.get_playing_track_index();
let new_index = (current_index + 1) % (self.state.get_track().len() as u32);
self.state.set_playing_track_index(new_index);
self.state.set_position_ms(0);
self.state.set_position_measured_at(now_ms() as u64);
self.load_track(true);
self.notify(None);
}
fn position(&mut self) -> u32 {
let diff = now_ms() as u64 - self.state.get_position_measured_at();
self.state.get_position_ms() + diff as u32
}
fn update_tracks(&mut self, frame: &protocol::spirc::Frame) {
let index = frame.get_state().get_playing_track_index();
let tracks = frame.get_state().get_track();
self.state.set_playing_track_index(index);
self.state.set_track(tracks.into_iter().cloned().collect());
}
fn load_track(&mut self, play: bool) {
let index = self.state.get_playing_track_index();
let track = {
let gid = self.state.get_track()[index as usize].get_gid();
SpotifyId::from_raw(gid)
};
let position = self.state.get_position_ms();
let end_of_track = self.player.load(track, play, position);
if play {
self.state.set_status(PlayStatus::kPlayStatusPlay);
} else {
self.state.set_status(PlayStatus::kPlayStatusPause);
}
self.end_of_track = end_of_track.boxed();
}
fn hello(&mut self) {
CommandSender::new(self, MessageType::kMessageTypeHello).send();
}
fn notify(&mut self, recipient: Option<&str>) {
let mut cs = CommandSender::new(self, MessageType::kMessageTypeNotify);
if let Some(s) = recipient {
cs = cs.recipient(&s);
}
cs.send();
}
}
impl Drop for SpircTask {
fn drop(&mut self) {
debug!("drop Spirc[{}]", self.session.session_id());
}
}
struct CommandSender<'a> {
spirc: &'a mut SpircTask,
frame: protocol::spirc::Frame,
}
impl<'a> CommandSender<'a> {
fn new(spirc: &'a mut SpircTask, cmd: MessageType) -> CommandSender {
let frame = protobuf_init!(protocol::spirc::Frame::new(), {
version: 1,
protocol_version: "2.0.0",
ident: spirc.ident.clone(),
seq_nr: spirc.sequence.get(),
typ: cmd,
device_state: spirc.device.clone(),
state_update_id: now_ms(),
});
CommandSender {
spirc: spirc,
frame: frame,
}
}
fn recipient(mut self, recipient: &'a str) -> CommandSender {
self.frame.mut_recipient().push(recipient.to_owned());
self
}
#[allow(dead_code)]
fn state(mut self, state: protocol::spirc::State) -> CommandSender<'a> {
self.frame.set_state(state);
self
}
fn send(mut self) {
if !self.frame.has_state() && self.spirc.device.get_is_active() {
self.frame.set_state(self.spirc.state.clone());
}
let send = self.spirc.sender.start_send(self.frame).unwrap();
assert!(send.is_ready());
}
}