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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    fuchsia_async::{Time, TimeoutExt},
    fuchsia_bluetooth::types::Channel,
    fuchsia_zircon::Duration,
    futures::{future, future::Ready, stream::FilterMap, Stream, StreamExt},
    packet_encoding::{Decodable, Encodable},
    tracing::{info, trace},
};

#[cfg(test)]
mod tests;

mod types;

use crate::{
    avctp::{
        Command as AvctpCommand, CommandStream as AvctpCommandStream, Header as AvctpHeader,
        Packet as AvctpPacket, Peer as AvctpPeer,
    },
    Error, Result,
};

use self::types::BT_SIG_COMPANY_ID;

pub use self::types::{CommandType, Header, OpCode, PacketType, ResponseType, SubunitType};

pub type CommandStream = FilterMap<
    AvctpCommandStream,
    Ready<Option<Result<Command>>>,
    fn(Result<AvctpCommand>) -> Ready<Option<Result<Command>>>,
>;

/// Represents a received AVC Command from a `Peer`.
#[derive(Debug)]
pub struct Command {
    inner: AvctpCommand,
    avc_header: Header,
}

impl Command {
    pub fn avctp_header(&self) -> &AvctpHeader {
        self.inner.header()
    }

    pub fn avc_header(&self) -> &Header {
        &self.avc_header
    }

    pub fn body(&self) -> &[u8] {
        &self.inner.body()[self.avc_header.encoded_len()..]
    }

    pub fn send_response(&self, response_type: ResponseType, body: &[u8]) -> Result<()> {
        let response_header = self.avc_header.create_response(response_type)?;
        let mut rbuf = vec![0 as u8; response_header.encoded_len()];
        response_header.encode(&mut rbuf[..])?;
        if body.len() > 0 {
            rbuf.extend_from_slice(body);
        }
        self.inner.send_response(rbuf.as_slice())
    }

    pub fn is_vendor_dependent(&self) -> bool {
        self.avc_header.op_code() == &OpCode::VendorDependent
    }
}

impl TryFrom<Result<AvctpCommand>> for Command {
    type Error = Error;

