diff --git a/.github/workflows/check_ap2_systemd_basic.yml b/.github/workflows/check_ap2_systemd_basic.yml index 2c61293d..3287a4a6 100644 --- a/.github/workflows/check_ap2_systemd_basic.yml +++ b/.github/workflows/check_ap2_systemd_basic.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install libpipewire-0.3-dev libplist-utils xmltoman libpopt-dev libconfig-dev libasound2-dev avahi-daemon libavahi-client-dev libsoxr-dev libplist-dev libsodium-dev libavutil-dev libavcodec-dev libavformat-dev libgcrypt-dev uuid-dev - name: Configure diff --git a/.github/workflows/check_ap2_systemd_full.yml b/.github/workflows/check_ap2_systemd_full.yml index 7643601d..89f80df9 100644 --- a/.github/workflows/check_ap2_systemd_full.yml +++ b/.github/workflows/check_ap2_systemd_full.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install libglib2.0-dev libplist-utils xmltoman libpopt-dev libconfig-dev libasound2-dev libao-dev libjack-dev libmosquitto-dev avahi-daemon libavahi-client-dev libsoxr-dev libplist-dev libsodium-dev libavutil-dev libavcodec-dev libavformat-dev libgcrypt-dev - name: Configure diff --git a/.github/workflows/check_ap2_systemd_full_build_folder.yml b/.github/workflows/check_ap2_systemd_full_build_folder.yml index e7a94ffe..a541aa72 100644 --- a/.github/workflows/check_ap2_systemd_full_build_folder.yml +++ b/.github/workflows/check_ap2_systemd_full_build_folder.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install libpipewire-0.3-dev libplist-utils xmltoman libpopt-dev libconfig-dev libasound2-dev libao-dev libjack-dev libglib2.0-dev libmosquitto-dev avahi-daemon libavahi-client-dev libssl-dev libsoxr-dev libplist-dev libsodium-dev libavutil-dev libavcodec-dev libavformat-dev libgcrypt-dev - name: Configure diff --git a/.github/workflows/check_ap2_systemv_full.yml b/.github/workflows/check_ap2_systemv_full.yml index 4ef61d26..136275c8 100644 --- a/.github/workflows/check_ap2_systemv_full.yml +++ b/.github/workflows/check_ap2_systemv_full.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install libpipewire-0.3-dev libplist-utils xmltoman libpopt-dev libdaemon-dev libconfig-dev libasound2-dev libao-dev libjack-dev libglib2.0-dev libmosquitto-dev avahi-daemon libavahi-client-dev libssl-dev libsoxr-dev libplist-dev libsodium-dev libavutil-dev libavcodec-dev libavformat-dev uuid-dev libgcrypt-dev - name: Configure diff --git a/.github/workflows/check_classic_mac_basic.yml b/.github/workflows/check_classic_mac_basic.yml index 44f0def6..a9412914 100644 --- a/.github/workflows/check_classic_mac_basic.yml +++ b/.github/workflows/check_classic_mac_basic.yml @@ -11,7 +11,7 @@ jobs: build: runs-on: macos-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: | brew install automake diff --git a/.github/workflows/check_classic_systemd_basic.yml b/.github/workflows/check_classic_systemd_basic.yml index ee198608..6bf3ef98 100644 --- a/.github/workflows/check_classic_systemd_basic.yml +++ b/.github/workflows/check_classic_systemd_basic.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install xmltoman libpopt-dev libconfig-dev libasound2-dev avahi-daemon libavahi-client-dev libssl-dev libsoxr-dev - name: Configure diff --git a/.github/workflows/check_classic_systemd_full.yml b/.github/workflows/check_classic_systemd_full.yml index b3c46588..08070a40 100644 --- a/.github/workflows/check_classic_systemd_full.yml +++ b/.github/workflows/check_classic_systemd_full.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v7.0.0 - name: Install Dependencies run: sudo apt-get -y --no-install-recommends install xmltoman libpipewire-0.3-dev libpopt-dev libconfig-dev libasound2-dev libao-dev libjack-dev libglib2.0-dev libmosquitto-dev avahi-daemon libavahi-client-dev libssl-dev libsoxr-dev libavutil-dev libavcodec-dev libavformat-dev - name: Configure diff --git a/.github/workflows/docker-on-push-tag-or-pr.yaml b/.github/workflows/docker-on-push-tag-or-pr.yaml index c3380f4e..bdd01bf7 100644 --- a/.github/workflows/docker-on-push-tag-or-pr.yaml +++ b/.github/workflows/docker-on-push-tag-or-pr.yaml @@ -38,7 +38,7 @@ jobs: NQPTP_BRANCH=${{ needs.docker-vars.outputs.nqptp_branch }} steps: - name: Checkout shairport sync repo - uses: actions/checkout@v6.0.2 + uses: actions/checkout@v7.0.0 with: fetch-depth: 0 @@ -59,7 +59,7 @@ jobs: fi - name: Login to Docker Registry - uses: docker/login-action@v4.1.0 + uses: docker/login-action@v4.2.0 with: registry: ${{ secrets.DOCKER_REGISTRY }} username: ${{ secrets.DOCKER_REGISTRY_USER }} @@ -67,13 +67,13 @@ jobs: if: needs.docker-vars.outputs.push_docker_image == 'true' - name: Set up QEMU - uses: docker/setup-qemu-action@v4.0.0 + uses: docker/setup-qemu-action@v4.1.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4.0.0 + uses: docker/setup-buildx-action@v4.1.0 - name: Build and push ${{ matrix.name }} - uses: docker/build-push-action@v7.1.0 + uses: docker/build-push-action@v7.2.0 env: registry_and_name: ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_IMAGE_NAME }} with: diff --git a/.github/workflows/docker-vars.yaml b/.github/workflows/docker-vars.yaml index c9f9f8fb..614f70ef 100644 --- a/.github/workflows/docker-vars.yaml +++ b/.github/workflows/docker-vars.yaml @@ -23,7 +23,7 @@ jobs: outputs: nqptp_branch: ${{ env.NQPTP_BRANCH }} push_docker_image: ${{ env.PUSH_DOCKER_IMAGE }} - docker_platforms: linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64 + docker_platforms: linux/386,linux/amd64,linux/arm/v7,linux/arm64 steps: - name: Push docker image if this is a tag. if: github.ref_type == 'tag' diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml index a74358a1..820c8862 100644 --- a/.github/workflows/stale.yaml +++ b/.github/workflows/stale.yaml @@ -11,7 +11,7 @@ jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v10.2.0 + - uses: actions/stale@v10.3.0 with: stale-issue-message: 'This issue has been inactive for 28 days so will be closed 7 days from now. To prevent this, please remove the "stale" label or post a comment.' stale-pr-message: 'This PR has been inactive for 28 days so will be closed 7 days from now. To prevent this, please remove the "stale" label or post a comment.' diff --git a/ADVANCED TOPICS/PulseAudioAndPipeWire.md b/ADVANCED TOPICS/PulseAudioAndPipeWire.md index 9ba50812..e0c99e68 100644 --- a/ADVANCED TOPICS/PulseAudioAndPipeWire.md +++ b/ADVANCED TOPICS/PulseAudioAndPipeWire.md @@ -1,6 +1,9 @@ # Working with PulseAudio or PipeWire Many Linux systems, especially desktop Linuxes with a GUI, have [PipeWire](https://pipewire.org) or [PulseAudio](https://www.freedesktop.org/wiki/Software/PulseAudio/) installed as [sound servers](https://en.wikipedia.org/wiki/Sound_server). -PipeWire and PulseAudio are widely used and have the great advantage of being easily able to mix audio from multiple sources. The slight downside is that audio may be further processed (e.g. transcoded) on its way to the output device. +PipeWire and PulseAudio are widely used and have the great advantage of being easily able to mix audio from multiple sources. + +However, the main thing to remember about PipeWire and PulseAudio sound servers is they only become available when a user logs in -- that is, they are set up as _user services_. +Shairport Sync relies on them and therefore it must also be set up as a user service. Shairport Sync can not be set up as a system service because the PipeWire or PulseAudio services are not available when system services are launched just after system startup. To use PipeWire or PulseAudio-based systems, Shairport Sync must be set up as a user service. @@ -10,26 +13,5 @@ To use PipeWire or PulseAudio-based systems, Shairport Sync must be set up as a 3. To check if PipeWire support is built into Shairport Sync, check that the string `PipeWire` is included in the version string. (Enter `$ shairport-sync -V` to get the version string.) Similarly, the version string will include `PulseAudio` if the PulseAudio backend is built in. 4. Remember to specify which backend Shairport Sync should use in the configuration file or on the command line. -## Automatic Startup of Shairport Sync - -The main thing to remember about PipeWire and PulseAudio sound servers is that the services they offer only become available when a user logs in -- that is, they are set up as _user services_. -Shairport Sync relies on them, so it must also be set up as a user service; it can not be set up as a system service because the PipeWire or PulseAudio services needed by Shairport Sync are not available when system services are launched just after system startup. - -### Starting Shairport Sync as a User Service -To make Shairport Sync start as a user service, (assuming you built and installed Shairport Sync using the BUILD.md guide), ensure you are logged in as the appropriate user and enter: -``` -$ systemctl --user enable shairport-sync -``` -Make sure it is _not enabled_ as a system service: -``` -# systemctl disable shairport-sync -``` -and then reboot. - -#### Problems with User Service -Shairport Sync will function perfectly well as a user service, but there are a number of things to bear in mind: - -1. The AirPlay service will only be available when the user is logged in. When the user logs out, Shairport Sync will terminate and the AirPlay service will disappear. -2. If the Linux system is a desktop Linux with a GUI, audio will be sent to the default output only when the user is logged in through the GUI. - -Automatic user login may help address these problems. +## Starting Shairport Sync as a User Service +Please refer to [this](https://github.com/mikebrady/shairport-sync/blob/development/BUILD.md#5-enable-and-start-service) section to discover how to start Shairport Sync as a user service. diff --git a/BUILD.md b/BUILD.md index e19c70c9..a17727ed 100644 --- a/BUILD.md +++ b/BUILD.md @@ -83,10 +83,14 @@ If you are building classic Shairport Sync, the list of packages is shorter: libpopt-dev libconfig-dev libasound2-dev avahi-daemon libavahi-client-dev libssl-dev libsoxr-dev \ libavutil-dev libavcodec-dev libavformat-dev ``` -Building on Ubuntu 24.10 or Debian 13 ("Trixie") and later – and possibly on other distributions – requires `systemd-dev`. Be very careful here if you are using backports -- there is a [report](https://github.com/mikebrady/shairport-sync/issues/2195#issuecomment-4325326002) that installing `systemd-dev` on a backported system can severely damage it: +Building on Ubuntu 24.10 or Debian 13 ("Trixie") and later – and possibly on other distributions – requires `systemd-dev`. Be very careful here if you are using backports -- there is a [report](https://github.com/mikebrady/shairport-sync/issues/2195#issuecomment-4325326002) that installing `systemd-dev` on a backported system can severely damage it. ``` -# apt install --no-install-recommends systemd-dev +$ apt install --dry-run --no-install-recommends systemd-dev +``` +Only if that looks okay, proceed to: +``` +# apt install --no-install-recommends systemd-dev ``` ### Fedora (Fedora 40) diff --git a/FFTConvolver/AudioFFT.cpp b/FFTConvolver/AudioFFT.cpp old mode 100755 new mode 100644 index 4f013d05..768e8e0f --- a/FFTConvolver/AudioFFT.cpp +++ b/FFTConvolver/AudioFFT.cpp @@ -25,317 +25,258 @@ #include #include - #if defined(AUDIOFFT_APPLE_ACCELERATE) - #define AUDIOFFT_APPLE_ACCELERATE_USED - #include - #include -#elif defined (AUDIOFFT_FFTW3) - #define AUDIOFFT_FFTW3_USED - #include +#define AUDIOFFT_APPLE_ACCELERATE_USED +#include +#include +#elif defined(AUDIOFFT_FFTW3) +#define AUDIOFFT_FFTW3_USED +#include #else - #if !defined(AUDIOFFT_OOURA) - #define AUDIOFFT_OOURA - #endif - #define AUDIOFFT_OOURA_USED - #include +#if !defined(AUDIOFFT_OOURA) +#define AUDIOFFT_OOURA +#endif +#define AUDIOFFT_OOURA_USED +#include #endif +namespace audiofft { -namespace audiofft -{ +namespace detail { - namespace detail - { +class AudioFFTImpl { +public: + AudioFFTImpl() = default; + AudioFFTImpl(const AudioFFTImpl &) = delete; + AudioFFTImpl &operator=(const AudioFFTImpl &) = delete; + virtual ~AudioFFTImpl() = default; + virtual void init(size_t size) = 0; + virtual void fft(const float *data, float *re, float *im) = 0; + virtual void ifft(float *data, const float *re, const float *im) = 0; +}; - class AudioFFTImpl - { - public: - AudioFFTImpl() = default; - AudioFFTImpl(const AudioFFTImpl&) = delete; - AudioFFTImpl& operator=(const AudioFFTImpl&) = delete; - virtual ~AudioFFTImpl() = default; - virtual void init(size_t size) = 0; - virtual void fft(const float* data, float* re, float* im) = 0; - virtual void ifft(float* data, const float* re, const float* im) = 0; - }; +constexpr bool IsPowerOf2(size_t val) { return (val == 1 || (val & (val - 1)) == 0); } +template +void ConvertBuffer(TypeDest *dest, const TypeSrc *src, size_t len) { + for (size_t i = 0; i < len; ++i) { + dest[i] = static_cast(src[i]); + } +} - constexpr bool IsPowerOf2(size_t val) - { - return (val == 1 || (val & (val-1)) == 0); - } +template +void ScaleBuffer(TypeDest *dest, const TypeSrc *src, const TypeFactor factor, size_t len) { + for (size_t i = 0; i < len; ++i) { + dest[i] = static_cast(static_cast(src[i]) * factor); + } +} +} // End of namespace detail - template - void ConvertBuffer(TypeDest* dest, const TypeSrc* src, size_t len) - { - for (size_t i=0; i(src[i]); - } - } - - - template - void ScaleBuffer(TypeDest* dest, const TypeSrc* src, const TypeFactor factor, size_t len) - { - for (size_t i=0; i(static_cast(src[i]) * factor); - } - } - - } // End of namespace detail - - - // ================================================================ - +// ================================================================ #ifdef AUDIOFFT_OOURA_USED - /** - * @internal - * @class OouraFFT - * @brief FFT implementation based on the great radix-4 routines by Takuya Ooura - */ - class OouraFFT : public detail::AudioFFTImpl - { - public: - OouraFFT() : - detail::AudioFFTImpl(), - _size(0), - _ip(), - _w(), - _buffer() - { +/** + * @internal + * @class OouraFFT + * @brief FFT implementation based on the great radix-4 routines by Takuya Ooura + */ +class OouraFFT : public detail::AudioFFTImpl { +public: + OouraFFT() : detail::AudioFFTImpl(), _size(0), _ip(), _w(), _buffer() {} + + OouraFFT(const OouraFFT &) = delete; + OouraFFT &operator=(const OouraFFT &) = delete; + + virtual void init(size_t size) override { + if (_size != size) { + _ip.resize(2 + static_cast(std::sqrt(static_cast(size)))); + _w.resize(size / 2); + _buffer.resize(size); + _size = size; + + const int size4 = static_cast(_size) / 4; + makewt(size4, _ip.data(), _w.data()); + makect(size4, _ip.data(), _w.data() + size4); } + } - OouraFFT(const OouraFFT&) = delete; - OouraFFT& operator=(const OouraFFT&) = delete; + virtual void fft(const float *data, float *re, float *im) override { + // Convert into the format as required by the Ooura FFT + detail::ConvertBuffer(_buffer.data(), data, _size); - virtual void init(size_t size) override + rdft(static_cast(_size), +1, _buffer.data(), _ip.data(), _w.data()); + + // Convert back to split-complex { - if (_size != size) - { - _ip.resize(2 + static_cast(std::sqrt(static_cast(size)))); - _w.resize(size / 2); - _buffer.resize(size); - _size = size; - - const int size4 = static_cast(_size) / 4; - makewt(size4, _ip.data(), _w.data()); - makect(size4, _ip.data(), _w.data() + size4); + double *b = _buffer.data(); + double *bEnd = b + _size; + float *r = re; + float *i = im; + while (b != bEnd) { + *(r++) = static_cast(*(b++)); + *(i++) = static_cast(-(*(b++))); } } + const size_t size2 = _size / 2; + re[size2] = -im[0]; + im[0] = 0.0; + im[size2] = 0.0; + } - virtual void fft(const float* data, float* re, float* im) override + virtual void ifft(float *data, const float *re, const float *im) override { + // Convert into the format as required by the Ooura FFT { - // Convert into the format as required by the Ooura FFT - detail::ConvertBuffer(_buffer.data(), data, _size); - - rdft(static_cast(_size), +1, _buffer.data(), _ip.data(), _w.data()); - - // Convert back to split-complex - { - double* b = _buffer.data(); - double* bEnd = b + _size; - float *r = re; - float *i = im; - while (b != bEnd) - { - *(r++) = static_cast(*(b++)); - *(i++) = static_cast(-(*(b++))); - } + double *b = _buffer.data(); + double *bEnd = b + _size; + const float *r = re; + const float *i = im; + while (b != bEnd) { + *(b++) = static_cast(*(r++)); + *(b++) = -static_cast(*(i++)); } - const size_t size2 = _size / 2; - re[size2] = -im[0]; - im[0] = 0.0; - im[size2] = 0.0; + _buffer[1] = re[_size / 2]; } - virtual void ifft(float* data, const float* re, const float* im) override - { - // Convert into the format as required by the Ooura FFT - { - double* b = _buffer.data(); - double* bEnd = b + _size; - const float *r = re; - const float *i = im; - while (b != bEnd) - { - *(b++) = static_cast(*(r++)); - *(b++) = -static_cast(*(i++)); - } - _buffer[1] = re[_size / 2]; + rdft(static_cast(_size), -1, _buffer.data(), _ip.data(), _w.data()); + + // Convert back to split-complex + detail::ScaleBuffer(data, _buffer.data(), 2.0 / static_cast(_size), _size); + } + +private: + size_t _size; + std::vector _ip; + std::vector _w; + std::vector _buffer; + + void rdft(int n, int isgn, double *a, int *ip, double *w) { + int nw = ip[0]; + int nc = ip[1]; + + if (isgn >= 0) { + if (n > 4) { + bitrv2(n, ip + 2, a); + cftfsub(n, a, w); + rftfsub(n, a, nc, w + nw); + } else if (n == 4) { + cftfsub(n, a, w); } - - rdft(static_cast(_size), -1, _buffer.data(), _ip.data(), _w.data()); - - // Convert back to split-complex - detail::ScaleBuffer(data, _buffer.data(), 2.0 / static_cast(_size), _size); - } - - private: - size_t _size; - std::vector _ip; - std::vector _w; - std::vector _buffer; - - void rdft(int n, int isgn, double *a, int *ip, double *w) - { - int nw = ip[0]; - int nc = ip[1]; - - if (isgn >= 0) - { - if (n > 4) - { - bitrv2(n, ip + 2, a); - cftfsub(n, a, w); - rftfsub(n, a, nc, w + nw); - } - else if (n == 4) - { - cftfsub(n, a, w); - } - double xi = a[0] - a[1]; - a[0] += a[1]; - a[1] = xi; - } - else - { - a[1] = 0.5 * (a[0] - a[1]); - a[0] -= a[1]; - if (n > 4) - { - rftbsub(n, a, nc, w + nw); - bitrv2(n, ip + 2, a); - cftbsub(n, a, w); - } - else if (n == 4) - { - cftfsub(n, a, w); - } + double xi = a[0] - a[1]; + a[0] += a[1]; + a[1] = xi; + } else { + a[1] = 0.5 * (a[0] - a[1]); + a[0] -= a[1]; + if (n > 4) { + rftbsub(n, a, nc, w + nw); + bitrv2(n, ip + 2, a); + cftbsub(n, a, w); + } else if (n == 4) { + cftfsub(n, a, w); } } + } + /* -------- initializing routines -------- */ - /* -------- initializing routines -------- */ + void makewt(int nw, int *ip, double *w) { + int j, nwh; + double delta, x, y; - void makewt(int nw, int *ip, double *w) - { - int j, nwh; - double delta, x, y; - - ip[0] = nw; - ip[1] = 1; - if (nw > 2) { - nwh = nw >> 1; - delta = atan(1.0) / nwh; - w[0] = 1; - w[1] = 0; - w[nwh] = cos(delta * nwh); - w[nwh + 1] = w[nwh]; - if (nwh > 2) { - for (j = 2; j < nwh; j += 2) { - x = cos(delta * j); - y = sin(delta * j); - w[j] = x; - w[j + 1] = y; - w[nw - j] = y; - w[nw - j + 1] = x; - } - bitrv2(nw, ip + 2, w); + ip[0] = nw; + ip[1] = 1; + if (nw > 2) { + nwh = nw >> 1; + delta = atan(1.0) / nwh; + w[0] = 1; + w[1] = 0; + w[nwh] = cos(delta * nwh); + w[nwh + 1] = w[nwh]; + if (nwh > 2) { + for (j = 2; j < nwh; j += 2) { + x = cos(delta * j); + y = sin(delta * j); + w[j] = x; + w[j + 1] = y; + w[nw - j] = y; + w[nw - j + 1] = x; } + bitrv2(nw, ip + 2, w); } } + } + void makect(int nc, int *ip, double *c) { + int j, nch; + double delta; - void makect(int nc, int *ip, double *c) - { - int j, nch; - double delta; - - ip[1] = nc; - if (nc > 1) { - nch = nc >> 1; - delta = atan(1.0) / nch; - c[0] = cos(delta * nch); - c[nch] = 0.5 * c[0]; - for (j = 1; j < nch; j++) { - c[j] = 0.5 * cos(delta * j); - c[nc - j] = 0.5 * sin(delta * j); - } + ip[1] = nc; + if (nc > 1) { + nch = nc >> 1; + delta = atan(1.0) / nch; + c[0] = cos(delta * nch); + c[nch] = 0.5 * c[0]; + for (j = 1; j < nch; j++) { + c[j] = 0.5 * cos(delta * j); + c[nc - j] = 0.5 * sin(delta * j); } } + } + /* -------- child routines -------- */ - /* -------- child routines -------- */ + void bitrv2(int n, int *ip, double *a) { + int j, j1, k, k1, l, m, m2; + double xr, xi, yr, yi; - - void bitrv2(int n, int *ip, double *a) - { - int j, j1, k, k1, l, m, m2; - double xr, xi, yr, yi; - - ip[0] = 0; - l = n; - m = 1; - while ((m << 3) < l) { - l >>= 1; - for (j = 0; j < m; j++) { - ip[m + j] = ip[j] + l; - } - m <<= 1; + ip[0] = 0; + l = n; + m = 1; + while ((m << 3) < l) { + l >>= 1; + for (j = 0; j < m; j++) { + ip[m + j] = ip[j] + l; } - m2 = 2 * m; - if ((m << 3) == l) { - for (k = 0; k < m; k++) { - for (j = 0; j < k; j++) { - j1 = 2 * j + ip[k]; - k1 = 2 * k + ip[j]; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - j1 += m2; - k1 += 2 * m2; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - j1 += m2; - k1 -= m2; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - j1 += m2; - k1 += 2 * m2; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - } - j1 = 2 * k + m2 + ip[k]; - k1 = j1 + m2; + m <<= 1; + } + m2 = 2 * m; + if ((m << 3) == l) { + for (k = 0; k < m; k++) { + for (j = 0; j < k; j++) { + j1 = 2 * j + ip[k]; + k1 = 2 * k + ip[j]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 -= m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; xr = a[j1]; xi = a[j1 + 1]; yr = a[k1]; @@ -345,247 +286,59 @@ namespace audiofft a[k1] = xr; a[k1 + 1] = xi; } - } else { - for (k = 1; k < m; k++) { - for (j = 0; j < k; j++) { - j1 = 2 * j + ip[k]; - k1 = 2 * k + ip[j]; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - j1 += m2; - k1 += m2; - xr = a[j1]; - xi = a[j1 + 1]; - yr = a[k1]; - yi = a[k1 + 1]; - a[j1] = yr; - a[j1 + 1] = yi; - a[k1] = xr; - a[k1 + 1] = xi; - } + j1 = 2 * k + m2 + ip[k]; + k1 = j1 + m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + } else { + for (k = 1; k < m; k++) { + for (j = 0; j < k; j++) { + j1 = 2 * j + ip[k]; + k1 = 2 * k + ip[j]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; } } } + } + void cftfsub(int n, double *a, double *w) { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; - void cftfsub(int n, double *a, double *w) - { - int j, j1, j2, j3, l; - double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; - - l = 2; - if (n > 8) { - cft1st(n, a, w); - l = 8; - while ((l << 2) < n) { - cftmdl(n, l, a, w); - l <<= 2; - } - } - if ((l << 2) == n) { - for (j = 0; j < l; j += 2) { - j1 = j + l; - j2 = j1 + l; - j3 = j2 + l; - x0r = a[j] + a[j1]; - x0i = a[j + 1] + a[j1 + 1]; - x1r = a[j] - a[j1]; - x1i = a[j + 1] - a[j1 + 1]; - x2r = a[j2] + a[j3]; - x2i = a[j2 + 1] + a[j3 + 1]; - x3r = a[j2] - a[j3]; - x3i = a[j2 + 1] - a[j3 + 1]; - a[j] = x0r + x2r; - a[j + 1] = x0i + x2i; - a[j2] = x0r - x2r; - a[j2 + 1] = x0i - x2i; - a[j1] = x1r - x3i; - a[j1 + 1] = x1i + x3r; - a[j3] = x1r + x3i; - a[j3 + 1] = x1i - x3r; - } - } else { - for (j = 0; j < l; j += 2) { - j1 = j + l; - x0r = a[j] - a[j1]; - x0i = a[j + 1] - a[j1 + 1]; - a[j] += a[j1]; - a[j + 1] += a[j1 + 1]; - a[j1] = x0r; - a[j1 + 1] = x0i; - } + l = 2; + if (n > 8) { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) { + cftmdl(n, l, a, w); + l <<= 2; } } - - - void cftbsub(int n, double *a, double *w) - { - int j, j1, j2, j3, l; - double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; - - l = 2; - if (n > 8) { - cft1st(n, a, w); - l = 8; - while ((l << 2) < n) { - cftmdl(n, l, a, w); - l <<= 2; - } - } - if ((l << 2) == n) { - for (j = 0; j < l; j += 2) { - j1 = j + l; - j2 = j1 + l; - j3 = j2 + l; - x0r = a[j] + a[j1]; - x0i = -a[j + 1] - a[j1 + 1]; - x1r = a[j] - a[j1]; - x1i = -a[j + 1] + a[j1 + 1]; - x2r = a[j2] + a[j3]; - x2i = a[j2 + 1] + a[j3 + 1]; - x3r = a[j2] - a[j3]; - x3i = a[j2 + 1] - a[j3 + 1]; - a[j] = x0r + x2r; - a[j + 1] = x0i - x2i; - a[j2] = x0r - x2r; - a[j2 + 1] = x0i + x2i; - a[j1] = x1r - x3i; - a[j1 + 1] = x1i - x3r; - a[j3] = x1r + x3i; - a[j3 + 1] = x1i + x3r; - } - } else { - for (j = 0; j < l; j += 2) { - j1 = j + l; - x0r = a[j] - a[j1]; - x0i = -a[j + 1] + a[j1 + 1]; - a[j] += a[j1]; - a[j + 1] = -a[j + 1] - a[j1 + 1]; - a[j1] = x0r; - a[j1 + 1] = x0i; - } - } - } - - - void cft1st(int n, double *a, double *w) - { - int j, k1, k2; - double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; - double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; - - x0r = a[0] + a[2]; - x0i = a[1] + a[3]; - x1r = a[0] - a[2]; - x1i = a[1] - a[3]; - x2r = a[4] + a[6]; - x2i = a[5] + a[7]; - x3r = a[4] - a[6]; - x3i = a[5] - a[7]; - a[0] = x0r + x2r; - a[1] = x0i + x2i; - a[4] = x0r - x2r; - a[5] = x0i - x2i; - a[2] = x1r - x3i; - a[3] = x1i + x3r; - a[6] = x1r + x3i; - a[7] = x1i - x3r; - wk1r = w[2]; - x0r = a[8] + a[10]; - x0i = a[9] + a[11]; - x1r = a[8] - a[10]; - x1i = a[9] - a[11]; - x2r = a[12] + a[14]; - x2i = a[13] + a[15]; - x3r = a[12] - a[14]; - x3i = a[13] - a[15]; - a[8] = x0r + x2r; - a[9] = x0i + x2i; - a[12] = x2i - x0i; - a[13] = x0r - x2r; - x0r = x1r - x3i; - x0i = x1i + x3r; - a[10] = wk1r * (x0r - x0i); - a[11] = wk1r * (x0r + x0i); - x0r = x3i + x1r; - x0i = x3r - x1i; - a[14] = wk1r * (x0i - x0r); - a[15] = wk1r * (x0i + x0r); - k1 = 0; - for (j = 16; j < n; j += 16) { - k1 += 2; - k2 = 2 * k1; - wk2r = w[k1]; - wk2i = w[k1 + 1]; - wk1r = w[k2]; - wk1i = w[k2 + 1]; - wk3r = wk1r - 2 * wk2i * wk1i; - wk3i = 2 * wk2i * wk1r - wk1i; - x0r = a[j] + a[j + 2]; - x0i = a[j + 1] + a[j + 3]; - x1r = a[j] - a[j + 2]; - x1i = a[j + 1] - a[j + 3]; - x2r = a[j + 4] + a[j + 6]; - x2i = a[j + 5] + a[j + 7]; - x3r = a[j + 4] - a[j + 6]; - x3i = a[j + 5] - a[j + 7]; - a[j] = x0r + x2r; - a[j + 1] = x0i + x2i; - x0r -= x2r; - x0i -= x2i; - a[j + 4] = wk2r * x0r - wk2i * x0i; - a[j + 5] = wk2r * x0i + wk2i * x0r; - x0r = x1r - x3i; - x0i = x1i + x3r; - a[j + 2] = wk1r * x0r - wk1i * x0i; - a[j + 3] = wk1r * x0i + wk1i * x0r; - x0r = x1r + x3i; - x0i = x1i - x3r; - a[j + 6] = wk3r * x0r - wk3i * x0i; - a[j + 7] = wk3r * x0i + wk3i * x0r; - wk1r = w[k2 + 2]; - wk1i = w[k2 + 3]; - wk3r = wk1r - 2 * wk2r * wk1i; - wk3i = 2 * wk2r * wk1r - wk1i; - x0r = a[j + 8] + a[j + 10]; - x0i = a[j + 9] + a[j + 11]; - x1r = a[j + 8] - a[j + 10]; - x1i = a[j + 9] - a[j + 11]; - x2r = a[j + 12] + a[j + 14]; - x2i = a[j + 13] + a[j + 15]; - x3r = a[j + 12] - a[j + 14]; - x3i = a[j + 13] - a[j + 15]; - a[j + 8] = x0r + x2r; - a[j + 9] = x0i + x2i; - x0r -= x2r; - x0i -= x2i; - a[j + 12] = -wk2i * x0r - wk2r * x0i; - a[j + 13] = -wk2i * x0i + wk2r * x0r; - x0r = x1r - x3i; - x0i = x1i + x3r; - a[j + 10] = wk1r * x0r - wk1i * x0i; - a[j + 11] = wk1r * x0i + wk1i * x0r; - x0r = x1r + x3i; - x0i = x1i - x3r; - a[j + 14] = wk3r * x0r - wk3i * x0i; - a[j + 15] = wk3r * x0i + wk3i * x0r; - } - } - - - void cftmdl(int n, int l, double *a, double *w) - { - int j, j1, j2, j3, k, k1, k2, m, m2; - double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; - double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; - - m = l << 2; + if ((l << 2) == n) { for (j = 0; j < l; j += 2) { j1 = j + l; j2 = j1 + l; @@ -607,8 +360,235 @@ namespace audiofft a[j3] = x1r + x3i; a[j3 + 1] = x1i - x3r; } - wk1r = w[2]; - for (j = m; j < l + m; j += 2) { + } else { + for (j = 0; j < l; j += 2) { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = a[j + 1] - a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] += a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + void cftbsub(int n, double *a, double *w) { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + l = 2; + if (n > 8) { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) { + cftmdl(n, l, a, w); + l <<= 2; + } + } + if ((l << 2) == n) { + for (j = 0; j < l; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = -a[j + 1] - a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = -a[j + 1] + a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i - x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i + x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i - x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i + x3r; + } + } else { + for (j = 0; j < l; j += 2) { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = -a[j + 1] + a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] = -a[j + 1] - a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + void cft1st(int n, double *a, double *w) { + int j, k1, k2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + x0r = a[0] + a[2]; + x0i = a[1] + a[3]; + x1r = a[0] - a[2]; + x1i = a[1] - a[3]; + x2r = a[4] + a[6]; + x2i = a[5] + a[7]; + x3r = a[4] - a[6]; + x3i = a[5] - a[7]; + a[0] = x0r + x2r; + a[1] = x0i + x2i; + a[4] = x0r - x2r; + a[5] = x0i - x2i; + a[2] = x1r - x3i; + a[3] = x1i + x3r; + a[6] = x1r + x3i; + a[7] = x1i - x3r; + wk1r = w[2]; + x0r = a[8] + a[10]; + x0i = a[9] + a[11]; + x1r = a[8] - a[10]; + x1i = a[9] - a[11]; + x2r = a[12] + a[14]; + x2i = a[13] + a[15]; + x3r = a[12] - a[14]; + x3i = a[13] - a[15]; + a[8] = x0r + x2r; + a[9] = x0i + x2i; + a[12] = x2i - x0i; + a[13] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[10] = wk1r * (x0r - x0i); + a[11] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[14] = wk1r * (x0i - x0r); + a[15] = wk1r * (x0i + x0r); + k1 = 0; + for (j = 16; j < n; j += 16) { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + x0r = a[j] + a[j + 2]; + x0i = a[j + 1] + a[j + 3]; + x1r = a[j] - a[j + 2]; + x1i = a[j + 1] - a[j + 3]; + x2r = a[j + 4] + a[j + 6]; + x2i = a[j + 5] + a[j + 7]; + x3r = a[j + 4] - a[j + 6]; + x3i = a[j + 5] - a[j + 7]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 4] = wk2r * x0r - wk2i * x0i; + a[j + 5] = wk2r * x0i + wk2i * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 2] = wk1r * x0r - wk1i * x0i; + a[j + 3] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 6] = wk3r * x0r - wk3i * x0i; + a[j + 7] = wk3r * x0i + wk3i * x0r; + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + x0r = a[j + 8] + a[j + 10]; + x0i = a[j + 9] + a[j + 11]; + x1r = a[j + 8] - a[j + 10]; + x1i = a[j + 9] - a[j + 11]; + x2r = a[j + 12] + a[j + 14]; + x2i = a[j + 13] + a[j + 15]; + x3r = a[j + 12] - a[j + 14]; + x3i = a[j + 13] - a[j + 15]; + a[j + 8] = x0r + x2r; + a[j + 9] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 12] = -wk2i * x0r - wk2r * x0i; + a[j + 13] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 10] = wk1r * x0r - wk1i * x0i; + a[j + 11] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 14] = wk3r * x0r - wk3i * x0i; + a[j + 15] = wk3r * x0i + wk3i * x0r; + } + } + + void cftmdl(int n, int l, double *a, double *w) { + int j, j1, j2, j3, k, k1, k2, m, m2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + m = l << 2; + for (j = 0; j < l; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i - x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i + x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i - x3r; + } + wk1r = w[2]; + for (j = m; j < l + m; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x2i - x0i; + a[j2 + 1] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * (x0r - x0i); + a[j1 + 1] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[j3] = wk1r * (x0i - x0r); + a[j3 + 1] = wk1r * (x0i + x0r); + } + k1 = 0; + m2 = 2 * m; + for (k = m2; k < n; k += m2) { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + for (j = k; j < l + k; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; @@ -622,420 +602,308 @@ namespace audiofft x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; - a[j2] = x2i - x0i; - a[j2 + 1] = x0r - x2r; + x0r -= x2r; + x0i -= x2i; + a[j2] = wk2r * x0r - wk2i * x0i; + a[j2 + 1] = wk2r * x0i + wk2i * x0r; x0r = x1r - x3i; x0i = x1i + x3r; - a[j1] = wk1r * (x0r - x0i); - a[j1 + 1] = wk1r * (x0r + x0i); - x0r = x3i + x1r; - x0i = x3r - x1i; - a[j3] = wk1r * (x0i - x0r); - a[j3 + 1] = wk1r * (x0i + x0r); + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; } - k1 = 0; - m2 = 2 * m; - for (k = m2; k < n; k += m2) { - k1 += 2; - k2 = 2 * k1; - wk2r = w[k1]; - wk2i = w[k1 + 1]; - wk1r = w[k2]; - wk1i = w[k2 + 1]; - wk3r = wk1r - 2 * wk2i * wk1i; - wk3i = 2 * wk2i * wk1r - wk1i; - for (j = k; j < l + k; j += 2) { - j1 = j + l; - j2 = j1 + l; - j3 = j2 + l; - x0r = a[j] + a[j1]; - x0i = a[j + 1] + a[j1 + 1]; - x1r = a[j] - a[j1]; - x1i = a[j + 1] - a[j1 + 1]; - x2r = a[j2] + a[j3]; - x2i = a[j2 + 1] + a[j3 + 1]; - x3r = a[j2] - a[j3]; - x3i = a[j2 + 1] - a[j3 + 1]; - a[j] = x0r + x2r; - a[j + 1] = x0i + x2i; - x0r -= x2r; - x0i -= x2i; - a[j2] = wk2r * x0r - wk2i * x0i; - a[j2 + 1] = wk2r * x0i + wk2i * x0r; - x0r = x1r - x3i; - x0i = x1i + x3r; - a[j1] = wk1r * x0r - wk1i * x0i; - a[j1 + 1] = wk1r * x0i + wk1i * x0r; - x0r = x1r + x3i; - x0i = x1i - x3r; - a[j3] = wk3r * x0r - wk3i * x0i; - a[j3 + 1] = wk3r * x0i + wk3i * x0r; - } - wk1r = w[k2 + 2]; - wk1i = w[k2 + 3]; - wk3r = wk1r - 2 * wk2r * wk1i; - wk3i = 2 * wk2r * wk1r - wk1i; - for (j = k + m; j < l + (k + m); j += 2) { - j1 = j + l; - j2 = j1 + l; - j3 = j2 + l; - x0r = a[j] + a[j1]; - x0i = a[j + 1] + a[j1 + 1]; - x1r = a[j] - a[j1]; - x1i = a[j + 1] - a[j1 + 1]; - x2r = a[j2] + a[j3]; - x2i = a[j2 + 1] + a[j3 + 1]; - x3r = a[j2] - a[j3]; - x3i = a[j2 + 1] - a[j3 + 1]; - a[j] = x0r + x2r; - a[j + 1] = x0i + x2i; - x0r -= x2r; - x0i -= x2i; - a[j2] = -wk2i * x0r - wk2r * x0i; - a[j2 + 1] = -wk2i * x0i + wk2r * x0r; - x0r = x1r - x3i; - x0i = x1i + x3r; - a[j1] = wk1r * x0r - wk1i * x0i; - a[j1 + 1] = wk1r * x0i + wk1i * x0r; - x0r = x1r + x3i; - x0i = x1i - x3r; - a[j3] = wk3r * x0r - wk3i * x0i; - a[j3 + 1] = wk3r * x0i + wk3i * x0r; - } + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + for (j = k + m; j < l + (k + m); j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j2] = -wk2i * x0r - wk2r * x0i; + a[j2 + 1] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; } } + } + void rftfsub(int n, double *a, int nc, double *c) { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; - void rftfsub(int n, double *a, int nc, double *c) - { - int j, k, kk, ks, m; - double wkr, wki, xr, xi, yr, yi; - - m = n >> 1; - ks = 2 * nc / m; - kk = 0; - for (j = 2; j < m; j += 2) { - k = n - j; - kk += ks; - wkr = 0.5 - c[nc - kk]; - wki = c[kk]; - xr = a[j] - a[k]; - xi = a[j + 1] + a[k + 1]; - yr = wkr * xr - wki * xi; - yi = wkr * xi + wki * xr; - a[j] -= yr; - a[j + 1] -= yi; - a[k] += yr; - a[k + 1] -= yi; - } + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) { + k = n - j; + kk += ks; + wkr = 0.5 - c[nc - kk]; + wki = c[kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr - wki * xi; + yi = wkr * xi + wki * xr; + a[j] -= yr; + a[j + 1] -= yi; + a[k] += yr; + a[k + 1] -= yi; } + } + void rftbsub(int n, double *a, int nc, double *c) { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; - void rftbsub(int n, double *a, int nc, double *c) - { - int j, k, kk, ks, m; - double wkr, wki, xr, xi, yr, yi; - - a[1] = -a[1]; - m = n >> 1; - ks = 2 * nc / m; - kk = 0; - for (j = 2; j < m; j += 2) { - k = n - j; - kk += ks; - wkr = 0.5 - c[nc - kk]; - wki = c[kk]; - xr = a[j] - a[k]; - xi = a[j + 1] + a[k + 1]; - yr = wkr * xr + wki * xi; - yi = wkr * xi - wki * xr; - a[j] -= yr; - a[j + 1] = yi - a[j + 1]; - a[k] += yr; - a[k + 1] = yi - a[k + 1]; - } - a[m + 1] = -a[m + 1]; + a[1] = -a[1]; + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) { + k = n - j; + kk += ks; + wkr = 0.5 - c[nc - kk]; + wki = c[kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr + wki * xi; + yi = wkr * xi - wki * xr; + a[j] -= yr; + a[j + 1] = yi - a[j + 1]; + a[k] += yr; + a[k + 1] = yi - a[k + 1]; } - }; - - - /** - * @internal - * @brief Concrete FFT implementation - */ - typedef OouraFFT AudioFFTImplementation; + a[m + 1] = -a[m + 1]; + } +}; +/** + * @internal + * @brief Concrete FFT implementation + */ +typedef OouraFFT AudioFFTImplementation; #endif // AUDIOFFT_OOURA_USED - - // ================================================================ - +// ================================================================ #ifdef AUDIOFFT_APPLE_ACCELERATE_USED +/** + * @internal + * @class AppleAccelerateFFT + * @brief FFT implementation using the Apple Accelerate framework internally + */ +class AppleAccelerateFFT : public detail::AudioFFTImpl { +public: + AppleAccelerateFFT() + : detail::AudioFFTImpl(), _size(0), _powerOf2(0), _fftSetup(0), _re(), _im() {} - /** - * @internal - * @class AppleAccelerateFFT - * @brief FFT implementation using the Apple Accelerate framework internally - */ - class AppleAccelerateFFT : public detail::AudioFFTImpl - { - public: - AppleAccelerateFFT() : - detail::AudioFFTImpl(), - _size(0), - _powerOf2(0), - _fftSetup(0), - _re(), - _im() - { + AppleAccelerateFFT(const AppleAccelerateFFT &) = delete; + AppleAccelerateFFT &operator=(const AppleAccelerateFFT &) = delete; + + virtual ~AppleAccelerateFFT() { init(0); } + + virtual void init(size_t size) override { + if (_fftSetup) { + vDSP_destroy_fftsetup(_fftSetup); + _size = 0; + _powerOf2 = 0; + _fftSetup = 0; + _re.clear(); + _im.clear(); } - AppleAccelerateFFT(const AppleAccelerateFFT&) = delete; - AppleAccelerateFFT& operator=(const AppleAccelerateFFT&) = delete; - - virtual ~AppleAccelerateFFT() - { - init(0); - } - - virtual void init(size_t size) override - { - if (_fftSetup) - { - vDSP_destroy_fftsetup(_fftSetup); - _size = 0; - _powerOf2 = 0; - _fftSetup = 0; - _re.clear(); - _im.clear(); - } - - if (size > 0) - { - _size = size; - _powerOf2 = 0; - while ((1 << _powerOf2) < _size) - { - ++_powerOf2; - } - _fftSetup = vDSP_create_fftsetup(_powerOf2, FFT_RADIX2); - _re.resize(_size / 2); - _im.resize(_size / 2); + if (size > 0) { + _size = size; + _powerOf2 = 0; + while ((1 << _powerOf2) < _size) { + ++_powerOf2; } + _fftSetup = vDSP_create_fftsetup(_powerOf2, FFT_RADIX2); + _re.resize(_size / 2); + _im.resize(_size / 2); } + } - virtual void fft(const float* data, float* re, float* im) override - { - const size_t size2 = _size / 2; - DSPSplitComplex splitComplex; - splitComplex.realp = re; - splitComplex.imagp = im; - vDSP_ctoz(reinterpret_cast(data), 2, &splitComplex, 1, size2); - vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_FORWARD); - const float factor = 0.5f; - vDSP_vsmul(re, 1, &factor, re, 1, size2); - vDSP_vsmul(im, 1, &factor, im, 1, size2); - re[size2] = im[0]; - im[0] = 0.0f; - im[size2] = 0.0f; - } + virtual void fft(const float *data, float *re, float *im) override { + const size_t size2 = _size / 2; + DSPSplitComplex splitComplex; + splitComplex.realp = re; + splitComplex.imagp = im; + vDSP_ctoz(reinterpret_cast(data), 2, &splitComplex, 1, size2); + vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_FORWARD); + const float factor = 0.5f; + vDSP_vsmul(re, 1, &factor, re, 1, size2); + vDSP_vsmul(im, 1, &factor, im, 1, size2); + re[size2] = im[0]; + im[0] = 0.0f; + im[size2] = 0.0f; + } - virtual void ifft(float* data, const float* re, const float* im) override - { - const size_t size2 = _size / 2; - ::memcpy(_re.data(), re, size2 * sizeof(float)); - ::memcpy(_im.data(), im, size2 * sizeof(float)); - _im[0] = re[size2]; - DSPSplitComplex splitComplex; - splitComplex.realp = _re.data(); - splitComplex.imagp = _im.data(); - vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_INVERSE); - vDSP_ztoc(&splitComplex, 1, reinterpret_cast(data), 2, size2); - const float factor = 1.0f / static_cast(_size); - vDSP_vsmul(data, 1, &factor, data, 1, _size); - } + virtual void ifft(float *data, const float *re, const float *im) override { + const size_t size2 = _size / 2; + ::memcpy(_re.data(), re, size2 * sizeof(float)); + ::memcpy(_im.data(), im, size2 * sizeof(float)); + _im[0] = re[size2]; + DSPSplitComplex splitComplex; + splitComplex.realp = _re.data(); + splitComplex.imagp = _im.data(); + vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_INVERSE); + vDSP_ztoc(&splitComplex, 1, reinterpret_cast(data), 2, size2); + const float factor = 1.0f / static_cast(_size); + vDSP_vsmul(data, 1, &factor, data, 1, _size); + } - private: - size_t _size; - size_t _powerOf2; - FFTSetup _fftSetup; - std::vector _re; - std::vector _im; - }; - - - /** - * @internal - * @brief Concrete FFT implementation - */ - typedef AppleAccelerateFFT AudioFFTImplementation; +private: + size_t _size; + size_t _powerOf2; + FFTSetup _fftSetup; + std::vector _re; + std::vector _im; +}; +/** + * @internal + * @brief Concrete FFT implementation + */ +typedef AppleAccelerateFFT AudioFFTImplementation; #endif // AUDIOFFT_APPLE_ACCELERATE_USED - - // ================================================================ - +// ================================================================ #ifdef AUDIOFFT_FFTW3_USED +/** + * @internal + * @class FFTW3FFT + * @brief FFT implementation using FFTW3 internally (see fftw.org) + */ +class FFTW3FFT : public detail::AudioFFTImpl { +public: + FFTW3FFT() + : detail::AudioFFTImpl(), _size(0), _complexSize(0), _planForward(0), _planBackward(0), + _data(0), _re(0), _im(0) {} - /** - * @internal - * @class FFTW3FFT - * @brief FFT implementation using FFTW3 internally (see fftw.org) - */ - class FFTW3FFT : public detail::AudioFFTImpl - { - public: - FFTW3FFT() : - detail::AudioFFTImpl(), - _size(0), - _complexSize(0), - _planForward(0), - _planBackward(0), - _data(0), - _re(0), - _im(0) - { - } + FFTW3FFT(const FFTW3FFT &) = delete; + FFTW3FFT &operator=(const FFTW3FFT &) = delete; - FFTW3FFT(const FFTW3FFT&) = delete; - FFTW3FFT& operator=(const FFTW3FFT&) = delete; + virtual ~FFTW3FFT() { init(0); } - virtual ~FFTW3FFT() - { - init(0); - } + virtual void init(size_t size) override { + if (_size != size) { + if (_size > 0) { + fftwf_destroy_plan(_planForward); + fftwf_destroy_plan(_planBackward); + _planForward = 0; + _planBackward = 0; + _size = 0; + _complexSize = 0; - virtual void init(size_t size) override - { - if (_size != size) - { - if (_size > 0) - { - fftwf_destroy_plan(_planForward); - fftwf_destroy_plan(_planBackward); - _planForward = 0; - _planBackward = 0; - _size = 0; - _complexSize = 0; - - if (_data) - { - fftwf_free(_data); - _data = 0; - } - - if (_re) - { - fftwf_free(_re); - _re = 0; - } - - if (_im) - { - fftwf_free(_im); - _im = 0; - } + if (_data) { + fftwf_free(_data); + _data = 0; } - if (size > 0) - { - - _size = size; - _complexSize = AudioFFT::ComplexSize(_size); - const size_t complexSize = AudioFFT::ComplexSize(_size); - _data = reinterpret_cast(fftwf_malloc(_size * sizeof(float))); - _re = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); - _im = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); - fftwf_set_timelimit(0.01); - fftw_iodim dim; - dim.n = static_cast(size); - dim.is = 1; - dim.os = 1; - _planForward = fftwf_plan_guru_split_dft_r2c(1, &dim, 0, 0, _data, _re, _im, FFTW_MEASURE); - _planBackward = fftwf_plan_guru_split_dft_c2r(1, &dim, 0, 0, _re, _im, _data, FFTW_MEASURE); + if (_re) { + fftwf_free(_re); + _re = 0; + } + + if (_im) { + fftwf_free(_im); + _im = 0; } } + + if (size > 0) { + + _size = size; + _complexSize = AudioFFT::ComplexSize(_size); + const size_t complexSize = AudioFFT::ComplexSize(_size); + _data = reinterpret_cast(fftwf_malloc(_size * sizeof(float))); + _re = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); + _im = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); + fftwf_set_timelimit(0.01); + fftw_iodim dim; + dim.n = static_cast(size); + dim.is = 1; + dim.os = 1; + _planForward = fftwf_plan_guru_split_dft_r2c(1, &dim, 0, 0, _data, _re, _im, FFTW_MEASURE); + _planBackward = fftwf_plan_guru_split_dft_c2r(1, &dim, 0, 0, _re, _im, _data, FFTW_MEASURE); + } } + } - virtual void fft(const float* data, float* re, float* im) override - { - ::memcpy(_data, data, _size * sizeof(float)); - fftwf_execute_split_dft_r2c(_planForward, _data, _re, _im); - ::memcpy(re, _re, _complexSize * sizeof(float)); - ::memcpy(im, _im, _complexSize * sizeof(float)); - } + virtual void fft(const float *data, float *re, float *im) override { + ::memcpy(_data, data, _size * sizeof(float)); + fftwf_execute_split_dft_r2c(_planForward, _data, _re, _im); + ::memcpy(re, _re, _complexSize * sizeof(float)); + ::memcpy(im, _im, _complexSize * sizeof(float)); + } - virtual void ifft(float* data, const float* re, const float* im) override - { - ::memcpy(_re, re, _complexSize * sizeof(float)); - ::memcpy(_im, im, _complexSize * sizeof(float)); - fftwf_execute_split_dft_c2r(_planBackward, _re, _im, _data); - detail::ScaleBuffer(data, _data, 1.0f / static_cast(_size), _size); - } + virtual void ifft(float *data, const float *re, const float *im) override { + ::memcpy(_re, re, _complexSize * sizeof(float)); + ::memcpy(_im, im, _complexSize * sizeof(float)); + fftwf_execute_split_dft_c2r(_planBackward, _re, _im, _data); + detail::ScaleBuffer(data, _data, 1.0f / static_cast(_size), _size); + } - private: - size_t _size; - size_t _complexSize; - fftwf_plan _planForward; - fftwf_plan _planBackward; - float* _data; - float* _re; - float* _im; - }; - - - /** - * @internal - * @brief Concrete FFT implementation - */ - typedef FFTW3FFT AudioFFTImplementation; +private: + size_t _size; + size_t _complexSize; + fftwf_plan _planForward; + fftwf_plan _planBackward; + float *_data; + float *_re; + float *_im; +}; +/** + * @internal + * @brief Concrete FFT implementation + */ +typedef FFTW3FFT AudioFFTImplementation; #endif // AUDIOFFT_FFTW3_USED +// ============================================================= - // ============================================================= +AudioFFT::AudioFFT() : _impl(new AudioFFTImplementation()) {} +AudioFFT::~AudioFFT() {} - AudioFFT::AudioFFT() : - _impl(new AudioFFTImplementation()) - { - } +void AudioFFT::init(size_t size) { + assert(detail::IsPowerOf2(size)); + _impl->init(size); +} +void AudioFFT::fft(const float *data, float *re, float *im) { _impl->fft(data, re, im); } - AudioFFT::~AudioFFT() - { - } +void AudioFFT::ifft(float *data, const float *re, const float *im) { _impl->ifft(data, re, im); } +size_t AudioFFT::ComplexSize(size_t size) { return (size / 2) + 1; } - void AudioFFT::init(size_t size) - { - assert(detail::IsPowerOf2(size)); - _impl->init(size); - } - - - void AudioFFT::fft(const float* data, float* re, float* im) - { - _impl->fft(data, re, im); - } - - - void AudioFFT::ifft(float* data, const float* re, const float* im) - { - _impl->ifft(data, re, im); - } - - - size_t AudioFFT::ComplexSize(size_t size) - { - return (size / 2) + 1; - } - -} // End of namespace +} // namespace audiofft diff --git a/FFTConvolver/AudioFFT.h b/FFTConvolver/AudioFFT.h old mode 100755 new mode 100644 index dadf32e6..04bc7d07 --- a/FFTConvolver/AudioFFT.h +++ b/FFTConvolver/AudioFFT.h @@ -22,147 +22,143 @@ #ifndef _AUDIOFFT_H #define _AUDIOFFT_H - /** -* AudioFFT provides real-to-complex/complex-to-real FFT routines. -* -* Features: -* -* - Real-complex FFT and complex-real inverse FFT for power-of-2-sized real data. -* -* - Uniform interface to different FFT implementations (currently Ooura, FFTW3 and Apple Accelerate). -* -* - Complex data is handled in "split-complex" format, i.e. there are separate -* arrays for the real and imaginary parts which can be useful for SIMD optimizations -* (split-complex arrays have to be of length (size/2+1) representing bins from DC -* to Nyquist frequency). -* -* - Output is "ready to use" (all scaling etc. is already handled internally). -* -* - No allocations/deallocations after the initialization which makes it usable -* for real-time audio applications (that's what I wrote it for and using it). -* -* -* How to use it in your project: -* -* - Add the .h and .cpp file to your project - that's all. -* -* - To get extra speed, you can link FFTW3 to your project and define -* AUDIOFFT_FFTW3 (however, please check whether your project suits the -* according license). -* -* - To get the best speed on Apple platforms, you can link the Apple -* Accelerate framework to your project and define -* AUDIOFFT_APPLE_ACCELERATE (however, please check whether your -* project suits the according license). -* -* -* Remarks: -* -* - AudioFFT is not intended to be the fastest FFT, but to be a fast-enough -* FFT suitable for most audio applications. -* -* - AudioFFT uses the quite liberal MIT license. -* -* -* Example usage: -* @code -* #include "AudioFFT.h" -* -* void Example() -* { -* const size_t fftSize = 1024; // Needs to be power of 2! -* -* std::vector input(fftSize, 0.0f); -* std::vector re(audiofft::AudioFFT::ComplexSize(fftSize)); -* std::vector im(audiofft::AudioFFT::ComplexSize(fftSize)); -* std::vector output(fftSize); -* -* audiofft::AudioFFT fft; -* fft.init(1024); -* fft.fft(input.data(), re.data(), im.data()); -* fft.ifft(output.data(), re.data(), im.data()); -* } -* @endcode -*/ - + * AudioFFT provides real-to-complex/complex-to-real FFT routines. + * + * Features: + * + * - Real-complex FFT and complex-real inverse FFT for power-of-2-sized real data. + * + * - Uniform interface to different FFT implementations (currently Ooura, FFTW3 and Apple + * Accelerate). + * + * - Complex data is handled in "split-complex" format, i.e. there are separate + * arrays for the real and imaginary parts which can be useful for SIMD optimizations + * (split-complex arrays have to be of length (size/2+1) representing bins from DC + * to Nyquist frequency). + * + * - Output is "ready to use" (all scaling etc. is already handled internally). + * + * - No allocations/deallocations after the initialization which makes it usable + * for real-time audio applications (that's what I wrote it for and using it). + * + * + * How to use it in your project: + * + * - Add the .h and .cpp file to your project - that's all. + * + * - To get extra speed, you can link FFTW3 to your project and define + * AUDIOFFT_FFTW3 (however, please check whether your project suits the + * according license). + * + * - To get the best speed on Apple platforms, you can link the Apple + * Accelerate framework to your project and define + * AUDIOFFT_APPLE_ACCELERATE (however, please check whether your + * project suits the according license). + * + * + * Remarks: + * + * - AudioFFT is not intended to be the fastest FFT, but to be a fast-enough + * FFT suitable for most audio applications. + * + * - AudioFFT uses the quite liberal MIT license. + * + * + * Example usage: + * @code + * #include "AudioFFT.h" + * + * void Example() + * { + * const size_t fftSize = 1024; // Needs to be power of 2! + * + * std::vector input(fftSize, 0.0f); + * std::vector re(audiofft::AudioFFT::ComplexSize(fftSize)); + * std::vector im(audiofft::AudioFFT::ComplexSize(fftSize)); + * std::vector output(fftSize); + * + * audiofft::AudioFFT fft; + * fft.init(1024); + * fft.fft(input.data(), re.data(), im.data()); + * fft.ifft(output.data(), re.data(), im.data()); + * } + * @endcode + */ #include #include +namespace audiofft { -namespace audiofft -{ +namespace detail { +class AudioFFTImpl; +} - namespace detail - { - class AudioFFTImpl; - } +// ============================================================= +/** + * @class AudioFFT + * @brief Performs 1D FFTs + */ +class AudioFFT { +public: + /** + * @brief Constructor + */ + AudioFFT(); - // ============================================================= - + AudioFFT(const AudioFFT &) = delete; + AudioFFT &operator=(const AudioFFT &) = delete; /** - * @class AudioFFT - * @brief Performs 1D FFTs + * @brief Destructor */ - class AudioFFT - { - public: - /** - * @brief Constructor - */ - AudioFFT(); - - AudioFFT(const AudioFFT&) = delete; - AudioFFT& operator=(const AudioFFT&) = delete; - - /** - * @brief Destructor - */ - ~AudioFFT(); - - /** - * @brief Initializes the FFT object - * @param size Size of the real input (must be power 2) - */ - void init(size_t size); - - /** - * @brief Performs the forward FFT - * @param data The real input data (has to be of the length as specified in init()) - * @param re The real part of the complex output (has to be of length as returned by ComplexSize()) - * @param im The imaginary part of the complex output (has to be of length as returned by ComplexSize()) - */ - void fft(const float* data, float* re, float* im); - - /** - * @brief Performs the inverse FFT - * @param data The real output data (has to be of the length as specified in init()) - * @param re The real part of the complex input (has to be of length as returned by ComplexSize()) - * @param im The imaginary part of the complex input (has to be of length as returned by ComplexSize()) - */ - void ifft(float* data, const float* re, const float* im); - - /** - * @brief Calculates the necessary size of the real/imaginary complex arrays - * @param size The size of the real data - * @return The size of the real/imaginary complex arrays - */ - static size_t ComplexSize(size_t size); - - private: - std::unique_ptr _impl; - }; - + ~AudioFFT(); /** - * @deprecated - * @brief Let's keep an AudioFFTBase type around for now because it has been here already in the 1st version in order to avoid breaking existing code. + * @brief Initializes the FFT object + * @param size Size of the real input (must be power 2) */ - typedef AudioFFT AudioFFTBase; + void init(size_t size); -} // End of namespace + /** + * @brief Performs the forward FFT + * @param data The real input data (has to be of the length as specified in init()) + * @param re The real part of the complex output (has to be of length as returned by + * ComplexSize()) + * @param im The imaginary part of the complex output (has to be of length as returned by + * ComplexSize()) + */ + void fft(const float *data, float *re, float *im); + + /** + * @brief Performs the inverse FFT + * @param data The real output data (has to be of the length as specified in init()) + * @param re The real part of the complex input (has to be of length as returned by ComplexSize()) + * @param im The imaginary part of the complex input (has to be of length as returned by + * ComplexSize()) + */ + void ifft(float *data, const float *re, const float *im); + + /** + * @brief Calculates the necessary size of the real/imaginary complex arrays + * @param size The size of the real data + * @return The size of the real/imaginary complex arrays + */ + static size_t ComplexSize(size_t size); + +private: + std::unique_ptr _impl; +}; + +/** + * @deprecated + * @brief Let's keep an AudioFFTBase type around for now because it has been here already in the 1st + * version in order to avoid breaking existing code. + */ +typedef AudioFFT AudioFFTBase; + +} // namespace audiofft #endif // Header guard diff --git a/FFTConvolver/ConvolverThreadPool.cpp b/FFTConvolver/ConvolverThreadPool.cpp index ef969572..f41befd1 100644 --- a/FFTConvolver/ConvolverThreadPool.cpp +++ b/FFTConvolver/ConvolverThreadPool.cpp @@ -140,8 +140,11 @@ void ConvolverThreadPool::clearState(size_t convolverId) { if (convolverId < _convolvers.size()) { waitForAll(); } else { - debug(1, "assert(convolverId < _convolvers.size()) failed, with convolverId: %u and _convolvers.size(): %u.", convolverId, _convolvers.size()); - } + debug(1, + "assert(convolverId < _convolvers.size()) failed, with convolverId: %u and " + "_convolvers.size(): %u.", + convolverId, _convolvers.size()); + } } /* this is the old version diff --git a/FFTConvolver/ConvolverThreadPool.h b/FFTConvolver/ConvolverThreadPool.h index a690b34f..fc49daa1 100644 --- a/FFTConvolver/ConvolverThreadPool.h +++ b/FFTConvolver/ConvolverThreadPool.h @@ -61,7 +61,7 @@ public: // Get the number of threads size_t getNumThreads() const { return _threads.size(); } - + void shutdown(); private: diff --git a/FFTConvolver/FFTConvolver.cpp b/FFTConvolver/FFTConvolver.cpp old mode 100755 new mode 100644 index 693b5b0f..d79620eb --- a/FFTConvolver/FFTConvolver.cpp +++ b/FFTConvolver/FFTConvolver.cpp @@ -20,47 +20,25 @@ #include #include -#if defined (FFTCONVOLVER_USE_SSE) - #include +#if defined(FFTCONVOLVER_USE_SSE) +#include #endif +namespace fftconvolver { -namespace fftconvolver -{ +FFTConvolver::FFTConvolver() + : _blockSize(0), _segSize(0), _segCount(0), _fftComplexSize(0), _segments(), _segmentsIR(), + _fftBuffer(), _fft(), _preMultiplied(), _conv(), _overlap(), _current(0), _inputBuffer(), + _inputBufferFill(0) {} -FFTConvolver::FFTConvolver() : - _blockSize(0), - _segSize(0), - _segCount(0), - _fftComplexSize(0), - _segments(), - _segmentsIR(), - _fftBuffer(), - _fft(), - _preMultiplied(), - _conv(), - _overlap(), - _current(0), - _inputBuffer(), - _inputBufferFill(0) -{ -} +FFTConvolver::~FFTConvolver() { reset(); } - -FFTConvolver::~FFTConvolver() -{ - reset(); -} - - -void FFTConvolver::reset() -{ - for (size_t i=0; i<_segCount; ++i) - { +void FFTConvolver::reset() { + for (size_t i = 0; i < _segCount; ++i) { delete _segments[i]; delete _segmentsIR[i]; } - + _blockSize = 0; _segSize = 0; _segCount = 0; @@ -77,115 +55,101 @@ void FFTConvolver::reset() _inputBufferFill = 0; } -void FFTConvolver::clearState() -{ - if (_segCount == 0) - { +void FFTConvolver::clearState() { + if (_segCount == 0) { return; // Not initialized } - + _inputBuffer.setZero(); _inputBufferFill = 0; _overlap.setZero(); - - for (size_t i = 0; i < _segCount; ++i) - { + + for (size_t i = 0; i < _segCount; ++i) { _segments[i]->setZero(); } - + _preMultiplied.setZero(); _conv.setZero(); _current = 0; } - -bool FFTConvolver::init(size_t blockSize, const Sample* ir, size_t irLen) -{ + +bool FFTConvolver::init(size_t blockSize, const Sample *ir, size_t irLen) { reset(); - if (blockSize == 0) - { + if (blockSize == 0) { return false; } - + // Ignore zeros at the end of the impulse response because they only waste computation time - while (irLen > 0 && ::fabs(ir[irLen-1]) < 0.000001f) - { + while (irLen > 0 && ::fabs(ir[irLen - 1]) < 0.000001f) { --irLen; } - if (irLen == 0) - { + if (irLen == 0) { return true; } - + _blockSize = NextPowerOf2(blockSize); _segSize = 2 * _blockSize; - _segCount = static_cast(::ceil(static_cast(irLen) / static_cast(_blockSize))); + _segCount = + static_cast(::ceil(static_cast(irLen) / static_cast(_blockSize))); _fftComplexSize = audiofft::AudioFFT::ComplexSize(_segSize); - + // FFT _fft.init(_segSize); _fftBuffer.resize(_segSize); - + // Prepare segments - for (size_t i=0; i<_segCount; ++i) - { - _segments.push_back(new SplitComplex(_fftComplexSize)); + for (size_t i = 0; i < _segCount; ++i) { + _segments.push_back(new SplitComplex(_fftComplexSize)); } - + // Prepare IR - for (size_t i=0; i<_segCount; ++i) - { - SplitComplex* segment = new SplitComplex(_fftComplexSize); + for (size_t i = 0; i < _segCount; ++i) { + SplitComplex *segment = new SplitComplex(_fftComplexSize); const size_t remaining = irLen - (i * _blockSize); const size_t sizeCopy = (remaining >= _blockSize) ? _blockSize : remaining; - CopyAndPad(_fftBuffer, &ir[i*_blockSize], sizeCopy); + CopyAndPad(_fftBuffer, &ir[i * _blockSize], sizeCopy); _fft.fft(_fftBuffer.data(), segment->re(), segment->im()); _segmentsIR.push_back(segment); } - - // Prepare convolution buffers + + // Prepare convolution buffers _preMultiplied.resize(_fftComplexSize); _conv.resize(_fftComplexSize); _overlap.resize(_blockSize); - + // Prepare input buffer _inputBuffer.resize(_blockSize); _inputBufferFill = 0; // Reset current position _current = 0; - + return true; } - -void FFTConvolver::process(const Sample* input, Sample* output, size_t len) -{ - if (_segCount == 0) - { +void FFTConvolver::process(const Sample *input, Sample *output, size_t len) { + if (_segCount == 0) { ::memset(output, 0, len * sizeof(Sample)); return; } size_t processed = 0; - while (processed < len) - { + while (processed < len) { const bool inputBufferWasEmpty = (_inputBufferFill == 0); - const size_t processing = std::min(len-processed, _blockSize-_inputBufferFill); + const size_t processing = std::min(len - processed, _blockSize - _inputBufferFill); const size_t inputBufferPos = _inputBufferFill; - ::memcpy(_inputBuffer.data()+inputBufferPos, input+processed, processing * sizeof(Sample)); + ::memcpy(_inputBuffer.data() + inputBufferPos, input + processed, processing * sizeof(Sample)); // Forward FFT - CopyAndPad(_fftBuffer, &_inputBuffer[0], _blockSize); + CopyAndPad(_fftBuffer, &_inputBuffer[0], _blockSize); _fft.fft(_fftBuffer.data(), _segments[_current]->re(), _segments[_current]->im()); // Complex multiplication - if (inputBufferWasEmpty) - { + if (inputBufferWasEmpty) { _preMultiplied.setZero(); - for (size_t i=1; i<_segCount; ++i) - { + for (size_t i = 1; i < _segCount; ++i) { const size_t indexIr = i; const size_t indexAudio = (_current + i) % _segCount; ComplexMultiplyAccumulate(_preMultiplied, *_segmentsIR[indexIr], *_segments[indexAudio]); @@ -198,18 +162,18 @@ void FFTConvolver::process(const Sample* input, Sample* output, size_t len) _fft.ifft(_fftBuffer.data(), _conv.re(), _conv.im()); // Add overlap - Sum(output+processed, _fftBuffer.data()+inputBufferPos, _overlap.data()+inputBufferPos, processing); + Sum(output + processed, _fftBuffer.data() + inputBufferPos, _overlap.data() + inputBufferPos, + processing); // Input buffer full => Next block _inputBufferFill += processing; - if (_inputBufferFill == _blockSize) - { + if (_inputBufferFill == _blockSize) { // Input buffer is empty again now _inputBuffer.setZero(); _inputBufferFill = 0; // Save the overlap - ::memcpy(_overlap.data(), _fftBuffer.data()+_blockSize, _blockSize * sizeof(Sample)); + ::memcpy(_overlap.data(), _fftBuffer.data() + _blockSize, _blockSize * sizeof(Sample)); // Update current segment _current = (_current > 0) ? (_current - 1) : (_segCount - 1); @@ -218,5 +182,5 @@ void FFTConvolver::process(const Sample* input, Sample* output, size_t len) processed += processing; } } - + } // End of namespace fftconvolver diff --git a/FFTConvolver/FFTConvolver.h b/FFTConvolver/FFTConvolver.h old mode 100755 new mode 100644 index 125fd12b..a6ed4aba --- a/FFTConvolver/FFTConvolver.h +++ b/FFTConvolver/FFTConvolver.h @@ -27,61 +27,58 @@ #include - -namespace fftconvolver -{ +namespace fftconvolver { /** -* @class FFTConvolver -* @brief Implementation of a partitioned FFT convolution algorithm with uniform block size -* -* Some notes on how to use it: -* -* - After initialization with an impulse response, subsequent data portions of -* arbitrary length can be convolved. The convolver internally can handle -* this by using appropriate buffering. -* -* - The convolver works without "latency" (except for the required -* processing time, of course), i.e. the output always is the convolved -* input for each processing call. -* -* - The convolver is suitable for real-time processing which means that no -* "unpredictable" operations like allocations, locking, API calls, etc. are -* performed during processing (all necessary allocations and preparations take -* place during initialization). -*/ -class FFTConvolver -{ + * @class FFTConvolver + * @brief Implementation of a partitioned FFT convolution algorithm with uniform block size + * + * Some notes on how to use it: + * + * - After initialization with an impulse response, subsequent data portions of + * arbitrary length can be convolved. The convolver internally can handle + * this by using appropriate buffering. + * + * - The convolver works without "latency" (except for the required + * processing time, of course), i.e. the output always is the convolved + * input for each processing call. + * + * - The convolver is suitable for real-time processing which means that no + * "unpredictable" operations like allocations, locking, API calls, etc. are + * performed during processing (all necessary allocations and preparations take + * place during initialization). + */ +class FFTConvolver { public: - FFTConvolver(); + FFTConvolver(); virtual ~FFTConvolver(); - - /** - * @brief Initializes the convolver - * @param blockSize Block size internally used by the convolver (partition size) - * @param ir The impulse response - * @param irLen Length of the impulse response - * @return true: Success - false: Failed - */ - bool init(size_t blockSize, const Sample* ir, size_t irLen); /** - * @brief Convolves the the given input samples and immediately outputs the result - * @param input The input samples - * @param output The convolution result - * @param len Number of input/output samples - */ - void process(const Sample* input, Sample* output, size_t len); + * @brief Initializes the convolver + * @param blockSize Block size internally used by the convolver (partition size) + * @param ir The impulse response + * @param irLen Length of the impulse response + * @return true: Success - false: Failed + */ + bool init(size_t blockSize, const Sample *ir, size_t irLen); /** - * @brief Resets the convolver and discards the set impulse response - */ + * @brief Convolves the the given input samples and immediately outputs the result + * @param input The input samples + * @param output The convolution result + * @param len Number of input/output samples + */ + void process(const Sample *input, Sample *output, size_t len); + + /** + * @brief Resets the convolver and discards the set impulse response + */ void reset(); - + /** - * @brief Clears audio history - */ - + * @brief Clears audio history + */ + void clearState(); private: @@ -89,8 +86,8 @@ private: size_t _segSize; size_t _segCount; size_t _fftComplexSize; - std::vector _segments; - std::vector _segmentsIR; + std::vector _segments; + std::vector _segmentsIR; SampleBuffer _fftBuffer; audiofft::AudioFFT _fft; SplitComplex _preMultiplied; @@ -101,10 +98,10 @@ private: size_t _inputBufferFill; // Prevent uncontrolled usage - FFTConvolver(const FFTConvolver&); - FFTConvolver& operator=(const FFTConvolver&); + FFTConvolver(const FFTConvolver &); + FFTConvolver &operator=(const FFTConvolver &); }; - + } // End of namespace fftconvolver #endif // Header guard diff --git a/FFTConvolver/Utilities.cpp b/FFTConvolver/Utilities.cpp index 3d00e6f5..fde81851 100644 --- a/FFTConvolver/Utilities.cpp +++ b/FFTConvolver/Utilities.cpp @@ -21,12 +21,9 @@ #include "Utilities.h" +namespace fftconvolver { -namespace fftconvolver -{ - -bool SSEEnabled() -{ +bool SSEEnabled() { #if defined(FFTCONVOLVER_USE_SSE) return true; #else @@ -34,47 +31,35 @@ bool SSEEnabled() #endif } - -void Sum(Sample* FFTCONVOLVER_RESTRICT result, - const Sample* FFTCONVOLVER_RESTRICT a, - const Sample* FFTCONVOLVER_RESTRICT b, - size_t len) -{ +void Sum(Sample *FFTCONVOLVER_RESTRICT result, const Sample *FFTCONVOLVER_RESTRICT a, + const Sample *FFTCONVOLVER_RESTRICT b, size_t len) { const size_t end4 = 4 * (len / 4); - for (size_t i=0; i #include - -namespace fftconvolver -{ +namespace fftconvolver { #if defined(__SSE__) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2) - #if !defined(FFTCONVOLVER_USE_SSE) && !defined(FFTCONVOLVER_DONT_USE_SSE) - #define FFTCONVOLVER_USE_SSE - #endif +#if !defined(FFTCONVOLVER_USE_SSE) && !defined(FFTCONVOLVER_DONT_USE_SSE) +#define FFTCONVOLVER_USE_SSE +#endif #endif - -#if defined (FFTCONVOLVER_USE_SSE) - #include +#if defined(FFTCONVOLVER_USE_SSE) +#include #endif - #if defined(__GNUC__) - #define FFTCONVOLVER_RESTRICT __restrict__ +#define FFTCONVOLVER_RESTRICT __restrict__ #else - #define FFTCONVOLVER_RESTRICT +#define FFTCONVOLVER_RESTRICT #endif - /** -* @brief Returns whether SSE optimization for the convolver is enabled -* @return true: Enabled - false: Disabled -*/ + * @brief Returns whether SSE optimization for the convolver is enabled + * @return true: Enabled - false: Disabled + */ bool SSEEnabled(); - /** -* @class Buffer -* @brief Simple buffer implementation (uses 16-byte alignment if SSE optimization is enabled) -*/ -template -class Buffer -{ -public: - explicit Buffer(size_t initialSize = 0) : - _data(0), - _size(0) - { - resize(initialSize); - } + * @class Buffer + * @brief Simple buffer implementation (uses 16-byte alignment if SSE optimization is enabled) + */ +template class Buffer { +public: + explicit Buffer(size_t initialSize = 0) : _data(0), _size(0) { resize(initialSize); } - virtual ~Buffer() - { - clear(); - } + virtual ~Buffer() { clear(); } - void clear() - { + void clear() { deallocate(_data); _data = 0; _size = 0; } - void resize(size_t size) - { - if (_size != size) - { + void resize(size_t size) { + if (_size != size) { clear(); - if (size > 0) - { + if (size > 0) { assert(!_data && _size == 0); _data = allocate(size); _size = size; @@ -101,172 +81,118 @@ public: setZero(); } - size_t size() const - { - return _size; - } + size_t size() const { return _size; } - void setZero() - { - ::memset(_data, 0, _size * sizeof(T)); - } + void setZero() { ::memset(_data, 0, _size * sizeof(T)); } - void copyFrom(const Buffer& other) - { + void copyFrom(const Buffer &other) { assert(_size == other._size); - if (this != &other) - { + if (this != &other) { ::memcpy(_data, other._data, _size * sizeof(T)); } } - T& operator[](size_t index) - { + T &operator[](size_t index) { assert(_data && index < _size); return _data[index]; } - const T& operator[](size_t index) const - { + const T &operator[](size_t index) const { assert(_data && index < _size); return _data[index]; } - operator bool() const - { - return (_data != 0 && _size > 0); - } + operator bool() const { return (_data != 0 && _size > 0); } - T* data() - { - return _data; - } + T *data() { return _data; } - const T* data() const - { - return _data; - } + const T *data() const { return _data; } - static void Swap(Buffer& a, Buffer& b) - { + static void Swap(Buffer &a, Buffer &b) { std::swap(a._data, b._data); std::swap(a._size, b._size); } private: - T* allocate(size_t size) - { + T *allocate(size_t size) { #if defined(FFTCONVOLVER_USE_SSE) - return static_cast(_mm_malloc(size * sizeof(T), 16)); + return static_cast(_mm_malloc(size * sizeof(T), 16)); #else return new T[size]; #endif } - - void deallocate(T* ptr) - { + + void deallocate(T *ptr) { #if defined(FFTCONVOLVER_USE_SSE) _mm_free(ptr); #else - delete [] ptr; + delete[] ptr; #endif } - T* _data; + T *_data; size_t _size; // Prevent uncontrolled usage - Buffer(const Buffer&); - Buffer& operator=(const Buffer&); + Buffer(const Buffer &); + Buffer &operator=(const Buffer &); }; - /** -* @brief Type of one sample -*/ + * @brief Type of one sample + */ typedef float Sample; - /** -* @brief Buffer for samples -*/ + * @brief Buffer for samples + */ typedef Buffer SampleBuffer; - /** -* @class SplitComplex -* @brief Buffer for split-complex representation of FFT results -* -* The split-complex representation stores the real and imaginary parts -* of FFT results in two different memory buffers which is useful e.g. for -* SIMD optimizations. -*/ -class SplitComplex -{ + * @class SplitComplex + * @brief Buffer for split-complex representation of FFT results + * + * The split-complex representation stores the real and imaginary parts + * of FFT results in two different memory buffers which is useful e.g. for + * SIMD optimizations. + */ +class SplitComplex { public: - explicit SplitComplex(size_t initialSize = 0) : - _size(0), - _re(), - _im() - { - resize(initialSize); - } + explicit SplitComplex(size_t initialSize = 0) : _size(0), _re(), _im() { resize(initialSize); } - ~SplitComplex() - { - clear(); - } + ~SplitComplex() { clear(); } - void clear() - { + void clear() { _re.clear(); _im.clear(); _size = 0; } - void resize(size_t newSize) - { + void resize(size_t newSize) { _re.resize(newSize); _im.resize(newSize); _size = newSize; } - void setZero() - { + void setZero() { _re.setZero(); _im.setZero(); } - void copyFrom(const SplitComplex& other) - { + void copyFrom(const SplitComplex &other) { _re.copyFrom(other._re); _im.copyFrom(other._im); } - Sample* re() - { - return _re.data(); - } + Sample *re() { return _re.data(); } - const Sample* re() const - { - return _re.data(); - } + const Sample *re() const { return _re.data(); } - Sample* im() - { - return _im.data(); - } + Sample *im() { return _im.data(); } - const Sample* im() const - { - return _im.data(); - } + const Sample *im() const { return _im.data(); } - size_t size() const - { - return _size; - } + size_t size() const { return _size; } private: size_t _size; @@ -274,82 +200,68 @@ private: SampleBuffer _im; // Prevent uncontrolled usage - SplitComplex(const SplitComplex&); - SplitComplex& operator=(const SplitComplex&); + SplitComplex(const SplitComplex &); + SplitComplex &operator=(const SplitComplex &); }; - /** -* @brief Returns the next power of 2 of a given number -* @param val The number -* @return The next power of 2 -*/ -template -T NextPowerOf2(const T& val) -{ + * @brief Returns the next power of 2 of a given number + * @param val The number + * @return The next power of 2 + */ +template T NextPowerOf2(const T &val) { T nextPowerOf2 = 1; - while (nextPowerOf2 < val) - { + while (nextPowerOf2 < val) { nextPowerOf2 *= 2; } return nextPowerOf2; } - /** -* @brief Sums two given sample arrays -* @param result The result array -* @param a The 1st array -* @param b The 2nd array -* @param len The length of the arrays -*/ -void Sum(Sample* FFTCONVOLVER_RESTRICT result, - const Sample* FFTCONVOLVER_RESTRICT a, - const Sample* FFTCONVOLVER_RESTRICT b, - size_t len); - + * @brief Sums two given sample arrays + * @param result The result array + * @param a The 1st array + * @param b The 2nd array + * @param len The length of the arrays + */ +void Sum(Sample *FFTCONVOLVER_RESTRICT result, const Sample *FFTCONVOLVER_RESTRICT a, + const Sample *FFTCONVOLVER_RESTRICT b, size_t len); /** -* @brief Copies a source array into a destination buffer and pads the destination buffer with zeros -* @param dest The destination buffer -* @param src The source array -* @param srcSize The size of the source array -*/ -template -void CopyAndPad(Buffer& dest, const T* src, size_t srcSize) -{ + * @brief Copies a source array into a destination buffer and pads the destination buffer with zeros + * @param dest The destination buffer + * @param src The source array + * @param srcSize The size of the source array + */ +template void CopyAndPad(Buffer &dest, const T *src, size_t srcSize) { assert(dest.size() >= srcSize); ::memcpy(dest.data(), src, srcSize * sizeof(T)); - ::memset(dest.data() + srcSize, 0, (dest.size()-srcSize) * sizeof(T)); + ::memset(dest.data() + srcSize, 0, (dest.size() - srcSize) * sizeof(T)); } +/** + * @brief Adds the complex product of two split-complex buffers to a result buffer + * @param result The result buffer + * @param a The 1st factor of the complex product + * @param b The 2nd factor of the complex product + */ +void ComplexMultiplyAccumulate(SplitComplex &result, const SplitComplex &a, const SplitComplex &b); /** -* @brief Adds the complex product of two split-complex buffers to a result buffer -* @param result The result buffer -* @param a The 1st factor of the complex product -* @param b The 2nd factor of the complex product -*/ -void ComplexMultiplyAccumulate(SplitComplex& result, const SplitComplex& a, const SplitComplex& b); + * @brief Adds the complex product of two split-complex arrays to a result array + * @param re The real part of the result buffer + * @param im The imaginary part of the result buffer + * @param reA The real part of the 1st factor of the complex product + * @param imA The imaginary part of the 1st factor of the complex product + * @param reB The real part of the 2nd factor of the complex product + * @param imB The imaginary part of the 2nd factor of the complex product + */ +void ComplexMultiplyAccumulate(Sample *FFTCONVOLVER_RESTRICT re, Sample *FFTCONVOLVER_RESTRICT im, + const Sample *FFTCONVOLVER_RESTRICT reA, + const Sample *FFTCONVOLVER_RESTRICT imA, + const Sample *FFTCONVOLVER_RESTRICT reB, + const Sample *FFTCONVOLVER_RESTRICT imB, const size_t len); - -/** -* @brief Adds the complex product of two split-complex arrays to a result array -* @param re The real part of the result buffer -* @param im The imaginary part of the result buffer -* @param reA The real part of the 1st factor of the complex product -* @param imA The imaginary part of the 1st factor of the complex product -* @param reB The real part of the 2nd factor of the complex product -* @param imB The imaginary part of the 2nd factor of the complex product -*/ -void ComplexMultiplyAccumulate(Sample* FFTCONVOLVER_RESTRICT re, - Sample* FFTCONVOLVER_RESTRICT im, - const Sample* FFTCONVOLVER_RESTRICT reA, - const Sample* FFTCONVOLVER_RESTRICT imA, - const Sample* FFTCONVOLVER_RESTRICT reB, - const Sample* FFTCONVOLVER_RESTRICT imB, - const size_t len); - } // End of namespace fftconvolver #endif // Header guard diff --git a/FFTConvolver/convolver.cpp b/FFTConvolver/convolver.cpp index c276d778..a7372e29 100644 --- a/FFTConvolver/convolver.cpp +++ b/FFTConvolver/convolver.cpp @@ -46,8 +46,8 @@ void convolver_pool_init(size_t numThreads, size_t numConvolvers) { if (!pool.init(numThreads, numConvolvers)) { debug(1, "failed to initialize thread pool!"); } else { - debug(1, "thread pool initialized with %u thread%s and %u convolver%s.", numThreads, numThreads == 1 ? "" : "s", - numConvolvers, numConvolvers == 1 ? "" : "s"); + debug(1, "thread pool initialized with %u thread%s and %u convolver%s.", numThreads, + numThreads == 1 ? "" : "s", numConvolvers, numConvolvers == 1 ? "" : "s"); } } @@ -56,8 +56,8 @@ void convolver_pool_closedown() { debug(3, "thread pool shut down"); } -int convolver_init(const char *filename, unsigned char channel_count, - double max_length_in_seconds, size_t block_size) { +int convolver_init(const char *filename, unsigned char channel_count, double max_length_in_seconds, + size_t block_size) { debug(3, "convolver_init"); int success = 0; SF_INFO info = {}; // Zero everything, including format @@ -67,10 +67,10 @@ int convolver_init(const char *filename, unsigned char channel_count, size_t max_length = (size_t)(max_length_in_seconds * info.samplerate); const size_t size = (unsigned int)info.frames > max_length ? max_length : (unsigned int)info.frames; - float *buffer = (float*)malloc(sizeof(float) * size * info.channels); + float *buffer = (float *)malloc(sizeof(float) * size * info.channels); if (buffer != NULL) { // float buffer[size * info.channels]; - float *abuffer = (float*)malloc(sizeof(float) * size); + float *abuffer = (float *)malloc(sizeof(float) * size); if (abuffer != NULL) { size_t l = sf_readf_float(file, buffer, size); if (l != 0) { @@ -91,7 +91,7 @@ int convolver_init(const char *filename, unsigned char channel_count, } if (!pool.initConvolver(cc, block_size, abuffer, size)) { debug(1, "new convolver failed to initialize convolver %u ", cc); - } + } } } success = 1; @@ -101,11 +101,11 @@ int convolver_init(const char *filename, unsigned char channel_count, "%d samples", filename, info.channels, info.channels == 1 ? "" : "s", size); sf_close(file); - free((void*)abuffer); + free((void *)abuffer); } else { debug(1, "failed to init convolvers because insufficient memory was available"); } - free((void*)buffer); + free((void *)buffer); } else { warn("failed to init convolvers because insufficient memory was available"); } @@ -124,9 +124,7 @@ void convolver_process(unsigned int channel, float *data, int length) { void convolver_wait_for_all() { pool.waitForAll(); } -void convolver_clear_state() { - pool.clearAllStates(); -} +void convolver_clear_state() { pool.clearAllStates(); } const unsigned int max_channels = 8; fftconvolver::FFTConvolver convolvers[max_channels]; diff --git a/FFTConvolver/convolver.h b/FFTConvolver/convolver.h index c49c70a2..5259fe67 100644 --- a/FFTConvolver/convolver.h +++ b/FFTConvolver/convolver.h @@ -5,22 +5,24 @@ extern "C" { #endif - #include - -// int convolver_init(const char* file, unsigned char channel_count, double max_length_in_seconds, size_t block_size); +#include + +// int convolver_init(const char* file, unsigned char channel_count, double max_length_in_seconds, +// size_t block_size); void convolver_reset(); -//void convolver_clear_state(); -// void convolver_process(unsigned int channel, float *data, int length); -// void convolver_process_l(float* data, int length); -// void convolver_process_r(float* data, int length); +// void convolver_clear_state(); +// void convolver_process(unsigned int channel, float *data, int length); +// void convolver_process_l(float* data, int length); +// void convolver_process_r(float* data, int length); void convolver_pool_init(size_t numThreads, size_t numConvolvers); void convolver_pool_closedown(); -int convolver_init(const char* file, unsigned char channel_count, double max_length_in_seconds, size_t block_size); +int convolver_init(const char *file, unsigned char channel_count, double max_length_in_seconds, + size_t block_size); void convolver_process(unsigned int channel, float *data, int length); void convolver_clear_state(); void convolver_wait_for_all(); - + #ifdef __cplusplus } #endif diff --git a/Makefile.am b/Makefile.am index 1d5bf176..64763533 100644 --- a/Makefile.am +++ b/Makefile.am @@ -5,13 +5,13 @@ homedir = @HOME@ # Note that xmlmantohtml isn't producing correct HTML. # Uncomment the if/else and SUBDIR lines in this stanza to make xmltoman build shairport-sync.1 -# if USE_XMLTOMAN -# SUBDIRS = man -# else +if USE_XMLTOMAN + SUBDIRS = man +else man_MANS = $(top_srcdir)/man/shairport-sync.1 -# endif +endif -lib_pair_ap_a_CFLAGS = -Wall -g -DCONFIG_GCRYPT -pthread +lib_pair_ap_a_CFLAGS = -Wall -g -DCONFIG_GCRYPT -pthread --include=utilities/debug.h lib_tinyhttp_a_CFLAGS = -pthread lib_dbus_interface_a_CFLAGS = -pthread lib_mpris_interface_a_CFLAGS = -pthread @@ -27,7 +27,11 @@ noinst_LIBRARIES = # See below for the flags for the test client program -shairport_sync_SOURCES = shairport.c bonjour_strings.c rtsp.c mdns.c common.c rtp.c player.c audio.c loudness.c activity_monitor.c utilities/debug.c utilities/network_utilities.c +shairport_sync_SOURCES = shairport.c bonjour_strings.c mdns.c common.c rtp.c \ + player.c audio.c loudness.c activity_monitor.c \ + rtsp.c \ + utilities/debug.c utilities/network_utilities.c utilities/rtsp_message_utilities.c \ + utilities/string_utilities.c if BUILD_FOR_DARWIN AM_CXXFLAGS = -I/usr/local/include -Wno-multichar -Wall -Wextra -Wno-deprecated-declarations -pthread -DSYSCONFDIR=\"$(sysconfdir)\" @@ -132,8 +136,20 @@ if USE_DNS_SD shairport_sync_SOURCES += mdns_dns_sd.c endif +if USE_METADATA +shairport_sync_SOURCES += metadata/pc_queue.c metadata/core.c +endif + +if USE_METADATA_PIPE +shairport_sync_SOURCES += metadata/pipe.c +endif + +if USE_METADATA_MULTICAST +shairport_sync_SOURCES += metadata/multicast.c +endif + if USE_METADATA_HUB -shairport_sync_SOURCES += metadata_hub.c +shairport_sync_SOURCES += metadata/hub.c endif if USE_MQTT @@ -148,7 +164,11 @@ lib_tinyhttp_a_SOURCES = tinyhttp/chunk.c tinyhttp/header.c tinyhttp/http.c endif if USE_AIRPLAY_2 -shairport_sync_SOURCES += ap2_buffered_audio_processor.c ap2_event_receiver.c ap2_rc_event_receiver.c ptp-utilities.c utilities/buffered_read.c utilities/structured_buffer.c utilities/mod23.c plists/get_info_response.c +shairport_sync_SOURCES += ap2_buffered_audio_processor.c ap2_event_receiver.c \ + ap2_event_message_handler.c ptp-utilities.c \ + utilities/buffered_read.c utilities/structured_buffer.c utilities/mod23.c \ + utilities/generate_random_uuid.c utilities/generate_device_uuid.c \ + plists/get_info_response.c shairport_sync_LDADD += lib_pair_ap.a lib_pair_ap_a_SOURCES = pair_ap/pair.c pair_ap/pair_fruit.c pair_ap/pair_homekit.c pair_ap/pair-tlv.c noinst_LIBRARIES += lib_pair_ap.a diff --git a/README.md b/README.md index 211ce56f..521f56ca 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,13 @@ Shairport Sync does not support AirPlay video or photo streaming. # Features * Outputs AirPlay audio to [ALSA](https://www.alsa-project.org/wiki/Main_Page), [sndio](http://www.sndio.org), [PipeWire](https://pipewire.org), [PulseAudio](https://www.freedesktop.org/wiki/Software/PulseAudio/), to a unix pipe or to `STDOUT`. It also has limited support for [libao](https://xiph.org/ao/). * Metadata — Shairport Sync can deliver metadata supplied by the source, such as Album Name, Artist Name, Cover Art, etc. through a pipe or UDP socket to a recipient application program — see https://github.com/mikebrady/shairport-sync-metadata-reader for a sample recipient. Sources that supply metadata include iTunes and the Music app in macOS and iOS. -* An interface to [MQTT](https://en.wikipedia.org/wiki/MQTT), a popular protocol for Inter Process Communication, Machine-to-Machine, Internet of Things and Home Automation projects. The interface provides access to metadata and artwork, and has limited remote control. +* An interface to [MQTT](https://en.wikipedia.org/wiki/MQTT), a popular protocol for Inter Process Communication, Machine-to-Machine, Internet of Things and Home Automation projects. The interface provides access to metadata and artwork, with remote control for Classic AirPlay clients. * Digital Signal Processing facilities – please see the [DSP Wiki Page Guide](https://github.com/mikebrady/shairport-sync/wiki/Digital-Signal-Processing-with-Shairport-Sync). (Thanks to [Yann Pomarède](https://github.com/yannpom) for the code and to [Paul Wieland](https://github.com/PaulWieland) for the guide.) -* An [MPRIS](https://specifications.freedesktop.org/mpris-spec/2.2/)-like interface, partially complete and very functional, including access to metadata and artwork, and limited remote control. -* A native D-Bus interface, including access to metadata and artwork, limited remote control and system settings. +* An [MPRIS](https://specifications.freedesktop.org/mpris-spec/2.2/)-like interface, partially complete and very functional, including access to metadata and artwork, and partial remote control for Classic AirPlay clients. +* A native D-Bus interface, including access to metadata, artwork and system settings. Remote control is also available for Classic AirPlay clients. * Better Volume Control — Shairport Sync offers finer control at very top and very bottom of the volume range. See http://tangentsoft.net/audio/atten.html for a good discussion of audio "attenuators", upon which volume control in Shairport Sync is modelled. See also the diagram of the volume transfer function in the documents folder. In addition, Shairport Sync can offer an extended volume control range on devices with a restricted range. * Flexible output rates, formats and channels with built-in transcoding. +* Remote Control (Classic AirPLay only) – Remote control commands -- such as `play`, `pause`, and volume-setting commands -- can be sent to Classic AirPlay clients via the D-Bus, MPRIS and MQTT interfaces. Remote Control is unfortunately not available for AirPlay 2 clients, as the system used has not been discovered. Some features require configuration at build time – see [CONFIGURATION FLAGS.md](CONFIGURATION%20FLAGS.md). diff --git a/activity_monitor.c b/activity_monitor.c index bdd81c59..06fe4fee 100644 --- a/activity_monitor.c +++ b/activity_monitor.c @@ -40,7 +40,10 @@ #include "activity_monitor.h" #include "common.h" -#include "rtsp.h" + +#ifdef CONFIG_METADATA +#include "metadata/core.h" +#endif #ifdef CONFIG_DBUS_INTERFACE #include "dbus-service.h" @@ -128,7 +131,7 @@ void activity_monitor_signify_activity(int active) { pthread_mutex_unlock(&activity_monitor_mutex); } // lock the mutex again to send a signal - pthread_cleanup_debug_mutex_lock(&activity_monitor_mutex, 10000, 1); + pthread_cleanup_debug_mutex_lock(&activity_monitor_mutex, 10000, 4); pthread_cond_signal(&activity_monitor_cv); pthread_cleanup_pop(1); // release the mutex } diff --git a/alac.c b/alac.c index 0b5587f3..daca81c9 100644 --- a/alac.c +++ b/alac.c @@ -44,13 +44,13 @@ static const int host_bigendian = 0; #define _Swap32(v) \ do { \ - v = (((v)&0x000000FF) << 0x18) | (((v)&0x0000FF00) << 0x08) | (((v)&0x00FF0000) >> 0x08) | \ - (((v)&0xFF000000) >> 0x18); \ + v = (((v) & 0x000000FF) << 0x18) | (((v) & 0x0000FF00) << 0x08) | \ + (((v) & 0x00FF0000) >> 0x08) | (((v) & 0xFF000000) >> 0x18); \ } while (0) #define _Swap16(v) \ do { \ - v = (((v)&0x00FF) << 0x08) | (((v)&0xFF00) >> 0x08); \ + v = (((v) & 0x00FF) << 0x08) | (((v) & 0xFF00) >> 0x08); \ } while (0) struct { @@ -603,11 +603,11 @@ static void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b, int uncompresse right |= uncompressed_bytes_buffer_b[i] & mask; } - ((uint8_t *)buffer_out)[i * numchannels * 3] = (left)&0xFF; + ((uint8_t *)buffer_out)[i * numchannels * 3] = (left) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF; - ((uint8_t *)buffer_out)[i * numchannels * 3 + 3] = (right)&0xFF; + ((uint8_t *)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF; } @@ -631,11 +631,11 @@ static void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b, int uncompresse right |= uncompressed_bytes_buffer_b[i] & mask; } - ((uint8_t *)buffer_out)[i * numchannels * 3] = (left)&0xFF; + ((uint8_t *)buffer_out)[i * numchannels * 3] = (left) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF; - ((uint8_t *)buffer_out)[i * numchannels * 3 + 3] = (right)&0xFF; + ((uint8_t *)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF; ((uint8_t *)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF; } @@ -798,7 +798,7 @@ void alac_decode_frame(alac_file *alac, unsigned char *inbuffer, void *outbuffer sample |= alac->uncompressed_bytes_buffer_a[i] & mask; } - ((uint8_t *)outbuffer)[i * alac->numchannels * 3] = (sample)&0xFF; + ((uint8_t *)outbuffer)[i * alac->numchannels * 3] = (sample) & 0xFF; ((uint8_t *)outbuffer)[i * alac->numchannels * 3 + 1] = (sample >> 8) & 0xFF; ((uint8_t *)outbuffer)[i * alac->numchannels * 3 + 2] = (sample >> 16) & 0xFF; } diff --git a/ap2_buffered_audio_processor.c b/ap2_buffered_audio_processor.c index 09581ded..e7fa237f 100644 --- a/ap2_buffered_audio_processor.c +++ b/ap2_buffered_audio_processor.c @@ -30,6 +30,7 @@ #include "rtp.h" #include "utilities/buffered_read.h" #include "utilities/mod23.h" +#include "utilities/network_utilities.h" #include #include @@ -91,10 +92,9 @@ void addADTStoPacket(uint8_t *packet, int packetLen, int rate, int channel_confi void rtp_buffered_audio_cleanup_handler(__attribute__((unused)) void *arg) { debug(2, "Buffered Audio Receiver Cleanup Start."); rtsp_conn_info *conn = (rtsp_conn_info *)arg; - close(conn->buffered_audio_socket); + safe_socket_close(&conn->buffered_audio_socket); debug(3, "Connection %d: closing TCP Buffered Audio port: %u.", conn->connection_number, conn->local_buffered_audio_port); - conn->buffered_audio_socket = 0; debug(2, "Connection %d: rtp_buffered_audio_processor exit.", conn->connection_number); } @@ -198,7 +198,7 @@ void *rtp_buffered_audio_processor(void *arg) { int packets_played_in_this_sequence = 0; int play_enabled = 0; - + int very_early_packets_signalled = 0; // double requested_lead_time = 0.0; // normal lead time minimum -- maybe it should be about 0.1 @@ -276,20 +276,19 @@ void *rtp_buffered_audio_processor(void *arg) { if (payload_ssrc != SSRC_NONE) previous_ssrc = payload_ssrc; payload_ssrc = nctohl(&packet[8]); - - if ((payload_ssrc != previous_ssrc) && (payload_ssrc != SSRC_NONE)) { if (ssrc_is_recognised(payload_ssrc) == 0) { debug(2, "Unrecognised SSRC: %u.", payload_ssrc); } else { debug(2, "Connection %d: incoming audio encoding is%s \"%s\".", - conn->connection_number, previous_ssrc == SSRC_NONE ? "" : " switching to", get_ssrc_name(payload_ssrc)); + conn->connection_number, previous_ssrc == SSRC_NONE ? "" : " switching to", + get_ssrc_name(payload_ssrc)); } } if ((payload_ssrc != previous_ssrc) && (ssrc_is_recognised(payload_ssrc) == 0)) { - debug(2, "Unrecognised SSRC: %u.", payload_ssrc); + debug(2, "Unrecognised SSRC: %u.", payload_ssrc); } if (blocks_read_since_play_began == 1) { @@ -327,7 +326,8 @@ void *rtp_buffered_audio_processor(void *arg) { finished = 1; } else if (nread < 0) { char errorstring[1024]; - strerror_r(errno, (char *)errorstring, sizeof(errorstring)); + (void)!strerror_r(errno, (char *)errorstring, + sizeof(errorstring)); // (void) ! to suppress unused response warning debug(1, "error in rtp_buffered_audio_processor %d: \"%s\". Could not recv a data_len .", errno, errorstring); finished = 1; @@ -343,34 +343,42 @@ void *rtp_buffered_audio_processor(void *arg) { debug(2, "immediate flush started at sequence number %u until sequence number of %u.", seq_no, conn->ap2_immediate_flush_until_sequence_number); } - if ((blocks_read != 0) && ((a_minus_b_mod23(seq_no, conn->ap2_immediate_flush_until_sequence_number) > 0))) { - debug(1, "immediate flush may have escaped its endpoint! Seq_no is %u, conn->ap2_immediate_flush_until_sequence_number is %u.", seq_no, conn->ap2_immediate_flush_until_sequence_number); + if ((blocks_read != 0) && + ((a_minus_b_mod23(seq_no, conn->ap2_immediate_flush_until_sequence_number) > 0))) { + debug(1, + "immediate flush may have escaped its endpoint! Seq_no is %u, " + "conn->ap2_immediate_flush_until_sequence_number is %u.", + seq_no, conn->ap2_immediate_flush_until_sequence_number); } - - if ((blocks_read != 0) && ((a_minus_b_mod23(seq_no, conn->ap2_immediate_flush_until_sequence_number) >= 0))) { - debug(2, "immediate flush completed at seq_no: %u, conn->ap2_immediate_flush_until_sequence_number: %u.", seq_no, conn->ap2_immediate_flush_until_sequence_number); + + if ((blocks_read != 0) && + ((a_minus_b_mod23(seq_no, conn->ap2_immediate_flush_until_sequence_number) >= 0))) { + debug(2, + "immediate flush completed at seq_no: %u, " + "conn->ap2_immediate_flush_until_sequence_number: %u.", + seq_no, conn->ap2_immediate_flush_until_sequence_number); conn->ap2_immediate_flush_requested = 0; ap2_immediate_flush_requested = 0; - // turn off all deferred requests. Not sure if this is right... unsigned int f = 0; for (f = 0; f < MAX_DEFERRED_FLUSH_REQUESTS; f++) { - if ((conn->ap2_deferred_flush_requests[f].inUse != 0) && (conn->ap2_deferred_flush_requests[f].active = 0)) { + if ((conn->ap2_deferred_flush_requests[f].inUse != 0) && + (conn->ap2_deferred_flush_requests[f].active = 0)) { debug(1, - "deferred flush cancelled by an immediate flush: flushFromTS: %12u, flushFromSeq: %12u, " - "flushUntilTS: %12u, flushUntilSeq: %12u, timestamp: %12u.", - conn->ap2_deferred_flush_requests[f].flushFromTS, - conn->ap2_deferred_flush_requests[f].flushFromSeq, - conn->ap2_deferred_flush_requests[f].flushUntilTS, - conn->ap2_deferred_flush_requests[f].flushUntilSeq, timestamp); + "deferred flush cancelled by an immediate flush: flushFromTS: %12u, " + "flushFromSeq: %12u, " + "flushUntilTS: %12u, flushUntilSeq: %12u, timestamp: %12u.", + conn->ap2_deferred_flush_requests[f].flushFromTS, + conn->ap2_deferred_flush_requests[f].flushFromSeq, + conn->ap2_deferred_flush_requests[f].flushUntilTS, + conn->ap2_deferred_flush_requests[f].flushUntilSeq, timestamp); } conn->ap2_deferred_flush_requests[f].inUse = 0; conn->ap2_deferred_flush_requests[f].active = 0; } - } else { debug(4, "immediate flush of block %u until block %u", seq_no, conn->ap2_immediate_flush_until_sequence_number); @@ -426,11 +434,10 @@ void *rtp_buffered_audio_processor(void *arg) { } else if (conn->ap2_deferred_flush_requests[f].active != 0) { new_audio_block_needed = 1; debug(4, - "deferred flush of block: %u, timestamp: %u, SSRC: \"%s\". flushFromTS: %12u, flushFromSeq: %12u, " + "deferred flush of block: %u, timestamp: %u, SSRC: \"%s\". flushFromTS: %12u, " + "flushFromSeq: %12u, " "flushUntilTS: %12u, flushUntilSeq: %12u, timestamp: %12u.", - seq_no, - timestamp, - get_ssrc_name(payload_ssrc), + seq_no, timestamp, get_ssrc_name(payload_ssrc), conn->ap2_deferred_flush_requests[f].flushFromTS, conn->ap2_deferred_flush_requests[f].flushFromSeq, conn->ap2_deferred_flush_requests[f].flushUntilTS, @@ -453,22 +460,28 @@ void *rtp_buffered_audio_processor(void *arg) { // and send it to the player. Otherwise, keep the block and sleep for a while. // calculate if there is room in the decoded audio buffer... - - // debug(1, "frames buffered: %f seconds, desired length: %f seconds.", (1.0 * player_buffer_occupancy * conn->frames_per_packet) / conn->input_rate, config.audio_decoded_buffer_desired_length); - - // int audio_decoded_buffer_below_desired_length = ((1.0 * player_buffer_occupancy * conn->frames_per_packet) / conn->input_rate) <= config.audio_decoded_buffer_desired_length; + + // debug(1, "frames buffered: %f seconds, desired length: %f seconds.", (1.0 * + // player_buffer_occupancy * conn->frames_per_packet) / conn->input_rate, + // config.audio_decoded_buffer_desired_length); + + // int audio_decoded_buffer_below_desired_length = ((1.0 * player_buffer_occupancy * + // conn->frames_per_packet) / conn->input_rate) <= + // config.audio_decoded_buffer_desired_length; uint64_t buffer_should_be_time; - + int have_valid_time = (frame_to_local_time(timestamp, &buffer_should_be_time, conn) == 0); - + // calculate the lead time to make sure it's not too early... int64_t lead_time = buffer_should_be_time - get_absolute_time_in_ns(); - - - // debug(1,"play_enabled: %d, have_valid_time: %d, audio_decoded_buffer_below_desired_length: %d, lead_time * 1E-9: %f, (config.audio_decoded_buffer_desired_length + 0.1): %f, player_buffer_occupancy: %zu", - // play_enabled, have_valid_time, audio_decoded_buffer_below_desired_length, lead_time * 1E-9, (config.audio_decoded_buffer_desired_length + 0.1), player_buffer_occupancy + + // debug(1,"play_enabled: %d, have_valid_time: %d, + // audio_decoded_buffer_below_desired_length: %d, lead_time * 1E-9: %f, + // (config.audio_decoded_buffer_desired_length + 0.1): %f, player_buffer_occupancy: %zu", + // play_enabled, have_valid_time, audio_decoded_buffer_below_desired_length, lead_time * + // 1E-9, (config.audio_decoded_buffer_desired_length + 0.1), player_buffer_occupancy // ); - + // A slight problem here is that counting the number of buffers may not be sufficient, // because the actual device may be // taking data in large quantities at a single time. @@ -476,196 +489,201 @@ void *rtp_buffered_audio_processor(void *arg) { // So we just have to ensure that there // is enough of a lead time maintained for sufficient audio to be available to prevent // the device from under-running. - + // If means that the Shairport Sync player might riun out of audio occasionally, but // as long as the device has enough in its buffer, everything is fine. - + // But it also means that Shairport Sync's buffers must be sufficient to hold all the // entire lead-time's amount of audio in case the device has a zero-sized buffer. - - if ((play_enabled != 0) && (have_valid_time != 0) -// (audio_decoded_buffer_below_desired_length != 0) && - && (lead_time * 1E-9 < (config.audio_decoded_buffer_desired_length + 0.1)) -// && (audio_decoded_buffer_below_desired_length != 0) - ) { - - very_early_packets_signalled = 0; //reset very early packet warning signaller - - // try to identify blocks that are timed to before the last buffer, and drop 'em - int64_t time_from_last_buffer_time = - buffer_should_be_time - previous_buffer_should_be_time; - - if ((packets_played_in_this_sequence == 0) || (time_from_last_buffer_time > 0)) { - - payload_length = 0; - if (ssrc_is_recognised(payload_ssrc) != 0) { - // prepare_decoding_chain(conn, payload_ssrc); - unsigned long long new_payload_length = 0; - payload_pointer = m + leading_free_space_length; - if (lead_time >= 0) { // only decipher the packet if it's not too late - int response = -1; // guess that there is a problem - if (conn->session_key != NULL) { - unsigned char nonce[12]; - memset(nonce, 0, sizeof(nonce)); - memcpy( - nonce + 4, packet + nread - 8, - 8); // front-pad the 8-byte nonce received to get the 12-byte nonce expected - - // https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/chacha20-poly1305/ietf_chacha20-poly1305_construction - // Note: the eight-byte nonce must be front-padded out to 12 bytes. - - // Leave leading_free_space_length bytes at the start for possible headers like an - // ADTS header (7 bytes) - memset(m, 0, leading_free_space_length); - response = crypto_aead_chacha20poly1305_ietf_decrypt( - payload_pointer, // where the decrypted payload will start - &new_payload_length, // mlen_p - NULL, // nsec, - packet + - 12, // the ciphertext starts 12 bytes in and is followed by the MAC tag, - nread - (8 + 12), // clen -- the last 8 bytes are the nonce - packet + 4, // authenticated additional data - 8, // authenticated additional data length - nonce, - conn->session_key); // *k - if (response != 0) - debug(1, "Error decrypting audio packet %u -- packet length %zd.", seq_no, - nread); - } else { - debug(2, "No session key, so the audio packet can not be deciphered -- skipped."); - } - - if ((response == 0) && (new_payload_length > 0)) { - // now we have the deciphered block, so send it to the player if we can - payload_length = new_payload_length; - - if (ssrc_is_aac(payload_ssrc)) { - payload_pointer = - payload_pointer - 7; // including the 7-byte leader for the ADTS - payload_length = payload_length + 7; - - // now, fill in the 7-byte ADTS information, which seems to be needed by the - // decoder we made room for it in the front of the buffer by filling from m + 7. - int channelConfiguration = 2; // 2: 2 channels: front-left, front-right - if (payload_ssrc == AAC_48000_F24_5P1) - channelConfiguration = 6; // 6: 6 channels: front-center, front-left, - // front-right, back-left, back-right, LFE-channel - else if (payload_ssrc == AAC_48000_F24_7P1) - channelConfiguration = - 7; // 7: 8 channels: front-center, front-left, front-right, - // side-left, side-right, back-left, back-right, LFE-channel - addADTStoPacket(payload_pointer, payload_length, conn->input_rate, - channelConfiguration); - } - int mute = - ((packets_played_in_this_sequence == 0) && (ssrc_is_aac(payload_ssrc))); - if (mute) { - debug(2, "Connection %d: muting first AAC block -- block %u -- timestamp %u.", - conn->connection_number, seq_no, timestamp); - } - int32_t timestamp_difference = 0; - if (packets_played_in_this_sequence == 0) { - // first_block_in_this_sequence = seq_no; - first_timestamp_in_this_sequence = timestamp; - debug(2, - "Connection %d: " - "first block %u, first timestamp %u.", - conn->connection_number, seq_no, timestamp); + + if (have_valid_time != 0) { + if ((play_enabled != 0) && (lead_time * 1E-9 < (config.audio_decoded_buffer_desired_length + 0.1))) { + // && (audio_decoded_buffer_below_desired_length != 0) + very_early_packets_signalled = 0; // reset very early packet warning signaller + + // try to identify blocks that are timed to before the last buffer, and drop 'em + int64_t time_from_last_buffer_time = + buffer_should_be_time - previous_buffer_should_be_time; + + if ((packets_played_in_this_sequence == 0) || (time_from_last_buffer_time > 0)) { + + payload_length = 0; + if (ssrc_is_recognised(payload_ssrc) != 0) { + // prepare_decoding_chain(conn, payload_ssrc); + unsigned long long new_payload_length = 0; + payload_pointer = m + leading_free_space_length; + if (lead_time >= 0) { // only decipher the packet if it's not too late + int response = -1; // guess that there is a problem + if (conn->session_key != NULL) { + unsigned char nonce[12]; + memset(nonce, 0, sizeof(nonce)); + memcpy( + nonce + 4, packet + nread - 8, + 8); // front-pad the 8-byte nonce received to get the 12-byte nonce expected + + // https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/chacha20-poly1305/ietf_chacha20-poly1305_construction + // Note: the eight-byte nonce must be front-padded out to 12 bytes. + + // Leave leading_free_space_length bytes at the start for possible headers like an + // ADTS header (7 bytes) + memset(m, 0, leading_free_space_length); + response = crypto_aead_chacha20poly1305_ietf_decrypt( + payload_pointer, // where the decrypted payload will start + &new_payload_length, // mlen_p + NULL, // nsec, + packet + + 12, // the ciphertext starts 12 bytes in and is followed by the MAC tag, + nread - (8 + 12), // clen -- the last 8 bytes are the nonce + packet + 4, // authenticated additional data + 8, // authenticated additional data length + nonce, + conn->session_key); // *k + if (response != 0) + debug(1, "Error decrypting audio packet %u -- packet length %zd.", seq_no, + nread); } else { - timestamp_difference = timestamp - expected_timestamp; - if (timestamp_difference != 0) { + debug(2, "No session key, so the audio packet can not be deciphered -- skipped."); + } + + if ((response == 0) && (new_payload_length > 0)) { + // now we have the deciphered block, so send it to the player if we can + payload_length = new_payload_length; + + if (ssrc_is_aac(payload_ssrc)) { + payload_pointer = + payload_pointer - 7; // including the 7-byte leader for the ADTS + payload_length = payload_length + 7; + + // now, fill in the 7-byte ADTS information, which seems to be needed by the + // decoder we made room for it in the front of the buffer by filling from m + 7. + int channelConfiguration = 2; // 2: 2 channels: front-left, front-right + if (payload_ssrc == AAC_48000_F24_5P1) + channelConfiguration = 6; // 6: 6 channels: front-center, front-left, + // front-right, back-left, back-right, LFE-channel + else if (payload_ssrc == AAC_48000_F24_7P1) + channelConfiguration = + 7; // 7: 8 channels: front-center, front-left, front-right, + // side-left, side-right, back-left, back-right, LFE-channel + addADTStoPacket(payload_pointer, payload_length, conn->input_rate, + channelConfiguration); + } + int mute = + ((packets_played_in_this_sequence == 0) && (ssrc_is_aac(payload_ssrc))); + if (mute) { + debug(2, "Connection %d: muting first AAC block -- block %u -- timestamp %u.", + conn->connection_number, seq_no, timestamp); + } + int32_t timestamp_difference = 0; + if (packets_played_in_this_sequence == 0) { + // first_block_in_this_sequence = seq_no; + first_timestamp_in_this_sequence = timestamp; debug(2, "Connection %d: " - "unexpected timestamp in block %u. Actual: %u, expected: %u " - "difference: %d, " - "%f ms. " - "Positive means later, i.e. a gap. First timestamp was %u, payload " - "type: \"%s\".", - conn->connection_number, seq_no, timestamp, expected_timestamp, - timestamp_difference, 1000.0 * timestamp_difference / conn->input_rate, - first_timestamp_in_this_sequence, get_ssrc_name(payload_ssrc)); - // mute the first packet after a discontinuity - if (ssrc_is_aac(payload_ssrc)) { + "first block %u, first timestamp %u.", + conn->connection_number, seq_no, timestamp); + } else { + timestamp_difference = timestamp - expected_timestamp; + if (timestamp_difference != 0) { debug(2, - "Connection %d: muting first AAC block -- block %u -- following a " - "timestamp discontinuity, timestamp %u.", - conn->connection_number, seq_no, timestamp); - mute = 1; + "Connection %d: " + "unexpected timestamp in block %u. Actual: %u, expected: %u " + "difference: %d, " + "%f ms. " + "Positive means later, i.e. a gap. First timestamp was %u, payload " + "type: \"%s\".", + conn->connection_number, seq_no, timestamp, expected_timestamp, + timestamp_difference, 1000.0 * timestamp_difference / conn->input_rate, + first_timestamp_in_this_sequence, get_ssrc_name(payload_ssrc)); + // mute the first packet after a discontinuity + if (ssrc_is_aac(payload_ssrc)) { + debug(2, + "Connection %d: muting first AAC block -- block %u -- following a " + "timestamp discontinuity, timestamp %u.", + conn->connection_number, seq_no, timestamp); + mute = 1; + } } } - } - int skip_this_block = 0; - if (timestamp_difference < 0) { - - // uncomment this to work back to replace buffers that have been already decoded - // and placed in the player queue with the incoming new buffers this is a bit - // trickier, but maybe the new buffers are better than the previous ones they - // will replace (?) - /* - seq_t revised_seqno = get_revised_seqno(conn, timestamp); - if (revised_seqno != sequence_number_for_player) { - debug(1, "revised seqno calculated: conn->ab_read: %u, revised_seqno: %u, - conn->ab_write: %u.", conn->ab_read, revised_seqno, conn->ab_write); - clear_buffers_from(conn, revised_seqno); - sequence_number_for_player = revised_seqno; - timestamp_difference = 0; + int skip_this_block = 0; + if (timestamp_difference < 0) { + + // uncomment this to work back to replace buffers that have been already decoded + // and placed in the player queue with the incoming new buffers this is a bit + // trickier, but maybe the new buffers are better than the previous ones they + // will replace (?) + /* + seq_t revised_seqno = get_revised_seqno(conn, timestamp); + if (revised_seqno != sequence_number_for_player) { + debug(1, "revised seqno calculated: conn->ab_read: %u, revised_seqno: %u, + conn->ab_write: %u.", conn->ab_read, revised_seqno, conn->ab_write); + clear_buffers_from(conn, revised_seqno); + sequence_number_for_player = revised_seqno; + timestamp_difference = 0; + } + */ + + // uncomment this to drop incoming new buffers that are too old and for whose + // timings buffers have already been decoded and placed in the player queue this + // is easier, but maybe the new late buffers are better than the previous ones + // (?) + + int32_t abs_timestamp_difference = -timestamp_difference; + if ((size_t)abs_timestamp_difference > get_ssrc_block_length(payload_ssrc)) { + skip_this_block = 1; + debug(2, + "skipping block %u because it is too old. Timestamp " + "difference: %d, length of block: %zu.", + seq_no, timestamp_difference, get_ssrc_block_length(payload_ssrc)); + } } - */ - - // uncomment this to drop incoming new buffers that are too old and for whose - // timings buffers have already been decoded and placed in the player queue this - // is easier, but maybe the new late buffers are better than the previous ones - // (?) - - int32_t abs_timestamp_difference = -timestamp_difference; - if ((size_t)abs_timestamp_difference > get_ssrc_block_length(payload_ssrc)) { - skip_this_block = 1; - debug(2, - "skipping block %u because it is too old. Timestamp " - "difference: %d, length of block: %zu.", - seq_no, timestamp_difference, get_ssrc_block_length(payload_ssrc)); + if (skip_this_block == 0) { + uint32_t packet_size = player_put_packet( + payload_ssrc, sequence_number_for_player, timestamp, payload_pointer, + payload_length, mute, timestamp_difference, conn); + debug(4, "block %u, timestamp %u, length %u sent to the player.", seq_no, + timestamp, packet_size); + sequence_number_for_player++; // simply increment + expected_timestamp = timestamp + packet_size; // for the next time + packets_played_in_this_sequence++; } } - if (skip_this_block == 0) { - uint32_t packet_size = player_put_packet( - payload_ssrc, sequence_number_for_player, timestamp, payload_pointer, - payload_length, mute, timestamp_difference, conn); - debug(4, "block %u, timestamp %u, length %u sent to the player.", seq_no, - timestamp, packet_size); - sequence_number_for_player++; // simply increment - expected_timestamp = timestamp + packet_size; // for the next time - packets_played_in_this_sequence++; + } else { + debug(3, + "skipped deciphering block %u with timestamp %u because its lead time is " + "out of range at %f " + "seconds.", + seq_no, timestamp, lead_time * 1.0E-9); + uint32_t currentAnchorRTP = 0; + uint64_t currentAnchorLocalTime = 0; + if (get_ptp_anchor_local_time_info(conn, ¤tAnchorRTP, + ¤tAnchorLocalTime) == clock_ok) { + debug(3, "anchorRTP: %u, anchorLocalTime: %" PRIu64 ".", currentAnchorRTP, + currentAnchorLocalTime); + } else { + debug(3, "Clock not okay"); } } } else { - debug(3, - "skipped deciphering block %u with timestamp %u because its lead time is " - "out of range at %f " - "seconds.", - seq_no, timestamp, lead_time * 1.0E-9); - uint32_t currentAnchorRTP = 0; - uint64_t currentAnchorLocalTime = 0; - if (get_ptp_anchor_local_time_info(conn, ¤tAnchorRTP, - ¤tAnchorLocalTime) == clock_ok) { - debug(3, "anchorRTP: %u, anchorLocalTime: %" PRIu64 ".", currentAnchorRTP, - currentAnchorLocalTime); - } else { - debug(3, "Clock not okay"); - } + debug(2, "Unrecognised or invalid ssrc: %s.", get_ssrc_name(payload_ssrc)); } } else { - debug(2, "Unrecognised or invalid ssrc: %s.", get_ssrc_name(payload_ssrc)); + debug(1, "dropping buffer that should have played before the last actually played."); } + new_audio_block_needed = 1; // the block has been used up and is no longer current } else { - debug(1, "dropping buffer that should have played before the last actually played."); + if ((very_early_packets_signalled == 0) && (lead_time * 1E-9 > (config.audio_decoded_buffer_desired_length + 0.2))) { + debug(1, + "incoming frame suddenly (?) has a lead time of %f seconds, with a desired " + "decoded buffer length of %f.", + 1.0 * lead_time * 1E-9, config.audio_decoded_buffer_desired_length); + very_early_packets_signalled = 1; + } + usleep(((1000000 * conn->frames_per_packet) / conn->input_rate) * + 2); // wait for approximately the length of two packets } - new_audio_block_needed = 1; // the block has been used up and is no longer current } else { - if ((have_valid_time != 0) && (very_early_packets_signalled == 0) && (lead_time * 1E-9 > (config.audio_decoded_buffer_desired_length + 0.2))) { - debug(1, "incoming frame suddenly (?) has a lead time of %f seconds, with a desired decoded buffer length of %f.", 1.0 * lead_time * 1E-9, config.audio_decoded_buffer_desired_length); - very_early_packets_signalled = 1; - } - usleep(((1000000 * conn->frames_per_packet) / conn->input_rate) * 2); // wait for approximately the length of two packets + debug(3, "just you wait, Henry Higgins, without valid timing information..."); + usleep(20000); // just you wait, Henry Higgins... } } } diff --git a/ap2_event_message_handler.c b/ap2_event_message_handler.c new file mode 100644 index 00000000..94a84d0d --- /dev/null +++ b/ap2_event_message_handler.c @@ -0,0 +1,139 @@ +/* + * AirPlay 2 Event Port Message Handler. This file is part of Shairport Sync + * Copyright (c) Mike Brady 2025 + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "ap2_event_message_handler.h" +#include "common.h" +#include "rtsp.h" +#include "utilities/generate_random_uuid.h" +#include "utilities/structured_buffer.h" + +void decodeAndLogPlist(plist_t plist_to_log) { + if (plist_to_log != NULL) { + char *plist_as_string = plist_as_xml_text(plist_to_log); + if (plist_as_string != NULL) { + debug(3, "--\n%s\n--\n", plist_as_string); + free(plist_as_string); + } + } +} + +// will return -1 if there is an error or port is not open, 0 if the port was closed and a positive +// number if okay +ssize_t ap2_event_port_send_message(rtsp_conn_info *conn, char *data, size_t data_length) { + ssize_t result = -1; // assume a problem + debug_mutex_lock(&conn->event_sender_mutex, 1000000, 4); + pthread_cleanup_push(mutex_unlock, &conn->event_sender_mutex); + if (conn->event_channel_fd != 0) { + result = write_encrypted(conn->event_channel_fd, &conn->ap2_pairing_context.event_cipher_bundle, + data, data_length); + if ((result != -1) && ((size_t)result == data_length)) { + debug(3, "Connection %d: Packet of %zu bytes successfully written on the Event Port.", + conn->connection_number, result); + uint8_t packet[4096]; + result = + read_encrypted(conn->event_channel_fd, &conn->ap2_pairing_context.event_cipher_bundle, + packet, sizeof(packet)); + debug(3, "Connection %d: Packet of %zu bytes successfully read on the Event Port.", + conn->connection_number, result); + if (result > 0) { + packet[result] = '\0'; + debug(3, "Connection %d: Packet Received on Event Port with contents: \n--\n%s\n--\n", + conn->connection_number, packet); + } else { + debug(2, "Connection %d: Event Port connection closed by client", conn->connection_number); + } + } else { + result = -1; // this covers a situation where the result is positive but not the same as the + // data_length + } + } else { + debug(1, "Connection %d: attempt to send a command to the event port over a closed socket", + conn->connection_number); + } + pthread_cleanup_pop(1); // unlock the mutex + return result; +} + +ssize_t ap2_event_port_post_command(rtsp_conn_info *conn, plist_t command) { + ssize_t result = 0; + decodeAndLogPlist(command); + structured_buffer *sbuf = sbuf_new(4096); + if (sbuf != NULL) { + pthread_cleanup_push(sbuf_cleanup, sbuf); + char *plistString = NULL; + uint32_t plistStringLength = 0; + + plist_to_bin(command, &plistString, &plistStringLength); + if (plistString != NULL) { + sbuf_printf(sbuf, "POST /command RTSP/1.0\r\nContent-Length: %u\r\n", plistStringLength); + sbuf_printf(sbuf, "Content-Type: application/x-apple-binary-plist\r\n\r\n"); + sbuf_append(sbuf, plistString, plistStringLength); + free(plistString); // should be plist_to_bin_free, but it's not defined in older + // libraries + char *b = 0; + size_t l = 0; + sbuf_buf_and_length(sbuf, &b, &l); + result = ap2_event_port_send_message(conn, b, l); + debug(3, "Connection %d: POST /command sent on the event port. Result is %zd.", + conn->connection_number, result); + sbuf_clear(sbuf); + } + pthread_cleanup_pop(1); // delete the structured buffer + } + return result; +} + +ssize_t ap2_event_send_update_info(rtsp_conn_info *conn) { + // sends the updateInfo plist on the event port + ssize_t result = -1; + plist_t value_plist = generateInfoPlist(conn); + if (value_plist != NULL) { + void *txtData = NULL; + size_t txtDataLength = 0; + generateTxtDataValueInfo(conn, &txtData, &txtDataLength); + plist_dict_set_item(value_plist, "txtAirPlay", plist_new_data(txtData, txtDataLength)); + free(txtData); + plist_t update_info_plist = plist_new_dict(); + if (update_info_plist != NULL) { + plist_dict_set_item(update_info_plist, "type", plist_new_string("updateInfo")); + plist_dict_set_item(update_info_plist, "value", value_plist); + + char *plist_as_string = plist_as_xml_text(update_info_plist); + if (plist_as_string != NULL) { + debug(3, "update_info_plist is:\n--\n\"%s\"\n--\n", plist_as_string); + free(plist_as_string); + } + + result = ap2_event_port_post_command(conn, update_info_plist); + plist_free(update_info_plist); + } else { + debug(1, "Could not build an updateInfo plist"); + } + } else { + debug(1, "Could not build an updateInfo value plist"); + } + return result; +} diff --git a/ap2_event_message_handler.h b/ap2_event_message_handler.h new file mode 100644 index 00000000..a632c33a --- /dev/null +++ b/ap2_event_message_handler.h @@ -0,0 +1,15 @@ +#ifndef _AP2_EVENT_COMMAND_SENDER_H +#define _AP2_EVENT_COMMAND_SENDER_H + +#include "player.h" +#include +#include + +ssize_t ap2_event_send_unit_volume_notification(rtsp_conn_info *conn, double volume); +ssize_t ap2_event_send_modern_media_remote_command(rtsp_conn_info *conn, + unsigned int command_number); +ssize_t ap2_event_send_update_info(rtsp_conn_info *conn); + +ssize_t ap2_event_send_dev_mule(); + +#endif // _AP2_EVENT_COMMAND_SENDER_H diff --git a/ap2_event_receiver.c b/ap2_event_receiver.c index 48d10d54..29f23970 100644 --- a/ap2_event_receiver.c +++ b/ap2_event_receiver.c @@ -1,6 +1,6 @@ /* * Apple AirPlay 2 Event Receiver. This file is part of Shairport Sync. - * Copyright (c) Mike Brady 2014--2025 + * Copyright (c) Mike Brady 2014--2026 * All rights reserved. * * Permission is hereby granted, free of charge, to any person @@ -25,23 +25,26 @@ */ #include "ap2_event_receiver.h" -#include "bonjour_strings.h" +#include "ap2_event_message_handler.h" #include "common.h" #include "player.h" -#include "ptp-utilities.h" -#include "rtsp.h" #include "utilities/network_utilities.h" -#include "utilities/structured_buffer.h" + +#ifdef CONFIG_METADATA +#include "metadata/core.h" +#endif void ap2_event_receiver_cleanup_handler(void *arg) { rtsp_conn_info *conn = (rtsp_conn_info *)arg; // debug(1, "Connection %d: AP2 Event Receiver Cleanup start.", conn->connection_number); - // only update these things if you're (still) the principal conn - #ifdef CONFIG_METADATA // this is here to ensure it's only performed once during a teardown of a ptp stream send_ssnc_metadata('disc', conn->client_ip_string, strlen(conn->client_ip_string), 1); #endif + debug_mutex_lock(&conn->event_sender_mutex, 1000000, 4); + pthread_cleanup_push(mutex_unlock, &conn->event_sender_mutex); + safe_socket_close(&conn->event_channel_fd); + pthread_cleanup_pop(1); // unlock the mutex if (conn->airplay_gid != NULL) { free(conn->airplay_gid); @@ -52,161 +55,43 @@ void ap2_event_receiver_cleanup_handler(void *arg) { free(conn->dacp_active_remote); conn->dacp_active_remote = NULL; } - if (conn->ap2_client_name) { - free(conn->ap2_client_name); - conn->ap2_client_name = NULL; - } - /* - pthread_rwlock_wrlock(&principal_conn_lock); // don't let the principal_conn be changed - pthread_cleanup_push(rwlock_unlock, (void *)&principal_conn_lock); - if (principal_conn) - debug(1, "principal_conn: %d.", principal_conn->connection_number); - else - debug(1, "principal_conn: is NULL."); - if (principal_conn == conn) { - config.airplay_statusflags &= (0xffffffff - (1 << 11)); // DeviceSupportsRelay - build_bonjour_strings(conn); - debug(1, "Connection %d: SETUP mdns_update on %s.", conn->connection_number, - get_category_string(conn->airplay_stream_category)); - mdns_update(NULL, secondary_txt_records); - principal_conn = NULL; - } - pthread_cleanup_pop(1); // release the principal_conn lock - */ debug(2, "Connection %d: AP2 Event Receiver Cleanup is complete.", conn->connection_number); } void *ap2_event_receiver(void *arg) { - // #include - // debug(1, "rtp_event_receiver PID %d", syscall(SYS_gettid)); rtsp_conn_info *conn = (rtsp_conn_info *)arg; debug(2, "Connection %d: AP2 Event Receiver started", conn->connection_number); - structured_buffer *sbuf = sbuf_new(4096); - if (sbuf != NULL) { - pthread_cleanup_push(sbuf_cleanup, sbuf); + SOCKADDR remote_addr; + memset(&remote_addr, 0, sizeof(remote_addr)); + socklen_t addr_size = sizeof(remote_addr); - /* - // only update these things if you're (still) the principal conn - pthread_rwlock_wrlock(&principal_conn_lock); // don't let the principal_conn be changed - pthread_cleanup_push(rwlock_unlock, (void *)&principal_conn_lock); - if (principal_conn == conn) { - config.airplay_statusflags |= 1 << 11; // DeviceSupportsRelay - // config.airplay_statusflags |= 1 << 17; // ReceiverSessionIsActive - build_bonjour_strings(conn); - debug(2, "Connection %d: SETUP mdns_update on %s.", conn->connection_number, - get_category_string(conn->airplay_stream_category)); - mdns_update(NULL, secondary_txt_records); - } - pthread_cleanup_pop(1); // release the principal_conn lock - */ - pthread_cleanup_push(ap2_event_receiver_cleanup_handler, arg); - - // listen(conn->event_socket, 5); // this is now done in the handle_setup_2 code - - uint8_t packet[4096]; - ssize_t nread; - SOCKADDR remote_addr; - memset(&remote_addr, 0, sizeof(remote_addr)); - socklen_t addr_size = sizeof(remote_addr); - - int fd = eintr_checked_accept(conn->event_socket, (struct sockaddr *)&remote_addr, &addr_size); + debug_mutex_lock(&conn->event_sender_mutex, 1000000, 4); + pthread_cleanup_push(mutex_unlock, &conn->event_sender_mutex); + conn->event_channel_fd = + eintr_checked_accept(conn->event_socket, (struct sockaddr *)&remote_addr, &addr_size); + pthread_cleanup_pop(1); // unlock the mutex + if (conn->event_channel_fd > 0) { debug(2, "Connection %d: ap2_event_receiver accepted a connection on socket %d and moved to a new " "socket %d.", - conn->connection_number, conn->event_socket, fd); - intptr_t pfd = fd; - pthread_cleanup_push(socket_cleanup, (void *)pfd); - int finished = 0; - do { + conn->connection_number, conn->event_socket, conn->event_channel_fd); + pthread_cleanup_push(ap2_event_receiver_cleanup_handler, arg); - plist_t value_plist = generateInfoPlist(conn); - if (value_plist != NULL) { - void *txtData = NULL; - size_t txtDataLength = 0; - generateTxtDataValueInfo(conn, &txtData, &txtDataLength); - plist_dict_set_item(value_plist, "txtAirPlay", plist_new_data(txtData, txtDataLength)); - free(txtData); - plist_t update_info_plist = plist_new_dict(); - if (update_info_plist != NULL) { - plist_dict_set_item(update_info_plist, "type", plist_new_string("updateInfo")); - plist_dict_set_item(update_info_plist, "value", value_plist); - char *plistString = NULL; - uint32_t plistStringLength = 0; - plist_to_bin(update_info_plist, &plistString, &plistStringLength); - if (plistString != NULL) { - char *plist_as_string = plist_as_xml_text(update_info_plist); - if (plist_as_string != NULL) { - debug(3, "Plist is: \"%s\".", plist_as_string); - free(plist_as_string); - } - sbuf_printf(sbuf, "POST /command RTSP/1.0\r\nContent-Length: %u\r\n", - plistStringLength); - sbuf_printf(sbuf, "Content-Type: application/x-apple-binary-plist\r\n\r\n"); - sbuf_append(sbuf, plistString, plistStringLength); + ap2_event_send_update_info(conn); - free(plistString); // should be plist_to_bin_free, but it's not defined in older - // libraries - char *b = 0; - size_t l = 0; - sbuf_buf_and_length(sbuf, &b, &l); - ssize_t wres = - write_encrypted(fd, &conn->ap2_pairing_context.event_cipher_bundle, b, l); - if ((wres == -1) || ((size_t)wres != l)) - debug(1, "Encrypted write error"); - - sbuf_clear(sbuf); - } else { - debug(1, "plist string not created!"); - } - plist_free(update_info_plist); - } else { - debug(1, "Could not build an updateInfo plist"); - } - // plist_free(value_plist); - } else { - debug(1, "Could not build an value plist"); - } - - while (finished == 0) { - nread = read_encrypted(fd, &conn->ap2_pairing_context.event_cipher_bundle, packet, - sizeof(packet)); - - // nread = recv(fd, packet, sizeof(packet), 0); - - if (nread < 0) { - char errorstring[1024]; - strerror_r(errno, (char *)errorstring, sizeof(errorstring)); - debug(1, - "Connection %d: error in ap2_event_receiver %d: \"%s\". Could not recv a packet.", - conn->connection_number, errno, errorstring); - // if ((config.diagnostic_drop_packet_fraction == 0.0) || - // (drand48() > config.diagnostic_drop_packet_fraction)) { - } else if (nread > 0) { - - // ssize_t plen = nread; - packet[nread] = '\0'; - debug(3, "Connection %d: Packet Received on Event Port with contents: \"%s\".", - conn->connection_number, packet); - } else { - debug(2, "Connection %d: Event Port connection closed by client", - conn->connection_number); - finished = 1; - } - } - - } while (finished == 0); + while (1) { + usleep(100000); + }; debug(3, "Connection %d: AP2 Event Receiver RTP thread starting \"normal\" exit.", conn->connection_number); - pthread_cleanup_pop(1); // close the socket - pthread_cleanup_pop(1); // do the cleanup - pthread_cleanup_pop(1); // delete the structured buffer - debug(2, "Connection %d: AP2 Event Receiver RTP thread \"normal\" exit.", - conn->connection_number); } else { - debug(1, "Could not allocate a structured buffer!"); + debug(1, "Connection %d: could not accept an event socket", conn->connection_number); + conn->event_channel_fd = -1; } + debug(2, "Connection %d: AP2 Event Receiver RTP thread \"normal\" exit.", + conn->connection_number); conn->ap2_event_receiver_exited = 1; pthread_exit(NULL); } diff --git a/ap2_rc_event_receiver.c b/ap2_rc_event_receiver.c deleted file mode 100644 index 0fba8562..00000000 --- a/ap2_rc_event_receiver.c +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Apple AirPlay 2 Remote Control (RC) Event Receiver. This file is part of Shairport Sync. - * Copyright (c) Mike Brady 2014--2025 - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "ap2_rc_event_receiver.h" -#include "common.h" -#include "player.h" -#include "rtsp.h" -#include "utilities/network_utilities.h" -#include "utilities/structured_buffer.h" - -void ap2_rc_event_receiver_cleanup_handler(void *arg) { - rtsp_conn_info *conn = (rtsp_conn_info *)arg; - debug(2, "Connection %d: AP2 Event Receiver Cleanup.", conn->connection_number); -} - -void *ap2_rc_event_receiver(void *arg) { - // #include - // debug(1, "rtp_event_receiver PID %d", syscall(SYS_gettid)); - rtsp_conn_info *conn = (rtsp_conn_info *)arg; - if (conn->airplay_stream_category == remote_control_stream) - debug(2, "Connection %d (RC): AP2 RC Event Receiver started", conn->connection_number); - else - debug(2, "Connection %d: AP2 RC Event Receiver started", conn->connection_number); - - structured_buffer *sbuf = sbuf_new(4096); - if (sbuf != NULL) { - pthread_cleanup_push(sbuf_cleanup, sbuf); - - pthread_cleanup_push(ap2_rc_event_receiver_cleanup_handler, arg); - - // listen(conn->event_socket, 5); // this is now done in the handle_setup_2 code - - uint8_t packet[4096]; - ssize_t nread; - SOCKADDR remote_addr; - memset(&remote_addr, 0, sizeof(remote_addr)); - socklen_t addr_size = sizeof(remote_addr); - - int fd = eintr_checked_accept(conn->event_socket, (struct sockaddr *)&remote_addr, &addr_size); - debug(2, - "Connection %d: ap2_rc_event_receiver accepted a connection on socket %d and moved to a " - "new " - "socket %d.", - conn->connection_number, conn->event_socket, fd); - intptr_t pfd = fd; - pthread_cleanup_push(socket_cleanup, (void *)pfd); - int finished = 0; - do { - - plist_t value_plist = generateInfoPlist(conn); - if (value_plist != NULL) { - void *txtData = NULL; - size_t txtDataLength = 0; - generateTxtDataValueInfo(conn, &txtData, &txtDataLength); - plist_dict_set_item(value_plist, "txtAirPlay", plist_new_data(txtData, txtDataLength)); - free(txtData); - plist_t update_info_plist = plist_new_dict(); - if (update_info_plist != NULL) { - plist_dict_set_item(update_info_plist, "type", plist_new_string("updateInfo")); - plist_dict_set_item(update_info_plist, "value", value_plist); - char *plistString = NULL; - uint32_t plistStringLength = 0; - plist_to_bin(update_info_plist, &plistString, &plistStringLength); - if (plistString != NULL) { - char *plist_as_string = plist_as_xml_text(update_info_plist); - if (plist_as_string != NULL) { - debug(3, "Plist is: \"%s\".", plist_as_string); - free(plist_as_string); - } - sbuf_printf(sbuf, "POST /command RTSP/1.0\r\nContent-Length: %u\r\n", - plistStringLength); - sbuf_printf(sbuf, "Content-Type: application/x-apple-binary-plist\r\n\r\n"); - sbuf_append(sbuf, plistString, plistStringLength); - - free(plistString); // should be plist_to_bin_free, but it's not defined in older - // libraries - char *b = 0; - size_t l = 0; - sbuf_buf_and_length(sbuf, &b, &l); - ssize_t wres = - write_encrypted(fd, &conn->ap2_pairing_context.event_cipher_bundle, b, l); - if ((wres == -1) || ((size_t)wres != l)) - debug(1, "Encrypted write error"); - - sbuf_clear(sbuf); - } else { - debug(1, "plist string not created!"); - } - plist_free(update_info_plist); - } else { - debug(1, "Could not build an updateInfo plist"); - } - // plist_free(value_plist); - } else { - debug(1, "Could not build an value plist"); - } - - while (finished == 0) { - nread = read_encrypted(fd, &conn->ap2_pairing_context.event_cipher_bundle, packet, - sizeof(packet)); - - // nread = recv(fd, packet, sizeof(packet), 0); - - if (nread < 0) { - char errorstring[1024]; - strerror_r(errno, (char *)errorstring, sizeof(errorstring)); - debug( - 1, - "Connection %d: error in ap2_rc_event_receiver %d: \"%s\". Could not recv a packet.", - conn->connection_number, errno, errorstring); - // if ((config.diagnostic_drop_packet_fraction == 0.0) || - // (drand48() > config.diagnostic_drop_packet_fraction)) { - } else if (nread > 0) { - - // ssize_t plen = nread; - packet[nread] = '\0'; - debug(2, - "Connection %d: ap2_rc_event_receiver Packet Received on Event Port with contents: " - "\"%s\".", - conn->connection_number, packet); - } else { - debug(2, "Connection %d: ap2_rc_event_receiver Event Port connection closed by client", - conn->connection_number); - finished = 1; - } - } - - } while (finished == 0); - pthread_cleanup_pop(1); // close the socket - pthread_cleanup_pop(1); // do the cleanup - pthread_cleanup_pop(1); // delete the structured buffer - debug(2, "Connection %d: AP2 ap2_rc_event_receiver \"normal\" exit.", conn->connection_number); - } else { - debug(1, "Could not allocate a structured buffer!"); - } - conn->ap2_event_receiver_exited = 1; - pthread_exit(NULL); -} diff --git a/ap2_rc_event_receiver.h b/ap2_rc_event_receiver.h deleted file mode 100644 index 200e785b..00000000 --- a/ap2_rc_event_receiver.h +++ /dev/null @@ -1,8 +0,0 @@ -// RC means Remote Control - -#ifndef _AP2_RC_EVENT_RECEIVER_H -#define _AP2_RC_EVENT_RECEIVER_H - -void *ap2_rc_event_receiver(void *arg); - -#endif // _AP2_RC_EVENT_RECEIVER_H diff --git a/audio.c b/audio.c index a703d660..90ca8fac 100644 --- a/audio.c +++ b/audio.c @@ -458,7 +458,7 @@ uint32_t get_channel_settings(const char *stanza_name, const char *setting_name) for (i = 0; i < channel_counts_count; i++) { debug(3, "channel count setting %d: %d.", i, channel_counts[i]); - if ((channel_counts[i] >= 1) && (channel_counts[i] <= 8)) { + if ((channel_counts[i] >= 1) && (channel_counts[i] <= SPS_GREATEST_CHANNEL_COUNT)) { #ifdef CONFIG_FFMPEG channel_set |= (1 << channel_counts[i]); #else @@ -492,7 +492,7 @@ uint32_t get_channel_settings(const char *stanza_name, const char *setting_name) char numbuf[32]; unsigned int c; uint32_t t_channel_set = channel_set; - for (c = 0; c <= 8; c++) { + for (c = 0; c <= SPS_GREATEST_CHANNEL_COUNT; c++) { if ((t_channel_set & (1 << c)) != 0) { snprintf(numbuf, sizeof(numbuf) - 1, "%u", c); snprintf(p, sizeof(buf) - (p - buf) - 1, "%s", numbuf); diff --git a/audio_alsa.c b/audio_alsa.c index b105457c..83ed20df 100644 --- a/audio_alsa.c +++ b/audio_alsa.c @@ -40,6 +40,7 @@ #include "activity_monitor.h" #include "audio.h" #include "common.h" +#include "utilities/string_utilities.h" enum alsa_backend_mode { abm_disconnected, @@ -306,7 +307,7 @@ static int get_permissible_configuration_settings() { debug(3, "\"%s\" can handle %u channels.", alsa_out_dev, c); } else { // the device can't handle this number of channels - debug(3, "\"%s\" can not handle %u channels.", alsa_out_dev, c); + debug(4, "\"%s\" can not handle %u channels.", alsa_out_dev, c); config.channel_set &= ~(1 << c); // the alsa device can't accommodate this number of channels } @@ -332,7 +333,7 @@ static int get_permissible_configuration_settings() { debug(3, "\"%s\" can handle a rate of %u fps.", alsa_out_dev, sps_rate_actual_rate(r)); } else { - debug(3, "\"%s\" can not handle a rate of %u fps.", alsa_out_dev, + debug(4, "\"%s\" can not handle a rate of %u fps.", alsa_out_dev, sps_rate_actual_rate(r)); config.rate_set &= ~(1 << r); // the alsa device doesn't do this rate } @@ -357,7 +358,7 @@ static int get_permissible_configuration_settings() { debug(3, "\"%s\" can handle the %s format.", alsa_out_dev, sps_format_description_string(f)); } else { - debug(3, "\"%s\" can not handle the %s format.", alsa_out_dev, + debug(4, "\"%s\" can not handle the %s format.", alsa_out_dev, sps_format_description_string(f)); config.format_set &= ~(1 << f); // the alsa device doesn't do this format } @@ -951,8 +952,8 @@ static int actual_open_alsa_device() { if ((snd_pcm_hw_params_get_rate_numden(alsa_params, &uval, &uval2) == 0) && (uval2 != 0)) // watch for a divide by zero too! - debug(log_level, " precise (rational) rate = %.3f frames per second (i.e. %u/%u).", (1.0 * uval) / uval2, uval, - uval2); + debug(log_level, " precise (rational) rate = %.3f frames per second (i.e. %u/%u).", + (1.0 * uval) / uval2, uval, uval2); else debug(log_level, " precise (rational) rate information unavailable."); @@ -1260,7 +1261,8 @@ static int init(int argc, char **argv) { else { warn("Invalid disable_synchronization option choice \"%s\". It should " "be \"yes\" or " - "\"no\". It is set to \"no\".", str); + "\"no\". It is set to \"no\".", + str); config.no_sync = 0; } } @@ -1276,7 +1278,8 @@ static int init(int argc, char **argv) { else { warn("Invalid mute_using_playback_switch option choice \"%s\". It " "should be \"yes\" or " - "\"no\". It is set to \"no\".", str); + "\"no\". It is set to \"no\".", + str); config.alsa_use_hardware_mute = 0; } } @@ -1290,7 +1293,8 @@ static int init(int argc, char **argv) { else { warn("Invalid use_hardware_mute_if_available option choice \"%s\". It " "should be \"yes\" or " - "\"no\". It is set to \"no\".", str); + "\"no\". It is set to \"no\".", + str); config.alsa_use_hardware_mute = 0; } } @@ -1304,7 +1308,8 @@ static int init(int argc, char **argv) { else { warn("Invalid use_mmap_if_available option choice \"%s\". It should be " "\"yes\" or \"no\". " - "It remains set to \"yes\".", str); + "It remains set to \"yes\".", + str); config.no_mmap = 0; } } @@ -1424,7 +1429,8 @@ static int init(int argc, char **argv) { else { warn("Invalid use_precision_timing option choice \"%s\". It should be " "\"yes\", \"auto\" or \"no\". " - "It remains set to \"%s\".", str, + "It remains set to \"%s\".", + str, config.use_precision_timing == YNA_NO ? "no" : config.use_precision_timing == YNA_AUTO ? "auto" : "yes"); @@ -2177,14 +2183,14 @@ static void flush(void) { } static void stop(void) { - pthread_cleanup_debug_mutex_lock(&alsa_mutex, 10000, 1); + pthread_cleanup_debug_mutex_lock(&alsa_mutex, 10000, 4); if (alsa_backend_state != abm_disconnected) { // must be playing or connected... if (config.keep_dac_busy == 0) { do_close(); } } else debug(3, "alsa: stop() -- called on a disconnected alsa backend"); - debug_mutex_unlock(&alsa_mutex, 3); + debug_mutex_unlock(&alsa_mutex, 4); pthread_cleanup_pop(0); // release the mutex } @@ -2252,7 +2258,7 @@ static void *alsa_buffer_monitor_thread_code(__attribute__((unused)) void *arg) // #include // debug(1, "alsa_buffer_monitor_thread_code PID %d", syscall(SYS_gettid)); // Wait until the output configuration has been set by the main program - debug(2, "alsa: alsa_buffer_monitor_thread_code started."); + debug(1, "alsa: alsa_buffer_monitor_thread_code started."); int frame_count = 0; int error_count = 0; int error_detected = 0; diff --git a/audio_pa.c b/audio_pa.c index a0c6afec..82f57cf5 100644 --- a/audio_pa.c +++ b/audio_pa.c @@ -506,7 +506,8 @@ static int init(__attribute__((unused)) int argc, __attribute__((unused)) char * // get the default channel mapping setting basis -- "alsa" or "pulseaudio". - if (config_lookup_non_empty_string(config.cfg, "pulseaudio.default_channel_layouts", &default_channel_layouts)) { + if (config_lookup_non_empty_string(config.cfg, "pulseaudio.default_channel_layouts", + &default_channel_layouts)) { if ((strcasecmp(default_channel_layouts, "alsa") == 0) || (strcasecmp(default_channel_layouts, "pulseaudio") == 0)) { debug(1, "pulseaudio default_channel_layouts setting: \"%s\".", default_channel_layouts); @@ -767,8 +768,6 @@ void stream_write_cb(pa_stream *local_stream, size_t requested_bytes, pthread_cleanup_pop(1); // release the mutex if (ret != 0) debug(1, "error writing to pa buffer"); - // debug(1,"<< #include +#include "utilities/network_utilities.h" + static int fd = -1; static int warned = 0; static unsigned int bytes_per_frame = 0; @@ -146,10 +148,7 @@ static int init(int argc, char **argv) { return 0; } -static void deinit(void) { - if (fd > 0) - close(fd); -} +static void deinit(void) { safe_socket_close(&fd); } static void help(void) { printf(" Provide the pipe's pathname. The default is \"%s\".\n", default_pipe_name); diff --git a/bonjour_strings.c b/bonjour_strings.c index 19d63e98..5edf400c 100644 --- a/bonjour_strings.c +++ b/bonjour_strings.c @@ -76,72 +76,76 @@ void build_bonjour_strings(__attribute((unused)) rtsp_conn_info *conn) { // the secondary_txt_records are for the _airplay._tcp items. #ifdef CONFIG_AIRPLAY_2 - txt_records[entry_number++] = "cn=0,1"; - txt_records[entry_number++] = "da=true"; - txt_records[entry_number++] = "et=0,1"; - if (config.password != NULL) - txt_records[entry_number++] = "pw=true"; uint64_t features_hi = config.airplay_features; features_hi = (features_hi >> 32) & 0xffffffff; uint64_t features_lo = config.airplay_features; features_lo = features_lo & 0xffffffff; - txt_records[entry_number++] = - bnprintf(ap1_featuresString, sizeof(ap1_featuresString), "ft=0x%" PRIX64 ",0x%" PRIX64 "", - features_lo, features_hi); + if (config.service_type == APST_airplay2) { + txt_records[entry_number++] = "cn=0,1"; + txt_records[entry_number++] = "da=true"; + txt_records[entry_number++] = "et=0,1"; + if (config.password != NULL) + txt_records[entry_number++] = "pw=true"; - txt_records[entry_number++] = - bnprintf(fwString, sizeof(fwString), "fv=%s", config.firmware_version); - txt_records[entry_number++] = bnprintf(ap1StatusFlagsString, sizeof(ap1StatusFlagsString), - "sf=0x%" PRIX32, config.airplay_statusflags); -#ifdef CONFIG_METADATA - if (config.get_coverart == 0) - txt_records[entry_number++] = "md=0,2"; - else - txt_records[entry_number++] = "md=0,1,2"; -#endif - txt_records[entry_number++] = - bnprintf(ap1ModelString, sizeof(ap1ModelString), "am=%s", config.model); - txt_records[entry_number++] = bnprintf(pkString, sizeof(pkString), "pk=%s", config.pk_string); - txt_records[entry_number++] = "tp=UDP"; - txt_records[entry_number++] = "vn=65537"; - txt_records[entry_number++] = - bnprintf(ap1SrcversString, sizeof(ap1SrcversString), "vs=%s", config.srcvers); - txt_records[entry_number++] = - bnprintf(ap1OsversString, sizeof(ap1OsversString), "ov=%s", config.osvers); - txt_records[entry_number++] = NULL; + txt_records[entry_number++] = + bnprintf(ap1_featuresString, sizeof(ap1_featuresString), "ft=0x%" PRIX64 ",0x%" PRIX64 "", + features_lo, features_hi); -#else - // here, just replicate what happens in mdns.h when using those #defines - txt_records[entry_number++] = - bnprintf(ap1StatusFlagsString, sizeof(ap1StatusFlagsString), "sf=0x4"); - txt_records[entry_number++] = - bnprintf(fwString, sizeof(fwString), "fv=%s", config.firmware_version); - txt_records[entry_number++] = - bnprintf(ap1ModelString, sizeof(ap1ModelString), "am=%s", config.model); - txt_records[entry_number++] = bnprintf(ap1SrcversString, sizeof(ap1SrcversString), "vs=105.1"); - txt_records[entry_number++] = "tp=TCP,UDP"; - txt_records[entry_number++] = "vn=65537"; + txt_records[entry_number++] = + bnprintf(fwString, sizeof(fwString), "fv=%s", config.firmware_version); + txt_records[entry_number++] = bnprintf(ap1StatusFlagsString, sizeof(ap1StatusFlagsString), + "sf=0x%" PRIX32, config.airplay_statusflags); #ifdef CONFIG_METADATA - if (config.get_coverart == 0) - txt_records[entry_number++] = "md=0,2"; - else - txt_records[entry_number++] = "md=0,1,2"; + if (config.get_coverart == 0) + txt_records[entry_number++] = "md=0,2"; + else + txt_records[entry_number++] = "md=0,1,2"; #endif - txt_records[entry_number++] = "ss=16"; - txt_records[entry_number++] = "sr=44100"; - txt_records[entry_number++] = "da=true"; - txt_records[entry_number++] = "sv=false"; - txt_records[entry_number++] = "et=0,1"; - txt_records[entry_number++] = "ek=1"; - txt_records[entry_number++] = "cn=0,1"; - txt_records[entry_number++] = "ch=2"; - txt_records[entry_number++] = "txtvers=1"; - if (config.password == NULL) - txt_records[entry_number++] = "pw=false"; - else - txt_records[entry_number++] = "pw=true"; - txt_records[entry_number++] = NULL; + txt_records[entry_number++] = + bnprintf(ap1ModelString, sizeof(ap1ModelString), "am=%s", config.model); + txt_records[entry_number++] = bnprintf(pkString, sizeof(pkString), "pk=%s", config.pk_string); + txt_records[entry_number++] = "tp=UDP"; + txt_records[entry_number++] = "vn=65537"; + txt_records[entry_number++] = + bnprintf(ap1SrcversString, sizeof(ap1SrcversString), "vs=%s", config.srcvers); + txt_records[entry_number++] = + bnprintf(ap1OsversString, sizeof(ap1OsversString), "ov=%s", config.osvers); + txt_records[entry_number++] = NULL; + } else { +#endif + // here, just replicate what happens in mdns.h when using those #defines + txt_records[entry_number++] = + bnprintf(ap1StatusFlagsString, sizeof(ap1StatusFlagsString), "sf=0x4"); + txt_records[entry_number++] = + bnprintf(fwString, sizeof(fwString), "fv=%s", config.firmware_version); + txt_records[entry_number++] = + bnprintf(ap1ModelString, sizeof(ap1ModelString), "am=%s", config.model); + txt_records[entry_number++] = bnprintf(ap1SrcversString, sizeof(ap1SrcversString), "vs=105.1"); + txt_records[entry_number++] = "tp=TCP,UDP"; + txt_records[entry_number++] = "vn=65537"; +#ifdef CONFIG_METADATA + if (config.get_coverart == 0) + txt_records[entry_number++] = "md=0,2"; + else + txt_records[entry_number++] = "md=0,1,2"; +#endif + txt_records[entry_number++] = "ss=16"; + txt_records[entry_number++] = "sr=44100"; + txt_records[entry_number++] = "da=true"; + txt_records[entry_number++] = "sv=false"; + txt_records[entry_number++] = "et=0,1"; + txt_records[entry_number++] = "ek=1"; + txt_records[entry_number++] = "cn=0,1"; + txt_records[entry_number++] = "ch=2"; + txt_records[entry_number++] = "txtvers=1"; + if (config.password == NULL) + txt_records[entry_number++] = "pw=false"; + else + txt_records[entry_number++] = "pw=true"; + txt_records[entry_number++] = NULL; +#ifdef CONFIG_AIRPLAY_2 + } #endif #ifdef CONFIG_AIRPLAY_2 @@ -149,7 +153,7 @@ void build_bonjour_strings(__attribute((unused)) rtsp_conn_info *conn) { entry_number = 0; secondary_txt_records[entry_number++] = "acl=0"; - secondary_txt_records[entry_number++] = "btaddr=00:00:00:00:00:00"; + // secondary_txt_records[entry_number++] = "btaddr=00:00:00:00:00:00"; secondary_txt_records[entry_number++] = bnprintf(deviceIdString, sizeof(deviceIdString), "deviceid=%s", config.airplay_device_id); secondary_txt_records[entry_number++] = diff --git a/common.c b/common.c index 5b3f8feb..c513077e 100644 --- a/common.c +++ b/common.c @@ -27,6 +27,7 @@ */ #include "common.h" +#include "utilities/network_utilities.h" #ifdef CONFIG_USE_GIT_VERSION_STRING #include "gitversion.h" @@ -51,8 +52,8 @@ #include #include -#include #include +#include #ifdef COMPILE_FOR_LINUX #include @@ -411,7 +412,7 @@ int bind_socket_and_port(int type, int ip_family, const char *self_ip_address, u #endif if (ret < 0) { ret = errno; - close(local_socket); + safe_socket_close(&local_socket); char errorstring[1024]; getErrorText((char *)errorstring, sizeof(errorstring)); warn("error %d: \"%s\". Could not bind a port!", errno, errorstring); @@ -422,7 +423,7 @@ int bind_socket_and_port(int type, int ip_family, const char *self_ip_address, u ret = getsockname(local_socket, (struct sockaddr *)&local, &local_len); if (ret < 0) { ret = errno; - close(local_socket); + safe_socket_close(&local_socket); char errorstring[1024]; getErrorText((char *)errorstring, sizeof(errorstring)); warn("error %d: \"%s\". Could not retrieve socket's port!", errno, errorstring); @@ -494,7 +495,7 @@ uint16_t bind_UDP_port(int ip_family, const char *self_ip_address, uint32_t scop // debug(1,"UDP port chosen: %d.",desired_port); if (ret < 0) { - close(local_socket); + safe_socket_close(&local_socket); char errorstring[1024]; getErrorText((char *)errorstring, sizeof(errorstring)); die("error %d: \"%s\". Could not bind a UDP port! Check the udp_port_range is large enough -- " @@ -950,7 +951,8 @@ uint8_t *rsa_apply(uint8_t *input, int inlen, int *outlen, int mode) { mbedtls_rsa_set_padding(trsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE); outbuf = malloc(trsa->MBEDTLS_PRIVATE_V3_ONLY(len)); #if MBEDTLS_VERSION_MAJOR == 3 - rc = mbedtls_pk_sign(&pkctx, MBEDTLS_MD_NONE, input, inlen, outbuf, mbedtls_pk_get_len(&pkctx), &olen, mbedtls_ctr_drbg_random, &ctr_drbg); + rc = mbedtls_pk_sign(&pkctx, MBEDTLS_MD_NONE, input, inlen, outbuf, mbedtls_pk_get_len(&pkctx), + &olen, mbedtls_ctr_drbg_random, &ctr_drbg); *outlen = olen; #else rc = mbedtls_rsa_pkcs1_encrypt(trsa, mbedtls_ctr_drbg_random, &ctr_drbg, MBEDTLS_RSA_PRIVATE, @@ -1066,7 +1068,7 @@ int config_set_lookup_bool(config_t *cfg, const char *where, int *dst) { const char *str = NULL; int response = CONFIG_FALSE; config_setting_t *s = config_lookup(cfg, where); - if (s != NULL) { + if (s != NULL) { if (config_setting_type(s) == CONFIG_TYPE_STRING) { str = config_setting_get_string(s); if (strcasecmp(str, "no") == 0) { @@ -1076,11 +1078,14 @@ int config_set_lookup_bool(config_t *cfg, const char *where, int *dst) { (*dst) = 1; response = CONFIG_TRUE; } else { - die("invalid boolean parameter \"%s\" option choice \"%s\". It should be \"yes\" or \"no\"", where, str); + die("invalid boolean parameter \"%s\" option choice \"%s\". It should be \"yes\" or \"no\"", + where, str); return 0; } } else { - warn("the \"%s\" parameter is not a string with a value of \"yes\" or \"no\", as required, and has been ignored.", where); + warn("the \"%s\" parameter is not a string with a value of \"yes\" or \"no\", as required, " + "and has been ignored.", + where); } } return response; @@ -1245,6 +1250,59 @@ int check_int_or_list_setting(config_setting_t *setting, const int item) { return result; } +void service_type_to_string(APST_t service_type, char *string_space) { + if (string_space != NULL) { + string_space[0] = '\0'; + switch (service_type) { + case APST_auto: + strcpy(string_space, "auto"); + break; + case APST_classic: + strcpy(string_space, "classic"); + break; + case APST_forced_classic: + strcpy(string_space, "forced_classic"); + break; + case APST_airplay2: + strcpy(string_space, "airplay2"); + break; + } + } +} + +APST_t string_to_service_type(const char *parameter, const char *setting_name) { + APST_t response = APST_auto; + if (parameter != NULL) { + if (strcasecmp(parameter, "auto") == 0) { + response = APST_auto; + } else if (strcasecmp(parameter, "classic") == 0) { + response = APST_classic; + } else if (strcasecmp(parameter, "airplay1") == 0) { + response = APST_classic; + } else if (strcasecmp(parameter, "airplay2") == 0) { + response = APST_airplay2; + } else { + warn("The %s \"%s\" was ignored. It must be \"auto\", \"classic\" or \"airplay2\". (You can " + "use \"airplay1\" instead of \"classic\".)", + setting_name, parameter); + } +#ifndef CONFIG_AIRPLAY_2 + if (response == APST_airplay2) { + warn("This version of Shairport Sync supports does not support AirPlay 2. The %s \"%s\" " + "setting has been ignored.", + setting_name, parameter); + response = APST_auto; // reset to default + } +#endif + } + /* + char service_type_string[32]; + service_type_to_string(response, service_type_string); + debug(1, "config.service_type read from %s is: \"%s\".", setting_name, service_type_string); + */ + return response; +} + void command_set_volume(double volume) { // this has a cancellation point if waiting is enabled if (config.cmd_set_volume) { @@ -1310,11 +1368,11 @@ void command_start(void) { char **argV; if (config.cmd_start_returns_output) { - close(pipes[0]); + safe_socket_close(&pipes[0]); if (dup2(pipes[1], 1) < 0) { warn("Unable to reopen pipe as stdout for popen of start command"); debug(1, "dup2 finished with error %d", errno); - close(pipes[1]); + safe_socket_close(&pipes[1]); return; } } @@ -1344,9 +1402,9 @@ void command_start(void) { if (config.cmd_start_returns_output) { static char buffer[256]; int len; - close(pipes[1]); + safe_socket_close(&pipes[1]); len = read(pipes[0], buffer, 255); - close(pipes[0]); + safe_socket_close(&pipes[0]); buffer[len] = '\0'; if (buffer[len - 1] == '\n') buffer[len - 1] = '\0'; // strip trailing newlines @@ -1705,45 +1763,6 @@ int try_to_open_pipe_for_writing(const char *pathname) { return fdis; } -/* from - * http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722 - */ - -char *str_replace(const char *string, const char *substr, const char *replacement) { - char *tok = NULL; - char *newstr = NULL; - char *oldstr = NULL; - char *head = NULL; - - /* if either substr or replacement is NULL, duplicate string a let caller handle it */ - if (substr == NULL || replacement == NULL) - return strdup(string); - newstr = strdup(string); - head = newstr; - if (head) { - while ((tok = strstr(head, substr))) { - oldstr = newstr; - newstr = malloc(strlen(oldstr) - strlen(substr) + strlen(replacement) + 1); - /*failed to alloc mem, free old string and return NULL */ - if (newstr == NULL) { - free(oldstr); - return NULL; - } - memcpy(newstr, oldstr, tok - oldstr); - memcpy(newstr + (tok - oldstr), replacement, strlen(replacement)); - memcpy(newstr + (tok - oldstr) + strlen(replacement), tok + strlen(substr), - strlen(oldstr) - strlen(substr) - (tok - oldstr)); - memset(newstr + strlen(oldstr) - strlen(substr) + strlen(replacement), 0, 1); - /* move back head right after the last replacement */ - head = newstr + (tok - oldstr) + strlen(replacement); - free(oldstr); - } - } else { - die("failed to allocate memory in str_replace."); - } - return newstr; -} - /* from http://burtleburtle.net/bob/rand/smallprng.html */ // this is not thread-safe, so we need a mutex on it to use it properly. @@ -1826,7 +1845,8 @@ void sps_nanosleep(const time_t sec, const long nanosec) { rem = req; } while ((result == -1) && (errno == EINTR)); if (result == -1) - debug(1, "Error in sps_nanosleep of %" PRIdMAX " sec and %ld nanoseconds: %d.", (intmax_t)sec, nanosec, errno); + debug(1, "Error in sps_nanosleep of %" PRIdMAX " sec and %ld nanoseconds: %d.", (intmax_t)sec, + nanosec, errno); } // Mac OS X doesn't have pthread_mutex_timedlock @@ -1914,7 +1934,7 @@ int _debug_mutex_unlock(pthread_mutex_t *mutex, const char *mutexname, const cha if (strerror_r(r, errstr, sizeof(errstr)) == 0) { debug(1, "error %d: \"%s\" unlocking mutex \"%s\" at \"%s\".", r, errstr, mutexname, dstring); } else { - debug(1, "error %d: unlocking mutex \"%s\" at \"%s\".", r, mutexname, dstring); + debug(1, "error %d: unlocking mutex \"%s\" at \"%s\".", r, mutexname, dstring); } } pthread_setcancelstate(oldState, NULL); @@ -1938,10 +1958,9 @@ void plist_cleanup(void *arg) { #endif void socket_cleanup(void *arg) { - intptr_t fdp = (intptr_t)arg; - int soc = fdp; - debug(3, "socket_cleanup called for socket: %d.", soc); - close(fdp); + int *p = (int *)arg; + debug(3, "socket_cleanup called for socket: %d.", *p); + safe_socket_close(p); } void cv_cleanup(void *arg) { @@ -2339,6 +2358,8 @@ int get_device_id(uint8_t *id, int int_length) { int64_t time_to_wait; do { + int oldState; + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState); // make this un-cancellable if (getifaddrs(&ifaddr) == 0) { t = id; int found = 0; @@ -2347,12 +2368,8 @@ int get_device_id(uint8_t *id, int int_length) { #ifdef AF_PACKET if ((ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_PACKET)) { struct sockaddr_ll *s = (struct sockaddr_ll *)ifa->ifa_addr; - if ( - ((ifa->ifa_flags & IFF_UP) != 0) && - ((ifa->ifa_flags & IFF_RUNNING) != 0) && - ((ifa->ifa_flags & IFF_LOOPBACK) == 0) && - (ifa->ifa_addr != 0) - ) { + if (((ifa->ifa_flags & IFF_UP) != 0) && ((ifa->ifa_flags & IFF_RUNNING) != 0) && + ((ifa->ifa_flags & IFF_LOOPBACK) == 0) && (ifa->ifa_addr != 0)) { found = 1; response = 0; for (i = 0; ((i < s->sll_halen) && (i < int_length)); i++) { @@ -2378,6 +2395,7 @@ int get_device_id(uint8_t *id, int int_length) { } freeifaddrs(ifaddr); } + pthread_setcancelstate(oldState, NULL); // wait a little time if we haven't got a response if (response != 0) { usleep(100000); @@ -2427,7 +2445,7 @@ int named_pthread_create(pthread_t *thread, const pthread_attr_t *attr, debug(1, "error creating thread \"%s\"", actual_name); } #ifndef COMPILE_FOR_OSX - else { + if (response == 0) { pthread_setname_np(*thread, actual_name); } #endif @@ -2478,6 +2496,7 @@ int named_pthread_create_with_priority(pthread_t *thread, int priority, } // ret == 0 if creating and setting up the attributes was successful if (ret == 0) { + ret = pthread_create(thread, &attr, start_routine, arg); pthread_attr_destroy(&attr); } @@ -2486,7 +2505,7 @@ int named_pthread_create_with_priority(pthread_t *thread, int priority, if (ret != 0) { ret = pthread_create(thread, NULL, start_routine, arg); if (failed_to_set_rt == 0) { - inform("Can not set realtime properties of a thread."); + inform("Can not set realtime properties of thread \"%s\".", actual_name); failed_to_set_rt = 1; } } diff --git a/common.h b/common.h index 7e35e6ab..3c523833 100644 --- a/common.h +++ b/common.h @@ -14,6 +14,14 @@ extern "C" { #include "definitions.h" #include "mdns.h" +// service type to be offered +typedef enum { + APST_auto = 0, + APST_classic, // must be classic / airplay 1 + APST_forced_classic, // must be classic / airplay 1 because no nqptp + APST_airplay2, // must be airplay 2; error if no NQPTP +} APST_t; // AirPlay Service Type + // struct sockaddr_in6 is bigger than struct sockaddr. derp #ifdef AF_INET6 #define SOCKADDR struct sockaddr_storage @@ -24,8 +32,10 @@ extern "C" { #endif #if defined(CONFIG_CONVOLUTION) +// impulse response filter file status typedef enum { ev_unchecked, ev_okay, ev_invalid } ir_file_evaluation; +// impulse response filter file record typedef struct { unsigned int samplerate; // initialized to 0, will be filter frame rate unsigned int channels; @@ -146,7 +156,14 @@ typedef enum { // these sets omit the _UNKNOWN, _AUTO and _ILLEGAL values #define SPS_FORMAT_SET (((1 << (SPS_FORMAT_HIGHEST_NATIVE + 1)) - 1) - (1 << SPS_FORMAT_UNKNOWN)) #define SPS_RATE_SET (((1 << (SPS_RATE_HIGHEST + 1)) - 1) - (1 << SPS_RATE_UNKNOWN)) -#define SPS_CHANNEL_SET (((1 << (8 + 1)) - 1) - (1 << 0)) // channels 1 to 8, not 0-based! + +// in SPS_CHANNEL_SET, bit 0 set means a channel set of no channels, bit 1 set means a channel set +// of 1 channel and so on to bit 31 meaning a channel set of 31 channels. We want to consider all +// possible channel sets apart from channel set 0. +#define SPS_GREATEST_CHANNEL_COUNT 31 // should be 32 to be fully in line with ALSA limits +#define SPS_CHANNEL_SET 0xFFFFFFFE // channel sets 31 to 1, but no channel set 0 +// #define SPS_CHANNEL_SET (((1 << (SPS_GREATEST_CHANNEL_COUNT + 1)) - 1) - (1 << 0)) // channels 1 +// to 31, not 0-based! #ifndef CONFIG_AIRPLAY_2 #define SPS_FORMAT_NON_FFMPEG_SET SPS_FORMAT_SET @@ -396,14 +413,17 @@ typedef struct { uint32_t airplay_statusflags; char *airplay_fex; // a base64-encoded version of the airplay_features in little-endian form char *airplay_device_id; // for the Bonjour advertisement and the GETINFO PList - char *airplay_pin; // non-NULL, 4 char PIN, if required for pairing char *airplay_pi; // UUID in the Bonjour advertisement and the GETINFO Plist char *airplay_pgid; // UUID in the txtAirPlay data sent on the event channel char *airplay_psi; // type 4 fixed UUID uint8_t airplay_pk[32]; // public key char *pk_string; char *nqptp_shared_memory_interface_name; // client name for nqptp service + int enable_HK_Access_Control; // true if the device is part of an Apple Home #endif + + APST_t service_type; // APST_auto, APST_classic, APST_forced_classic, APST_airplay2 + int unfixable_error_reported; // only report once. uint64_t eight_channel_layout; // non-zero means enabled and is a channel layout @@ -454,11 +474,6 @@ void set_requested_connection_state_to_output(int v); int try_to_open_pipe_for_writing( const char *pathname); // open it without blocking if it's not hooked up -/* from - * http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722 - */ -char *str_replace(const char *string, const char *substr, const char *replacement); - // based on http://burtleburtle.net/bob/rand/smallprng.html void r64init(uint64_t seed); @@ -478,19 +493,6 @@ uint16_t nextFreeUDPPort(); extern volatile int debuglev; -void _die(const char *filename, const int linenumber, const char *format, ...); -void _warn(const char *filename, const int linenumber, const char *format, ...); -void _inform(const char *filename, const int linenumber, const char *format, ...); -void _debug(const char *filename, const int linenumber, int level, const char *format, ...); -void _debug_print_buffer(const char *thefilename, const int linenumber, int level, void *buf, - size_t buf_len); - -#define die(...) _die(__FILE__, __LINE__, __VA_ARGS__) -#define debug(...) _debug(__FILE__, __LINE__, __VA_ARGS__) -#define warn(...) _warn(__FILE__, __LINE__, __VA_ARGS__) -#define inform(...) _inform(__FILE__, __LINE__, __VA_ARGS__) -#define debug_print_buffer(...) _debug_print_buffer(__FILE__, __LINE__, __VA_ARGS__) - // Thanks to https://stackoverflow.com/a/1597129 for the inspiration for this identifier generation #define MAKEUNIQUEID2(x, y) x##y #define MADEID(x, y) MAKEUNIQUEID2(x, y) @@ -569,6 +571,9 @@ unsigned int config_get_string_settings_as_string_array(config_setting_t *settin const char ***result); unsigned int config_get_int_settings_as_int_array(config_setting_t *setting, int **result); +APST_t string_to_service_type(const char *parameter, const char *setting_name); +void service_type_to_string(APST_t service_type, char *string_space); + void command_start(void); void command_stop(void); void command_execute(const char *command, const char *extra_argument, const int block); diff --git a/configure.ac b/configure.ac index d10990ab..8cad1b17 100644 --- a/configure.ac +++ b/configure.ac @@ -1,7 +1,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ([2.50]) -AC_INIT([shairport-sync], [5.0.4], [4265913+mikebrady@users.noreply.github.com]) +AC_INIT([shairport-sync], [5.1], [4265913+mikebrady@users.noreply.github.com]) : ${CFLAGS="-O3"} : ${CXXFLAGS="-O3"} AM_INIT_AUTOMAKE([subdir-objects]) @@ -219,6 +219,12 @@ fi # Look for metadata flag and resolve it further down the script AC_ARG_WITH(metadata,[AS_HELP_STRING([--with-metadata],[include support for a metadata feed])]) +# Look for metadata_pipe flag and resolve it further down the script +AC_ARG_WITH(metadata_pipe,[AS_HELP_STRING([--with-metadata-pipe],[include support for piping metadata out through a unix pipe])]) + +# Look for metadata_multicast flag and resolve it further down the script +AC_ARG_WITH(metadata_multicast,[AS_HELP_STRING([--with-metadata-multicast],[include support for metadata multicasting])]) + # What follows is a bit messy, because if the relevant library is requested, a compiler flag is defined, a file is included in the compilation # and the relevant link files are added. @@ -404,10 +410,28 @@ fi AM_CONDITIONAL([USE_METADATA_HUB], [test "x$REQUESTED_EXTENDED_METADATA_SUPPORT" = "x1"]) AM_CONDITIONAL([USE_DACP_CLIENT], [test "x$REQUESTED_EXTENDED_METADATA_SUPPORT" = "x1"]) -if test "x$REQUESTED_EXTENDED_METADATA_SUPPORT" = "x1" || test "x$with_metadata" = "xyes" ; then +if test "x$REQUESTED_EXTENDED_METADATA_SUPPORT" = "x1" || test "x$with_metadata" = "xyes" || test "x$with_metadata_pipe" = "xyes" || test "x$with_metadata_multicast" = "xyes" ; then + REQUESTED_METADATA_SUPPORT=1 +fi + +if test "x$REQUESTED_METADATA_SUPPORT" = "x1" ; then AC_DEFINE([CONFIG_METADATA], 1, [Needed by the compiler.]) fi -AM_CONDITIONAL([USE_METADATA], [test "x$with_metadata" = "xyes"]) +AM_CONDITIONAL([USE_METADATA], [test "x$REQUESTED_METADATA_SUPPORT" = "x1"]) + +if test "x$with_metadata" = "xyes" ; then + DEFAULT_INCLUDE_PIPE_METADATA=1 +fi + +if test "x$DEFAULT_INCLUDE_PIPE_METADATA" = "x1" || test "x$with_metadata_pipe" = "xyes" ; then + AC_DEFINE([CONFIG_METADATA_PIPE], 1, [Needed by the compiler.]) +fi +AM_CONDITIONAL([USE_METADATA_PIPE], [test "x$DEFAULT_INCLUDE_PIPE_METADATA" = "x1" || test "x$with_metadata_pipe" = "xyes"]) + +if test "x$with_metadata_multicast" = "xyes" ; then + AC_DEFINE([CONFIG_METADATA_MULTICAST], 1, [Needed by the compiler.]) +fi +AM_CONDITIONAL([USE_METADATA_MULTICAST], [test "x$with_metadata_multicast" = "xyes"]) # Look for AirPlay 2 flag AC_ARG_WITH(airplay-2, [AS_HELP_STRING([--with-airplay-2],[Build for AirPlay 2])]) @@ -445,7 +469,7 @@ if test "x$with_airplay_2" = "xyes" ; then ]) AC_CHECK_LIB([uuid],[uuid_generate], [], [AC_MSG_ERROR([AirPlay 2 support requires the uuid library -- uuid-dev suggested])]) systemd_after_args="${systemd_after_args}${systemd_after_args:+ }nqptp.service" - systemd_requires_args="${systemd_requires_args}${systemd_requires_args:+ }nqptp.service" + systemd_wants_args="${systemd_wants_args}${systemd_wants_args:+ }nqptp.service" fi AM_CONDITIONAL([USE_AIRPLAY_2], [test "x$with_airplay_2" = "xyes"]) @@ -562,8 +586,13 @@ if test "x${systemd_requires_args}" != x ; then systemd_requires_args="Requires=${systemd_requires_args}" fi +if test "x${systemd_wants_args}" != x ; then + systemd_wants_args="Wants=${systemd_wants_args}" +fi + AC_SUBST([SYSTEMD_AFTER_ARGS], [${systemd_after_args}]) AC_SUBST([SYSTEMD_REQUIRES_ARGS], [${systemd_requires_args}]) +AC_SUBST([SYSTEMD_WANTS_ARGS], [${systemd_wants_args}]) # The man directory will not be recursively made unless you set the SUBDIR in Makefile.am. # But leave this as is to enable a distclean to be done. diff --git a/dacp.c b/dacp.c index aade558f..f8d90404 100644 --- a/dacp.c +++ b/dacp.c @@ -43,8 +43,9 @@ #include #include -#include "metadata_hub.h" +#include "metadata/hub.h" #include "tinyhttp/http.h" +#include "utilities/network_utilities.h" typedef struct { int players_connection_thread_index; // the connection thread index when a player thread is @@ -88,7 +89,7 @@ void *response_realloc(__attribute__((unused)) void *opaque, void *ptr, int size t = realloc(ptr, size); } if (t == NULL) - debug(1, "response_realloc of size %d to ptr %" PRIxPTR " failed!", size, (uintptr_t) ptr); + debug(1, "response_realloc of size %d to ptr %" PRIxPTR " failed!", size, (uintptr_t)ptr); } return t; } @@ -117,8 +118,7 @@ void response_body(void *opaque, const char *data, int size) { static void response_header(__attribute__((unused)) void *opaque, __attribute__((unused)) const char *ckey, __attribute__((unused)) int nkey, __attribute__((unused)) const char *cvalue, - __attribute__((unused)) int nvalue) { /* example doesn't care about headers */ -} + __attribute__((unused)) int nvalue) { /* example doesn't care about headers */ } static void response_code(void *opaque, int code) { struct HttpResponse *response = (struct HttpResponse *)opaque; @@ -150,12 +150,6 @@ void mutex_lock_cleanup(void *arg) { debug(1, "Error releasing mutex."); } -void connect_cleanup(void *arg) { - int *fd = (int *)arg; - // debug(2, "dacp_send_command: close socket %d.",*fd); - close(*fd); -} - void http_cleanup(void *arg) { // debug(1, "http cleanup called."); struct http_roundtripper *rt = (struct http_roundtripper *)arg; @@ -234,7 +228,7 @@ int dacp_send_command(const char *command, char **body, ssize_t *bodysize) { // \"%s\".",errno,strerror(errno)); response.code = 497; // Can't establish a socket to the DACP server } else { - pthread_cleanup_push(connect_cleanup, (void *)&sockfd); + pthread_cleanup_push(socket_cleanup, (void *)&sockfd); // debug(2, "dacp_send_command: open socket %d.",sockfd); // This is for limiting the time to be spent waiting for a response. @@ -350,9 +344,8 @@ int dacp_send_command(const char *command, char **body, ssize_t *bodysize) { 0); // this should *not* free the malloced buffer -- just pop the malloc cleanup } } - pthread_cleanup_pop(1); // this should close the socket - // close(sockfd); - // debug(1,"DACP socket closed."); + pthread_cleanup_pop(1); // this will close the socket + // debug(1,"DACP socket closed."); } pthread_cleanup_pop(1); // this should unlock the dacp_conversation_lock); // pthread_mutex_unlock(&dacp_conversation_lock); @@ -397,10 +390,10 @@ void relinquish_dacp_server_information(rtsp_conn_info *conn) { // as the conn's connection number // this is to signify that the player has stopped, but only if another thread (with a different // index) hasn't already taken over the dacp service - debug_mutex_lock(&dacp_server_information_lock, 500000, 2); + debug_mutex_lock(&dacp_server_information_lock, 500000, 4); if (dacp_server.players_connection_thread_index == conn->connection_number) dacp_server.players_connection_thread_index = 0; - debug_mutex_unlock(&dacp_server_information_lock, 3); + debug_mutex_unlock(&dacp_server_information_lock, 4); } // this will be running on the thread of its caller, not of the conversation thread... @@ -1302,8 +1295,8 @@ int dacp_set_volume(int32_t vo) { int32_t active_speakers = 0; for (i = 0; i < speaker_count; i++) { if (speaker_info[i].speaker_number == machine_number) { - debug(2, "Our speaker number found: %" PRId64 " with relative volume %" PRId32 ".", machine_number, - speaker_info[i].volume); + debug(2, "Our speaker number found: %" PRId64 " with relative volume %" PRId32 ".", + machine_number, speaker_info[i].volume); } if (speaker_info[i].active == 1) { active_speakers++; diff --git a/dbus-service.c b/dbus-service.c index c6b63251..4dbd1a6a 100644 --- a/dbus-service.c +++ b/dbus-service.c @@ -37,8 +37,11 @@ #include "rtp.h" +#ifdef CONFIG_DACP_CLIENT #include "dacp.h" -#include "metadata_hub.h" +#endif + +#include "metadata/hub.h" #include "dbus-service.h" @@ -335,7 +338,9 @@ static gboolean on_handle_set_volume(ShairportSyncAdvancedRemoteControl *skeleto GDBusMethodInvocation *invocation, const gint volume, __attribute__((unused)) gpointer user_data) { debug(2, "Set volume to %d.", volume); +#ifdef CONFIG_DACP_CLIENT dacp_set_volume(volume); +#endif shairport_sync_advanced_remote_control_complete_set_volume(skeleton, invocation); return TRUE; } @@ -343,7 +348,9 @@ static gboolean on_handle_set_volume(ShairportSyncAdvancedRemoteControl *skeleto static gboolean on_handle_fast_forward(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("beginff"); +#endif shairport_sync_remote_control_complete_fast_forward(skeleton, invocation); return TRUE; } @@ -351,7 +358,9 @@ static gboolean on_handle_fast_forward(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_rewind(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("beginrew"); +#endif shairport_sync_remote_control_complete_rewind(skeleton, invocation); return TRUE; } @@ -359,7 +368,9 @@ static gboolean on_handle_rewind(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_toggle_mute(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("mutetoggle"); +#endif shairport_sync_remote_control_complete_toggle_mute(skeleton, invocation); return TRUE; } @@ -367,7 +378,9 @@ static gboolean on_handle_toggle_mute(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_next(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("nextitem"); +#endif shairport_sync_remote_control_complete_next(skeleton, invocation); return TRUE; } @@ -375,7 +388,9 @@ static gboolean on_handle_next(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_previous(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("previtem"); +#endif shairport_sync_remote_control_complete_previous(skeleton, invocation); return TRUE; } @@ -383,7 +398,9 @@ static gboolean on_handle_previous(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_pause(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("pause"); +#endif shairport_sync_remote_control_complete_pause(skeleton, invocation); return TRUE; } @@ -391,7 +408,9 @@ static gboolean on_handle_pause(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_play_pause(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("playpause"); +#endif shairport_sync_remote_control_complete_play_pause(skeleton, invocation); return TRUE; } @@ -399,7 +418,9 @@ static gboolean on_handle_play_pause(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_play(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("play"); +#endif shairport_sync_remote_control_complete_play(skeleton, invocation); return TRUE; } @@ -407,7 +428,9 @@ static gboolean on_handle_play(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_stop(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("stop"); +#endif shairport_sync_remote_control_complete_stop(skeleton, invocation); return TRUE; } @@ -415,7 +438,9 @@ static gboolean on_handle_stop(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_resume(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("playresume"); +#endif shairport_sync_remote_control_complete_resume(skeleton, invocation); return TRUE; } @@ -423,7 +448,9 @@ static gboolean on_handle_resume(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_shuffle_songs(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("shuffle_songs"); +#endif shairport_sync_remote_control_complete_shuffle_songs(skeleton, invocation); return TRUE; } @@ -431,7 +458,9 @@ static gboolean on_handle_shuffle_songs(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_volume_up(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("volumeup"); +#endif shairport_sync_remote_control_complete_volume_up(skeleton, invocation); return TRUE; } @@ -439,7 +468,9 @@ static gboolean on_handle_volume_up(ShairportSyncRemoteControl *skeleton, static gboolean on_handle_volume_down(ShairportSyncRemoteControl *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { +#ifdef CONFIG_DACP_CLIENT send_simple_dacp_command("volumedown"); +#endif shairport_sync_remote_control_complete_volume_down(skeleton, invocation); return TRUE; } @@ -449,9 +480,11 @@ static gboolean on_handle_set_airplay_volume(ShairportSyncRemoteControl *skeleto const gdouble volume, __attribute__((unused)) gpointer user_data) { debug(2, "Set airplay volume to %.6f.", volume); +#ifdef CONFIG_DACP_CLIENT char command[256] = ""; snprintf(command, sizeof(command), "setproperty?dmcp.device-volume=%.6f", volume); send_simple_dacp_command(command); +#endif shairport_sync_remote_control_complete_set_airplay_volume(skeleton, invocation); return TRUE; } @@ -563,9 +596,9 @@ gboolean notify_convolution_enabled_callback(__attribute__((unused)) ShairportSy #endif #ifdef CONFIG_CONVOLUTION -gboolean notify_convolution_maximum_length_in_seconds_callback(ShairportSync *skeleton, - __attribute__((unused)) - gpointer user_data) { +gboolean +notify_convolution_maximum_length_in_seconds_callback(ShairportSync *skeleton, + __attribute__((unused)) gpointer user_data) { gdouble th = shairport_sync_get_convolution_maximum_length_in_seconds(skeleton); if ((th >= 0.0) && (th <= 15.0)) { @@ -579,10 +612,8 @@ gboolean notify_convolution_maximum_length_in_seconds_callback(ShairportSync *sk return TRUE; } #else -gboolean notify_convolution_maximum_length_in_seconds_callback(__attribute__((unused)) - ShairportSync *skeleton, - __attribute__((unused)) - gpointer user_data) { +gboolean notify_convolution_maximum_length_in_seconds_callback( + __attribute__((unused)) ShairportSync *skeleton, __attribute__((unused)) gpointer user_data) { warn(">> Convolution support is not built in to this build of Shairport Sync."); return TRUE; } @@ -610,16 +641,16 @@ gboolean notify_convolution_gain_callback(__attribute__((unused)) ShairportSync } #endif #ifdef CONFIG_CONVOLUTION -gboolean notify_convolution_impulse_response_files_callback(ShairportSync *skeleton, - __attribute__((unused)) - gpointer user_data) { +gboolean +notify_convolution_impulse_response_files_callback(ShairportSync *skeleton, + __attribute__((unused)) gpointer user_data) { char *th = (char *)shairport_sync_get_convolution_impulse_response_files(skeleton); if (th != NULL) { debug(1, ">> freeing current configuration impulse response filter files."); free_ir_filenames(config.convolution_ir_files, config.convolution_ir_file_count); config.convolution_ir_files = NULL; config.convolution_ir_file_count = 0; - + config.convolution_ir_files = parse_ir_filenames(th, &config.convolution_ir_file_count); sanity_check_ir_files(1, config.convolution_ir_files, config.convolution_ir_file_count); debug(1, ">> setting %d configuration impulse response filter%s", @@ -629,10 +660,9 @@ gboolean notify_convolution_impulse_response_files_callback(ShairportSync *skele return TRUE; } #else -gboolean notify_convolution_impulse_response_files_callback(__attribute__((unused)) - ShairportSync *skeleton, - __attribute__((unused)) - gpointer user_data) { +gboolean +notify_convolution_impulse_response_files_callback(__attribute__((unused)) ShairportSync *skeleton, + __attribute__((unused)) gpointer user_data) { __attribute__((unused)) char *th = (char *)shairport_sync_get_convolution_impulse_response_files(skeleton); return TRUE; @@ -683,16 +713,6 @@ gboolean notify_volume_callback(ShairportSync *skeleton, gdouble iv = shairport_sync_get_volume(skeleton); if (((iv >= -30.0) && (iv <= 0.0)) || (iv == -144.0)) { debug(2, ">> set volume to %7.4f.", iv); - - pthread_rwlock_rdlock(&principal_conn_lock); // don't let the principal_conn be changed - pthread_cleanup_push(rwlock_unlock, (void *)&principal_conn_lock); - - if (principal_conn != NULL) { - player_volume(iv, principal_conn); - principal_conn->own_airplay_volume = iv; - principal_conn->own_airplay_volume_set = 1; - } - pthread_cleanup_pop(1); // release the principal_conn lock config.airplay_volume = iv; } else { debug(1, ">> invalid volume: %f. Ignored.", iv); @@ -737,9 +757,10 @@ gboolean notify_alacdecoder_callback(ShairportSync *skeleton, __attribute__((unused)) gpointer user_data) { char *th = (char *)shairport_sync_get_alacdecoder(skeleton); -#ifdef CONFIG_AIRPLAY_2 +#ifdef CONFIG_AIRPLAY_2 if (strcasecmp(th, "ffmpeg") != 0) { - warn(" This request, to set the decoder to \"%s\", is ignored. For AirPlay 2, the FFmpeg decoder is always used.", + warn(" This request, to set the decoder to \"%s\", is ignored. For AirPlay 2, the FFmpeg " + "decoder is always used.", th); } #else @@ -845,6 +866,7 @@ gboolean notify_volume_control_profile_callback(ShairportSync *skeleton, return TRUE; } +#ifdef CONFIG_DACP_CLIENT gboolean notify_shuffle_callback(ShairportSyncAdvancedRemoteControl *skeleton, __attribute__((unused)) gpointer user_data) { // debug(1,"notify_shuffle_callback called"); @@ -854,9 +876,18 @@ gboolean notify_shuffle_callback(ShairportSyncAdvancedRemoteControl *skeleton, send_simple_dacp_command("setproperty?dacp.shufflestate=0"); return TRUE; } +#else +gboolean notify_shuffle_callback(__attribute__((unused)) + ShairportSyncAdvancedRemoteControl *skeleton, + __attribute__((unused)) gpointer user_data) { + return TRUE; +} +#endif +#ifdef CONFIG_DACP_CLIENT gboolean notify_loop_status_callback(ShairportSyncAdvancedRemoteControl *skeleton, __attribute__((unused)) gpointer user_data) { + // debug(1,"notify_loop_status_callback called"); char *th = (char *)shairport_sync_advanced_remote_control_get_loop_status(skeleton); // enum volume_control_profile_type previous_volume_control_profile = @@ -891,6 +922,13 @@ gboolean notify_loop_status_callback(ShairportSyncAdvancedRemoteControl *skeleto } return TRUE; } +#else +gboolean notify_loop_status_callback(__attribute__((unused)) + ShairportSyncAdvancedRemoteControl *skeleton, + __attribute__((unused)) gpointer user_data) { + return TRUE; +} +#endif static gboolean on_handle_quit(ShairportSync *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) const gchar *command, @@ -907,10 +945,12 @@ static gboolean on_handle_remote_command(ShairportSync *skeleton, GDBusMethodInv __attribute__((unused)) gpointer user_data) { debug(1, "RemoteCommand with command \"%s\".", command); int reply = 0; + char *client_reply_hex = ""; +#ifdef CONFIG_DACP_CLIENT char *client_reply = NULL; ssize_t reply_size = 0; reply = dacp_send_command((const char *)command, &client_reply, &reply_size); - char *client_reply_hex = alloca(reply_size * 2 + 1); + client_reply_hex = alloca(reply_size * 2 + 1); if (client_reply_hex) { char *p = client_reply_hex; if (client_reply) { @@ -924,22 +964,21 @@ static gboolean on_handle_remote_command(ShairportSync *skeleton, GDBusMethodInv } *p = '\0'; } +#endif shairport_sync_complete_remote_command(skeleton, invocation, reply, client_reply_hex); return TRUE; } static gboolean on_handle_drop_session(ShairportSync *skeleton, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { - release_play_lock(NULL); // stop any current session and don't replace it + stop_play(); // stop any current session and don't replace it shairport_sync_complete_drop_session(skeleton, invocation); return TRUE; } -static gboolean on_handle_set_frame_position_update_interval(ShairportSync *skeleton, - GDBusMethodInvocation *invocation, - const gdouble seconds, - __attribute__((unused)) - gpointer user_data) { +static gboolean on_handle_set_frame_position_update_interval( + ShairportSync *skeleton, GDBusMethodInvocation *invocation, const gdouble seconds, + __attribute__((unused)) gpointer user_data) { debug(1, ">> set frame position update interval to %.6f.", seconds); config.metadata_progress_interval = seconds; shairport_sync_complete_set_frame_position_update_interval(skeleton, invocation); @@ -965,7 +1004,6 @@ static void on_dbus_name_acquired(GDBusConnection *connection, const gchar *name shairportSyncAdvancedRemoteControlSkeleton = shairport_sync_advanced_remote_control_skeleton_new(); - g_dbus_interface_skeleton_export( G_DBUS_INTERFACE_SKELETON(shairportSyncAdvancedRemoteControlSkeleton), connection, "/org/gnome/ShairportSync", NULL); @@ -1025,6 +1063,7 @@ static void on_dbus_name_acquired(GDBusConnection *connection, const gchar *name g_signal_connect(shairportSyncRemoteControlSkeleton, "handle-fast-forward", G_CALLBACK(on_handle_fast_forward), NULL); + g_signal_connect(shairportSyncRemoteControlSkeleton, "handle-rewind", G_CALLBACK(on_handle_rewind), NULL); g_signal_connect(shairportSyncRemoteControlSkeleton, "handle-toggle-mute", diff --git a/definitions.h b/definitions.h index 3eeaf79c..b27cba71 100644 --- a/definitions.h +++ b/definitions.h @@ -5,6 +5,9 @@ #include "config.h" +// for generating our own UUIDs +#define SHAIRPORT_SYNC_DEVICE_NAMESPACE "01d7c137-6316-455d-a52f-dfb529f26adf" + #if defined(__APPLE__) && defined(__MACH__) /* Apple OSX and iOS (Darwin). ------------------------------ */ #include diff --git a/docker/Dockerfile b/docker/Dockerfile index 1cda43e3..106e07f5 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,7 +1,7 @@ ARG NQPTP_BRANCH=main -ARG FFMPEG_BRANCH=release/7.1 +ARG FFMPEG_BRANCH=release/8.1 ARG SHAIRPORT_SYNC_BRANCH=. -ARG ALPINE_VERSION=20250108 +ARG ALPINE_VERSION=3.23.4 ##### FFMPEGLITE ##### FROM alpine:$ALPINE_VERSION AS ffmpeglite @@ -28,10 +28,9 @@ RUN ./configure \ --disable-network \ --disable-iamf \ --disable-pixelutils \ - --disable-postproc \ --enable-decoder=alac \ --enable-decoder=aac -RUN make -j $(nproc) +RUN make RUN make install ##### FFMPEGLITE END ##### @@ -51,7 +50,7 @@ RUN git clone --depth=1 -b "$NQPTP_BRANCH" https://github.com/mikebrady/nqptp WORKDIR /nqptp RUN autoreconf -i RUN ./configure -RUN make -j $(nproc) +RUN make WORKDIR / ##### NQPTP END ##### @@ -102,11 +101,38 @@ RUN ../configure --sysconfdir=/etc --with-alsa --with-pulseaudio --with-soxr --w --with-airplay-2 --with-metadata --with-dummy --with-pipe --with-dbus-interface \ --with-stdout --with-mpris-interface --with-mqtt-client \ --with-convolution --with-pipewire -RUN make -j $(nproc) +RUN make RUN DESTDIR=install make install WORKDIR / ##### SPS END ##### +# Shairport Sync Development Environment +# This (large) image contains the custom-built FFmpeg library and NQPTP, Avahi, D-Bus, etc., Shairport Sync source and all tools. +# When started, D-Bus, Avahi and NQPTP are set to run in the background. +# To build it, here is a sample local build instruction: +# $ docker build --build-arg SHAIRPORT_SYNC_BRANCH=development --build-arg NQPTP_BRANCH=main --target dev -t shairport-sync-dev -f docker/Dockerfile . +# Sample local use (remember to save your changes): +# $ docker run -it \ +# --cap-add=SYS_NICE --net host --device /dev/snd \ +# -v /etc/shairport-sync.conf:/etc/shairport-sync.conf \ +# shairport-sync-dev + +##### DEV ##### +FROM shairport-sync AS dev +RUN apk add bash + +RUN addgroup shairport-sync && \ + adduser -D shairport-sync -G shairport-sync && \ + addgroup -g 29 docker_audio && \ + addgroup shairport-sync docker_audio && \ + addgroup shairport-sync audio && \ + mkdir -p /run/dbus + +COPY --from=nqptp /nqptp/nqptp /usr/local/bin/nqptp +COPY --chmod=755 ./docker/devrun.sh ./devrun.sh +ENTRYPOINT ["./devrun.sh"] +##### DEV END ##### + ##### STATIC FILES ##### FROM scratch AS files diff --git a/docker/classic/Dockerfile b/docker/classic/Dockerfile index a71a41c0..67d57929 100644 --- a/docker/classic/Dockerfile +++ b/docker/classic/Dockerfile @@ -1,8 +1,8 @@ # Classic Shairport-Sync build. Note: the only decoder in FFmpeg is ALAC. ARG SHAIRPORT_SYNC_BRANCH=. -ARG FFMPEG_BRANCH=release/7.1 -ARG ALPINE_VERSION=20250108 +ARG FFMPEG_BRANCH=release/8.1 +ARG ALPINE_VERSION=3.23.4 ##### FFMPEGLITE ##### FROM alpine:$ALPINE_VERSION AS ffmpeglite @@ -29,7 +29,6 @@ RUN ./configure \ --disable-network \ --disable-iamf \ --disable-pixelutils \ - --disable-postproc \ --enable-decoder=alac RUN make RUN make install diff --git a/docker/devrun.sh b/docker/devrun.sh new file mode 100755 index 00000000..8d59a639 --- /dev/null +++ b/docker/devrun.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# exit if any command returns a non-zero result +set -e +echo "Shairport Sync Dev Startup ($(date))" +if [ -z ${ENABLE_AVAHI+x} ] || [ $ENABLE_AVAHI -eq 1 ]; then + rm -rf /run/dbus/dbus.pid + rm -rf /run/avahi-daemon/pid + dbus-uuidgen --ensure + dbus-daemon --system + avahi-daemon --daemonize --no-chroot +fi +# Don't launch NQPTP if classic only +SERVICE_TYPE="" +for arg in "$@"; do + case "$arg" in + --service-type=classic|--service-type=airplay1) + SERVICE_TYPE="${arg#--service-type=}" + ;; + esac +done +if [ -z "$SERVICE_TYPE" ]; then + # not looking for Classic aka AirPlay 1 so start NQPTP for AirPlay 2 + echo "Starting NQPTP ($(date))" + (/usr/local/bin/nqptp > /dev/null 2>&1) & +fi +while [ ! -f /var/run/avahi-daemon/pid ]; do + echo "Warning: avahi is not running, sleeping for 5 seconds before checking again" + sleep 5 +done +# for PipeWire +export XDG_RUNTIME_DIR=/tmp +# for PulseAudio +export PULSE_SERVER=unix:/tmp/pulseaudio.socket +export PULSE_COOKIE=/tmp/pulseaudio.cookie +echo "Finished startup tasks ($(date)), starting bash." +exec /bin/bash \ No newline at end of file diff --git a/docker/run.sh b/docker/run.sh index bb1b1da7..f02daa66 100755 --- a/docker/run.sh +++ b/docker/run.sh @@ -15,9 +15,23 @@ if [ -z ${ENABLE_AVAHI+x} ] || [ $ENABLE_AVAHI -eq 1 ]; then avahi-daemon --daemonize --no-chroot fi -echo "Starting NQPTP ($(date))" +# Don't launch NQPTP if it classic only -(/usr/local/bin/nqptp > /dev/null 2>&1) & +SERVICE_TYPE="" + +for arg in "$@"; do + case "$arg" in + --service-type=classic|--service-type=airplay1) + SERVICE_TYPE="${arg#--service-type=}" + ;; + esac +done + +if [ -z "$SERVICE_TYPE" ]; then + # not looking for Classic aka AirPlay 1 so start NQPTP for AirPlay 2 + echo "Starting NQPTP ($(date))" + (/usr/local/bin/nqptp > /dev/null 2>&1) & +fi while [ ! -f /var/run/avahi-daemon/pid ]; do echo "Warning: avahi is not running, sleeping for 5 seconds before trying to start shairport-sync" diff --git a/documents/D-Bus.md b/documents/D-Bus.md index 012e4f65..99c5ef3e 100644 --- a/documents/D-Bus.md +++ b/documents/D-Bus.md @@ -2,6 +2,8 @@ Shairport Sync can have a D-Bus interface, which can be used to control aspects of its operation and get status information from it. +For Classic AirPlay only, remote control commands, for example `play`, `pause` and volume control, can be sent to the player. + To include the D-Bus interface at build time, add the `--with-dbus-interface` flag at the `./configure…` stage. When the D-Bus interface is included in Shairport Sync, its Version String will include the term `dbus`, for instance: ``` $ shairport-sync -V @@ -143,7 +145,7 @@ The examples below are based on Shairport Sync running as a `system` service and #### Remote Control Remote Control commands are sent as requests to the player (iOS, iTunes, macOS Music, etc.). Different versions of the players implement different subsets of the following commands. -**Note:** Unfortunately, at this time -- early 2026 -- these requests are ignored, so remote control doesn't work. +**Note:** Remote Control only works on Classic Airplay * Check if Remote Control is available: ``` @@ -162,7 +164,7 @@ Remote Control commands are sent as requests to the player (iOS, iTunes, macOS M #### Advanced Remote Control Some commands and properties are accessible only through the `AdvancedRemoteControl` interface. -**Note:** Unfortunately, at this time -- early 2026 -- these requests are ignored, so advanced remote control doesn't work. +**Note:** Advanced Remote Control only works on Classic Airplay and has only been observed to work with the macOS Music app. * Check if Advanced Remote Control is available: ``` diff --git a/man/shairport-sync.1 b/man/shairport-sync.1 index 2d2de85d..d7d7336c 100644 --- a/man/shairport-sync.1 +++ b/man/shairport-sync.1 @@ -2,7 +2,7 @@ .SH NAME shairport-sync \- AirPlay and AirPlay 2 Audio Player .SH SYNOPSIS -\fBshairport-sync [-djvw]\fB [-a \fB\fIservice-name\fB | --name=\fB\fIservice-name\fB]\fB [-B \fB\fIcommand\fB | --onstart=\fB\fIcommand\fB]\fB [-c \fB\fIconfigurationfile\fB | --configfile=\fB\fIconfigurationfile\fB]\fB [-d | --daemon]\fB [-E \fB\fIcommand\fB | --onstop=\fB\fIcommand\fB]\fB [-g | --get-cover-art]\fB [-j | --justDaemoniseNoPIDFile]\fB [--logOutputLevel]\fB [--log-to-syslog]\fB [-L \fB\fIlatency\fB | --latency=\fB\fIlatency\fB]\fB [-m \fB\fIbackend\fB | --mdns=\fB\fIbackend\fB]\fB [-M | --metadata-enable]\fB [-o \fB\fIbackend\fB | --output=\fB\fIbackend\fB]\fB [-p \fB\fIport\fB | --port=\fB\fIport\fB]\fB [--password=\fB\fIsecret\fB]\fB [-r \fB\fIthreshold\fB | --resync=\fB\fIthreshold\fB]\fB [--statistics]\fB [-S \fB\fImode\fB | --stuffing=\fB\fImode\fB]\fB [-t \fB\fItimeout\fB | --timeout=\fB\fItimeout\fB]\fB [--tolerance=\fB\fIframes\fB]\fB [-v | --verbose]\fB [-w | --wait-cmd]\fB [-- \fB\fIaudio_backend_options\fB]\fB +\fBshairport-sync [-djvw]\fB [-a \fB\fIservice-name\fB | --name=\fB\fIservice-name\fB]\fB [-B \fB\fIcommand\fB | --onstart=\fB\fIcommand\fB]\fB [-c \fB\fIconfigurationfile\fB | --configfile=\fB\fIconfigurationfile\fB]\fB [-d | --daemon]\fB [--dbus-default-message-bus=\fB\fIbus\fB]\fB [-E \fB\fIcommand\fB | --onstop=\fB\fIcommand\fB]\fB [-g | --get-cover-art]\fB [-j | --justDaemoniseNoPIDFile]\fB [--logOutputLevel]\fB [--log-to-syslog]\fB [-L \fB\fIlatency\fB | --latency=\fB\fIlatency\fB]\fB [-m \fB\fIbackend\fB | --mdns=\fB\fIbackend\fB]\fB [-M | --metadata-enable]\fB [-o \fB\fIbackend\fB | --output=\fB\fIbackend\fB]\fB [-p \fB\fIport\fB | --port=\fB\fIport\fB]\fB [--password=\fB\fIsecret\fB]\fB [-r \fB\fIthreshold\fB | --resync=\fB\fIthreshold\fB]\fB [--service-type=\fB\fItype\fB]\fB [--statistics]\fB [-S \fB\fImode\fB | --stuffing=\fB\fImode\fB]\fB [-t \fB\fItimeout\fB | --timeout=\fB\fItimeout\fB]\fB [--tolerance=\fB\fIframes\fB]\fB [-v | --verbose]\fB [-w | --wait-cmd]\fB [-- \fB\fIaudio_backend_options\fB]\fB shairport-sync -X | --displayConfig\fB @@ -73,6 +73,9 @@ Read configuration settings from \fIfilename\f1. The default is to read them fro \fB-d | --daemon\f1 Instruct shairport-sync to demonise itself. It will write its Process ID (PID) to a file, usually at \fI/var/run/shairport-sync/shairport-sync.pid\f1, which is used by the \fB-k\f1, \fB-D\f1 and \fB-R\f1 options to locate the daemon at a later time. See also the \fB-j\f1 option. Only available if shairport-sync has been compiled with libdaemon support. .TP +\fB--dbus-default-message-bus=\f1\fIbus\f1 +Use the \fIbus\f1 specified for the native D-Bus and MPRIS interfaces. The \fIbus\f1 must be \fBsystem\f1 or \fBsession\f1. This option is only available if Shairport Sync is built with the D-Bus or MPRIS interface. +.TP \fB-E \f1\fIprogram\f1\fB | --on-stop=\f1\fIprogram\f1 Execute \fIprogram\f1 when playback has ended. Specify the full path to the program, e.g. \fI/usr/bin/logger\f1. Executable scripts can be used, but they must have the appropriate shebang (\fI#!/bin/sh\f1) in the headline. @@ -124,11 +127,14 @@ Require the password \fIsecret\f1 to be able to connect and stream to the servic \fB-r \f1\fIthreshold\f1\fB | --resync=\f1\fIthreshold\f1 Resynchronise if timings differ by more than \fIthreshold\f1 frames. If the output timing differs from the source timing by more than the threshold, output will be muted and a full resynchronisation will occur. The default threshold is 2,205 frames, i.e. 50 milliseconds. Specify \fB0\f1 to disable resynchronisation. This setting is deprecated and will be removed in a future version of shairport-sync. .TP +\fB--service-type=\f1\fItype\f1 +On an AirPlay-2-capable Shairport Sync, if you need offer only the older "classic" AirPlay (sometimes called AirPlay 1) service, set \fB--service-type=classic\f1. A potential use of this would be for Apple Music on Windows, which is not compatible with the AirPlay 2 service offered by Shairport Sync, but which is compatible with the classic-only service. To offer AirPlay 2 service only, set \fB--service-type=airplay2\f1 (note that this requires NQPTP). Set \fB--service-type=auto\f1 to allow Shairport Sync to choose AirPlay 2 service if NQPTP is present or classic AirPlay service if not, with "(Classic)" appended to the default service name. +.TP \fB--statistics\f1 -Print some performance information to \fISTDERR\f1, or to \fBsyslog\f1 if the \fB-log-to-syslog\f1 command line option is also chosen. +Print some performance information to \fISTDERR\f1, or to \fBsyslog\f1 if the \fB--log-to-syslog\f1 command line option is also chosen. .TP \fB-S \f1\fImode\f1\fB | --stuffing=\f1\fImode\f1 -Interpolate ("stuff") the audio stream using the \fImode\f1. "Stuffing" refers to the process of adding or removing frames of audio to or from the stream sent to the output device in order to keep it synchronised with the player. The \fBbasic\f1 mode is normally almost completely inaudible. The alternative mode, \fBsoxr\f1, is even less obtrusive but requires much more processing power. For this mode, support for \fBlibsoxr\f1, the SoX Resampler Library, must be selected when \fBshairport-sync\f1 is built. The default setting, \fBauto\f1, allows Shairport Sync to choose \fBsoxr\f1 mode if the system is powerful enough. +Interpolate ("stuff") the audio stream using the \fImode\f1. "Stuffing" refers to the process of adding or removing frames of audio to or from the stream sent to the output device in order to keep it synchronised with the player. The \fBvernier\f1 mode is normally almost completely inaudible and suitable for low-powered devices. An alternative mode, \fBsoxr\f1, is less obtrusive but requires much more processing power. For this mode, support for \fBlibsoxr\f1, the SoX Resampler Library, must be selected when \fBshairport-sync\f1 is built. The \fBbasic\f1 mode is also suitable for low-powered device, but \fBvernier\f1 is better. The default setting, \fBauto\f1, allows Shairport Sync to choose \fBsoxr\f1 mode if the system is powerful enough. .TP \fB-t \f1\fItimeout\f1\fB | --timeout=\f1\fItimeout\f1 Exit play mode if the stream disappears for more than \fItimeout\f1 seconds. @@ -142,7 +148,7 @@ Allow playback to be up to \fIframes\f1 out of exact synchronization before atte Print version information and exit. .TP \fB-v | --verbose\f1 -Print debug information to the \fISTDERR\f1, or to \fBsyslog\f1 if the \fB-log-to-syslog\f1 command line option is also chosen. Repeat up to three times (i.e. \fB-vv\f1 or \fB-vvv\f1) for more detail. You should use \fB-vvv\f1 very sparingly -- it is really noisy. +Print debug information to the \fISTDERR\f1, or to \fBsyslog\f1 if the \fB--log-to-syslog\f1 command line option is also chosen. Repeat up to three times (i.e. \fB-vv\f1 or \fB-vvv\f1) for more detail. You should use \fB-vvv\f1 very sparingly -- it is really noisy. .TP \fB-w | --wait-cmd\f1 Wait for commands specified using \fB-B\f1 or \fB-E\f1 to complete before continuing execution. @@ -165,6 +171,8 @@ The program will be visible as "Joe's Stereo" ( \fB-a "Joe's Stereo"\f1 ). The p The example above is slightly contrived: Firstly, if the \fBalsa\f1 backend has been included in the build, it will be the default, so it doesn't need to be specified and the \fB-o alsa\f1 option could be omitted. Secondly, subdevice 0 is the default for a soundcard, so the output device could simply be written \fB-d hw:1\f1. Thirdly, when a mixer name is given ( \fB-c "PCM"\f1 ), the default is that the mixer is on the output device, so the \fB-m hw:1\f1 is unnecessary here. Using these defaults and simplifications gives the following command: shairport-sync \fB-a "Joe's Stereo"\f1 \fB--\f1 \fB-d hw:1\f1 \fB-c PCM\f1 +.SH NOTE +The \fBdacquery\f1 utility (\fBhttps://github.com/mikebrady/dacquery\f1) might be useful for discovering the properties of your system's DACs. .SH CREDITS Mike Brady (\fBhttps://github.com/mikebrady\f1) developed Shairport Sync from Shairport by James Wah (\fBhttps://github.com/abrasive\f1). .SH COMMENTS diff --git a/man/shairport-sync.1.xml b/man/shairport-sync.1.xml index 44a3ff36..76170a5c 100644 --- a/man/shairport-sync.1.xml +++ b/man/shairport-sync.1.xml @@ -4,7 +4,7 @@