• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2018-2019 Pali Rohár <pali.rohar@gmail.com>
5 
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10 
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15 
16   You should have received a copy of the GNU Lesser General Public
17   License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
18 ***/
19 
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 
24 #include <pulsecore/core-util.h>
25 #include <pulsecore/log.h>
26 #include <pulsecore/macro.h>
27 #include <pulsecore/once.h>
28 #include <pulse/sample.h>
29 #include <pulse/xmalloc.h>
30 
31 #include <arpa/inet.h>
32 
33 #include <sbc/sbc.h>
34 
35 #include "a2dp-codecs.h"
36 #include "a2dp-codec-api.h"
37 #include "rtp.h"
38 
39 #define SBC_BITPOOL_DEC_LIMIT 32
40 #define SBC_BITPOOL_DEC_STEP 5
41 
42 struct sbc_info {
43     sbc_t sbc;                           /* Codec data */
44     size_t codesize, frame_length;       /* SBC Codesize, frame_length. We simply cache those values here */
45     uint16_t seq_num;                    /* Cumulative packet sequence */
46     uint8_t frequency;
47     uint8_t blocks;
48     uint8_t subbands;
49     uint8_t mode;
50     uint8_t allocation;
51     uint8_t initial_bitpool;
52     uint8_t min_bitpool;
53     uint8_t max_bitpool;
54 };
55 
can_accept_capabilities(const uint8_t * capabilities_buffer,uint8_t capabilities_size,bool for_encoding)56 static bool can_accept_capabilities(const uint8_t *capabilities_buffer, uint8_t capabilities_size, bool for_encoding) {
57     const a2dp_sbc_t *capabilities = (const a2dp_sbc_t *) capabilities_buffer;
58 
59     if (capabilities_size != sizeof(*capabilities))
60         return false;
61 
62     if (!(capabilities->frequency & (SBC_SAMPLING_FREQ_16000 | SBC_SAMPLING_FREQ_32000 | SBC_SAMPLING_FREQ_44100 | SBC_SAMPLING_FREQ_48000)))
63         return false;
64 
65     if (!(capabilities->channel_mode & (SBC_CHANNEL_MODE_MONO | SBC_CHANNEL_MODE_DUAL_CHANNEL | SBC_CHANNEL_MODE_STEREO | SBC_CHANNEL_MODE_JOINT_STEREO)))
66         return false;
67 
68     if (!(capabilities->allocation_method & (SBC_ALLOCATION_SNR | SBC_ALLOCATION_LOUDNESS)))
69         return false;
70 
71     if (!(capabilities->subbands & (SBC_SUBBANDS_4 | SBC_SUBBANDS_8)))
72         return false;
73 
74     if (!(capabilities->block_length & (SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 | SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16)))
75         return false;
76 
77     return true;
78 }
79 
choose_remote_endpoint(const pa_hashmap * capabilities_hashmap,const pa_sample_spec * default_sample_spec,bool for_encoding)80 static const char *choose_remote_endpoint(const pa_hashmap *capabilities_hashmap, const pa_sample_spec *default_sample_spec, bool for_encoding) {
81     const pa_a2dp_codec_capabilities *a2dp_capabilities;
82     const char *key;
83     void *state;
84 
85     /* There is no preference, just choose random valid entry */
86     PA_HASHMAP_FOREACH_KV(key, a2dp_capabilities, capabilities_hashmap, state) {
87         if (can_accept_capabilities(a2dp_capabilities->buffer, a2dp_capabilities->size, for_encoding))
88             return key;
89     }
90 
91     return NULL;
92 }
93 
fill_capabilities(uint8_t capabilities_buffer[MAX_A2DP_CAPS_SIZE])94 static uint8_t fill_capabilities(uint8_t capabilities_buffer[MAX_A2DP_CAPS_SIZE]) {
95     a2dp_sbc_t *capabilities = (a2dp_sbc_t *) capabilities_buffer;
96 
97     pa_zero(*capabilities);
98 
99     capabilities->channel_mode = SBC_CHANNEL_MODE_MONO | SBC_CHANNEL_MODE_DUAL_CHANNEL | SBC_CHANNEL_MODE_STEREO |
100                                  SBC_CHANNEL_MODE_JOINT_STEREO;
101     capabilities->frequency = SBC_SAMPLING_FREQ_16000 | SBC_SAMPLING_FREQ_32000 | SBC_SAMPLING_FREQ_44100 |
102                               SBC_SAMPLING_FREQ_48000;
103     capabilities->allocation_method = SBC_ALLOCATION_SNR | SBC_ALLOCATION_LOUDNESS;
104     capabilities->subbands = SBC_SUBBANDS_4 | SBC_SUBBANDS_8;
105     capabilities->block_length = SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 | SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16;
106     capabilities->min_bitpool = SBC_MIN_BITPOOL;
107     capabilities->max_bitpool = SBC_BITPOOL_HQ_JOINT_STEREO_44100;
108 
109     return sizeof(*capabilities);
110 }
111 
is_configuration_valid(const uint8_t * config_buffer,uint8_t config_size)112 static bool is_configuration_valid(const uint8_t *config_buffer, uint8_t config_size) {
113     const a2dp_sbc_t *config = (const a2dp_sbc_t *) config_buffer;
114 
115     if (config_size != sizeof(*config)) {
116         pa_log_error("Invalid size of config buffer");
117         return false;
118     }
119 
120     if (config->frequency != SBC_SAMPLING_FREQ_16000 && config->frequency != SBC_SAMPLING_FREQ_32000 &&
121         config->frequency != SBC_SAMPLING_FREQ_44100 && config->frequency != SBC_SAMPLING_FREQ_48000) {
122         pa_log_error("Invalid sampling frequency in configuration");
123         return false;
124     }
125 
126     if (config->channel_mode != SBC_CHANNEL_MODE_MONO && config->channel_mode != SBC_CHANNEL_MODE_DUAL_CHANNEL &&
127         config->channel_mode != SBC_CHANNEL_MODE_STEREO && config->channel_mode != SBC_CHANNEL_MODE_JOINT_STEREO) {
128         pa_log_error("Invalid channel mode in configuration");
129         return false;
130     }
131 
132     if (config->allocation_method != SBC_ALLOCATION_SNR && config->allocation_method != SBC_ALLOCATION_LOUDNESS) {
133         pa_log_error("Invalid allocation method in configuration");
134         return false;
135     }
136 
137     if (config->subbands != SBC_SUBBANDS_4 && config->subbands != SBC_SUBBANDS_8) {
138         pa_log_error("Invalid SBC subbands in configuration");
139         return false;
140     }
141 
142     if (config->block_length != SBC_BLOCK_LENGTH_4 && config->block_length != SBC_BLOCK_LENGTH_8 &&
143         config->block_length != SBC_BLOCK_LENGTH_12 && config->block_length != SBC_BLOCK_LENGTH_16) {
144         pa_log_error("Invalid block length in configuration");
145         return false;
146     }
147 
148     if (config->min_bitpool > config->max_bitpool) {
149         pa_log_error("Invalid bitpool in configuration");
150         return false;
151     }
152 
153     return true;
154 }
155 
default_bitpool(uint8_t freq,uint8_t mode)156 static uint8_t default_bitpool(uint8_t freq, uint8_t mode) {
157     /* These bitpool values were chosen based on the A2DP spec recommendation */
158     switch (freq) {
159         case SBC_SAMPLING_FREQ_16000:
160         case SBC_SAMPLING_FREQ_32000:
161             switch (mode) {
162                 case SBC_CHANNEL_MODE_MONO:
163                 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
164                 case SBC_CHANNEL_MODE_STEREO:
165                 case SBC_CHANNEL_MODE_JOINT_STEREO:
166                     return SBC_BITPOOL_HQ_JOINT_STEREO_44100;
167             }
168             break;
169 
170         case SBC_SAMPLING_FREQ_44100:
171             switch (mode) {
172                 case SBC_CHANNEL_MODE_MONO:
173                 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
174                     return SBC_BITPOOL_HQ_MONO_44100;
175 
176                 case SBC_CHANNEL_MODE_STEREO:
177                 case SBC_CHANNEL_MODE_JOINT_STEREO:
178                     return SBC_BITPOOL_HQ_JOINT_STEREO_44100;
179             }
180             break;
181 
182         case SBC_SAMPLING_FREQ_48000:
183             switch (mode) {
184                 case SBC_CHANNEL_MODE_MONO:
185                 case SBC_CHANNEL_MODE_DUAL_CHANNEL:
186                     return SBC_BITPOOL_HQ_MONO_48000;
187 
188                 case SBC_CHANNEL_MODE_STEREO:
189                 case SBC_CHANNEL_MODE_JOINT_STEREO:
190                     return SBC_BITPOOL_HQ_JOINT_STEREO_48000;
191             }
192             break;
193     }
194 
195     pa_assert_not_reached();
196 }
197 
fill_preferred_configuration(const pa_sample_spec * default_sample_spec,const uint8_t * capabilities_buffer,uint8_t capabilities_size,uint8_t config_buffer[MAX_A2DP_CAPS_SIZE])198 static uint8_t fill_preferred_configuration(const pa_sample_spec *default_sample_spec, const uint8_t *capabilities_buffer, uint8_t capabilities_size, uint8_t config_buffer[MAX_A2DP_CAPS_SIZE]) {
199     a2dp_sbc_t *config = (a2dp_sbc_t *) config_buffer;
200     const a2dp_sbc_t *capabilities = (const a2dp_sbc_t *) capabilities_buffer;
201     int i;
202 
203     static const struct {
204         uint32_t rate;
205         uint8_t cap;
206     } freq_table[] = {
207         { 16000U, SBC_SAMPLING_FREQ_16000 },
208         { 32000U, SBC_SAMPLING_FREQ_32000 },
209         { 44100U, SBC_SAMPLING_FREQ_44100 },
210         { 48000U, SBC_SAMPLING_FREQ_48000 }
211     };
212 
213     if (capabilities_size != sizeof(*capabilities)) {
214         pa_log_error("Invalid size of capabilities buffer");
215         return 0;
216     }
217 
218     pa_zero(*config);
219 
220     /* Find the lowest freq that is at least as high as the requested sampling rate */
221     for (i = 0; (unsigned) i < PA_ELEMENTSOF(freq_table); i++)
222         if (freq_table[i].rate >= default_sample_spec->rate && (capabilities->frequency & freq_table[i].cap)) {
223             config->frequency = freq_table[i].cap;
224             break;
225         }
226 
227     if ((unsigned) i == PA_ELEMENTSOF(freq_table)) {
228         for (--i; i >= 0; i--) {
229             if (capabilities->frequency & freq_table[i].cap) {
230                 config->frequency = freq_table[i].cap;
231                 break;
232             }
233         }
234 
235         if (i < 0) {
236             pa_log_error("Not suitable sample rate");
237             return 0;
238         }
239     }
240 
241     pa_assert((unsigned) i < PA_ELEMENTSOF(freq_table));
242 
243     if (default_sample_spec->channels <= 1) {
244         if (capabilities->channel_mode & SBC_CHANNEL_MODE_MONO)
245             config->channel_mode = SBC_CHANNEL_MODE_MONO;
246         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_JOINT_STEREO)
247             config->channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
248         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_STEREO)
249             config->channel_mode = SBC_CHANNEL_MODE_STEREO;
250         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_DUAL_CHANNEL)
251             config->channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
252         else {
253             pa_log_error("No supported channel modes");
254             return 0;
255         }
256     } else {
257         if (capabilities->channel_mode & SBC_CHANNEL_MODE_JOINT_STEREO)
258             config->channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
259         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_STEREO)
260             config->channel_mode = SBC_CHANNEL_MODE_STEREO;
261         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_DUAL_CHANNEL)
262             config->channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
263         else if (capabilities->channel_mode & SBC_CHANNEL_MODE_MONO)
264             config->channel_mode = SBC_CHANNEL_MODE_MONO;
265         else {
266             pa_log_error("No supported channel modes");
267             return 0;
268         }
269     }
270 
271     if (capabilities->block_length & SBC_BLOCK_LENGTH_16)
272         config->block_length = SBC_BLOCK_LENGTH_16;
273     else if (capabilities->block_length & SBC_BLOCK_LENGTH_12)
274         config->block_length = SBC_BLOCK_LENGTH_12;
275     else if (capabilities->block_length & SBC_BLOCK_LENGTH_8)
276         config->block_length = SBC_BLOCK_LENGTH_8;
277     else if (capabilities->block_length & SBC_BLOCK_LENGTH_4)
278         config->block_length = SBC_BLOCK_LENGTH_4;
279     else {
280         pa_log_error("No supported block lengths");
281         return 0;
282     }
283 
284     if (capabilities->subbands & SBC_SUBBANDS_8)
285         config->subbands = SBC_SUBBANDS_8;
286     else if (capabilities->subbands & SBC_SUBBANDS_4)
287         config->subbands = SBC_SUBBANDS_4;
288     else {
289         pa_log_error("No supported subbands");
290         return 0;
291     }
292 
293     if (capabilities->allocation_method & SBC_ALLOCATION_LOUDNESS)
294         config->allocation_method = SBC_ALLOCATION_LOUDNESS;
295     else if (capabilities->allocation_method & SBC_ALLOCATION_SNR)
296         config->allocation_method = SBC_ALLOCATION_SNR;
297     else {
298         pa_log_error("No supported allocation method");
299         return 0;
300     }
301 
302     config->min_bitpool = (uint8_t) PA_MAX(SBC_MIN_BITPOOL, capabilities->min_bitpool);
303     config->max_bitpool = (uint8_t) PA_MIN(default_bitpool(config->frequency, config->channel_mode), capabilities->max_bitpool);
304 
305     if (config->min_bitpool > config->max_bitpool) {
306         pa_log_error("No supported bitpool");
307         return 0;
308     }
309 
310     return sizeof(*config);
311 }
312 
set_params(struct sbc_info * sbc_info)313 static void set_params(struct sbc_info *sbc_info) {
314     sbc_info->sbc.frequency = sbc_info->frequency;
315     sbc_info->sbc.blocks = sbc_info->blocks;
316     sbc_info->sbc.subbands = sbc_info->subbands;
317     sbc_info->sbc.mode = sbc_info->mode;
318     sbc_info->sbc.allocation = sbc_info->allocation;
319     sbc_info->sbc.bitpool = sbc_info->initial_bitpool;
320     sbc_info->sbc.endian = SBC_LE;
321 
322     sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
323     sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
324 }
325 
init(bool for_encoding,bool for_backchannel,const uint8_t * config_buffer,uint8_t config_size,pa_sample_spec * sample_spec)326 static void *init(bool for_encoding, bool for_backchannel, const uint8_t *config_buffer, uint8_t config_size, pa_sample_spec *sample_spec) {
327     struct sbc_info *sbc_info;
328     const a2dp_sbc_t *config = (const a2dp_sbc_t *) config_buffer;
329     int ret;
330 
331     pa_assert(config_size == sizeof(*config));
332     pa_assert(!for_backchannel);
333 
334     sbc_info = pa_xnew0(struct sbc_info, 1);
335 
336     ret = sbc_init(&sbc_info->sbc, 0);
337     if (ret != 0) {
338         pa_xfree(sbc_info);
339         pa_log_error("SBC initialization failed: %d", ret);
340         return NULL;
341     }
342 
343     sample_spec->format = PA_SAMPLE_S16LE;
344 
345     switch (config->frequency) {
346         case SBC_SAMPLING_FREQ_16000:
347             sbc_info->frequency = SBC_FREQ_16000;
348             sample_spec->rate = 16000U;
349             break;
350         case SBC_SAMPLING_FREQ_32000:
351             sbc_info->frequency = SBC_FREQ_32000;
352             sample_spec->rate = 32000U;
353             break;
354         case SBC_SAMPLING_FREQ_44100:
355             sbc_info->frequency = SBC_FREQ_44100;
356             sample_spec->rate = 44100U;
357             break;
358         case SBC_SAMPLING_FREQ_48000:
359             sbc_info->frequency = SBC_FREQ_48000;
360             sample_spec->rate = 48000U;
361             break;
362         default:
363             pa_assert_not_reached();
364     }
365 
366     switch (config->channel_mode) {
367         case SBC_CHANNEL_MODE_MONO:
368             sbc_info->mode = SBC_MODE_MONO;
369             sample_spec->channels = 1;
370             break;
371         case SBC_CHANNEL_MODE_DUAL_CHANNEL:
372             sbc_info->mode = SBC_MODE_DUAL_CHANNEL;
373             sample_spec->channels = 2;
374             break;
375         case SBC_CHANNEL_MODE_STEREO:
376             sbc_info->mode = SBC_MODE_STEREO;
377             sample_spec->channels = 2;
378             break;
379         case SBC_CHANNEL_MODE_JOINT_STEREO:
380             sbc_info->mode = SBC_MODE_JOINT_STEREO;
381             sample_spec->channels = 2;
382             break;
383         default:
384             pa_assert_not_reached();
385     }
386 
387     switch (config->allocation_method) {
388         case SBC_ALLOCATION_SNR:
389             sbc_info->allocation = SBC_AM_SNR;
390             break;
391         case SBC_ALLOCATION_LOUDNESS:
392             sbc_info->allocation = SBC_AM_LOUDNESS;
393             break;
394         default:
395             pa_assert_not_reached();
396     }
397 
398     switch (config->subbands) {
399         case SBC_SUBBANDS_4:
400             sbc_info->subbands = SBC_SB_4;
401             break;
402         case SBC_SUBBANDS_8:
403             sbc_info->subbands = SBC_SB_8;
404             break;
405         default:
406             pa_assert_not_reached();
407     }
408 
409     switch (config->block_length) {
410         case SBC_BLOCK_LENGTH_4:
411             sbc_info->blocks = SBC_BLK_4;
412             break;
413         case SBC_BLOCK_LENGTH_8:
414             sbc_info->blocks = SBC_BLK_8;
415             break;
416         case SBC_BLOCK_LENGTH_12:
417             sbc_info->blocks = SBC_BLK_12;
418             break;
419         case SBC_BLOCK_LENGTH_16:
420             sbc_info->blocks = SBC_BLK_16;
421             break;
422         default:
423             pa_assert_not_reached();
424     }
425 
426     sbc_info->min_bitpool = config->min_bitpool;
427     sbc_info->max_bitpool = config->max_bitpool;
428 
429     /* Set minimum bitpool for source to get the maximum possible block_size
430      * in get_block_size() function. This block_size is length of buffer used
431      * for decoded audio data and so is inversely proportional to frame length
432      * which depends on bitpool value. Bitpool is controlled by other side from
433      * range [min_bitpool, max_bitpool]. */
434     sbc_info->initial_bitpool = for_encoding ? sbc_info->max_bitpool : sbc_info->min_bitpool;
435 
436     set_params(sbc_info);
437 
438     pa_log_info("SBC parameters: allocation=%s, subbands=%u, blocks=%u, mode=%s bitpool=%u codesize=%u frame_length=%u",
439                 sbc_info->sbc.allocation ? "SNR" : "Loudness", sbc_info->sbc.subbands ? 8 : 4,
440                 (sbc_info->sbc.blocks+1)*4, sbc_info->sbc.mode == SBC_MODE_MONO ? "Mono" :
441                 sbc_info->sbc.mode == SBC_MODE_DUAL_CHANNEL ? "DualChannel" :
442                 sbc_info->sbc.mode == SBC_MODE_STEREO ? "Stereo" : "JointStereo",
443                 sbc_info->sbc.bitpool, (unsigned)sbc_info->codesize, (unsigned)sbc_info->frame_length);
444 
445     return sbc_info;
446 }
447 
deinit(void * codec_info)448 static void deinit(void *codec_info) {
449     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
450 
451     sbc_finish(&sbc_info->sbc);
452     pa_xfree(sbc_info);
453 }
454 
set_bitpool(struct sbc_info * sbc_info,uint8_t bitpool)455 static void set_bitpool(struct sbc_info *sbc_info, uint8_t bitpool) {
456     if (bitpool > sbc_info->max_bitpool)
457         bitpool = sbc_info->max_bitpool;
458     else if (bitpool < sbc_info->min_bitpool)
459         bitpool = sbc_info->min_bitpool;
460 
461     sbc_info->sbc.bitpool = bitpool;
462 
463     sbc_info->codesize = sbc_get_codesize(&sbc_info->sbc);
464     sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
465 
466     pa_log_debug("Bitpool has changed to %u", sbc_info->sbc.bitpool);
467 }
468 
reset(void * codec_info)469 static int reset(void *codec_info) {
470     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
471     int ret;
472 
473     ret = sbc_reinit(&sbc_info->sbc, 0);
474     if (ret != 0) {
475         pa_log_error("SBC reinitialization failed: %d", ret);
476         return -1;
477     }
478 
479     /* sbc_reinit() sets also default parameters, so reset them back */
480     set_params(sbc_info);
481 
482     sbc_info->seq_num = 0;
483     return 0;
484 }
485 
get_block_size(void * codec_info,size_t link_mtu)486 static size_t get_block_size(void *codec_info, size_t link_mtu) {
487     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
488     size_t rtp_size = sizeof(struct rtp_header) + sizeof(struct rtp_sbc_payload);
489     size_t frame_count = (link_mtu - rtp_size) / sbc_info->frame_length;
490 
491     /* frame_count is only 4 bit number */
492     if (frame_count > 15)
493         frame_count = 15;
494 
495     return frame_count * sbc_info->codesize;
496 }
497 
reduce_encoder_bitrate(void * codec_info,size_t write_link_mtu)498 static size_t reduce_encoder_bitrate(void *codec_info, size_t write_link_mtu) {
499     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
500     uint8_t bitpool;
501 
502     /* Check if bitpool is already at its limit */
503     if (sbc_info->sbc.bitpool <= SBC_BITPOOL_DEC_LIMIT)
504         return 0;
505 
506     bitpool = sbc_info->sbc.bitpool - SBC_BITPOOL_DEC_STEP;
507 
508     if (bitpool < SBC_BITPOOL_DEC_LIMIT)
509         bitpool = SBC_BITPOOL_DEC_LIMIT;
510 
511     if (sbc_info->sbc.bitpool == bitpool)
512         return 0;
513 
514     set_bitpool(sbc_info, bitpool);
515     return get_block_size(codec_info, write_link_mtu);
516 }
517 
encode_buffer(void * codec_info,uint32_t timestamp,const uint8_t * input_buffer,size_t input_size,uint8_t * output_buffer,size_t output_size,size_t * processed)518 static size_t encode_buffer(void *codec_info, uint32_t timestamp, const uint8_t *input_buffer, size_t input_size, uint8_t *output_buffer, size_t output_size, size_t *processed) {
519     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
520     struct rtp_header *header;
521     struct rtp_sbc_payload *payload;
522     uint8_t *d;
523     const uint8_t *p;
524     size_t to_write, to_encode;
525     uint8_t frame_count;
526 
527     header = (struct rtp_header*) output_buffer;
528     payload = (struct rtp_sbc_payload*) (output_buffer + sizeof(*header));
529 
530     frame_count = 0;
531 
532     p = input_buffer;
533     to_encode = input_size;
534 
535     d = output_buffer + sizeof(*header) + sizeof(*payload);
536     to_write = output_size - sizeof(*header) - sizeof(*payload);
537 
538     /* frame_count is only 4 bit number */
539     while (PA_LIKELY(to_encode > 0 && to_write > 0 && frame_count < 15)) {
540         ssize_t written;
541         ssize_t encoded;
542 
543         encoded = sbc_encode(&sbc_info->sbc,
544                              p, to_encode,
545                              d, to_write,
546                              &written);
547 
548         if (PA_UNLIKELY(encoded <= 0)) {
549             pa_log_error("SBC encoding error (%li)", (long) encoded);
550             break;
551         }
552 
553         if (PA_UNLIKELY(written < 0)) {
554             pa_log_error("SBC encoding error (%li)", (long) written);
555             break;
556         }
557 
558         pa_assert_fp((size_t) encoded <= to_encode);
559         pa_assert_fp((size_t) encoded == sbc_info->codesize);
560 
561         pa_assert_fp((size_t) written <= to_write);
562         pa_assert_fp((size_t) written == sbc_info->frame_length);
563 
564         p += encoded;
565         to_encode -= encoded;
566 
567         d += written;
568         to_write -= written;
569 
570         frame_count++;
571     }
572 
573     PA_ONCE_BEGIN {
574         pa_log_debug("Using SBC codec implementation: %s", pa_strnull(sbc_get_implementation_info(&sbc_info->sbc)));
575     } PA_ONCE_END;
576 
577     if (PA_UNLIKELY(frame_count == 0)) {
578         *processed = 0;
579         return 0;
580     }
581 
582     /* write it to the fifo */
583     pa_memzero(output_buffer, sizeof(*header) + sizeof(*payload));
584     header->v = 2;
585 
586     /* A2DP spec: "A payload type in the RTP dynamic range shall be chosen".
587      * RFC3551 defines the dynamic range to span from 96 to 127, and 96 appears
588      * to be the most common choice in A2DP implementations. */
589     header->pt = 96;
590 
591     header->sequence_number = htons(sbc_info->seq_num++);
592     header->timestamp = htonl(timestamp);
593     header->ssrc = htonl(1);
594     payload->frame_count = frame_count;
595 
596     *processed = p - input_buffer;
597     return d - output_buffer;
598 }
599 
decode_buffer(void * codec_info,const uint8_t * input_buffer,size_t input_size,uint8_t * output_buffer,size_t output_size,size_t * processed)600 static size_t decode_buffer(void *codec_info, const uint8_t *input_buffer, size_t input_size, uint8_t *output_buffer, size_t output_size, size_t *processed) {
601     struct sbc_info *sbc_info = (struct sbc_info *) codec_info;
602 
603     struct rtp_header *header;
604     struct rtp_sbc_payload *payload;
605     const uint8_t *p;
606     uint8_t *d;
607     size_t to_write, to_decode;
608     uint8_t frame_count;
609 
610     header = (struct rtp_header *) input_buffer;
611     payload = (struct rtp_sbc_payload*) (input_buffer + sizeof(*header));
612 
613     frame_count = payload->frame_count;
614 
615     /* TODO: Add support for decoding fragmented SBC frames */
616     if (payload->is_fragmented) {
617         pa_log_error("Unsupported fragmented SBC frame");
618         *processed = 0;
619         return 0;
620     }
621 
622     p = input_buffer + sizeof(*header) + sizeof(*payload);
623     to_decode = input_size - sizeof(*header) - sizeof(*payload);
624 
625     d = output_buffer;
626     to_write = output_size;
627 
628     while (PA_LIKELY(to_decode > 0 && to_write > 0 && frame_count > 0)) {
629         size_t written;
630         ssize_t decoded;
631 
632         decoded = sbc_decode(&sbc_info->sbc,
633                              p, to_decode,
634                              d, to_write,
635                              &written);
636 
637         if (PA_UNLIKELY(decoded <= 0)) {
638             pa_log_error("SBC decoding error (%li)", (long) decoded);
639             break;
640         }
641 
642         /* Reset frame length, it can be changed due to bitpool change */
643         sbc_info->frame_length = sbc_get_frame_length(&sbc_info->sbc);
644 
645         pa_assert_fp((size_t) decoded <= to_decode);
646         pa_assert_fp((size_t) decoded == sbc_info->frame_length);
647 
648         pa_assert_fp((size_t) written <= to_write);
649         pa_assert_fp((size_t) written == sbc_info->codesize);
650 
651         p += decoded;
652         to_decode -= decoded;
653 
654         d += written;
655         to_write -= written;
656 
657         frame_count--;
658     }
659 
660     *processed = p - input_buffer;
661     return d - output_buffer;
662 }
663 
664 const pa_a2dp_codec pa_a2dp_codec_sbc = {
665     .name = "sbc",
666     .description = "SBC",
667     .id = { A2DP_CODEC_SBC, 0, 0 },
668     .support_backchannel = false,
669     .can_accept_capabilities = can_accept_capabilities,
670     .choose_remote_endpoint = choose_remote_endpoint,
671     .fill_capabilities = fill_capabilities,
672     .is_configuration_valid = is_configuration_valid,
673     .fill_preferred_configuration = fill_preferred_configuration,
674     .init = init,
675     .deinit = deinit,
676     .reset = reset,
677     .get_read_block_size = get_block_size,
678     .get_write_block_size = get_block_size,
679     .reduce_encoder_bitrate = reduce_encoder_bitrate,
680     .encode_buffer = encode_buffer,
681     .decode_buffer = decode_buffer,
682 };
683