    fn try_from(value: Result<AvctpCommand>) -> Result<Command> {
        let inner = match value {
            Err(e) => return Err(e),
            Ok(inner) => inner,
        };
        let avc_header = match Header::decode(inner.body()) {
            Err(e) => return Err(e),
            Ok(head) => head,
        };
        Ok(Command { inner, avc_header })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CommandResponse(pub ResponseType, pub Vec<u8>);

impl CommandResponse {
    pub fn response_type(&self) -> ResponseType {
        return self.0;
    }

    pub fn response(&self) -> &[u8] {
        return self.1.as_slice();
    }
}

impl TryFrom<AvctpPacket> for CommandResponse {
    type Error = Error;

    fn try_from(value: AvctpPacket) -> Result<CommandResponse> {
        let buf = value.body();
        let avc_header = Header::decode(buf)?;
        let body = buf[avc_header.encoded_len()..].to_vec();
        if let PacketType::Response(response_type) = avc_header.packet_type() {
            Ok(CommandResponse(response_type, body))
        } else {
            Err(Error::InvalidHeader)
        }
    }
}

/// Represents a peer connection to a remote device that uses the AV\C protocol over AVCTP encoded
/// L2CAP socket. Primarily used for the the control channel in AVRCP.
#[derive(Debug)]
pub struct Peer {
    /// The encapsulated AVCTP peer connection to the remote peer.
    inner: AvctpPeer,
}

impl Peer {
    /// Create a new peer object from a established L2CAP socket with the peer.
    pub fn new(channel: Channel) -> Self {
        Self { inner: AvctpPeer::new(channel) }
    }

    /// Decodes AV\C commands received over encapsulated AVCTP socket. Invalid AV|C commands are
    /// converted to errors.
    /// Note: Unit info and subunit info are responded to directly and swallowed since they return a
    /// static response.
    fn filter_internal_responses(
        avct_command_result: Result<AvctpCommand>,
    ) -> Option<Result<Command>> {
        let cmd = match Command::try_from(avct_command_result) {
            Ok(cmd) => cmd,
            Err(e) => return Some(Err(e)),
        };

        // Handle some early return short cutting logic.
        let avcth = cmd.avctp_header();
        let avch = cmd.avc_header();

        match (avcth.is_single(), avch.subunit_type(), avch.op_code()) {
            // The only type of subunit we support other than panel is unit subunit when a
            // unit info or sub unit info command is sent.
            (true, Some(SubunitType::Unit), &OpCode::UnitInfo) => {
                trace!("received UNITINFO command");
                // The packet needs to be 8 bytes long according to spec. First three bytes are
                // handled in the response header. Remaining buf is initialized to 0xff.
                let mut pbuf: [u8; 5] = [0xff; 5];
                // This constant is unexplained in the AVC spec but must always be 7.
                pbuf[0] = 0x07;
                // Set unit_type (bits 7-3) set to panel (0x09), and unit (bits 2-0) to 0.
                pbuf[1] = u8::from(&SubunitType::Panel) << 3;
                // Explicitly set company_id to 0xfffff for a generic company.
                pbuf[2] = 0xff;
                pbuf[3] = 0xff;
                pbuf[4] = 0xff;
                match cmd.send_response(ResponseType::ImplementedStable, &pbuf) {
                    Err(e) => Some(Err(e)),
                    Ok(_) => None,
                }
            }
            (true, Some(SubunitType::Unit), &OpCode::SubUnitInfo) => {
                trace!("received SUBUNITINFO command");
                // The packet needs to be 8 bytes long according to spec. First three bytes are
                // handled in the response header. Remaining buf is initialized to 0xff.
                let mut pbuf: [u8; 5] = [0xff; 5];
                // Set page (bits 6-4) to 0, and set all extension_code (bits 2-0) on.
                pbuf[0] = 0b111;
                // Set subunit_type (bits 7-3) to panel (0x09), and max_subunit_ID (bits 2-0) to 0.
                pbuf[1] = u8::from(&SubunitType::Panel) << 3;
                match cmd.send_response(ResponseType::ImplementedStable, &pbuf) {
                    Err(e) => Some(Err(e)),
                    Ok(_) => None,
                }
            }
            (_, Some(SubunitType::Panel), &OpCode::Passthrough)
            | (_, Some(SubunitType::Panel), &OpCode::VendorDependent) => Some(Ok(cmd)),
            _ => {
                info!("received invalid command");
                match cmd.send_response(ResponseType::NotImplemented, &[]) {
                    Err(e) => Some(Err(e)),
                    Ok(_) => None,
                }
            }
        }
    }

    /// Takes the command stream for incoming commands from the remote peer.
    pub fn take_command_stream(&self) -> CommandStream {
        self.inner
            .take_command_stream()
            .filter_map(|avct_command| future::ready(Self::filter_internal_responses(avct_command)))
    }

    /// The maximum amount of time we will wait for a response to a command packet.
    fn passthrough_command_timeout() -> Duration {
        const CMD_TIMER_MS: i64 = 1000;
        Duration::from_millis(CMD_TIMER_MS)
    }

    /// Sends a vendor specific command to the remote peer. Returns a CommandResponseStream to poll
    /// for the responses to the sent command. Returns error if the underlying socket is closed.
    pub fn send_vendor_dependent_command<'a>(
        &'a self,
        command_type: CommandType,
        payload: &'a [u8],
    ) -> Result<impl Stream<Item = Result<CommandResponse>>> {
        let avc_header = Header::new(
            command_type,
            u8::from(&SubunitType::Panel),
            0,
            OpCode::VendorDependent,
            Some(BT_SIG_COMPANY_ID),
        );

        let avc_h_len = avc_header.encoded_len();
        let mut buf = vec![0; avc_h_len];
        avc_header.encode(&mut buf[..])?;
        buf.extend_from_slice(payload);

        let stream = self.inner.send_command(buf.as_slice())?;
        let stream = stream.map(|resp| CommandResponse::try_from(resp?));
        Ok(stream)
    }

    /// Sends an AVC passthrough command to the remote peer. Returns the command response ignoring
    /// any interim responses. Returns error if the underlying socket is closed or the command isn't
    /// acknowledged with an interim response after 1000 ms.
    pub async fn send_avc_passthrough_command<'a>(
        &'a self,
        payload: &'a [u8],
    ) -> Result<CommandResponse> {
        let avc_header = Header::new(
            CommandType::Control,
            u8::from(&SubunitType::Panel),
            0,
            OpCode::Passthrough,
            Some(BT_SIG_COMPANY_ID),
        );

        let avc_h_len = avc_header.encoded_len();
        let mut buf = vec![0; avc_h_len];
        avc_header.encode(&mut buf[..])?;
        buf.extend_from_slice(payload);

        let mut response_stream = self.inner.send_command(buf.as_slice())?;

        let timeout = Time::after(Peer::passthrough_command_timeout());
        loop {
            if let Some(resp) = response_stream
                .next()
                .on_timeout(timeout, || return Some(Err(Error::Timeout)))
                .await
            {
                let value = CommandResponse::try_from(resp?)?;
                if value.0 == ResponseType::Interim {
                    continue;
                }
                return Ok(value);
            } else {
                return Err(Error::PeerDisconnected);
            }
        }
    }
}