Bluetooth A2DP on Linux

– 삽질 기록용 –

라즈베리파이의 블루투스를 사용해서 aux단자 출력을 하려했는데… 연결된 장치에서 전송하는 포맷에따라서 디코딩이 실시간으로 안되어 툭툭 끊기는 현상이있었다(…)

결국 메인 PC에서 사용하고있던 인텔 듀얼링크 무선랜을 때다가 사용하고있는 젠투리눅스에 연결-_-;; (어차피 유선으로 사용하고있었고 블루투스도 연결된 기기가 없기에)

기본적으로 Gentoo Wiki의 이 페이지에 기술된 내용대로 빌드되어있으면 일부 기기(ex 안드로이드)에서 스트리밍되는 음원 재생 문제없지만, TV나 아이폰에서 전송되는 음원을 디코딩하지 못하였다. 대부분 다른 배포본 위주의 설명이라 그냥 감으로 해보았는데… 일단 성공하였다. (아직 해결되어야할게 한가지있지만.)

일단 사용한 pulseaudio의 USE 옵션은 아래와같다. 아마도 libsamplerate 이 USE 옵션이 핵심인거같다. (우분투같은경우 리소스가 너무나도 많으니 패스.)
X alsa alsa-plugin asyncns bluetooth caps dbus gdbm glib gnome gtk ipv6 libsamplerate native-headset orc qt4 realtime ssl systemd tcpd udev webrtc-aec

이제 블루투스에서 오디오를 사용하기 위해서는 아래와같이 설정한다.

/etc/bluetooth/audio.conf (기본적으로 없으므로 생성, 내용출처)

# Configuration file for the audio service

# This section contains options which are not specific to any
# particular interface
[General]

# Switch to master role for incoming connections (defaults to true)
Master=true

# If we want to disable support for specific services
# Defaults to supporting all implemented services
#Disable=Control,Source
Enable=Source

# SCO routing. Either PCM or HCI (in which case audio is routed to/from ALSA)
# Defaults to HCI
#SCORouting=PCM

# Automatically connect both A2DP and HFP/HSP profiles for incoming
# connections. Some headsets that support both profiles will only connect the
# other one automatically so the default setting of true is usually a good
# idea.
AutoConnect=true

# Headset interface specific options (i.e. options which affect how the audio
# service interacts with remote headset devices)
[Headset]

# Set to true to support HFP, false means only HSP is supported
# Defaults to true
HFP=true

# Maximum number of connected HSP/HFP devices per adapter. Defaults to 1
MaxConnected=1

# Just an example of potential config options for the other interfaces
#[A2DP]
#SBCSources=1
#MPEG12Sources=0

/etc/pulse/system.pa (마지막 부분에 추가, 내용출처)

### Automatically load driver modules for Bluetooth hardware
.ifexists module-bluetooth-policy.so
load-module module-bluetooth-policy
.endif

.ifexists module-bluetooth-discover.so
load-module module-bluetooth-discover
.endif

load-module module-switch-on-connect 도 한라인 추가하였다. 정확한 내용은… 기억 안난다. 패스.

마지막으로 아래 github 저장소에서 simple-agent.autotrust, bluezutils.py 두개의 파일을 다운받아서 simple-agent.autotrust를 실행시킨다. (이벤트를 처리안하면 오디오 연결이 안된다.)
https://github.com/BaReinhard/Super-Simple-Raspberry-Pi-Audio-Receiver-Install/tree/master/usr/local/bin

만약 장치이름을 바꾸고싶다면 /etc/bluetooth/main.conf 파일에서 Name을 바꿔주면 되고 DiscoverableTimeout 항목을 0으로 설정하면 discovering를 무한으로 한다. Policy에서 AutoEnable을 true로 설정하는것도 있던데 차이는 모르겠다.

또한 Class 항목을 0x200414로 바꾸면 오디오 장치로 블루투스가 인식된다. 일부 장치는 기본값을 사용하면 스피커 장치가 아니여서 목록에 나타나지않는다. 젠투에서는 Class 값이 적용되지않아 hciconfig hci0 class 0x200414 명령을 실행하여 변경하였다.

systemctl restart bluetooth 명령으로 서비스를 재실행하여 변경된 내용들 적용. (아마 재부팅 해야할수도있다.)

