video: tegra: dc: Add quick for Vizio P series
[linux-3.10.git] / drivers / hid / hid-atv-remote.c
1 /*
2  *  HID driver for the Android TV remote
3  *  providing keys and microphone audio functionality
4  *
5  * Copyright (C) 2014 Google, Inc.
6  *
7  * This software is licensed under the terms of the GNU General Public
8  * License version 2, as published by the Free Software Foundation, and
9  * may be copied, distributed, and modified under those terms.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  */
16
17 #include <linux/device.h>
18 #include <linux/module.h>
19 #include <linux/hid.h>
20 #include <linux/hiddev.h>
21 #include <linux/hardirq.h>
22 #include <linux/jiffies.h>
23 #include <linux/slab.h>
24 #include <linux/time.h>
25 #include <linux/wait.h>
26 #include <linux/timer.h>
27 #include <linux/spinlock.h>
28 #include <linux/vmalloc.h>
29 #include <linux/switch.h>
30 #include <sound/core.h>
31 #include <sound/control.h>
32 #include <sound/info.h>
33 #include <sound/initval.h>
34 #include <sound/pcm.h>
35
36 #include "hid-ids.h"
37 #include "sbcdec.h"
38
39 MODULE_LICENSE("GPL v2");
40
41 #define snd_atvr_log(...) pr_info("snd_atvr: " __VA_ARGS__)
42
43 /* These values are copied from Android WiredAccessoryObserver */
44 enum headset_state {
45         BIT_NO_HEADSET = 0,
46         BIT_HEADSET = (1 << 0),
47         BIT_HEADSET_NO_MIC = (1 << 1),
48 };
49
50 /* This has to be static and created at init/boot, or else Android
51  * WiredAccessoryManager won't watch for it since it only checks
52  * for it's existence once on boot.
53  */
54 static struct switch_dev h2w_switch = {
55         .name = "h2w",
56 };
57
58 #define ADPCM_AUDIO_REPORT_ID 30
59
60 #define MSBC_AUDIO1_REPORT_ID 0xF7
61 #define MSBC_AUDIO2_REPORT_ID 0xFA
62 #define MSBC_AUDIO3_REPORT_ID 0xFB
63
64 #define INPUT_REPORT_ID 2
65
66 #define KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG 0x80
67
68 /* defaults */
69 #define MAX_PCM_DEVICES     1
70 #define MAX_PCM_SUBSTREAMS  4
71 #define MAX_MIDI_DEVICES    0
72
73 /* Define these all in one place so they stay in sync. */
74 #define USE_RATE_MIN          8000
75 #define USE_RATE_MAX          8000
76 #define USE_RATES_ARRAY      {USE_RATE_MIN}
77 #define USE_RATES_MASK       (SNDRV_PCM_RATE_8000)
78
79 #define MAX_FRAMES_PER_BUFFER  (8192)
80
81 #define USE_CHANNELS_MIN   1
82 #define USE_CHANNELS_MAX   1
83 #define USE_PERIODS_MIN    1
84 #define USE_PERIODS_MAX    1024
85
86 #define MAX_PCM_BUFFER_SIZE  (MAX_FRAMES_PER_BUFFER * sizeof(int16_t))
87 #define MIN_PERIOD_SIZE      64
88 #define MAX_PERIOD_SIZE      (MAX_PCM_BUFFER_SIZE / 8)
89 #define USE_FORMATS          (SNDRV_PCM_FMTBIT_S16_LE)
90
91 #define PACKET_TYPE_ADPCM 0
92 #define PACKET_TYPE_MSBC  1
93
94
95 /* Normally SBC has a H2 header but because we want
96  * to embed keycode support while audio is active without
97  * incuring an additional packet in the connection interval,
98  * we only use half the H2 header.  A normal H2 header has
99  * a 12-bit synchronization word and a 2-bit sequence number
100  * (SN0, SN1).  The sequence number is duplicated, so each
101  * pair of bits in the sequence number shall be always 00
102  * or 11 (see 5.7.2 of HFP_SPEC_V16).  We only receive
103  * the second byte of the H2 header that has the latter part
104  * of the sync word and the entire sequence number.
105  *
106  *  0      70      7
107  * b100000000001XXYY - where X is SN0 repeated and Y is SN1 repeated
108  *
109  * So the sequence numbers are:
110  * b1000000000010000 - 0x01 0x08  - only the 0x08 is received
111  * b1000000000011100 - 0x01 0x38  - only the 0x38 is received
112  * b1000000000010011 - 0x01 0xc8  - only the 0xc8 is received
113  * b1000000000011111 - 0x01 0xf8  - only the 0xf8 is received
114  *
115  * Each mSBC frame is split over 3 BLE frames, where each BLE packet has
116  * a 20 byte payload.
117  * The first BLE packet has the format:
118  * byte 0: keycode LSB
119  * byte 1: keycode MSB, with most significant bit 0 for no key
120  *         code active and 1 if keycode is active
121  * byte 2: Second byte of H2
122  * bytes 3-19: then four byte SBC header, then 13 bytes of audio data
123  *
124  * The second and third packet are purely 20 bytes of audio
125  * data.  Second packet arrives on report 0xFA and third packet
126  * arrives on report 0xFB.
127  *
128  * The mSBC decoder works on a mSBC frame, including the four byte SBC header,
129  * so we have to accumulate 3 BLE packets before sending it to the decoder.
130  */
131 #define NUM_SEQUENCES 4
132 const uint8_t mSBC_sequence_table[NUM_SEQUENCES] = {0x08, 0x38, 0xc8, 0xf8};
133 #define BLE_PACKETS_PER_MSBC_FRAME 3
134 #define MSBC_PACKET1_BYTES 17
135 #define MSBC_PACKET2_BYTES 20
136 #define MSBC_PACKET3_BYTES 20
137
138 #define BYTES_PER_MSBC_FRAME \
139       (MSBC_PACKET1_BYTES + MSBC_PACKET2_BYTES + MSBC_PACKET3_BYTES)
140
141 const uint8_t mSBC_start_offset_in_packet[BLE_PACKETS_PER_MSBC_FRAME] = {
142         1, /* SBC header starts after 1 byte sequence num portion of H2 */
143         0,
144         0
145 };
146 const uint8_t mSBC_start_offset_in_buffer[BLE_PACKETS_PER_MSBC_FRAME] = {
147         0,
148         MSBC_PACKET1_BYTES,
149         MSBC_PACKET1_BYTES + MSBC_PACKET2_BYTES
150 };
151 const uint8_t mSBC_bytes_in_packet[BLE_PACKETS_PER_MSBC_FRAME] = {
152         MSBC_PACKET1_BYTES, /* includes the SBC header but not the sequence num or keycode */
153         MSBC_PACKET2_BYTES,
154         MSBC_PACKET3_BYTES
155 };
156
157 struct fifo_packet {
158         uint8_t  type;
159         uint8_t  num_bytes;
160         /* Expect no more than 20 bytes. But align struct size to power of 2. */
161         uint8_t  raw_data[30];
162 };
163
164 #define MAX_SAMPLES_PER_PACKET 128
165 #define MIN_SAMPLES_PER_PACKET_P2  32
166 #define MAX_PACKETS_PER_BUFFER  \
167                 (MAX_FRAMES_PER_BUFFER / MIN_SAMPLES_PER_PACKET_P2)
168 #define MAX_BUFFER_SIZE  \
169                 (MAX_PACKETS_PER_BUFFER * sizeof(struct fifo_packet))
170
171 #define SND_ATVR_RUNNING_TIMEOUT_MSEC    (500)
172
173
174 #define TIMER_STATE_BEFORE_DECODE    0
175 #define TIMER_STATE_DURING_DECODE    1
176 #define TIMER_STATE_AFTER_DECODE     2
177
178 static int packet_counter;
179 static int num_remotes;
180 static bool card_created = false;
181 static int dev;
182 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;  /* Index 0-MAX */
183 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;   /* ID for this card */
184 static bool enable[SNDRV_CARDS] = {true, false};
185 /* Linux does not like NULL initialization. */
186 static char *model[SNDRV_CARDS]; /* = {[0 ... (SNDRV_CARDS - 1)] = NULL}; */
187 static int pcm_devs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
188 static int pcm_substreams[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
189
190 module_param_array(index, int, NULL, 0444);
191 MODULE_PARM_DESC(index, "Index value for AndroidTV Remote soundcard.");
192 module_param_array(id, charp, NULL, 0444);
193 MODULE_PARM_DESC(id, "ID string for AndroidTV Remote soundcard.");
194 module_param_array(enable, bool, NULL, 0444);
195 MODULE_PARM_DESC(enable, "Enable this AndroidTV Remote soundcard.");
196 module_param_array(model, charp, NULL, 0444);
197 MODULE_PARM_DESC(model, "Soundcard model.");
198 module_param_array(pcm_devs, int, NULL, 0444);
199 MODULE_PARM_DESC(pcm_devs, "PCM devices # (0-4) for AndroidTV Remote driver.");
200 module_param_array(pcm_substreams, int, NULL, 0444);
201 MODULE_PARM_DESC(pcm_substreams,
202         "PCM substreams # (1-128) for AndroidTV Remote driver?");
203
204 /* Debug feature to save captured raw and decoded audio into buffers
205  * and make them available for reading from misc devices.
206  * It will record the last session only and only up to the buffer size.
207  * The recording is cleared on read.
208  */
209 #define DEBUG_WITH_MISC_DEVICE 0
210
211 /* Debug feature to trace audio packets being received */
212 #define DEBUG_AUDIO_RECEPTION 1
213
214 /* Debug feature to trace HID reports we see */
215 #define DEBUG_HID_RAW_INPUT 0
216
217 #if (DEBUG_WITH_MISC_DEVICE == 1)
218 static int16_t large_pcm_buffer[1280*1024];
219 static int large_pcm_index;
220
221 static struct miscdevice pcm_dev_node;
222 static int pcm_dev_open(struct inode *inode, struct file *file)
223 {
224         /* nothing special to do here right now. */
225         return 0;
226 }
227
228 static ssize_t pcm_dev_read(struct file *file, char __user *buffer,
229                             size_t count, loff_t *ppos)
230 {
231         const uint8_t *data = (const uint8_t *)large_pcm_buffer;
232         size_t bytes_left = large_pcm_index * sizeof(int16_t) - *ppos;
233         if (count > bytes_left)
234                 count = bytes_left;
235         if (copy_to_user(buffer, &data[*ppos], count))
236                 return -EFAULT;
237
238         *ppos += count;
239         return count;
240 }
241
242 static const struct file_operations pcm_fops = {
243         .owner = THIS_MODULE,
244         .open = pcm_dev_open,
245         .llseek = no_llseek,
246         .read = pcm_dev_read,
247 };
248
249 static uint8_t raw_adpcm_buffer[640*1024];
250 static int raw_adpcm_index;
251 static struct miscdevice adpcm_dev_node;
252 static int adpcm_dev_open(struct inode *inode, struct file *file)
253 {
254         /* nothing special to do here right now. */
255         return 0;
256 }
257
258 static ssize_t adpcm_dev_read(struct file *file, char __user *buffer,
259                           size_t count, loff_t *ppos)
260 {
261         size_t bytes_left = raw_adpcm_index - *ppos;
262         if (count > bytes_left)
263                 count = bytes_left;
264         if (copy_to_user(buffer, &raw_adpcm_buffer[*ppos], count))
265                 return -EFAULT;
266
267         *ppos += count;
268         return count;
269 }
270
271 static const struct file_operations adpcm_fops = {
272         .owner = THIS_MODULE,
273         .open = adpcm_dev_open,
274         .llseek = no_llseek,
275         .read = adpcm_dev_read,
276 };
277
278 static uint8_t raw_mSBC_buffer[640*1024];
279 static int raw_mSBC_index;
280 static struct miscdevice mSBC_dev_node;
281 static int mSBC_dev_open(struct inode *inode, struct file *file)
282 {
283         /* nothing special to do here right now. */
284         return 0;
285 }
286
287 static ssize_t mSBC_dev_read(struct file *file, char __user *buffer,
288                           size_t count, loff_t *ppos)
289 {
290         size_t bytes_left = raw_mSBC_index - *ppos;
291         if (count > bytes_left)
292                 count = bytes_left;
293         if (copy_to_user(buffer, &raw_mSBC_buffer[*ppos], count))
294                 return -EFAULT;
295
296         *ppos += count;
297         return count;
298 }
299
300 static const struct file_operations mSBC_fops = {
301         .owner = THIS_MODULE,
302         .open = mSBC_dev_open,
303         .llseek = no_llseek,
304         .read = mSBC_dev_read,
305 };
306
307 #endif
308
309 /*
310  * Static substream is needed so Bluetooth can pass encoded audio
311  * to a running stream.
312  * This also serves to enable or disable the decoding of audio in the callback.
313  */
314 static struct snd_pcm_substream *s_substream_for_btle;
315 static DEFINE_SPINLOCK(s_substream_lock);
316
317 struct simple_atomic_fifo {
318         /* Read and write cursors are modified by different threads. */
319         uint read_cursor;
320         uint write_cursor;
321         /* Size must be a power of two. */
322         uint size;
323         /* internal mask is 2*size - 1
324          * This allows us to tell the difference between full and empty. */
325         uint internal_mask;
326         uint external_mask;
327 };
328
329 struct snd_atvr {
330         struct snd_card *card;
331         struct snd_pcm *pcm;
332         struct snd_pcm_hardware pcm_hw;
333
334         uint32_t sample_rate;
335
336         uint previous_jiffies; /* Used to detect underflows. */
337         uint timeout_jiffies;
338         struct timer_list decoding_timer;
339         uint timer_state;
340         bool timer_enabled;
341         uint timer_callback_count;
342
343         int16_t peak_level;
344         struct simple_atomic_fifo fifo_controller;
345         struct fifo_packet *fifo_packet_buffer;
346
347         /* IMA/DVI ADPCM Decoder */
348         int pcm_value;
349         int step_index;
350         bool first_packet;
351
352         /* mSBC decoder */
353         uint8_t mSBC_frame_data[BYTES_PER_MSBC_FRAME];
354         int16_t audio_output[MAX_SAMPLES_PER_PACKET];
355         uint8_t packet_in_frame;
356         uint8_t seq_index;
357
358         /*
359          * Write_index is the circular buffer position.
360          * It is advanced by the BTLE thread after decoding.
361          * It is read by ALSA in snd_atvr_pcm_pointer().
362          * It is not declared volatile because that is not
363          * allowed in the Linux kernel.
364          */
365         uint32_t write_index;
366         uint32_t frames_per_buffer;
367         /* count frames generated so far in this period */
368         uint32_t frames_in_period;
369         int16_t *pcm_buffer;
370
371 };
372
373 /***************************************************************************/
374 /************* Atomic FIFO *************************************************/
375 /***************************************************************************/
376 /*
377  * This FIFO is atomic if used by no more than 2 threads.
378  * One thread modifies the read cursor and the other
379  * thread modifies the write_cursor.
380  * Size and mask are not modified while being used.
381  *
382  * The read and write cursors range internally from 0 to (2*size)-1.
383  * This allows us to tell the difference between full and empty.
384  * When we get the cursors for external use we mask with size-1.
385  *
386  * Memory barriers required on SMP platforms.
387  */
388 static int atomic_fifo_init(struct simple_atomic_fifo *fifo_ptr, uint size)
389 {
390         /* Make sure size is a power of 2. */
391         if ((size & (size-1)) != 0) {
392                 pr_err("%s:%d - ERROR FIFO size = %d, not power of 2!\n",
393                         __func__, __LINE__, size);
394                 return -EINVAL;
395         }
396         fifo_ptr->read_cursor = 0;
397         fifo_ptr->write_cursor = 0;
398         fifo_ptr->size = size;
399         fifo_ptr->internal_mask = (size * 2) - 1;
400         fifo_ptr->external_mask = size - 1;
401         smp_wmb();
402         return 0;
403 }
404
405
406 static uint atomic_fifo_available_to_read(struct simple_atomic_fifo *fifo_ptr)
407 {
408         smp_rmb();
409         return (fifo_ptr->write_cursor - fifo_ptr->read_cursor)
410                         & fifo_ptr->internal_mask;
411 }
412
413 static uint atomic_fifo_available_to_write(struct simple_atomic_fifo *fifo_ptr)
414 {
415         smp_rmb();
416         return fifo_ptr->size - atomic_fifo_available_to_read(fifo_ptr);
417 }
418
419 static void atomic_fifo_advance_read(
420                 struct simple_atomic_fifo *fifo_ptr,
421                 uint frames)
422 {
423         smp_rmb();
424         BUG_ON(frames > atomic_fifo_available_to_read(fifo_ptr));
425         fifo_ptr->read_cursor = (fifo_ptr->read_cursor + frames)
426                         & fifo_ptr->internal_mask;
427         smp_wmb();
428 }
429
430 static void atomic_fifo_advance_write(
431                 struct simple_atomic_fifo *fifo_ptr,
432                 uint frames)
433 {
434         smp_rmb();
435         BUG_ON(frames > atomic_fifo_available_to_write(fifo_ptr));
436         fifo_ptr->write_cursor = (fifo_ptr->write_cursor + frames)
437                 & fifo_ptr->internal_mask;
438         smp_wmb();
439 }
440
441 static uint atomic_fifo_get_read_index(struct simple_atomic_fifo *fifo_ptr)
442 {
443         smp_rmb();
444         return fifo_ptr->read_cursor & fifo_ptr->external_mask;
445 }
446
447 static uint atomic_fifo_get_write_index(struct simple_atomic_fifo *fifo_ptr)
448 {
449         smp_rmb();
450         return fifo_ptr->write_cursor & fifo_ptr->external_mask;
451 }
452
453 /****************************************************************************/
454 static void snd_atvr_handle_frame_advance(
455                 struct snd_pcm_substream *substream, uint num_frames)
456 {
457         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
458         atvr_snd->frames_in_period += num_frames;
459         /* Tell ALSA if we have advanced by one or more periods. */
460         if (atvr_snd->frames_in_period >= substream->runtime->period_size) {
461                 snd_pcm_period_elapsed(substream);
462                 atvr_snd->frames_in_period %= substream->runtime->period_size;
463         }
464 }
465
466 static uint32_t snd_atvr_bump_write_index(
467                         struct snd_pcm_substream *substream,
468                         uint32_t num_samples)
469 {
470         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
471         uint32_t pos = atvr_snd->write_index;
472
473         /* Advance write position. */
474         pos += num_samples;
475         /* Wrap around at end of the circular buffer. */
476         pos %= atvr_snd->frames_per_buffer;
477         atvr_snd->write_index = pos;
478
479         snd_atvr_handle_frame_advance(substream, num_samples);
480
481         return pos;
482 }
483
484 /*
485  * Decode an IMA/DVI ADPCM packet and write the PCM data into a circular buffer.
486  * ADPCM is 4:1 16kHz@256kbps -> 16kHz@64kbps.
487  * ADPCM is 4:1 8kHz@128kbps -> 8kHz@32kbps.
488  */
489 static const int ima_index_table[16] = {
490         -1, -1, -1, -1, /* +0 - +3, decrease the step size */
491         2, 4, 6, 8,     /* +4 - +7, increase the step size */
492         -1, -1, -1, -1, /* -0 - -3, decrease the step size */
493         2, 4, 6, 8      /* -4 - -7, increase the step size */
494 };
495 static const int16_t ima_step_table[89] = {
496         7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
497         19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
498         50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
499         130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
500         337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
501         876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
502         2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
503         5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
504         15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
505 };
506
507 static void decode_adpcm_nibble(uint8_t nibble, struct snd_atvr *atvr_snd,
508                                 struct snd_pcm_substream *substream)
509 {
510         int step_index = atvr_snd->step_index;
511         int value = atvr_snd->pcm_value;
512         int step = ima_step_table[step_index];
513         int diff;
514
515         diff = step >> 3;
516         if (nibble & 1)
517                 diff += (step >> 2);
518         if (nibble & 2)
519                 diff += (step >> 1);
520         if (nibble & 4)
521                 diff += step;
522
523         if (nibble & 8) {
524                 value -= diff;
525                 if (value < -32768)
526                         value = -32768;
527         } else {
528                 value += diff;
529                 if (value > 32767)
530                         value = 32767;
531         }
532         atvr_snd->pcm_value = value;
533
534         /* copy to stream */
535         atvr_snd->pcm_buffer[atvr_snd->write_index] = value;
536 #if (DEBUG_WITH_MISC_DEVICE == 1)
537         if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
538                 large_pcm_buffer[large_pcm_index++] = value;
539 #endif
540         snd_atvr_bump_write_index(substream, 1);
541         if (value > atvr_snd->peak_level)
542                 atvr_snd->peak_level = value;
543
544         /* update step_index */
545         step_index += ima_index_table[nibble];
546         /* clamp step_index */
547         if (step_index < 0)
548                 step_index = 0;
549         else if (step_index >= ARRAY_SIZE(ima_step_table))
550                 step_index = ARRAY_SIZE(ima_step_table) - 1;
551         atvr_snd->step_index = step_index;
552 }
553
554 static int snd_atvr_decode_adpcm_packet(
555                         struct snd_pcm_substream *substream,
556                         const uint8_t *adpcm_input,
557                         size_t num_bytes
558                         )
559 {
560         uint i;
561         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
562
563         /* Decode IMA ADPCM data to PCM. */
564         if (atvr_snd->first_packet) {
565                 /* the first two bytes of the first packet
566                  * is the unencoded first 16-bit sample, high
567                  * byte first.
568                  */
569                 int value = ((int)adpcm_input[0] << 8) | adpcm_input[1];
570                 pr_info("%s: first packet, initial value is %d (0x%x, 0x%x)\n",
571                         __func__, value, adpcm_input[0], adpcm_input[1]);
572                 atvr_snd->pcm_value = value;
573                 atvr_snd->pcm_buffer[atvr_snd->write_index] = value;
574 #if (DEBUG_WITH_MISC_DEVICE == 1)
575                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
576                         raw_adpcm_buffer[raw_adpcm_index++] = adpcm_input[0];
577                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
578                         raw_adpcm_buffer[raw_adpcm_index++] = adpcm_input[1];
579                 if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
580                         large_pcm_buffer[large_pcm_index++] = value;
581 #endif
582                 snd_atvr_bump_write_index(substream, 1);
583                 atvr_snd->peak_level = value;
584                 atvr_snd->first_packet = false;
585                 i = 2;
586         } else {
587                 i = 0;
588         }
589
590         for (; i < num_bytes; i++) {
591                 uint8_t raw = adpcm_input[i];
592                 uint8_t nibble;
593
594 #if (DEBUG_WITH_MISC_DEVICE == 1)
595                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
596                         raw_adpcm_buffer[raw_adpcm_index++] = raw;
597 #endif
598
599                 /* process first nibble */
600                 nibble = (raw >> 4) & 0x0f;
601                 decode_adpcm_nibble(nibble, atvr_snd, substream);
602
603                 /* process second nibble */
604                 nibble = raw & 0x0f;
605                 decode_adpcm_nibble(nibble, atvr_snd, substream);
606         }
607
608         return num_bytes * 2;
609 }
610
611 /*
612  * Decode an mSBC packet and write the PCM data into a circular buffer.
613  * mSBC is supposed to be 16KHz but this is a 8KHz variant version.
614  */
615 #define BLOCKS_PER_PACKET 15
616 #define NUM_BITS 26
617
618 static int snd_atvr_decode_8KHz_mSBC_packet(
619                         struct snd_pcm_substream *substream,
620                         const uint8_t *sbc_input,
621                         size_t num_bytes
622                         )
623 {
624         uint num_samples = 0;
625         uint remaining;
626         uint i;
627         uint32_t pos;
628         uint read_index;
629         uint write_index;
630         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
631
632         /* Decode mSBC data to PCM. */
633 #if (DEBUG_WITH_MISC_DEVICE == 1)
634         for (i = 0; i < num_bytes; i++) {
635                 if (raw_mSBC_index < ARRAY_SIZE(raw_mSBC_buffer))
636                         raw_mSBC_buffer[raw_mSBC_index++] = sbc_input[i];
637                 else
638                         break;
639         }
640 #endif
641         if (atvr_snd->packet_in_frame == 0) {
642                 if (sbc_input[0] != mSBC_sequence_table[atvr_snd->seq_index]) {
643                         snd_atvr_log("sequence_num err, 0x%02x != 0x%02x\n",
644                                      sbc_input[1],
645                                      mSBC_sequence_table[atvr_snd->seq_index]);
646                         return 0;
647                 }
648                 atvr_snd->seq_index++;
649                 if (atvr_snd->seq_index == NUM_SEQUENCES)
650                         atvr_snd->seq_index = 0;
651
652                 /* subtract the sequence number */
653                 num_bytes--;
654         }
655         if (num_bytes != mSBC_bytes_in_packet[atvr_snd->packet_in_frame]) {
656                 pr_err("%s: received %zd audio bytes but expected %d bytes\n",
657                        __func__, num_bytes,
658                        mSBC_bytes_in_packet[atvr_snd->packet_in_frame]);
659                 return 0;
660         }
661         write_index = mSBC_start_offset_in_buffer[atvr_snd->packet_in_frame];
662         read_index = mSBC_start_offset_in_packet[atvr_snd->packet_in_frame];
663         memcpy(&atvr_snd->mSBC_frame_data[write_index],
664                &sbc_input[read_index],
665                mSBC_bytes_in_packet[atvr_snd->packet_in_frame]);
666         atvr_snd->packet_in_frame++;
667         if (atvr_snd->packet_in_frame < BLE_PACKETS_PER_MSBC_FRAME) {
668                 /* we don't have a complete mSBC frame yet, just return */
669                 return 0;
670         }
671         /* reset for next mSBC frame */
672         atvr_snd->packet_in_frame = 0;
673
674         /* we have a complete mSBC frame, send it to the decoder */
675         num_samples = sbc_decode(BLOCKS_PER_PACKET, NUM_BITS,
676                                  atvr_snd->mSBC_frame_data,
677                                  BYTES_PER_MSBC_FRAME,
678                                  &atvr_snd->audio_output[0]);
679
680         /* Write PCM data to the buffer. */
681         pos = atvr_snd->write_index;
682         read_index = 0;
683         if ((pos + num_samples) > atvr_snd->frames_per_buffer) {
684                 for (i = pos; i < atvr_snd->frames_per_buffer; i++) {
685                         int16_t sample = atvr_snd->audio_output[read_index++];
686                         if (sample > atvr_snd->peak_level)
687                                 atvr_snd->peak_level = sample;
688 #if (DEBUG_WITH_MISC_DEVICE == 1)
689                         if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
690                                 large_pcm_buffer[large_pcm_index++] = sample;
691 #endif
692                         atvr_snd->pcm_buffer[i] = sample;
693                 }
694
695                 remaining = (pos + num_samples) - atvr_snd->frames_per_buffer;
696                 for (i = 0; i < remaining; i++) {
697                         int16_t sample = atvr_snd->audio_output[read_index++];
698                         if (sample > atvr_snd->peak_level)
699                                 atvr_snd->peak_level = sample;
700 #if (DEBUG_WITH_MISC_DEVICE == 1)
701                         if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
702                                 large_pcm_buffer[large_pcm_index++] = sample;
703 #endif
704
705                         atvr_snd->pcm_buffer[i] = sample;
706                 }
707
708         } else {
709                 for (i = 0; i < num_samples; i++) {
710                         int16_t sample = atvr_snd->audio_output[read_index++];
711                         if (sample > atvr_snd->peak_level)
712                                 atvr_snd->peak_level = sample;
713 #if (DEBUG_WITH_MISC_DEVICE == 1)
714                         if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
715                                 large_pcm_buffer[large_pcm_index++] = sample;
716 #endif
717                         atvr_snd->pcm_buffer[i + pos] = sample;
718                 }
719         }
720
721         snd_atvr_bump_write_index(substream, num_samples);
722
723         return num_samples;
724 }
725
726 /**
727  * This is called by the event filter when it gets an audio packet
728  * from the AndroidTV remote.  It writes the packet into a FIFO
729  * which is then read and decoded by the timer task.
730  * @param input pointer to data to be decoded
731  * @param num_bytes how many bytes in raw_input
732  * @return number of samples decoded or negative error.
733  */
734 static void audio_dec(const uint8_t *raw_input, int type, size_t num_bytes)
735 {
736         bool dropped_packet = false;
737         struct snd_pcm_substream *substream;
738
739         spin_lock(&s_substream_lock);
740         substream = s_substream_for_btle;
741         if (substream != NULL) {
742                 struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
743                 /* Write data to a FIFO for decoding by the timer task. */
744                 uint writable = atomic_fifo_available_to_write(
745                         &atvr_snd->fifo_controller);
746                 if (writable > 0) {
747                         uint fifo_index = atomic_fifo_get_write_index(
748                                 &atvr_snd->fifo_controller);
749                         struct fifo_packet *packet =
750                                 &atvr_snd->fifo_packet_buffer[fifo_index];
751                         packet->type = type;
752                         packet->num_bytes = (uint8_t)num_bytes;
753                         memcpy(packet->raw_data, raw_input, num_bytes);
754                         atomic_fifo_advance_write(
755                                 &atvr_snd->fifo_controller, 1);
756                 } else {
757                         dropped_packet = true;
758                         s_substream_for_btle = NULL; /* Stop decoding. */
759                 }
760         }
761         packet_counter++;
762         spin_unlock(&s_substream_lock);
763
764         if (dropped_packet)
765                 snd_atvr_log("WARNING, raw audio packet dropped, FIFO full\n");
766 }
767
768 /*
769  * Note that smp_rmb() is called by snd_atvr_timer_callback()
770  * before calling this function.
771  *
772  * Reads:
773  *    jiffies
774  *    atvr_snd->previous_jiffies
775  * Writes:
776  *    atvr_snd->previous_jiffies
777  * Returns:
778  *    num_frames needed to catch up to the current time
779  */
780 static uint snd_atvr_calc_frame_advance(struct snd_atvr *atvr_snd)
781 {
782         /* Determine how much time passed. */
783         uint now_jiffies = jiffies;
784         uint elapsed_jiffies = now_jiffies - atvr_snd->previous_jiffies;
785         /* Convert jiffies to frames. */
786         uint frames_by_time = jiffies_to_msecs(elapsed_jiffies)
787                 * atvr_snd->sample_rate / 1000;
788         atvr_snd->previous_jiffies = now_jiffies;
789
790         /* Don't write more than one buffer full. */
791         if (frames_by_time > (atvr_snd->frames_per_buffer - 4))
792                 frames_by_time  = atvr_snd->frames_per_buffer - 4;
793
794         return frames_by_time;
795 }
796
797 /* Write zeros into the PCM buffer. */
798 static uint32_t snd_atvr_write_silence(struct snd_atvr *atvr_snd,
799                         uint32_t pos,
800                         int frames_to_advance)
801 {
802         /* Does it wrap? */
803         if ((pos + frames_to_advance) > atvr_snd->frames_per_buffer) {
804                 /* Write to end of buffer. */
805                 int16_t *destination = &atvr_snd->pcm_buffer[pos];
806                 size_t num_frames = atvr_snd->frames_per_buffer - pos;
807                 size_t num_bytes = num_frames * sizeof(int16_t);
808                 memset(destination, 0, num_bytes);
809                 /* Write from start of buffer to new pos. */
810                 destination = &atvr_snd->pcm_buffer[0];
811                 num_frames = frames_to_advance - num_frames;
812                 num_bytes = num_frames * sizeof(int16_t);
813                 memset(destination, 0, num_bytes);
814         } else {
815                 /* Write within the buffer. */
816                 int16_t *destination = &atvr_snd->pcm_buffer[pos];
817                 size_t num_bytes = frames_to_advance * sizeof(int16_t);
818                 memset(destination, 0, num_bytes);
819         }
820         /* Advance and wrap write_index */
821         pos += frames_to_advance;
822         pos %= atvr_snd->frames_per_buffer;
823         return pos;
824 }
825
826 /*
827  * Called by timer task to decode raw audio data from the FIFO into the PCM
828  * buffer.  Returns the number of packets decoded.
829  */
830 static uint snd_atvr_decode_from_fifo(struct snd_pcm_substream *substream)
831 {
832         uint i;
833         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
834         uint readable = atomic_fifo_available_to_read(
835                 &atvr_snd->fifo_controller);
836         for (i = 0; i < readable; i++) {
837                 uint fifo_index = atomic_fifo_get_read_index(
838                         &atvr_snd->fifo_controller);
839                 struct fifo_packet *packet =
840                         &atvr_snd->fifo_packet_buffer[fifo_index];
841                 if (packet->type == PACKET_TYPE_ADPCM) {
842                         snd_atvr_decode_adpcm_packet(substream,
843                                                      packet->raw_data,
844                                                      packet->num_bytes);
845                 } else if (packet->type == PACKET_TYPE_MSBC) {
846                         snd_atvr_decode_8KHz_mSBC_packet(substream,
847                                                          packet->raw_data,
848                                                          packet->num_bytes);
849                 } else {
850                         pr_err("Unknown packet type %d\n", packet->type);
851                 }
852
853                 atomic_fifo_advance_read(&atvr_snd->fifo_controller, 1);
854         }
855         return readable;
856 }
857
858 static int snd_atvr_schedule_timer(struct snd_pcm_substream *substream)
859 {
860         int ret;
861         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
862         uint msec_to_sleep = (substream->runtime->period_size * 1000)
863                         / atvr_snd->sample_rate;
864         uint jiffies_to_sleep = msecs_to_jiffies(msec_to_sleep);
865         if (jiffies_to_sleep < 2)
866                 jiffies_to_sleep = 2;
867         ret = mod_timer(&atvr_snd->decoding_timer, jiffies + jiffies_to_sleep);
868         if (ret < 0)
869                 pr_err("%s:%d - ERROR in mod_timer, ret = %d\n",
870                            __func__, __LINE__, ret);
871         return ret;
872 }
873
874 static void snd_atvr_timer_callback(unsigned long data)
875 {
876         uint readable;
877         uint packets_read;
878         bool need_silence = false;
879         struct snd_pcm_substream *substream = (struct snd_pcm_substream *)data;
880         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
881
882         /* timer_enabled will be false when stopping a stream. */
883         smp_rmb();
884         if (!atvr_snd->timer_enabled)
885                 return;
886         atvr_snd->timer_callback_count++;
887
888         switch (atvr_snd->timer_state) {
889         case TIMER_STATE_BEFORE_DECODE:
890                 readable = atomic_fifo_available_to_read(
891                                 &atvr_snd->fifo_controller);
892                 if (readable > 0) {
893                         atvr_snd->timer_state = TIMER_STATE_DURING_DECODE;
894                         /* Fall through into next state. */
895                 } else {
896                         need_silence = true;
897                         break;
898                 }
899
900         case TIMER_STATE_DURING_DECODE:
901                 packets_read = snd_atvr_decode_from_fifo(substream);
902                 if (packets_read > 0) {
903                         /* Defer timeout */
904                         atvr_snd->previous_jiffies = jiffies;
905                         break;
906                 }
907                 if (s_substream_for_btle == NULL) {
908                         atvr_snd->timer_state = TIMER_STATE_AFTER_DECODE;
909                         /* Decoder died. Overflowed?
910                          * Fall through into next state. */
911                 } else if ((jiffies - atvr_snd->previous_jiffies) >
912                            atvr_snd->timeout_jiffies) {
913                         snd_atvr_log("audio UNDERFLOW detected\n");
914                         /*  Not fatal.  Reset timeout. */
915                         atvr_snd->previous_jiffies = jiffies;
916                         break;
917                 } else
918                         break;
919
920         case TIMER_STATE_AFTER_DECODE:
921                 need_silence = true;
922                 break;
923         }
924
925         /* Write silence before and after decoding. */
926         if (need_silence) {
927                 uint frames_to_silence = snd_atvr_calc_frame_advance(atvr_snd);
928                 atvr_snd->write_index = snd_atvr_write_silence(
929                                 atvr_snd,
930                                 atvr_snd->write_index,
931                                 frames_to_silence);
932                 /* This can cause snd_atvr_pcm_trigger() to be called, which
933                  * may try to stop the timer. */
934                 snd_atvr_handle_frame_advance(substream, frames_to_silence);
935         }
936
937         smp_rmb();
938         if (atvr_snd->timer_enabled)
939                 snd_atvr_schedule_timer(substream);
940 }
941
942 static void snd_atvr_timer_start(struct snd_pcm_substream *substream)
943 {
944         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
945         atvr_snd->timer_enabled = true;
946         atvr_snd->previous_jiffies = jiffies;
947         atvr_snd->timeout_jiffies =
948                 msecs_to_jiffies(SND_ATVR_RUNNING_TIMEOUT_MSEC);
949         atvr_snd->timer_callback_count = 0;
950         smp_wmb();
951         setup_timer(&atvr_snd->decoding_timer,
952                 snd_atvr_timer_callback,
953                 (unsigned long)substream);
954
955         snd_atvr_schedule_timer(substream);
956 }
957
958 static void snd_atvr_timer_stop(struct snd_pcm_substream *substream)
959 {
960         int ret;
961         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
962
963         /* Tell timer function not to reschedule itself if it runs. */
964         atvr_snd->timer_enabled = false;
965         smp_wmb();
966         if (!in_interrupt()) {
967                 /* del_timer_sync will hang if called in the timer callback. */
968                 ret = del_timer_sync(&atvr_snd->decoding_timer);
969                 if (ret < 0)
970                         pr_err("%s:%d - ERROR del_timer_sync failed, %d\n",
971                                 __func__, __LINE__, ret);
972         }
973         /*
974          * Else if we are in an interrupt then we are being called from the
975          * middle of the snd_atvr_timer_callback(). The timer will not get
976          * rescheduled because atvr_snd->timer_enabled will be false
977          * at the end of snd_atvr_timer_callback().
978          * We do not need to "delete" the timer.
979          * The del_timer functions just cancel pending timers.
980          * There are no resources that need to be cleaned up.
981          */
982 }
983
984 /* ===================================================================== */
985 /*
986  * PCM interface
987  */
988
989 static int snd_atvr_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
990 {
991         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
992         switch (cmd) {
993         case SNDRV_PCM_TRIGGER_START:
994         case SNDRV_PCM_TRIGGER_RESUME:
995                 snd_atvr_log("%s starting audio\n", __func__);
996
997 #if (DEBUG_WITH_MISC_DEVICE == 1)
998                 large_pcm_index = 0;
999                 raw_adpcm_index = 0;
1000                 raw_mSBC_index = 0;
1001 #endif
1002                 packet_counter = 0;
1003                 atvr_snd->peak_level = -32768;
1004                 atvr_snd->previous_jiffies = jiffies;
1005                 atvr_snd->timer_state = TIMER_STATE_BEFORE_DECODE;
1006
1007                 /* ADPCM decoder state */
1008                 atvr_snd->step_index = 0;
1009                 atvr_snd->pcm_value = 0;
1010                 atvr_snd->first_packet = true;
1011
1012                 /* mSBC decoder */
1013                 atvr_snd->packet_in_frame = 0;
1014                 atvr_snd->seq_index = 0;
1015
1016                 snd_atvr_timer_start(substream);
1017                  /* Enables callback from BTLE driver. */
1018                 s_substream_for_btle = substream;
1019                 smp_wmb(); /* so other thread will see s_substream_for_btle */
1020                 return 0;
1021
1022         case SNDRV_PCM_TRIGGER_STOP:
1023         case SNDRV_PCM_TRIGGER_SUSPEND:
1024                 snd_atvr_log("%s stopping audio, peak = %d, # packets = %d\n",
1025                         __func__, atvr_snd->peak_level, packet_counter);
1026
1027                 s_substream_for_btle = NULL;
1028                 smp_wmb(); /* so other thread will see s_substream_for_btle */
1029                 snd_atvr_timer_stop(substream);
1030                 return 0;
1031         }
1032         return -EINVAL;
1033 }
1034
1035 static int snd_atvr_pcm_prepare(struct snd_pcm_substream *substream)
1036 {
1037         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1038         struct snd_pcm_runtime *runtime = substream->runtime;
1039         snd_atvr_log("%s, rate = %d, period_size = %d, buffer_size = %d\n",
1040                 __func__, (int) runtime->rate,
1041                 (int) runtime->period_size,
1042                 (int) runtime->buffer_size);
1043
1044         if (runtime->buffer_size > MAX_FRAMES_PER_BUFFER)
1045                 return -EINVAL;
1046
1047         atvr_snd->sample_rate = runtime->rate;
1048         atvr_snd->frames_per_buffer = runtime->buffer_size;
1049
1050         return 0; /* TODO - review */
1051 }
1052
1053 static struct snd_pcm_hardware atvr_pcm_hardware = {
1054         .info =                 (SNDRV_PCM_INFO_MMAP |
1055                                  SNDRV_PCM_INFO_INTERLEAVED |
1056                                  SNDRV_PCM_INFO_RESUME |
1057                                  SNDRV_PCM_INFO_MMAP_VALID),
1058         .formats =              USE_FORMATS,
1059         .rates =                USE_RATES_MASK,
1060         .rate_min =             USE_RATE_MIN,
1061         .rate_max =             USE_RATE_MAX,
1062         .channels_min =         USE_CHANNELS_MIN,
1063         .channels_max =         USE_CHANNELS_MAX,
1064         .buffer_bytes_max =     MAX_PCM_BUFFER_SIZE,
1065         .period_bytes_min =     MIN_PERIOD_SIZE,
1066         .period_bytes_max =     MAX_PERIOD_SIZE,
1067         .periods_min =          USE_PERIODS_MIN,
1068         .periods_max =          USE_PERIODS_MAX,
1069         .fifo_size =            0,
1070 };
1071
1072 static int snd_atvr_pcm_hw_params(struct snd_pcm_substream *substream,
1073                                         struct snd_pcm_hw_params *hw_params)
1074 {
1075         int ret = 0;
1076         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1077
1078         atvr_snd->write_index = 0;
1079         smp_wmb();
1080
1081         return ret;
1082 }
1083
1084 static int snd_atvr_pcm_hw_free(struct snd_pcm_substream *substream)
1085 {
1086         return 0;
1087 }
1088
1089 static int snd_atvr_pcm_open(struct snd_pcm_substream *substream)
1090 {
1091         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1092         struct snd_pcm_runtime *runtime = substream->runtime;
1093
1094         int ret = atomic_fifo_init(&atvr_snd->fifo_controller,
1095                                    MAX_PACKETS_PER_BUFFER);
1096         if (ret)
1097                 return ret;
1098
1099         runtime->hw = atvr_snd->pcm_hw;
1100         if (substream->pcm->device & 1) {
1101                 runtime->hw.info &= ~SNDRV_PCM_INFO_INTERLEAVED;
1102                 runtime->hw.info |= SNDRV_PCM_INFO_NONINTERLEAVED;
1103         }
1104         if (substream->pcm->device & 2)
1105                 runtime->hw.info &= ~(SNDRV_PCM_INFO_MMAP
1106                         | SNDRV_PCM_INFO_MMAP_VALID);
1107
1108         snd_atvr_log("%s, built %s %s\n", __func__, __DATE__, __TIME__);
1109
1110         /*
1111          * Allocate the maximum buffer now and then just use part of it when
1112          * the substream starts. We don't need DMA because it will just
1113          * get written to by the BTLE code.
1114          */
1115         /* We only use this buffer in the kernel and we do not do
1116          * DMA so vmalloc should be OK. */
1117         atvr_snd->pcm_buffer = vmalloc(MAX_PCM_BUFFER_SIZE);
1118         if (atvr_snd->pcm_buffer == NULL) {
1119                 pr_err("%s:%d - ERROR PCM buffer allocation failed\n",
1120                         __func__, __LINE__);
1121                 return -ENOMEM;
1122         }
1123
1124         /* We only use this buffer in the kernel and we do not do
1125          * DMA so vmalloc should be OK.
1126          */
1127         atvr_snd->fifo_packet_buffer = vmalloc(MAX_BUFFER_SIZE);
1128         if (atvr_snd->fifo_packet_buffer == NULL) {
1129                 pr_err("%s:%d - ERROR buffer allocation failed\n",
1130                         __func__, __LINE__);
1131                 vfree(atvr_snd->pcm_buffer);
1132                 atvr_snd->pcm_buffer = NULL;
1133                 return -ENOMEM;
1134         }
1135
1136         return 0;
1137 }
1138
1139 static int snd_atvr_pcm_close(struct snd_pcm_substream *substream)
1140 {
1141         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1142
1143         /* Make sure the timer is not running */
1144         if (atvr_snd->timer_enabled)
1145                 snd_atvr_timer_stop(substream);
1146
1147         if (atvr_snd->timer_callback_count > 0)
1148                 snd_atvr_log("processed %d packets in %d timer callbacks\n",
1149                         packet_counter, atvr_snd->timer_callback_count);
1150
1151         if (atvr_snd->pcm_buffer) {
1152                 vfree(atvr_snd->pcm_buffer);
1153                 atvr_snd->pcm_buffer = NULL;
1154         }
1155
1156         /*
1157          * Use spinlock so we don't free the FIFO when the
1158          * driver is writing to it.
1159          * The s_substream_for_btle should already be NULL by now.
1160          */
1161         spin_lock(&s_substream_lock);
1162         if (atvr_snd->fifo_packet_buffer) {
1163                 vfree(atvr_snd->fifo_packet_buffer);
1164                 atvr_snd->fifo_packet_buffer = NULL;
1165         }
1166         spin_unlock(&s_substream_lock);
1167         return 0;
1168 }
1169
1170 static snd_pcm_uframes_t snd_atvr_pcm_pointer(
1171                 struct snd_pcm_substream *substream)
1172 {
1173         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1174         /* write_index is written by another driver thread */
1175         smp_rmb();
1176         return atvr_snd->write_index;
1177 }
1178
1179 static int snd_atvr_pcm_copy(struct snd_pcm_substream *substream,
1180                           int channel, snd_pcm_uframes_t pos,
1181                           void __user *dst, snd_pcm_uframes_t count)
1182 {
1183         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1184         short *output = (short *)dst;
1185
1186         /* TODO Needs to be modified if we support more than 1 channel. */
1187         /*
1188          * Copy from PCM buffer to user memory.
1189          * Are we reading past the end of the buffer?
1190          */
1191         if ((pos + count) > atvr_snd->frames_per_buffer) {
1192                 const int16_t *source = &atvr_snd->pcm_buffer[pos];
1193                 int16_t *destination = output;
1194                 size_t num_frames = atvr_snd->frames_per_buffer - pos;
1195                 size_t num_bytes = num_frames * sizeof(int16_t);
1196                 memcpy(destination, source, num_bytes);
1197
1198                 source = &atvr_snd->pcm_buffer[0];
1199                 destination += num_frames;
1200                 num_frames = count - num_frames;
1201                 num_bytes = num_frames * sizeof(int16_t);
1202                 memcpy(destination, source, num_bytes);
1203         } else {
1204                 const int16_t *source = &atvr_snd->pcm_buffer[pos];
1205                 int16_t *destination = output;
1206                 size_t num_bytes = count * sizeof(int16_t);
1207                 memcpy(destination, source, num_bytes);
1208         }
1209
1210         return 0;
1211 }
1212
1213 static int snd_atvr_pcm_silence(struct snd_pcm_substream *substream,
1214                                 int channel, snd_pcm_uframes_t pos,
1215                                 snd_pcm_uframes_t count)
1216 {
1217         return 0; /* Do nothing. Only used by output? */
1218 }
1219
1220 static struct snd_pcm_ops snd_atvr_pcm_ops_no_buf = {
1221         .open =         snd_atvr_pcm_open,
1222         .close =        snd_atvr_pcm_close,
1223         .ioctl =        snd_pcm_lib_ioctl,
1224         .hw_params =    snd_atvr_pcm_hw_params,
1225         .hw_free =      snd_atvr_pcm_hw_free,
1226         .prepare =      snd_atvr_pcm_prepare,
1227         .trigger =      snd_atvr_pcm_trigger,
1228         .pointer =      snd_atvr_pcm_pointer,
1229         .copy =         snd_atvr_pcm_copy,
1230         .silence =      snd_atvr_pcm_silence,
1231 };
1232
1233 static int snd_card_atvr_pcm(struct snd_atvr *atvr_snd,
1234                              int device,
1235                              int substreams)
1236 {
1237         struct snd_pcm *pcm;
1238         struct snd_pcm_ops *ops;
1239         int err;
1240
1241         err = snd_pcm_new(atvr_snd->card, "ATVR PCM", device,
1242                           0, /* no playback substreams */
1243                           1, /* 1 capture substream */
1244                           &pcm);
1245         if (err < 0)
1246                 return err;
1247         atvr_snd->pcm = pcm;
1248         ops = &snd_atvr_pcm_ops_no_buf;
1249         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, ops);
1250         pcm->private_data = atvr_snd;
1251         pcm->info_flags = 0;
1252         strcpy(pcm->name, "ATVR PCM");
1253
1254         return 0;
1255 }
1256
1257 static int atvr_snd_initialize(struct hid_device *hdev)
1258 {
1259         struct snd_card *card;
1260         struct snd_atvr *atvr_snd;
1261         int err;
1262         int i;
1263
1264         if (dev >= SNDRV_CARDS)
1265                 return -ENODEV;
1266         if (!enable[dev]) {
1267                 dev++;
1268                 return -ENOENT;
1269         }
1270         err = snd_card_create(index[dev], id[dev], THIS_MODULE,
1271                               sizeof(struct snd_atvr), &card);
1272         if (err < 0) {
1273                 pr_err("%s: snd_card_create() returned err %d\n",
1274                        __func__, err);
1275                 return err;
1276         }
1277         hid_set_drvdata(hdev, card);
1278         atvr_snd = card->private_data;
1279         atvr_snd->card = card;
1280         for (i = 0; i < MAX_PCM_DEVICES && i < pcm_devs[dev]; i++) {
1281                 if (pcm_substreams[dev] < 1)
1282                         pcm_substreams[dev] = 1;
1283                 if (pcm_substreams[dev] > MAX_PCM_SUBSTREAMS)
1284                         pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
1285                 err = snd_card_atvr_pcm(atvr_snd, i, pcm_substreams[dev]);
1286                 if (err < 0) {
1287                         pr_err("%s: snd_card_atvr_pcm() returned err %d\n",
1288                                __func__, err);
1289                         goto __nodev;
1290                 }
1291         }
1292
1293
1294         atvr_snd->pcm_hw = atvr_pcm_hardware;
1295
1296         strcpy(card->driver, "AndroidTV Remote Audio");
1297         strcpy(card->shortname, "ATVRAudio");
1298         sprintf(card->longname, "AndroidTV Remote %i audio", dev + 1);
1299
1300         snd_card_set_dev(card, &hdev->dev);
1301
1302         err = snd_card_register(card);
1303         if (!err)
1304                 return 0;
1305
1306 __nodev:
1307         snd_card_free(card);
1308         return err;
1309 }
1310
1311 static int atvr_raw_event(struct hid_device *hdev, struct hid_report *report,
1312         u8 *data, int size)
1313 {
1314 #if (DEBUG_HID_RAW_INPUT == 1)
1315         pr_info("%s: report->id = 0x%x, size = %d\n",
1316                 __func__, report->id, size);
1317         if (size < 20) {
1318                 int i;
1319                 for (i = 1; i < size; i++) {
1320                         pr_info("data[%d] = 0x%02x\n", i, data[i]);
1321                 }
1322         }
1323 #endif
1324         if (report->id == ADPCM_AUDIO_REPORT_ID) {
1325                 /* send the data, minus the report-id in data[0], to the
1326                  * alsa audio decoder driver for ADPCM
1327                  */
1328 #if (DEBUG_AUDIO_RECEPTION == 1)
1329                 if (packet_counter == 0) {
1330                         snd_atvr_log("first ADPCM packet received\n");
1331                 }
1332 #endif
1333                 audio_dec(&data[1], PACKET_TYPE_ADPCM, size - 1);
1334                 /* we've handled the event */
1335                 return 1;
1336         } else if (report->id == MSBC_AUDIO1_REPORT_ID) {
1337                 /* first do special case check if there is any
1338                  * keyCode active in this report.  if so, we
1339                  * generate the same keyCode but on report 2, which
1340                  * is where normal keys are reported.  the keycode
1341                  * is being sent in the audio packet to save packets
1342                  * and over the air bandwidth.
1343                  */
1344                 if (data[2] & KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG) {
1345                         u8 key_data[3];
1346                         key_data[0] = INPUT_REPORT_ID;
1347                         key_data[1] = data[1]; /* low byte */
1348                         key_data[2] = data[2]; /* high byte */
1349                         key_data[2] &= ~KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG;
1350                         hid_report_raw_event(hdev, 0, key_data,
1351                                              sizeof(key_data), 0);
1352                         pr_info("%s: generated hid keycode 0x%02x%02x\n",
1353                                 __func__, key_data[2], key_data[1]);
1354                 }
1355
1356                 /* send the audio part to the alsa audio decoder for mSBC */
1357 #if (DEBUG_AUDIO_RECEPTION == 1)
1358                 if (packet_counter == 0) {
1359                         snd_atvr_log("first MSBC packet received\n");
1360                 }
1361 #endif
1362                 /* strip the one byte report id and two byte keycode field */
1363                 audio_dec(&data[1 + 2], PACKET_TYPE_MSBC, size - 1 - 2);
1364                 /* we've handled the event */
1365                 return 1;
1366         } else if ((report->id == MSBC_AUDIO2_REPORT_ID) ||
1367                    (report->id == MSBC_AUDIO3_REPORT_ID)) {
1368                 /* strip the one byte report id */
1369                 audio_dec(&data[1], PACKET_TYPE_MSBC, size - 1);
1370                 /* we've handled the event */
1371                 return 1;
1372         }
1373         /* let the event through for regular input processing */
1374         return 0;
1375 }
1376
1377 static int atvr_probe(struct hid_device *hdev, const struct hid_device_id *id)
1378 {
1379         int ret;
1380
1381         /* since vendor/product id filter doesn't work yet, because
1382          * Bluedroid is unable to get the vendor/product id, we
1383          * have to filter on name
1384          */
1385         pr_info("%s: hdev->name = %s, vendor_id = %d, product_id = %d, num %d\n",
1386                 __func__, hdev->name, hdev->vendor, hdev->product, num_remotes);
1387         if (strcmp(hdev->name, "ADT-1_Remote") &&
1388             strcmp(hdev->name, "Spike") &&
1389             strcmp(hdev->name, "Nexus Remote")) {
1390                 ret = -ENODEV;
1391                 goto err_match;
1392         }
1393         pr_info("%s: Found target remote %s\n", __func__, hdev->name);
1394
1395         ret = hid_parse(hdev);
1396         if (ret) {
1397                 hid_err(hdev, "hid parse failed\n");
1398                 goto err_parse;
1399         }
1400
1401         ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
1402         if (ret) {
1403                 hid_err(hdev, "hw start failed\n");
1404                 goto err_start;
1405         }
1406
1407         // Lazy-creation of the soundcard, and enable the wired headset only then
1408         // to avoid race conditions on subsequent connections.
1409         // AudioService.java delays enabling the output
1410         if (!card_created) {
1411                 ret = atvr_snd_initialize(hdev);
1412                 if (ret)
1413                         goto err_stop;
1414                 card_created = true;
1415                 switch_set_state(&h2w_switch, BIT_HEADSET);
1416         }
1417         pr_info("%s: num_remotes %d->%d\n", __func__, num_remotes, num_remotes + 1);
1418         num_remotes++;
1419
1420         return 0;
1421 err_stop:
1422         hid_hw_stop(hdev);
1423 err_start:
1424 err_parse:
1425 err_match:
1426         return ret;
1427 }
1428
1429 static void atvr_remove(struct hid_device *hdev)
1430 {
1431         pr_info("%s: hdev->name = %s removed, num %d->%d\n",
1432                 __func__, hdev->name, num_remotes, num_remotes - 1);
1433         num_remotes--;
1434         hid_hw_stop(hdev);
1435 }
1436
1437 static const struct hid_device_id atvr_devices[] = {
1438         {HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_GOOGLE,
1439                               USB_DEVICE_ID_ADT1_REMOTE)},
1440         {HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_GOOGLE,
1441                               USB_DEVICE_ID_NEXUS_REMOTE)},
1442         { }
1443 };
1444 MODULE_DEVICE_TABLE(hid, atvr_devices);
1445
1446 static struct hid_driver atvr_driver = {
1447         .name = "AndroidTV remote",
1448         .id_table = atvr_devices,
1449         .raw_event = atvr_raw_event,
1450         .probe = atvr_probe,
1451         .remove = atvr_remove,
1452 };
1453
1454 static int atvr_init(void)
1455 {
1456         int ret;
1457
1458         ret = switch_dev_register(&h2w_switch);
1459         if (ret)
1460                 pr_err("%s: failed to create h2w switch\n", __func__);
1461
1462         ret = hid_register_driver(&atvr_driver);
1463         if (ret)
1464                 pr_err("%s: can't register AndroidTV Remote driver\n", __func__);
1465
1466 #if (DEBUG_WITH_MISC_DEVICE == 1)
1467         pcm_dev_node.minor = MISC_DYNAMIC_MINOR;
1468         pcm_dev_node.name = "snd_atvr_pcm";
1469         pcm_dev_node.fops = &pcm_fops;
1470         ret = misc_register(&pcm_dev_node);
1471         if (ret)
1472                 pr_err("%s: failed to create pcm misc device %d\n",
1473                        __func__, ret);
1474         else
1475                 pr_info("%s: succeeded creating misc device %s\n",
1476                         __func__, pcm_dev_node.name);
1477
1478         adpcm_dev_node.minor = MISC_DYNAMIC_MINOR;
1479         adpcm_dev_node.name = "snd_atvr_adpcm";
1480         adpcm_dev_node.fops = &adpcm_fops;
1481         ret = misc_register(&adpcm_dev_node);
1482         if (ret)
1483                 pr_err("%s: failed to create adpcm misc device %d\n",
1484                        __func__, ret);
1485         else
1486                 pr_info("%s: succeeded creating misc device %s\n",
1487                         __func__, adpcm_dev_node.name);
1488
1489         mSBC_dev_node.minor = MISC_DYNAMIC_MINOR;
1490         mSBC_dev_node.name = "snd_atvr_mSBC";
1491         mSBC_dev_node.fops = &mSBC_fops;
1492         ret = misc_register(&mSBC_dev_node);
1493         if (ret)
1494                 pr_err("%s: failed to create mSBC misc device %d\n",
1495                        __func__, ret);
1496         else
1497                 pr_info("%s: succeeded creating misc device %s\n",
1498                         __func__, mSBC_dev_node.name);
1499 #endif
1500
1501         return ret;
1502 }
1503
1504 static void atvr_exit(void)
1505 {
1506 #if (DEBUG_WITH_MISC_DEVICE == 1)
1507         misc_deregister(&mSBC_dev_node);
1508         misc_deregister(&adpcm_dev_node);
1509         misc_deregister(&pcm_dev_node);
1510 #endif
1511
1512         hid_unregister_driver(&atvr_driver);
1513
1514         switch_set_state(&h2w_switch, BIT_NO_HEADSET);
1515         switch_dev_unregister(&h2w_switch);
1516 }
1517
1518 module_init(atvr_init);
1519 module_exit(atvr_exit);
1520 MODULE_LICENSE("GPL");