A2DP 스택이 적용되었으면 bluetoothctl에서 show 커맨드를 실행하면 아래와같이 나온다.

Controller 7C:5C:F8:D7:99:7E
        Name: BlueZ Gentoo
        Alias: BlueZ Gentoo
        Class: 0x000000
        Powered: yes
        Discoverable: yes
        Pairable: yes
        UUID: Headset AG                (00001112-0000-1000-8000-00805f9b34fb)
        UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
        UUID: A/V Remote Control        (0000110e-0000-1000-8000-00805f9b34fb)
        UUID: OBEX File Transfer        (00001106-0000-1000-8000-00805f9b34fb)
        UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
        UUID: OBEX Object Push          (00001105-0000-1000-8000-00805f9b34fb)
        UUID: PnP Information           (00001200-0000-1000-8000-00805f9b34fb)
        UUID: A/V Remote Control Target (0000110c-0000-1000-8000-00805f9b34fb)
        UUID: IrMC Sync                 (00001104-0000-1000-8000-00805f9b34fb)
        UUID: Audio Source              (0000110a-0000-1000-8000-00805f9b34fb)
        UUID: Audio Sink                (0000110b-0000-1000-8000-00805f9b34fb)
        UUID: Message Notification Se.. (00001133-0000-1000-8000-00805f9b34fb)
        UUID: Phonebook Access Server   (0000112f-0000-1000-8000-00805f9b34fb)
        UUID: Message Access Server     (00001132-0000-1000-8000-00805f9b34fb)
        Modalias: usb:v1D6Bp0246d052B
        Discovering: no

여기서 중요한것이 Audio Sink.

오디오 장치로 연결이 잘 되었다면 pactl list sources short명령을 치면 아래와같이 나온다.

1       alsa_output.pci-0000_00_1b.0.analog-stereo.monitor      module-alsa-card.c      s16le 2ch 48000Hz       IDLE
2       alsa_input.pci-0000_00_1b.0.analog-stereo       module-alsa-card.c      s16le 2ch 44100Hz       SUSPENDED
3       alsa_output.pci-0000_00_03.0.hdmi-stereo.monitor        module-alsa-card.c      s16le 2ch 44100Hz       SUSPENDED
7       bluez_source.F8_3F_51_27_C2_1F.a2dp_source      module-bluez5-device.c  s16le 2ch 48000Hz       RUNNING

아직은 Gnome Desktop에 사용자가 로그인되어야 음원이 출력되는 문제가있지만… 더 깊이 알아보기 귀찮다. 어차피 24시간 켜놓는것이니까 -_-;;
어차피 두면 잠금화면이 뜨기때문에 걍 다음에 의욕이 생길 때 까진 이렇게 써야겠다.

https://github.com/BaReinhard/Super-Simple-Raspberry-Pi-Audio-Receiver-Install/blob/master/usr/local/bin/volume-watcher.py 이 파일은 AVRCP 이벤트를 처리하는것이지만… 역시나 귀찮…

https://ludwig.im/en/projects/steam-pulseaudio-sound-latency-lagging-problem-noise 이것은 latency를 줄이기 위한 팁

덧) 위와같이 별별삽질 다 해봐야 무선 특유의 지연시간 사라지지않고 결국 그냥 제품으로 잘 나와있는거 사는게 정신건강과 시간적으로 더 이득이라는 생각이 드는건 안비밀. 결국 주머니 사정(…). 일단 두어달 후에 그냥 옵티컬 DAC 잘 나온거 하나 사야겠다 -_-;;

WinCrypt의 핸들은 스레드 안정성이 보장안되는거같다

영어가 안되어 크롬의 번역으로 https://stackoverflow.com/a/10807684 이 댓글을 읽어보니…

ECB 모드로 동작할때는 상태가 변경되지않아 상관없으나 기본 모드인 CBC 모드는 상태정보가 변경되기때문에 안정적이지 않다고 이해된다.
이걸 사용하면서 로직 손을 보고나서는 왜 자꾸 패킷이 깨지나했더니 이런거였구나(…) 이거때문에 거의 한달을 미궁에 빠져있었네 orz

복잡하게 처리할거는 없으니 Semaphore를 사용해서 해결해야겠다(…)

참고로 WinCrypt의 사용법 글은 이글의 바로 전 글