| 1 | /* melder_audio.cpp |
| 2 | * |
| 3 | * Copyright (C) 1992-2022,2025,2026 Paul Boersma, David Weenink |
| 4 | * |
| 5 | * This code is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 3 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 | * See the GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | #if defined (macintosh) |
| 20 | #include <sys/time.h> |
| 21 | #include <CoreAudio/CoreAudio.h> |
| 22 | #elif defined (_WIN32) |
| 23 | #include <windows.h> |
| 24 | #elif defined (linux) |
| 25 | #include <sys/time.h> |
| 26 | #include <signal.h> |
| 27 | #include <sys/types.h> |
| 28 | #include <sys/stat.h> |
| 29 | #include <sys/ioctl.h> |
| 30 | #include <fcntl.h> |
| 31 | #include <unistd.h> |
| 32 | #if defined HAVE_PULSEAUDIO |
| 33 | #include <pulse/pulseaudio.h> |
| 34 | #endif |
| 35 | #if ! defined (NO_AUDIO) |
| 36 | #if defined (__OpenBSD__) || defined (__NetBSD__) |
| 37 | #include <soundcard.h> |
| 38 | #else |
| 39 | #include <sys/soundcard.h> |
| 40 | #endif |
| 41 | #endif |
| 42 | #include <errno.h> |
| 43 | #endif |
| 44 | |
| 45 | #include "melder.h" |
| 46 | #include <time.h> |
| 47 | #include "../sys/Gui.h" |
| 48 | #include "../sys/Preferences.h" |
| 49 | #include "../external/portaudio/portaudio.h" |
| 50 | |
| 51 | #ifdef HAVE_PULSEAUDIO |
| 52 | #define PA_GETTINGINFO 1 |
| 53 | #define PA_GETTINGINFO_DONE 2 |
| 54 | #define PA_WRITING 4 |
| 55 | #define PA_WRITING_DONE 8 |
| 56 | #define PA_RECORDING 16 |
| 57 | #define PA_RECORDING_DONE 32 |
| 58 | #define PA_QUERY_NUMBEROFCHANNELS 64 |
| 59 | #define PA_QUERY_NUMBEROFCHANNELS_DONE 128 |
| 60 | void pulseAudio_initialize (); |
| 61 | void pulseAudio_cleanup (); |
| 62 | void pulseAudio_serverReport (); |
| 63 | void stream_state_cb (pa_stream *stream, void *userdata); |
| 64 | void stream_drain_complete_cb (pa_stream *stream, int success, void *userdata); |
| 65 | void context_state_cb (pa_context *context, void *userdata); |
| 66 | void context_drain_complete_cb (pa_context *context, void *userdata); |
| 67 | void prepare_and_play (struct MelderPlay *me); |
| 68 | void stream_write_cb (pa_stream *stream, size_t length, void *userdata); |
| 69 | void stream_write_cb2 (pa_stream *stream, size_t length, void *userdata); |
| 70 | void pulseAudio_server_info_cb (pa_context *context, const pa_server_info *info, void *userdata); |
| 71 | #endif |
| 72 | |
| 73 | static struct { |
| 74 | enum kMelder_asynchronicityLevel maximumAsynchronicity; |
| 75 | enum kMelder_inputSoundSystem inputSoundSystem; |
| 76 | enum kMelder_outputSoundSystem outputSoundSystem; |
| 77 | double silenceBefore, silenceAfter; |
| 78 | } preferences; |
| 79 | |
| 80 | void Melder_audio_prefs () { |
| 81 | Preferences_addEnum (U"Audio.maximumAsynchronicity", & preferences. maximumAsynchronicity, kMelder_asynchronicityLevel, kMelder_asynchronicityLevel::DEFAULT); |
| 82 | Preferences_addEnum (U"Audio.inputSoundSystem", & preferences. inputSoundSystem, kMelder_inputSoundSystem, kMelder_inputSoundSystem::DEFAULT); |
| 83 | Preferences_addEnum (U"Audio.outputSoundSystem", & preferences. outputSoundSystem, kMelder_outputSoundSystem, kMelder_outputSoundSystem::DEFAULT); |
| 84 | Preferences_addDouble (U"Audio.silenceBefore2", & preferences. silenceBefore, kMelderAudio_outputSilenceBefore_DEFAULT); |
| 85 | Preferences_addDouble (U"Audio.silenceAfter2", & preferences. silenceAfter, kMelderAudio_outputSilenceAfter_DEFAULT); |
| 86 | } |
| 87 | |
| 88 | void MelderAudio_setOutputMaximumAsynchronicity (enum kMelder_asynchronicityLevel maximumAsynchronicity) { |
| 89 | //MelderAudio_stopPlaying (MelderAudio_IMPLICIT); // BUG |
| 90 | preferences. maximumAsynchronicity = maximumAsynchronicity; |
| 91 | } |
| 92 | enum kMelder_asynchronicityLevel MelderAudio_getOutputMaximumAsynchronicity () { |
| 93 | return preferences. maximumAsynchronicity; |
| 94 | } |
| 95 | |
| 96 | void MelderAudio_setInputSoundSystem (enum kMelder_inputSoundSystem inputSoundSystem) { |
| 97 | preferences. inputSoundSystem = inputSoundSystem; |
| 98 | } |
| 99 | enum kMelder_inputSoundSystem MelderAudio_getInputSoundSystem () { |
| 100 | return preferences. inputSoundSystem; |
| 101 | } |
| 102 | |
| 103 | void MelderAudio_setOutputSoundSystem (enum kMelder_outputSoundSystem outputSoundSystem) { |
| 104 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); |
| 105 | preferences. outputSoundSystem = outputSoundSystem; |
| 106 | } |
| 107 | enum kMelder_outputSoundSystem MelderAudio_getOutputSoundSystem () { |
| 108 | return preferences. outputSoundSystem; |
| 109 | } |
| 110 | |
| 111 | void MelderAudio_setOutputSilenceBefore (double silenceBefore) { |
| 112 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); |
| 113 | preferences. silenceBefore = silenceBefore; |
| 114 | } |
| 115 | double MelderAudio_getOutputSilenceBefore () { return preferences. silenceBefore; } |
| 116 | |
| 117 | void MelderAudio_setOutputSilenceAfter (double silenceAfter) { |
| 118 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); |
| 119 | preferences. silenceAfter = silenceAfter; |
| 120 | } |
| 121 | double MelderAudio_getOutputSilenceAfter () { return preferences. silenceAfter; } |
| 122 | |
| 123 | integer MelderAudio_getOutputBestSampleRate (integer fsamp) { |
| 124 | #if defined (macintosh) |
| 125 | return fsamp == 44100 || fsamp == 48000 || fsamp == 96000 ? fsamp : 44100; |
| 126 | #elif defined (_WIN32) |
| 127 | return fsamp == 8000 || fsamp == 11025 || fsamp == 16000 || fsamp == 22050 || |
| 128 | fsamp == 32000 || fsamp == 44100 || fsamp == 48000 || fsamp == 96000 ? fsamp : 44100; |
| 129 | #elif defined (raspberrypi) |
| 130 | return 48000; |
| 131 | #elif defined (linux) |
| 132 | return fsamp == 44100 || fsamp == 48000 || fsamp == 96000 ? fsamp : 44100; |
| 133 | #else |
| 134 | return 44100; |
| 135 | #endif |
| 136 | } |
| 137 | |
| 138 | static double theStartingTime = 0.0; |
| 139 | |
| 140 | static struct MelderPlay { |
| 141 | int16 *playBuffer; |
| 142 | integer sampleRate, numberOfSamples, samplesLeft, samplesSent, samplesPlayed; |
| 143 | kMelder_asynchronicityLevel asynchronicity; |
| 144 | integer numberOfChannels; |
| 145 | bool explicitStop; |
| 146 | volatile int volatile_interrupted; |
| 147 | bool (*callback) (void *closure, integer samplesPlayed); |
| 148 | void *closure; |
| 149 | #if gtk |
| 150 | gint workProcId_gtk = 0; |
| 151 | #elif motif |
| 152 | XtWorkProcId workProcId_motif; |
| 153 | #elif cocoa |
| 154 | CFRunLoopTimerRef cocoaTimer; |
| 155 | #endif |
| 156 | bool usePortAudio, supports_paComplete, usePulseAudio; |
| 157 | PaStream *stream; |
| 158 | double paStartingTime; |
| 159 | #if defined (macintosh) |
| 160 | #elif defined (linux) |
| 161 | int audio_fd, val, err; |
| 162 | #elif defined (_WIN32) |
| 163 | HWAVEOUT hWaveOut; |
| 164 | WAVEHDR waveHeader; |
| 165 | MMRESULT status; |
| 166 | #endif |
| 167 | #ifdef HAVE_PULSEAUDIO |
| 168 | struct { |
| 169 | pa_sample_spec sample_spec; |
| 170 | pa_threaded_mainloop *mainloop = nullptr; |
| 171 | pa_mainloop_api *mainloop_api = nullptr; |
| 172 | pa_context *context = nullptr; |
| 173 | pa_stream *stream = nullptr; |
| 174 | pa_operation *operation_drain = nullptr; |
| 175 | pa_operation *operation_info = nullptr; |
| 176 | pa_stream_flags_t stream_flags; |
| 177 | const pa_timing_info *timing_info = nullptr; |
| 178 | struct timeval startTime = {0, 0}; |
| 179 | pa_usec_t timer_event_usec = 50000; // 50 ms |
| 180 | pa_time_event *timer_event = nullptr; |
| 181 | const pa_channel_map *channel_map = nullptr; |
| 182 | pa_usec_t r_usec; |
| 183 | pa_buffer_attr buffer_attr; |
| 184 | uint32 latency = 0; // in bytes of buffer |
| 185 | int32 latency_msec = 20; |
| 186 | bool pulseAudioInitialized = false; |
| 187 | unsigned int occupation = PA_WRITING; |
| 188 | } pulseAudio; |
| 189 | #endif |
| 190 | } thePlay; |
| 191 | |
| 192 | integer MelderAudio_getSamplesPlayed () { |
| 193 | return thePlay. samplesPlayed; |
| 194 | } |
| 195 | |
| 196 | bool MelderAudio_stopWasExplicit () { |
| 197 | return thePlay. explicitStop; |
| 198 | } |
| 199 | |
| 200 | /* |
| 201 | The flush () function will always have to be invoked after normal play, i.e. in the following cases: |
| 202 | 1. After synchronous play (asynchronicity = 0, 1, or 2). |
| 203 | 2. After interruption of asynchronicity 2 by the ESCAPE key. |
| 204 | 3. After asynchronous play, by the workProc. |
| 205 | 4. After interruption of asynchronicity 3 by MelderAudio_stopPlaying (). |
| 206 | */ |
| 207 | static bool flush () { |
| 208 | struct MelderPlay *me = & thePlay; |
| 209 | if (my usePortAudio) { |
| 210 | if (my stream) { |
| 211 | #ifdef linux |
| 212 | |
| 213 | Pa_Sleep (200); // this reduces the chance of seeing the Alsa/PulseAudio deadlock: |
| 214 | /* |
| 215 | (gdb) thread apply all bt |
| 216 | |
| 217 | Thread 13 (Thread 0x7fffde1d2700 (LWP 25620)): |
| 218 | #0 0x00007ffff65a3d67 in pthread_cond_wait@@GLIBC_2.3.2 () |
| 219 | from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 220 | #1 0x00007fffec0b3980 in pa_threaded_mainloop_wait () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 221 | #2 0x00007fffde407054 in pulse_wait_operation () |
| 222 | from /usr/lib/x86_64-linux-gnu/alsa-lib/libasound_module_pcm_pulse.so |
| 223 | #3 0x00007fffde405c10 in ?? () |
| 224 | from /usr/lib/x86_64-linux-gnu/alsa-lib/libasound_module_pcm_pulse.so |
| 225 | #4 0x00007ffff6843708 in alsa_snd_pcm_drop () from /usr/lib/x86_64-linux-gnu/libasound.so.2 |
| 226 | #5 0x0000000000812de0 in AlsaStop () |
| 227 | #6 0x00000000008183e1 in OnExit () |
| 228 | #7 0x0000000000818483 in CallbackThreadFunc () |
| 229 | #8 0x00007ffff659fe9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 230 | #9 0x00007ffff5aba3fd in clone () from /lib/x86_64-linux-gnu/libc.so.6 |
| 231 | #10 0x0000000000000000 in ?? () |
| 232 | |
| 233 | Thread 12 (Thread 0x7fffdffff700 (LWP 25619)): |
| 234 | #0 0x00007ffff659d9b0 in __pthread_mutex_lock_full () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 235 | #1 0x00007fffdf3d7e1e in pa_mutex_lock () from /usr/lib/x86_64-linux-gnu/libpulsecommon-1.1.so |
| 236 | #2 0x00007fffec0b3369 in ?? () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 237 | #3 0x00007fffec0a476c in pa_mainloop_poll () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 238 | #4 0x00007fffec0a4dd9 in pa_mainloop_iterate () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 239 | #5 0x00007fffec0a4e90 in pa_mainloop_run () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 240 | #6 0x00007fffec0b330f in ?? () from /usr/lib/x86_64-linux-gnu/libpulse.so.0 |
| 241 | #7 0x00007fffdf3d8d18 in ?? () from /usr/lib/x86_64-linux-gnu/libpulsecommon-1.1.so |
| 242 | #8 0x00007ffff659fe9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 243 | #9 0x00007ffff5aba3fd in clone () from /lib/x86_64-linux-gnu/libc.so.6 |
| 244 | #10 0x0000000000000000 in ?? () |
| 245 | |
| 246 | Thread 3 (Thread 0x7fffefd8b700 (LWP 25610)): |
| 247 | #0 0x00007ffff5aaea43 in poll () from /lib/x86_64-linux-gnu/libc.so.6 |
| 248 | #1 0x00007ffff6ae9ff6 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 249 | #2 0x00007ffff6aea45a in g_main_loop_run () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 250 | #3 0x00007ffff4bb75e6 in ?? () from /usr/lib/x86_64-linux-gnu/libgio-2.0.so.0 |
| 251 | #4 0x00007ffff6b0b9b5 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 252 | #5 0x00007ffff659fe9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 253 | ---Type <return> to continue, or q <return> to quit--- |
| 254 | #6 0x00007ffff5aba3fd in clone () from /lib/x86_64-linux-gnu/libc.so.6 |
| 255 | #7 0x0000000000000000 in ?? () |
| 256 | |
| 257 | Thread 2 (Thread 0x7ffff058c700 (LWP 25609)): |
| 258 | #0 0x00007ffff5aaea43 in poll () from /lib/x86_64-linux-gnu/libc.so.6 |
| 259 | #1 0x00007ffff6ae9ff6 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 260 | #2 0x00007ffff6aea45a in g_main_loop_run () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 261 | #3 0x00007ffff059698b in ?? () from /usr/lib/x86_64-linux-gnu/gio/modules/libdconfsettings.so |
| 262 | #4 0x00007ffff6b0b9b5 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 263 | #5 0x00007ffff659fe9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 264 | #6 0x00007ffff5aba3fd in clone () from /lib/x86_64-linux-gnu/libc.so.6 |
| 265 | #7 0x0000000000000000 in ?? () |
| 266 | |
| 267 | Thread 1 (Thread 0x7ffff7fce940 (LWP 25608)): |
| 268 | #0 0x00007ffff65a1148 in pthread_join () from /lib/x86_64-linux-gnu/libpthread.so.0 |
| 269 | #1 0x000000000081073e in PaUnixThread_Terminate () |
| 270 | #2 0x0000000000818239 in RealStop () |
| 271 | #3 0x00000000008182c7 in AbortStream () |
| 272 | #4 0x0000000000811ce5 in Pa_CloseStream () |
| 273 | #5 0x0000000000753a6d in flush () |
| 274 | #6 0x0000000000753dae in MelderAudio_stopPlaying () |
| 275 | #7 0x00000000004d80e1 in Sound_playPart () |
| 276 | #8 0x00000000004f7b48 in structSoundEditor::v_play () |
| 277 | #9 0x00000000004e7197 in gui_drawingarea_cb_click () |
| 278 | #10 0x00000000007d0d35 in _GuiGtkDrawingArea_clickCallback () |
| 279 | #11 0x00007ffff78d6e78 in ?? () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 |
| 280 | #12 0x00007ffff6da6ca2 in g_closure_invoke () from /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 |
| 281 | #13 0x00007ffff6db7d71 in ?? () from /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 |
| 282 | #14 0x00007ffff6dbfd4e in g_signal_emit_valist () |
| 283 | from /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 |
| 284 | #15 0x00007ffff6dc0212 in g_signal_emit () from /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 |
| 285 | #16 0x00007ffff79f1231 in ?? () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 |
| 286 | #17 0x00007ffff78d5003 in gtk_propagate_event () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 |
| 287 | #18 0x00007ffff78d5363 in gtk_main_do_event () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 |
| 288 | #19 0x00007ffff7549cac in ?? () from /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0 |
| 289 | #20 0x00007ffff6ae9d13 in g_main_context_dispatch () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 290 | #21 0x00007ffff6aea060 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 291 | ---Type <return> to continue, or q <return> to quit--- |
| 292 | #22 0x00007ffff6aea45a in g_main_loop_run () from /lib/x86_64-linux-gnu/libglib-2.0.so.0 |
| 293 | #23 0x00007ffff78d4397 in gtk_main () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 |
| 294 | #24 0x00000000007909eb in praat_run () |
| 295 | #25 0x000000000040e009 in main () |
| 296 | |
| 297 | Also see http://sourceforge.net/p/audacity/mailman/audacity-devel/thread/[email protected]/ |
| 298 | */ |
| 299 | #endif |
| 300 | Pa_CloseStream (my stream); |
| 301 | my stream = nullptr; |
| 302 | } |
| 303 | #ifdef HAVE_PULSEAUDIO |
| 304 | } else if (my usePulseAudio) { |
| 305 | if (my pulseAudio.mainloop) { |
| 306 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 307 | if (my pulseAudio.stream) { |
| 308 | pa_operation *operation = pa_stream_flush (my pulseAudio.stream, stream_drain_complete_cb, me); |
| 309 | // wait because of a threaded_mainloop |
| 310 | if (operation) { |
| 311 | while (MelderAudio_isPlaying) { |
| 312 | pa_threaded_mainloop_wait (my pulseAudio.mainloop); |
| 313 | trace (U"wait"); |
| 314 | } |
| 315 | pa_operation_unref (operation); |
| 316 | } |
| 317 | } |
| 318 | MelderAudio_isPlaying = false; |
| 319 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 320 | pulseAudio_cleanup (); |
| 321 | } |
| 322 | #endif |
| 323 | } else { |
| 324 | #if defined (macintosh) |
| 325 | #elif defined (linux) && ! defined (NO_AUDIO) |
| 326 | |
| 327 | /* |
| 328 | As on Sun. |
| 329 | */ |
| 330 | if (my audio_fd) { |
| 331 | ioctl (my audio_fd, SNDCTL_DSP_RESET, (my val = 0, & my val)); |
| 332 | close (my audio_fd), my audio_fd = 0; |
| 333 | } |
| 334 | #elif defined (_WIN32) |
| 335 | /* |
| 336 | FIX: Do not reset the sound card if played to the end: |
| 337 | the last 20 milliseconds may be truncated! |
| 338 | This used to happen on Barbertje's Dell PC, not with SoundBlaster. |
| 339 | */ |
| 340 | if (my samplesPlayed != my numberOfSamples || Melder_debug == 2) |
| 341 | waveOutReset (my hWaveOut); |
| 342 | my status = waveOutUnprepareHeader (my hWaveOut, & my waveHeader, sizeof (WAVEHDR)); |
| 343 | if (/* Melder_debug == 3 && */ my status == WAVERR_STILLPLAYING) { |
| 344 | waveOutReset (my hWaveOut); |
| 345 | waveOutUnprepareHeader (my hWaveOut, & my waveHeader, sizeof (WAVEHDR)); |
| 346 | } |
| 347 | waveOutClose (my hWaveOut), my hWaveOut = 0; |
| 348 | #endif |
| 349 | } |
| 350 | MelderAudio_isPlaying = false; |
| 351 | if (my samplesPlayed >= my numberOfSamples) |
| 352 | my samplesPlayed = my numberOfSamples; |
| 353 | if (my samplesPlayed <= 0) |
| 354 | my samplesPlayed = 1; |
| 355 | /* |
| 356 | Call the callback for the last time, which is recognizable by the value of MelderAudio_isPlaying. |
| 357 | In this way, the caller of Melder_play16 can be notified. |
| 358 | The caller can examine the actual number of samples played by testing MelderAudio_getSamplesPlayed (). |
| 359 | */ |
| 360 | if (my callback) |
| 361 | my callback (my closure, my samplesPlayed); |
| 362 | my callback = 0; |
| 363 | my closure = 0; |
| 364 | return true; /* Remove workProc if called from workProc. */ |
| 365 | } |
| 366 | |
| 367 | bool MelderAudio_stopPlaying (bool explicitStop) { |
| 368 | //Melder_casual (U"stop playing!"); |
| 369 | struct MelderPlay *me = & thePlay; |
| 370 | my explicitStop = explicitStop; |
| 371 | trace (U"playing = ", MelderAudio_isPlaying); |
| 372 | if (! MelderAudio_isPlaying || my asynchronicity < kMelder_asynchronicityLevel::ASYNCHRONOUS) return false; |
| 373 | #if gtk |
| 374 | if (thePlay.workProcId_gtk && ! my usePulseAudio) { |
| 375 | g_source_remove (thePlay.workProcId_gtk); |
| 376 | } |
| 377 | thePlay.workProcId_gtk = 0; |
| 378 | #elif motif |
| 379 | XtRemoveWorkProc (thePlay. workProcId_motif); |
| 380 | #elif cocoa |
| 381 | CFRunLoopRemoveTimer (CFRunLoopGetCurrent (), thePlay. cocoaTimer, kCFRunLoopCommonModes); |
| 382 | #endif |
| 383 | (void) flush (); |
| 384 | return true; |
| 385 | } |
| 386 | |
| 387 | static bool workProc (void *closure) { |
| 388 | struct MelderPlay *me = & thePlay; |
| 389 | //static integer n = 0; |
| 390 | //n ++; |
| 391 | //Melder_casual (U"workProc ", n); |
| 392 | if (my usePortAudio) { |
| 393 | #if defined (linux) |
| 394 | const double timeElapsed = Melder_clock () - theStartingTime - Pa_GetStreamInfo (my stream) -> outputLatency; |
| 395 | const integer samplesPlayed = timeElapsed * my sampleRate; |
| 396 | if (my callback && ! my callback (my closure, samplesPlayed)) { |
| 397 | my volatile_interrupted = 1; |
| 398 | return flush (); |
| 399 | } |
| 400 | if (my samplesLeft == 0) { |
| 401 | return flush (); |
| 402 | } |
| 403 | #elif defined (linuxXXX) |
| 404 | /* |
| 405 | Not all hostApis support paComplete or wait till all buffers have been played in Pa_StopStream. |
| 406 | Once pa_win_ds implements this, we can simply do: |
| 407 | */ |
| 408 | if (Pa_IsStreamActive (my stream)) { |
| 409 | if (my callback && ! my callback (my closure, my samplesPlayed)) |
| 410 | return flush (); |
| 411 | } else { |
| 412 | Pa_StopStream (my stream); |
| 413 | my samplesPlayed = my numberOfSamples; |
| 414 | return flush (); |
| 415 | } |
| 416 | /* |
| 417 | But then we also have to use paComplete in the stream callback. |
| 418 | */ |
| 419 | #else |
| 420 | const double timeElapsed = Melder_clock () - theStartingTime - Pa_GetStreamInfo (my stream) -> outputLatency; |
| 421 | my samplesPlayed = (integer) floor (timeElapsed * my sampleRate); |
| 422 | if (my supports_paComplete && Pa_IsStreamActive (my stream)) { |
| 423 | if (my callback && ! my callback (my closure, my samplesPlayed)) { |
| 424 | Pa_AbortStream (my stream); |
| 425 | return flush (); |
| 426 | } |
| 427 | } else if (my samplesPlayed < my numberOfSamples + my sampleRate / 2) { // allow the latency estimate to be 500 ms off. |
| 428 | if (my callback && ! my callback (my closure, my samplesPlayed)) { |
| 429 | Pa_AbortStream (my stream); |
| 430 | return flush (); |
| 431 | } |
| 432 | } else { |
| 433 | Pa_AbortStream (my stream); |
| 434 | my samplesPlayed = my numberOfSamples; |
| 435 | return flush (); |
| 436 | } |
| 437 | Pa_Sleep (10); |
| 438 | #endif |
| 439 | #ifdef HAVE_PULSEAUDIO |
| 440 | } else if (my usePulseAudio) { |
| 441 | if (my pulseAudio.mainloop) { |
| 442 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 443 | integer samplesPlayed = 0; |
| 444 | pa_usec_t diff_usec = 0; |
| 445 | if (my pulseAudio.startTime.tv_usec != 0) { |
| 446 | diff_usec = pa_timeval_age (& my pulseAudio.startTime); |
| 447 | const double timeElapsed = diff_usec / 1000000.0; |
| 448 | samplesPlayed = timeElapsed * my sampleRate; |
| 449 | } |
| 450 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 451 | trace (U"diff = ", diff_usec, U", samples played = ", samplesPlayed); |
| 452 | if (my callback && ! my callback (my closure, samplesPlayed)) { |
| 453 | my volatile_interrupted = 1; |
| 454 | return flush (); |
| 455 | } else if (my samplesLeft == 0 || samplesPlayed > my numberOfSamples) { |
| 456 | return flush (); |
| 457 | } |
| 458 | } |
| 459 | #endif |
| 460 | } else { |
| 461 | #if defined (macintosh) |
| 462 | #elif defined (linux) && ! defined (NO_AUDIO) |
| 463 | if (my samplesLeft > 0) { |
| 464 | int dsamples = my samplesLeft > 500 ? 500 : my samplesLeft; |
| 465 | write (my audio_fd, (char *) & my playBuffer [my samplesSent * my numberOfChannels], 2 * dsamples * my numberOfChannels); |
| 466 | my samplesLeft -= dsamples; |
| 467 | my samplesSent += dsamples; |
| 468 | my samplesPlayed = (Melder_clock () - theStartingTime) * my sampleRate; |
| 469 | if (my callback && ! my callback (my closure, my samplesPlayed)) |
| 470 | return flush (); |
| 471 | } else /*if (my samplesPlayed >= my numberOfSamples)*/ { |
| 472 | close (my audio_fd), my audio_fd = 0; |
| 473 | my samplesPlayed = my numberOfSamples; |
| 474 | return flush (); |
| 475 | /*} else { |
| 476 | my samplesPlayed = (Melder_clock () - theStartingTime) * my sampleRate; |
| 477 | if (my callback && ! my callback (my closure, my samplesPlayed)) |
| 478 | return flush ();*/ |
| 479 | } |
| 480 | #elif defined (_WIN32) |
| 481 | if (my waveHeader. dwFlags & WHDR_DONE) { |
| 482 | my samplesPlayed = my numberOfSamples; |
| 483 | return flush (); |
| 484 | } else { |
| 485 | static double previousTime = 0.0; |
| 486 | const double currentTime = Melder_clock (); |
| 487 | if (Melder_debug == 1) { |
| 488 | my samplesPlayed = (Melder_clock () - theStartingTime) * my sampleRate; |
| 489 | } else { |
| 490 | MMTIME mmtime; |
| 491 | mmtime. wType = TIME_BYTES; |
| 492 | waveOutGetPosition (my hWaveOut, & mmtime, sizeof (MMTIME)); |
| 493 | my samplesPlayed = mmtime. u.cb / (2 * my numberOfChannels); |
| 494 | } |
| 495 | if (/* Melder_debug != 4 || */ currentTime - previousTime > 0.01) { |
| 496 | previousTime = currentTime; |
| 497 | if (my callback && ! my callback (my closure, my samplesPlayed)) |
| 498 | return flush (); |
| 499 | } |
| 500 | Sleep (10); |
| 501 | } |
| 502 | #endif |
| 503 | } |
| 504 | (void) closure; |
| 505 | return false; |
| 506 | } |
| 507 | #if gtk |
| 508 | static gint workProc_gtk (gpointer closure) { |
| 509 | return ! workProc ((void *) closure); |
| 510 | } |
| 511 | #elif motif |
| 512 | static bool workProc_motif (XtPointer closure) { |
| 513 | return workProc ((void *) closure); |
| 514 | } |
| 515 | #elif cocoa |
| 516 | static void workProc_cocoa (CFRunLoopTimerRef timer, void *closure) { |
| 517 | bool result = workProc (closure); |
| 518 | if (result) { |
| 519 | CFRunLoopTimerInvalidate (timer); |
| 520 | //CFRunLoopRemoveTimer (CFRunLoopGetCurrent (), timer); |
| 521 | } |
| 522 | } |
| 523 | #endif |
| 524 | |
| 525 | static int thePaStreamCallback (const void *input, void *output, |
| 526 | unsigned long frameCount, |
| 527 | const PaStreamCallbackTimeInfo* timeInfo, |
| 528 | PaStreamCallbackFlags statusFlags, |
| 529 | void *userData) |
| 530 | { |
| 531 | (void) input; |
| 532 | (void) timeInfo; |
| 533 | (void) userData; |
| 534 | struct MelderPlay *me = & thePlay; |
| 535 | if (my volatile_interrupted) { |
| 536 | memset (output, '\0', 2 * frameCount * my numberOfChannels); |
| 537 | my samplesPlayed = my numberOfSamples; |
| 538 | return my supports_paComplete ? paComplete : paContinue; |
| 539 | } |
| 540 | if (statusFlags & paOutputUnderflow) { |
| 541 | if (Melder_debug == 20) Melder_casual (U"output underflow"); |
| 542 | } |
| 543 | if (statusFlags & paOutputOverflow) { |
| 544 | if (Melder_debug == 20) Melder_casual (U"output overflow"); |
| 545 | } |
| 546 | if (my samplesLeft > 0) { |
| 547 | const integer dsamples = Melder_clippedRight ((integer) frameCount, my samplesLeft); |
| 548 | if (Melder_debug == 20) Melder_casual (U"play ", dsamples, U" ", Pa_GetStreamCpuLoad (my stream)); |
| 549 | memset (output, '\0', 2 * frameCount * my numberOfChannels); |
| 550 | Melder_assert (my playBuffer); |
| 551 | memcpy (output, (char *) & my playBuffer [my samplesSent * my numberOfChannels], 2 * dsamples * my numberOfChannels); |
| 552 | my samplesLeft -= dsamples; |
| 553 | my samplesSent += dsamples; |
| 554 | my samplesPlayed = my samplesSent; |
| 555 | } else /*if (my samplesPlayed >= my numberOfSamples)*/ { |
| 556 | memset (output, '\0', 2 * frameCount * my numberOfChannels); |
| 557 | //OSMemoryBarrier(); |
| 558 | my samplesPlayed = my numberOfSamples; |
| 559 | trace (U"paComplete"); |
| 560 | return my supports_paComplete ? paComplete : paContinue; |
| 561 | } |
| 562 | return paContinue; |
| 563 | } |
| 564 | |
| 565 | #ifdef HAVE_PULSEAUDIO |
| 566 | void pulseAudio_initialize () { |
| 567 | struct MelderPlay *me = & thePlay; |
| 568 | if (! my pulseAudio.pulseAudioInitialized) { |
| 569 | my pulseAudio.mainloop = pa_threaded_mainloop_new (); |
| 570 | if (! my pulseAudio.mainloop) { |
| 571 | MelderAudio_isPlaying = false; |
| 572 | Melder_throw (U"No connection to pulse audio server."); |
| 573 | } |
| 574 | pa_threaded_mainloop_start (my pulseAudio.mainloop); |
| 575 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 576 | my pulseAudio.mainloop_api = pa_threaded_mainloop_get_api (my pulseAudio.mainloop); |
| 577 | my pulseAudio.context = pa_context_new (my pulseAudio.mainloop_api, "praat"); |
| 578 | pa_context_set_state_callback (my pulseAudio.context, context_state_cb, me); |
| 579 | pa_context_connect (my pulseAudio.context, nullptr, PA_CONTEXT_NOFLAGS, nullptr); |
| 580 | trace (U"threading"); |
| 581 | my pulseAudio.pulseAudioInitialized = true; |
| 582 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | void pulseAudio_cleanup () { |
| 587 | struct MelderPlay *me = & thePlay; |
| 588 | |
| 589 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 590 | trace (U"mainloop to be freed, occupation was ", my pulseAudio.occupation); |
| 591 | |
| 592 | if (my pulseAudio.context) { |
| 593 | trace (U"still context"); |
| 594 | pa_context_unref (my pulseAudio.context); |
| 595 | my pulseAudio.context = nullptr; |
| 596 | } |
| 597 | if (my pulseAudio.timer_event) { |
| 598 | my pulseAudio.mainloop_api -> time_free (my pulseAudio.timer_event); |
| 599 | my pulseAudio.timer_event = nullptr; |
| 600 | } |
| 601 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 602 | pa_threaded_mainloop_free (my pulseAudio.mainloop); // automatically frees the mainloop_api too! |
| 603 | my pulseAudio.mainloop = nullptr; |
| 604 | my pulseAudio.mainloop_api = nullptr; |
| 605 | my pulseAudio.r_usec = 0; |
| 606 | MelderAudio_isPlaying = false; |
| 607 | my pulseAudio.occupation = 0; |
| 608 | my pulseAudio.startTime = {0, 0}; |
| 609 | my pulseAudio.pulseAudioInitialized = false; |
| 610 | } |
| 611 | |
| 612 | void pulseAudio_server_info_cb (pa_context *context, const pa_server_info *info, void *userdata) { |
| 613 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 614 | if (! info) { |
| 615 | return; |
| 616 | } |
| 617 | const pa_sample_spec *sp = & (info -> sample_spec); |
| 618 | my numberOfChannels = sp -> channels; |
| 619 | Melder_assert (context == my pulseAudio.context); |
| 620 | if ((my pulseAudio.occupation & PA_QUERY_NUMBEROFCHANNELS) != PA_QUERY_NUMBEROFCHANNELS) { |
| 621 | MelderInfo_open (); |
| 622 | MelderInfo_writeLine (U"PulseAudio Server characteristics:"); |
| 623 | MelderInfo_writeLine (U"User name: ", Melder_peek8to32_u (info -> user_name)); |
| 624 | MelderInfo_writeLine (U"Host name: ", Melder_peek8to32_u (info -> host_name)); |
| 625 | MelderInfo_writeLine (U"Server version: ", Melder_peek8to32_u (info -> server_version)); |
| 626 | MelderInfo_writeLine (U"Server name: ", Melder_peek8to32_u (info -> server_name)); |
| 627 | MelderInfo_writeLine (U"Sample specification: "); |
| 628 | MelderInfo_writeLine (U"\tNumber of channels: ", my numberOfChannels); |
| 629 | MelderInfo_writeLine (U"\tSampling frequency: ", sp -> rate); |
| 630 | const char *sample_format_string = pa_sample_format_to_string (sp -> format); |
| 631 | MelderInfo_writeLine (U"\tSample format: ", Melder_peek8to32_u (sample_format_string)); |
| 632 | MelderInfo_writeLine (U"Default sink name: ", Melder_peek8to32_u (info -> default_sink_name)); |
| 633 | MelderInfo_writeLine (U"Default source name: ", Melder_peek8to32_u (info -> default_source_name)); |
| 634 | const pa_channel_map *cm = &(info -> channel_map); |
| 635 | MelderInfo_writeLine (U"Channel specification: "); |
| 636 | for (integer channel = 1; channel <= cm -> channels; channel++) { |
| 637 | const char *channel_text = pa_channel_position_to_pretty_string (cm -> map[channel - 1]); // 0-.. |
| 638 | MelderInfo_writeLine (U"\t Channel ", channel, U": ", Melder_peek8to32_u (channel_text)); |
| 639 | } |
| 640 | MelderInfo_close (); |
| 641 | } |
| 642 | trace (U"before signal"); |
| 643 | my pulseAudio.occupation |= PA_GETTINGINFO_DONE; |
| 644 | // We are done, signal it to pulseAudio_serverReport |
| 645 | pa_threaded_mainloop_signal (my pulseAudio.mainloop, 0); |
| 646 | } |
| 647 | |
| 648 | void pulseAudio_serverReport () { |
| 649 | // TODO: initialize context |
| 650 | struct MelderPlay *me = & thePlay; |
| 651 | if (my pulseAudio.mainloop) { |
| 652 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 653 | my pulseAudio.occupation |= PA_GETTINGINFO; |
| 654 | if (my pulseAudio.context) { |
| 655 | pa_operation *operation = pa_context_get_server_info (my pulseAudio.context, pulseAudio_server_info_cb, me); |
| 656 | trace (U"operation started"); |
| 657 | if (! operation) { |
| 658 | Melder_throw (U"pulseAudioServer report: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 659 | } |
| 660 | while ((my pulseAudio.occupation & PA_GETTINGINFO_DONE) != PA_GETTINGINFO_DONE) { |
| 661 | pa_threaded_mainloop_wait (my pulseAudio.mainloop); |
| 662 | } |
| 663 | // Now it is save to unref because the server info operation has completed |
| 664 | pa_operation_unref (operation); |
| 665 | my pulseAudio.occupation &= ~ PA_GETTINGINFO_DONE; |
| 666 | } |
| 667 | my pulseAudio.occupation &= ~ PA_GETTINGINFO; |
| 668 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 669 | } else { |
| 670 | my pulseAudio.occupation |= PA_GETTINGINFO; |
| 671 | pulseAudio_initialize (); |
| 672 | /* |
| 673 | First acquire a lock because the operation to get server info (in context_state_cb) may not have started yet. |
| 674 | We therefore use our own signaling and wait until information has been acquired. |
| 675 | */ |
| 676 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 677 | |
| 678 | while ((my pulseAudio.occupation & PA_GETTINGINFO_DONE) != PA_GETTINGINFO_DONE) { |
| 679 | pa_threaded_mainloop_wait (my pulseAudio.mainloop); |
| 680 | } |
| 681 | // Now we know that the operation to get server info has succeeded! |
| 682 | pa_operation_unref (my pulseAudio.operation_info); |
| 683 | my pulseAudio.operation_info = nullptr; |
| 684 | my pulseAudio.occupation &= ~ PA_GETTINGINFO; |
| 685 | my pulseAudio.occupation &= ~ PA_GETTINGINFO_DONE; |
| 686 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 687 | if (! MelderAudio_isPlaying) { |
| 688 | my pulseAudio.occupation = 0; |
| 689 | trace (U"before cleanup"); |
| 690 | pulseAudio_cleanup (); |
| 691 | } |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | void context_drain_complete_cb (pa_context *context, void *userdata) { |
| 696 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 697 | Melder_assert (context == my pulseAudio.context); |
| 698 | if (context) { |
| 699 | trace (U"context exists"); |
| 700 | pa_context_disconnect (my pulseAudio.context); |
| 701 | pa_context_unref (my pulseAudio.context); |
| 702 | my pulseAudio.context = nullptr; |
| 703 | } |
| 704 | trace (U"after context test"); |
| 705 | pulseAudio_cleanup (); |
| 706 | } |
| 707 | |
| 708 | void stream_drain_complete_cb (pa_stream *stream, int success, void *userdata) { |
| 709 | (void) stream; |
| 710 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 711 | // Melder_assert (stream == my pulseAudio.stream); // not always true |
| 712 | |
| 713 | trace (U"succes = ", success); |
| 714 | if (stream == my pulseAudio.stream) { |
| 715 | trace (U"stream exists"); |
| 716 | pa_stream_disconnect (my pulseAudio.stream); |
| 717 | pa_stream_unref (my pulseAudio.stream); |
| 718 | my pulseAudio.stream = nullptr; |
| 719 | my pulseAudio.occupation &= ~ PA_WRITING; |
| 720 | my pulseAudio.occupation |= PA_WRITING_DONE; |
| 721 | MelderAudio_isPlaying = false; |
| 722 | if (my pulseAudio.timer_event) { |
| 723 | my pulseAudio.mainloop_api -> time_free (my pulseAudio.timer_event); |
| 724 | my pulseAudio.timer_event = nullptr; |
| 725 | } |
| 726 | pa_threaded_mainloop_signal (my pulseAudio.mainloop, 0); |
| 727 | } else { |
| 728 | trace (U"??"); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | static void free_cb (void * /* p */) { // to prevent copying of data |
| 733 | } |
| 734 | |
| 735 | // asynchronous version |
| 736 | void stream_write_cb2 (pa_stream *stream, size_t length, void *userdata) { |
| 737 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 738 | if (stream == my pulseAudio.stream) { |
| 739 | //length = my pulseAudio.latency; // overrule length given by server |
| 740 | integer writeSize_samples = length / (2 * my numberOfChannels); |
| 741 | my samplesLeft = my numberOfSamples - my samplesSent; |
| 742 | trace (U"length = ", length, U" left = ", my samplesLeft); |
| 743 | MelderAudio_isPlaying = true; |
| 744 | if (my samplesLeft == my numberOfSamples) { |
| 745 | pa_gettimeofday (& my pulseAudio.startTime); |
| 746 | } |
| 747 | if (my samplesLeft > 0) { |
| 748 | if (my volatile_interrupted) { |
| 749 | my samplesPlayed = my numberOfSamples; |
| 750 | my samplesLeft = 0; |
| 751 | flush (); |
| 752 | } else { |
| 753 | writeSize_samples = my samplesLeft < writeSize_samples ? my samplesLeft : writeSize_samples; |
| 754 | if (pa_stream_write (stream, my playBuffer + my samplesSent * my numberOfChannels, 2 * writeSize_samples * my numberOfChannels, free_cb, 0, PA_SEEK_RELATIVE) < 0) { |
| 755 | Melder_throw (U"pa_stream_write() failed: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 756 | } |
| 757 | integer samplesSent = writeSize_samples; |
| 758 | my samplesSent += samplesSent; |
| 759 | my samplesPlayed = my samplesSent; // not true: use timer info |
| 760 | trace (U"written ", samplesSent, U" (samples), total ", my samplesSent); |
| 761 | if (my samplesSent == my numberOfSamples) { |
| 762 | // my samplesLeft = 0; not here because still playing |
| 763 | trace (U"nothing left 1"); |
| 764 | //pa_stream_set_write_callback(my pulseAudio.stream, nullptr, nullptr); |
| 765 | my pulseAudio.operation_drain = pa_stream_drain (my pulseAudio.stream, stream_drain_complete_cb, me); |
| 766 | if (! my pulseAudio.operation_drain) { |
| 767 | pa_stream_disconnect (my pulseAudio.stream); |
| 768 | pa_stream_unref (my pulseAudio.stream); |
| 769 | my pulseAudio.stream = nullptr; |
| 770 | trace (U"stream exists"); |
| 771 | my pulseAudio.occupation &= ~ PA_WRITING; |
| 772 | my pulseAudio.occupation |= PA_WRITING_DONE; |
| 773 | pa_threaded_mainloop_signal (my pulseAudio.mainloop, 0); |
| 774 | if (my pulseAudio.timer_event) { |
| 775 | my pulseAudio.mainloop_api -> time_free (my pulseAudio.timer_event); |
| 776 | my pulseAudio.timer_event = nullptr; |
| 777 | } |
| 778 | } |
| 779 | } |
| 780 | } |
| 781 | } else { |
| 782 | trace (U"nothing left"); |
| 783 | } |
| 784 | } else { |
| 785 | trace (U"stream?"); |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | void stream_write_cb (pa_stream *stream, size_t length, void *userdata) { |
| 790 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 791 | if (stream == my pulseAudio.stream) { |
| 792 | my samplesLeft = my numberOfSamples - my samplesSent; |
| 793 | trace (U"length = ", length, U", left = ", my samplesLeft); |
| 794 | if (my samplesLeft > 0) { |
| 795 | if (my samplesLeft == my numberOfSamples) { |
| 796 | pa_gettimeofday (& my pulseAudio.startTime); |
| 797 | } |
| 798 | if (my volatile_interrupted) { |
| 799 | my samplesPlayed = my numberOfSamples; |
| 800 | my samplesLeft = 0; |
| 801 | flush (); |
| 802 | } else { |
| 803 | int16 *pa_buffer; // an internal pa buffer to minimize the number of memory transfers between client and server |
| 804 | size_t nbytes_left = my samplesLeft * my numberOfChannels * 2; // how many bytes do we still need to write ? |
| 805 | size_t nbytes = nbytes_left; |
| 806 | // returns the address of an internal buffer and the number of bytes that can maximally be written to it. |
| 807 | if (pa_stream_begin_write (stream, (void **) & pa_buffer, & nbytes) < 0) { |
| 808 | trace (U"error: no memory"); |
| 809 | Melder_throw (U"Pulseaudio has no internal memory left."); |
| 810 | } |
| 811 | trace (U"buffer size = ", nbytes); |
| 812 | // do we need the full buffer space ? |
| 813 | nbytes = nbytes <= nbytes_left ? nbytes : nbytes_left; |
| 814 | memcpy (pa_buffer, (void *) (my playBuffer + my samplesSent * my numberOfChannels), nbytes); |
| 815 | //memset (pa_buffer, 0, nbytes); |
| 816 | |
| 817 | if (pa_stream_write (stream, pa_buffer, nbytes, nullptr, 0, PA_SEEK_RELATIVE) < 0) { |
| 818 | Melder_throw (U"pa_stream_write() failed: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 819 | } |
| 820 | Melder_assert (nbytes % (my numberOfChannels * 2) == 0); |
| 821 | integer samplesSent = nbytes / (my numberOfChannels * 2); |
| 822 | my samplesSent += samplesSent; |
| 823 | my samplesPlayed = my samplesSent; // not true: use timer info |
| 824 | trace (U"written ", samplesSent, U" (samples), total ", my samplesSent, U", address = ", (integer) pa_buffer); |
| 825 | if (my samplesSent == my numberOfSamples) { |
| 826 | // my samplesLeft = 0; not here because still playing |
| 827 | trace (U"nothing left 1"); |
| 828 | pa_stream_set_write_callback (my pulseAudio.stream, nullptr, nullptr); |
| 829 | my pulseAudio.operation_drain = pa_stream_drain (my pulseAudio.stream, stream_drain_complete_cb, me); |
| 830 | if (! my pulseAudio.operation_drain) { |
| 831 | pa_stream_disconnect (my pulseAudio.stream); |
| 832 | pa_stream_unref (my pulseAudio.stream); |
| 833 | my pulseAudio.stream = nullptr; |
| 834 | trace (U"stream exists"); |
| 835 | my pulseAudio.occupation &= ~ PA_WRITING; |
| 836 | my pulseAudio.occupation |= PA_WRITING_DONE; |
| 837 | pa_threaded_mainloop_signal (my pulseAudio.mainloop, 0); |
| 838 | if (my pulseAudio.timer_event) { |
| 839 | my pulseAudio.mainloop_api -> time_free (my pulseAudio.timer_event); |
| 840 | my pulseAudio.timer_event = nullptr; |
| 841 | } |
| 842 | } |
| 843 | } |
| 844 | } |
| 845 | } else { |
| 846 | trace (U"nothing left"); |
| 847 | } |
| 848 | } else { |
| 849 | trace (U"stream?"); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | void stream_state_cb (pa_stream *stream, void *userdata) { |
| 854 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 855 | |
| 856 | if (stream == my pulseAudio.stream) { |
| 857 | switch (pa_stream_get_state (stream)) { |
| 858 | case PA_STREAM_UNCONNECTED: |
| 859 | trace (U"PA_STREAM_UNCONNECTED"); |
| 860 | break; |
| 861 | case PA_STREAM_CREATING: |
| 862 | trace (U"PA_STREAM_CREATING"); |
| 863 | break; |
| 864 | case PA_STREAM_TERMINATED: |
| 865 | trace (U"PA_STREAM_TERMINATED"); |
| 866 | break; |
| 867 | case PA_STREAM_READY: { |
| 868 | const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr (my pulseAudio.stream); |
| 869 | trace (U"PA_STREAM_READY : tlength = ", buffer_attr -> tlength, U", prebuf = ", buffer_attr -> prebuf, U", maxlength = ", buffer_attr -> maxlength); |
| 870 | break; |
| 871 | } |
| 872 | default: |
| 873 | trace (U"default"); |
| 874 | break; |
| 875 | case PA_STREAM_FAILED: |
| 876 | trace (U"PA_STREAM_FAILED"); |
| 877 | break; |
| 878 | } |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | static void stream_underflow_callback (pa_stream *s, void *userdata) { |
| 883 | (void) s; |
| 884 | (void) userdata; |
| 885 | trace (U"yes"); |
| 886 | } |
| 887 | |
| 888 | static void stream_overflow_callback (pa_stream *s, void *userdata) { |
| 889 | (void) s; |
| 890 | (void) userdata; |
| 891 | trace (U"yes"); |
| 892 | } |
| 893 | |
| 894 | void prepare_and_play (struct MelderPlay *me) { |
| 895 | my pulseAudio.sample_spec.format = ( Melder_integersAreBigEndian () ? PA_SAMPLE_S16BE : PA_SAMPLE_S16LE ); |
| 896 | my samplesPlayed = my samplesSent = 0; |
| 897 | my pulseAudio.sample_spec.rate = my sampleRate; |
| 898 | my pulseAudio.sample_spec.channels = my numberOfChannels; |
| 899 | my pulseAudio.stream = pa_stream_new (my pulseAudio.context, "Praat", &(my pulseAudio.sample_spec), nullptr); |
| 900 | if (! my pulseAudio.stream) { |
| 901 | Melder_throw (U"Cannot connect to sound server: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 902 | } |
| 903 | |
| 904 | //my pulseAudio.stream_flags = PA_STREAM_NOFLAGS; |
| 905 | my pulseAudio.stream_flags = (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE); |
| 906 | my pulseAudio.latency = pa_usec_to_bytes (1000 * my pulseAudio.latency_msec, & my pulseAudio.sample_spec); |
| 907 | |
| 908 | my pulseAudio.buffer_attr.maxlength = (uint32) -1; |
| 909 | my pulseAudio.buffer_attr.prebuf = (uint32) -1; |
| 910 | my pulseAudio.buffer_attr.minreq = (uint32) -1; |
| 911 | my pulseAudio.buffer_attr.prebuf = (uint32) -1; |
| 912 | my pulseAudio.buffer_attr.tlength = my pulseAudio.latency; |
| 913 | my pulseAudio.buffer_attr.fragsize = (uint32) -1; |
| 914 | |
| 915 | pa_stream_set_state_callback (my pulseAudio.stream, stream_state_cb, me); |
| 916 | pa_stream_set_write_callback (my pulseAudio.stream, stream_write_cb, me); |
| 917 | pa_stream_set_underflow_callback (my pulseAudio.stream, stream_underflow_callback, me); |
| 918 | pa_stream_set_overflow_callback (my pulseAudio.stream, stream_overflow_callback, me); |
| 919 | |
| 920 | // BUG in pa 5.9 & 6.0: the server doesn't honour our wish for a reasonable tlength. Instead it uses some |
| 921 | // ridiculously low value for tlength that will constantly give underflows. |
| 922 | // audio playback was completely shit if in the stream_write_cb we used pa_stream_write instead of |
| 923 | // first pa_stream_begin_write followed by pa_stream_write. |
| 924 | // |
| 925 | my pulseAudio.stream_flags = PA_STREAM_NOFLAGS; |
| 926 | if (pa_stream_connect_playback (my pulseAudio.stream, nullptr, & my pulseAudio.buffer_attr, my pulseAudio.stream_flags, nullptr, nullptr) < 0) { |
| 927 | Melder_throw (U"pa_stream_connect_playback() failed: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 928 | } |
| 929 | trace (U"tlength = ", my pulseAudio.buffer_attr.tlength, U", channels = ", my numberOfChannels); |
| 930 | } |
| 931 | |
| 932 | void context_state_cb (pa_context *context, void *userdata) { |
| 933 | struct MelderPlay *me = (struct MelderPlay *) userdata; |
| 934 | |
| 935 | pa_context_state context_state = pa_context_get_state (context); |
| 936 | switch (context_state) { |
| 937 | case PA_CONTEXT_UNCONNECTED: |
| 938 | trace (U"PA_CONTEXT_UNCONNECTED"); |
| 939 | break; |
| 940 | case PA_CONTEXT_CONNECTING: |
| 941 | trace (U"PA_CONTEXT_CONNECTING"); |
| 942 | break; |
| 943 | case PA_CONTEXT_AUTHORIZING: |
| 944 | trace (U"PA_CONTEXT_AUTHORIZING"); |
| 945 | break; |
| 946 | case PA_CONTEXT_SETTING_NAME: |
| 947 | trace (U"PA_CONTEXT_SETTING_NAME"); |
| 948 | break; |
| 949 | case PA_CONTEXT_FAILED: |
| 950 | trace (U"PA_CONTEXT_FAILED"); |
| 951 | break; |
| 952 | case PA_CONTEXT_TERMINATED: |
| 953 | trace (U"PA_CONTEXT_TERMINATED"); |
| 954 | break; |
| 955 | case PA_CONTEXT_READY: { |
| 956 | trace (U"PA_CONTEXT_READY"); |
| 957 | if ((my pulseAudio.occupation & PA_GETTINGINFO) == PA_GETTINGINFO) { |
| 958 | my pulseAudio.operation_info = pa_context_get_server_info (my pulseAudio.context, pulseAudio_server_info_cb, me); |
| 959 | trace (U"operation started"); |
| 960 | if (! my pulseAudio.operation_info) { |
| 961 | Melder_throw (U"pulseAudioServer report: ", Melder_peek8to32_u (pa_strerror (pa_context_errno (my pulseAudio.context)))); |
| 962 | } |
| 963 | } else if ((my pulseAudio.occupation & PA_WRITING) == PA_WRITING) { |
| 964 | prepare_and_play (me); |
| 965 | } else if ((my pulseAudio.occupation & PA_RECORDING) == PA_RECORDING) { |
| 966 | |
| 967 | } |
| 968 | break; |
| 969 | } |
| 970 | default: |
| 971 | trace (U"default"); |
| 972 | break; |
| 973 | } |
| 974 | } |
| 975 | #endif |
| 976 | |
| 977 | static bool deviceHasChanged = false; |
| 978 | #if defined (macintosh) |
| 979 | static int theCoreaudioPropertyListener (unsigned int, unsigned int, const AudioObjectPropertyAddress * _Nonnull, void * _Nullable) { |
| 980 | Melder_casual (U"coreaudio_property_listener"); |
| 981 | deviceHasChanged = true; |
| 982 | return 0; |
| 983 | } |
| 984 | #endif |
| 985 | |
| 986 | static bool interruptedByEscapeKey () { |
| 987 | #if defined(_WIN32) |
| 988 | MSG event; |
| 989 | BOOL messageAvailable = PeekMessage (& event, nullptr, 0, 0, PM_REMOVE); |
| 990 | if (messageAvailable) { |
| 991 | trace (U"Windows message: ", event.message); |
| 992 | if (event. message == WM_KEYDOWN) { |
| 993 | trace (U"Windows key: ", event. wParam); |
| 994 | if (LOWORD (event. wParam) == VK_ESCAPE) |
| 995 | return true; |
| 996 | } else if (event. message == WM_LBUTTONDOWN |
| 997 | || event.message == WM_NCLBUTTONDOWN) |
| 998 | { |
| 999 | // ignore all mouse events |
| 1000 | } else { |
| 1001 | // handle all other events, such as Chinese keyboard events |
| 1002 | XtDispatchEvent (& event); |
| 1003 | //TranslateMessage (& event); |
| 1004 | //DispatchMessage (& event); |
| 1005 | } |
| 1006 | } |
| 1007 | #endif |
| 1008 | return false; |
| 1009 | } |
| 1010 | |
| 1011 | void MelderAudio_play16 (int16 *buffer, integer sampleRate, integer numberOfSamples, integer numberOfChannels, |
| 1012 | bool (*playCallback) (void *playClosure, integer numberOfSamplesPlayed), void *playClosure) |
| 1013 | { |
| 1014 | #if defined (macintosh) |
| 1015 | {// scope |
| 1016 | static bool inited; |
| 1017 | if (! inited) { |
| 1018 | OSStatus err = noErr; |
| 1019 | AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; |
| 1020 | err = AudioObjectAddPropertyListener ( kAudioObjectSystemObject, & audioDevicesAddress, theCoreaudioPropertyListener, NULL); |
| 1021 | if (err) |
| 1022 | Melder_casual (U"error on AudioObjectAddPropertyListener"); |
| 1023 | inited = true; |
| 1024 | } |
| 1025 | } |
| 1026 | #endif |
| 1027 | |
| 1028 | struct MelderPlay *me = & thePlay; |
| 1029 | #ifdef _WIN32 |
| 1030 | bool wasPlaying = MelderAudio_isPlaying; |
| 1031 | #endif |
| 1032 | if (MelderAudio_isPlaying) |
| 1033 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); // otherwise, keep "explicitStop" tag |
| 1034 | #ifdef HAVE_PULSEAUDIO |
| 1035 | if (my usePulseAudio && my pulseAudio.mainloop) { |
| 1036 | pulseAudio_cleanup (); |
| 1037 | } |
| 1038 | #endif |
| 1039 | my playBuffer = buffer; // 0-based, as all buffers are |
| 1040 | static int16 *playBuffer2 = nullptr; // in case we have to redistribute up (not ideal) |
| 1041 | my sampleRate = sampleRate; |
| 1042 | my numberOfSamples = numberOfSamples; |
| 1043 | my numberOfChannels = numberOfChannels; |
| 1044 | my callback = playCallback; |
| 1045 | my closure = playClosure; |
| 1046 | my asynchronicity = |
| 1047 | Melder_batch ? kMelder_asynchronicityLevel::SYNCHRONOUS : |
| 1048 | (Melder_backgrounding && ! Melder_asynchronous) ? kMelder_asynchronicityLevel::INTERRUPTABLE : |
| 1049 | kMelder_asynchronicityLevel::ASYNCHRONOUS; |
| 1050 | if (my asynchronicity > preferences. maximumAsynchronicity) |
| 1051 | my asynchronicity = preferences. maximumAsynchronicity; |
| 1052 | trace (U"asynchronicity ", (int) my asynchronicity); |
| 1053 | my usePortAudio = |
| 1054 | #if defined (_WIN32) |
| 1055 | preferences. outputSoundSystem == kMelder_outputSoundSystem::MME_VIA_PORTAUDIO; |
| 1056 | #elif defined (macintosh) |
| 1057 | preferences. outputSoundSystem == kMelder_outputSoundSystem::COREAUDIO_VIA_PORTAUDIO; |
| 1058 | #elif defined (raspberrypi) |
| 1059 | preferences. outputSoundSystem == kMelder_outputSoundSystem::JACK_VIA_PORTAUDIO; |
| 1060 | #else |
| 1061 | preferences. outputSoundSystem == kMelder_outputSoundSystem::ALSA_OR_JACK_VIA_PORTAUDIO; |
| 1062 | #endif |
| 1063 | my usePulseAudio = ! my usePortAudio; |
| 1064 | |
| 1065 | my explicitStop = MelderAudio_IMPLICIT; |
| 1066 | my volatile_interrupted = 0; |
| 1067 | |
| 1068 | my samplesLeft = numberOfSamples; |
| 1069 | my samplesSent = 0; |
| 1070 | my samplesPlayed = 0; |
| 1071 | MelderAudio_isPlaying = true; |
| 1072 | if (my usePortAudio) { |
| 1073 | PaError err; |
| 1074 | if (deviceHasChanged) { |
| 1075 | Pa_Terminate (); |
| 1076 | Pa_Initialize (); |
| 1077 | deviceHasChanged = false; |
| 1078 | } |
| 1079 | if (! MelderAudio_hasBeenInitialized) { |
| 1080 | err = Pa_Initialize (); |
| 1081 | if (err) |
| 1082 | Melder_crash (U"PortAudio does not initialize: ", Melder_peek8to32_u (Pa_GetErrorText (err))); |
| 1083 | MelderAudio_hasBeenInitialized = true; |
| 1084 | } |
| 1085 | my supports_paComplete = Pa_GetHostApiInfo (Pa_GetDefaultHostApi ()) -> type != paDirectSound &&0; |
| 1086 | PaStreamParameters outputParameters = { 0 }; |
| 1087 | outputParameters. device = Pa_GetDefaultOutputDevice (); |
| 1088 | if (outputParameters. device == paNoDevice) |
| 1089 | Melder_throw (U"PortAudio sees no default output device.\nCannot play sound."); |
| 1090 | const PaDeviceInfo *deviceInfo = Pa_GetDeviceInfo (outputParameters. device); |
| 1091 | if (! deviceInfo) |
| 1092 | Melder_throw (U"PortAudio finds no info for device ", outputParameters. device, U".\nCannot play sound."); |
| 1093 | //Melder_casual (U"MelderAudio_play16: ", Melder_peek8to32_u (deviceInfo -> name)); |
| 1094 | trace (U"the device can handle ", deviceInfo -> maxOutputChannels, U" channels"); |
| 1095 | Melder_clipRight (& my numberOfChannels, integer (deviceInfo -> maxOutputChannels)); |
| 1096 | if (numberOfChannels > my numberOfChannels) { |
| 1097 | /* |
| 1098 | Redistribute the in channels over the out channels. |
| 1099 | */ |
| 1100 | if (numberOfChannels == 4 && my numberOfChannels == 2) { // a common case |
| 1101 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1102 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1103 | integer in1 = *in ++, in2 = *in ++, in3 = *in ++, in4 = *in ++; |
| 1104 | *out ++ = (in1 + in2) / 2; |
| 1105 | *out ++ = (in3 + in4) / 2; |
| 1106 | } |
| 1107 | } else { |
| 1108 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1109 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1110 | for (integer iout = 1; iout <= my numberOfChannels; iout ++) { |
| 1111 | integer outValue = 0; |
| 1112 | integer numberOfIn = numberOfChannels / my numberOfChannels; |
| 1113 | if (iout == my numberOfChannels) |
| 1114 | numberOfIn += numberOfChannels % my numberOfChannels; |
| 1115 | for (integer iin = 1; iin <= numberOfIn; iin ++) |
| 1116 | outValue += *in ++; |
| 1117 | outValue /= numberOfIn; |
| 1118 | *out ++ = outValue; |
| 1119 | } |
| 1120 | } |
| 1121 | } |
| 1122 | } |
| 1123 | outputParameters. channelCount = my numberOfChannels; |
| 1124 | outputParameters. sampleFormat = paInt16; |
| 1125 | outputParameters. suggestedLatency = deviceInfo -> defaultLowOutputLatency; |
| 1126 | outputParameters. hostApiSpecificStreamInfo = nullptr; |
| 1127 | err = Pa_OpenStream (& my stream, nullptr, & outputParameters, my sampleRate, paFramesPerBufferUnspecified, |
| 1128 | paDitherOff, thePaStreamCallback, me); |
| 1129 | if (err) |
| 1130 | Melder_throw (U"PortAudio cannot open sound output: ", Melder_peek8to32_u (Pa_GetErrorText (err)), U"."); |
| 1131 | theStartingTime = Melder_clock (); |
| 1132 | err = Pa_StartStream (my stream); |
| 1133 | if (err) |
| 1134 | Melder_throw (U"PortAudio cannot start sound output: ", Melder_peek8to32_u (Pa_GetErrorText (err)), U"."); |
| 1135 | my paStartingTime = Pa_GetStreamTime (my stream); |
| 1136 | if (my asynchronicity <= kMelder_asynchronicityLevel::INTERRUPTABLE) { |
| 1137 | for (;;) { |
| 1138 | #if defined (linux) |
| 1139 | /* |
| 1140 | This is how PortAudio was designed to work. |
| 1141 | */ |
| 1142 | if (my samplesLeft == 0) { |
| 1143 | my samplesPlayed = my numberOfSamples; |
| 1144 | break; |
| 1145 | } |
| 1146 | #else |
| 1147 | /* |
| 1148 | A version that doesn't trust that the stream callback will complete. |
| 1149 | */ |
| 1150 | const double timeElapsed = Melder_clock () - theStartingTime - Pa_GetStreamInfo (my stream) -> outputLatency; |
| 1151 | const integer samplesPlayed = (integer) floor (timeElapsed * my sampleRate); |
| 1152 | if (samplesPlayed >= my numberOfSamples + my sampleRate / 20) { |
| 1153 | my samplesPlayed = my numberOfSamples; |
| 1154 | break; |
| 1155 | } |
| 1156 | #endif |
| 1157 | bool interrupted = false; |
| 1158 | if (my asynchronicity != kMelder_asynchronicityLevel::SYNCHRONOUS && my callback && |
| 1159 | ! my callback (my closure, my samplesPlayed)) |
| 1160 | interrupted = true; |
| 1161 | /* |
| 1162 | Safe operation: only listen to key-down events. |
| 1163 | Do this on the lowest level that will work. |
| 1164 | */ |
| 1165 | if (my asynchronicity == kMelder_asynchronicityLevel::INTERRUPTABLE && ! interrupted) { |
| 1166 | #if gtk |
| 1167 | // TODO: implement a reaction to the Escape key |
| 1168 | #elif cocoa |
| 1169 | // TODO: implement a reaction to the Escape key |
| 1170 | #elif defined (macintosh) |
| 1171 | EventRecord event; |
| 1172 | if (EventAvail (keyDownMask, & event)) { |
| 1173 | /* |
| 1174 | Remove the event, even if it was a different key. |
| 1175 | Otherwise, the key will block the future availability of the Escape key. |
| 1176 | */ |
| 1177 | FlushEvents (keyDownMask, 0); |
| 1178 | /* |
| 1179 | Catch Escape and Command-period. |
| 1180 | */ |
| 1181 | if ((event. message & charCodeMask) == 27 || |
| 1182 | ((event. modifiers & cmdKey) && (event. message & charCodeMask) == '.')) |
| 1183 | { |
| 1184 | my explicitStop = MelderAudio_EXPLICIT; |
| 1185 | interrupted = true; |
| 1186 | } |
| 1187 | } |
| 1188 | #elif defined (_WIN32) |
| 1189 | if (interruptedByEscapeKey ()) { |
| 1190 | my explicitStop = MelderAudio_EXPLICIT; |
| 1191 | interrupted = true; |
| 1192 | } |
| 1193 | #endif |
| 1194 | } |
| 1195 | if (interrupted) { |
| 1196 | flush (); |
| 1197 | return; |
| 1198 | } |
| 1199 | Pa_Sleep (10); |
| 1200 | } |
| 1201 | if (my samplesPlayed != my numberOfSamples) |
| 1202 | Melder_crash (U"Played ", my samplesPlayed, U" instead of ", my numberOfSamples, U" samples."); |
| 1203 | #ifndef linux |
| 1204 | Pa_AbortStream (my stream); |
| 1205 | #endif |
| 1206 | } else /* my asynchronicity == kMelder_asynchronicityLevel::ASYNCHRONOUS */ { |
| 1207 | #if gtk |
| 1208 | trace (U"g_idle_add"); |
| 1209 | my workProcId_gtk = g_idle_add (workProc_gtk, nullptr); |
| 1210 | #elif motif |
| 1211 | my workProcId_motif = XtAddWorkProc (workProc_motif, nullptr); |
| 1212 | #elif cocoa |
| 1213 | CFRunLoopTimerContext context = { 0, nullptr, nullptr, nullptr, nullptr }; |
| 1214 | my cocoaTimer = CFRunLoopTimerCreate (nullptr, CFAbsoluteTimeGetCurrent () + 0.02, |
| 1215 | 0.02, 0, 0, workProc_cocoa, & context); |
| 1216 | CFRunLoopAddTimer (CFRunLoopGetCurrent (), my cocoaTimer, kCFRunLoopCommonModes); |
| 1217 | #endif |
| 1218 | return; |
| 1219 | } |
| 1220 | flush (); |
| 1221 | return; |
| 1222 | #ifdef HAVE_PULSEAUDIO |
| 1223 | } else if (my usePulseAudio) { |
| 1224 | my pulseAudio.occupation |= PA_QUERY_NUMBEROFCHANNELS; // set query bit on |
| 1225 | pulseAudio_serverReport (); |
| 1226 | my pulseAudio.occupation &= ~PA_QUERY_NUMBEROFCHANNELS; // set query bit off |
| 1227 | |
| 1228 | if (numberOfChannels > my numberOfChannels) { |
| 1229 | /* |
| 1230 | Redistribute the in channels over the out channels. TODO make channelmap |
| 1231 | */ |
| 1232 | if (numberOfChannels == 4 && my numberOfChannels == 2) { // a common case |
| 1233 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1234 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1235 | integer in1 = *in ++, in2 = *in ++, in3 = *in ++, in4 = *in ++; |
| 1236 | *out ++ = (in1 + in2) / 2; |
| 1237 | *out ++ = (in3 + in4) / 2; |
| 1238 | } |
| 1239 | } else { |
| 1240 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1241 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1242 | for (integer iout = 1; iout <= my numberOfChannels; iout ++) { |
| 1243 | integer outValue = 0; |
| 1244 | integer numberOfIn = numberOfChannels / my numberOfChannels; |
| 1245 | if (iout == my numberOfChannels) |
| 1246 | numberOfIn += numberOfChannels % my numberOfChannels; |
| 1247 | for (integer iin = 1; iin <= numberOfIn; iin ++) |
| 1248 | outValue += *in ++; |
| 1249 | outValue /= numberOfIn; |
| 1250 | *out ++ = outValue; |
| 1251 | } |
| 1252 | } |
| 1253 | } |
| 1254 | } else if (numberOfChannels < my numberOfChannels) { |
| 1255 | // pulseaudio will divide the input over the output channels |
| 1256 | my numberOfChannels = numberOfChannels; |
| 1257 | } |
| 1258 | |
| 1259 | my pulseAudio.occupation |= PA_WRITING; |
| 1260 | pulseAudio_initialize (); |
| 1261 | if (pa_context_get_state (my pulseAudio.context) == PA_CONTEXT_READY) { |
| 1262 | prepare_and_play (me); |
| 1263 | } |
| 1264 | |
| 1265 | if (my asynchronicity < kMelder_asynchronicityLevel::ASYNCHRONOUS) { |
| 1266 | pa_threaded_mainloop_lock (my pulseAudio.mainloop); |
| 1267 | trace (U"occupation ", my pulseAudio.occupation); |
| 1268 | while ((my pulseAudio.occupation & PA_WRITING_DONE) != PA_WRITING_DONE) { |
| 1269 | trace (U"waiting"); |
| 1270 | pa_threaded_mainloop_wait (my pulseAudio.mainloop); |
| 1271 | } |
| 1272 | // Now we know that the stream drain operation has succeeded ! |
| 1273 | if (my pulseAudio.operation_drain) { |
| 1274 | pa_operation_unref (my pulseAudio.operation_drain); |
| 1275 | } |
| 1276 | my pulseAudio.operation_drain = nullptr; |
| 1277 | my pulseAudio.occupation &= ~PA_WRITING_DONE; |
| 1278 | |
| 1279 | pa_threaded_mainloop_unlock (my pulseAudio.mainloop); |
| 1280 | //pa_threaded_mainloop_accept (my pulseAudio.mainloop); |
| 1281 | trace (U"before cleanup"); |
| 1282 | pulseAudio_cleanup (); |
| 1283 | } else { |
| 1284 | // my workProcId_gtk = g_timeout_add (ms, workProc_gtk, nullptr); |
| 1285 | // without a timer, on my computer the workproc would be called almost once in every sampling period. |
| 1286 | // Such frequent updates are not necessary, some 50 updates a second is fast enough for displaying a runnning cursor |
| 1287 | // the timeout will be automatically stopped if workProc_gtk returns false. |
| 1288 | #if gtk |
| 1289 | #ifndef NO_GRAPHICS |
| 1290 | my workProcId_gtk = g_timeout_add (20, workProc_gtk, nullptr); |
| 1291 | #endif |
| 1292 | #endif |
| 1293 | } |
| 1294 | #endif |
| 1295 | } else { |
| 1296 | #if defined (macintosh) |
| 1297 | #elif defined (linux) && ! defined (NO_AUDIO) |
| 1298 | #elif defined (_WIN32) |
| 1299 | try { |
| 1300 | WAVEFORMATEX waveFormat; |
| 1301 | MMRESULT err; |
| 1302 | waveFormat. wFormatTag = WAVE_FORMAT_PCM; |
| 1303 | waveFormat. nChannels = my numberOfChannels; |
| 1304 | waveFormat. nSamplesPerSec = my sampleRate; |
| 1305 | waveFormat. wBitsPerSample = 16; |
| 1306 | waveFormat. nBlockAlign = my numberOfChannels * waveFormat. wBitsPerSample / 8; |
| 1307 | waveFormat. nAvgBytesPerSec = waveFormat. nBlockAlign * waveFormat. nSamplesPerSec; |
| 1308 | waveFormat. cbSize = 0; |
| 1309 | err = waveOutOpen (& my hWaveOut, WAVE_MAPPER, & waveFormat, 0, 0, CALLBACK_NULL | WAVE_ALLOWSYNC); |
| 1310 | if (err != MMSYSERR_NOERROR) { |
| 1311 | MelderAudio_isPlaying = false; |
| 1312 | if (err == MMSYSERR_ALLOCATED) |
| 1313 | Melder_throw (U"Previous sound is still playing? Should not occur!\n" |
| 1314 | U"Report bug to the author: ", err, U"; wasPlaying: ", wasPlaying, U"."); |
| 1315 | if (err == MMSYSERR_BADDEVICEID) |
| 1316 | Melder_throw (U"Cannot play a sound. Perhaps another program is playing a sound at the same time?"); |
| 1317 | if (err == MMSYSERR_NODRIVER) |
| 1318 | Melder_throw (U"This computer probably has no sound card."); |
| 1319 | if (err == MMSYSERR_NOMEM) |
| 1320 | Melder_throw (U"Not enough free memory to play any sound at all."); |
| 1321 | if (err == WAVERR_BADFORMAT) { |
| 1322 | if (my numberOfChannels > 2) { |
| 1323 | /* |
| 1324 | * Retry with 2 channels. |
| 1325 | */ |
| 1326 | my numberOfChannels = 2; |
| 1327 | waveFormat. nChannels = my numberOfChannels; |
| 1328 | waveFormat. nBlockAlign = my numberOfChannels * waveFormat. wBitsPerSample / 8; |
| 1329 | waveFormat. nAvgBytesPerSec = waveFormat. nBlockAlign * waveFormat. nSamplesPerSec; |
| 1330 | err = waveOutOpen (& my hWaveOut, WAVE_MAPPER, & waveFormat, 0, 0, CALLBACK_NULL | WAVE_ALLOWSYNC); |
| 1331 | if (err != MMSYSERR_NOERROR) |
| 1332 | Melder_throw (U"Bad sound format even after reduction to 2 channels? Should not occur! Report bug to the author!"); |
| 1333 | MelderAudio_isPlaying = true; |
| 1334 | } else if (my numberOfChannels == 1) { |
| 1335 | /* |
| 1336 | * Retry with 2 channels. |
| 1337 | */ |
| 1338 | my numberOfChannels = 2; |
| 1339 | waveFormat. nChannels = my numberOfChannels; |
| 1340 | waveFormat. nBlockAlign = my numberOfChannels * waveFormat. wBitsPerSample / 8; |
| 1341 | waveFormat. nAvgBytesPerSec = waveFormat. nBlockAlign * waveFormat. nSamplesPerSec; |
| 1342 | err = waveOutOpen (& my hWaveOut, WAVE_MAPPER, & waveFormat, 0, 0, CALLBACK_NULL | WAVE_ALLOWSYNC); |
| 1343 | if (err != MMSYSERR_NOERROR) |
| 1344 | Melder_throw (U"Bad sound format even after expansion to 2 channels? Should not occur! Report bug to the author!"); |
| 1345 | MelderAudio_isPlaying = true; |
| 1346 | } else { |
| 1347 | Melder_throw (U"Bad sound format? Should not occur! Report bug to the author!"); |
| 1348 | } |
| 1349 | } else { |
| 1350 | Melder_throw (U"Unknown error ", err, U" while trying to play a sound? Report bug to the author!"); |
| 1351 | } |
| 1352 | } |
| 1353 | if (numberOfChannels > my numberOfChannels) { |
| 1354 | /* |
| 1355 | Redistribute the in channels over the out channels. |
| 1356 | */ |
| 1357 | if (numberOfChannels == 4 && my numberOfChannels == 2) { // a common case |
| 1358 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1359 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1360 | integer in1 = *in ++, in2 = *in ++, in3 = *in ++, in4 = *in ++; |
| 1361 | *out ++ = (in1 + in2) / 2; |
| 1362 | *out ++ = (in3 + in4) / 2; |
| 1363 | } |
| 1364 | } else { |
| 1365 | int16 *in = & my playBuffer [0], *out = & my playBuffer [0]; |
| 1366 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1367 | for (integer iout = 1; iout <= my numberOfChannels; iout ++) { |
| 1368 | integer outValue = 0; |
| 1369 | integer numberOfIn = numberOfChannels / my numberOfChannels; |
| 1370 | if (iout == my numberOfChannels) |
| 1371 | numberOfIn += numberOfChannels % my numberOfChannels; |
| 1372 | for (integer iin = 1; iin <= numberOfIn; iin ++) |
| 1373 | outValue += *in ++; |
| 1374 | outValue /= numberOfIn; |
| 1375 | *out ++ = outValue; |
| 1376 | } |
| 1377 | } |
| 1378 | } |
| 1379 | } else if (numberOfChannels == 1 && my numberOfChannels == 2) { |
| 1380 | if (playBuffer2) |
| 1381 | Melder_free (playBuffer2); |
| 1382 | playBuffer2 = Melder_malloc (int16, numberOfSamples * my numberOfChannels); |
| 1383 | Melder_assert (playBuffer2); |
| 1384 | int16 *in = & my playBuffer [0], *out = & playBuffer2 [0]; |
| 1385 | for (integer isamp = 1; isamp <= numberOfSamples; isamp ++) { |
| 1386 | const int16 inValue = *in ++; |
| 1387 | *out ++ = inValue; |
| 1388 | *out ++ = inValue; |
| 1389 | } |
| 1390 | } |
| 1391 | |
| 1392 | my waveHeader. dwFlags = 0; |
| 1393 | my waveHeader. lpData = |
| 1394 | ( numberOfChannels == 1 && my numberOfChannels == 2 ? (char *) playBuffer2 : (char *) my playBuffer ); |
| 1395 | my waveHeader. dwBufferLength = my numberOfSamples * 2 * my numberOfChannels; |
| 1396 | my waveHeader. dwLoops = 1; |
| 1397 | my waveHeader. lpNext = nullptr; |
| 1398 | my waveHeader. reserved = 0; |
| 1399 | err = waveOutPrepareHeader (my hWaveOut, & my waveHeader, sizeof (WAVEHDR)); |
| 1400 | //waveOutReset (my hWaveOut); |
| 1401 | if (err != MMSYSERR_NOERROR) { |
| 1402 | waveOutClose (my hWaveOut), my hWaveOut = 0; |
| 1403 | MelderAudio_isPlaying = false; |
| 1404 | if (err == MMSYSERR_INVALHANDLE) |
| 1405 | Melder_throw (U"No device? Should not occur!"); |
| 1406 | if (err == MMSYSERR_NODRIVER) |
| 1407 | Melder_throw (U"No driver? Should not occur!"); |
| 1408 | if (err == MMSYSERR_NOMEM) |
| 1409 | Melder_throw (U"Not enough free memory to play this sound.\n" |
| 1410 | U"Remove some objects, play a shorter sound, or buy more memory."); |
| 1411 | Melder_throw (U"Unknown error ", err, U" while preparing header? Should not occur!"); |
| 1412 | } |
| 1413 | |
| 1414 | err = waveOutWrite (my hWaveOut, & my waveHeader, sizeof (WAVEHDR)); |
| 1415 | if (err != MMSYSERR_NOERROR) { |
| 1416 | waveOutReset (my hWaveOut); |
| 1417 | waveOutUnprepareHeader (my hWaveOut, & my waveHeader, sizeof (WAVEHDR)); |
| 1418 | waveOutClose (my hWaveOut), my hWaveOut = 0; |
| 1419 | MelderAudio_isPlaying = false; |
| 1420 | Melder_throw (U"Error ", err, U" while writing audio output."); // BUG: should flush |
| 1421 | } |
| 1422 | |
| 1423 | theStartingTime = Melder_clock (); |
| 1424 | if (my asynchronicity == kMelder_asynchronicityLevel::SYNCHRONOUS) { |
| 1425 | while (! (my waveHeader. dwFlags & WHDR_DONE)) { |
| 1426 | Sleep (10); |
| 1427 | } |
| 1428 | my samplesPlayed = my numberOfSamples; |
| 1429 | } else if (my asynchronicity <= kMelder_asynchronicityLevel::INTERRUPTABLE) { |
| 1430 | while (! (my waveHeader. dwFlags & WHDR_DONE)) { |
| 1431 | Sleep (10); |
| 1432 | my samplesPlayed = (Melder_clock () - theStartingTime) * my sampleRate; |
| 1433 | if (my callback && ! my callback (my closure, my samplesPlayed)) |
| 1434 | break; |
| 1435 | if (my asynchronicity == kMelder_asynchronicityLevel::INTERRUPTABLE) { |
| 1436 | if (interruptedByEscapeKey ()) { |
| 1437 | my explicitStop = MelderAudio_EXPLICIT; |
| 1438 | break; |
| 1439 | } |
| 1440 | } |
| 1441 | } |
| 1442 | } else { |
| 1443 | my workProcId_motif = XtAddWorkProc (workProc_motif, nullptr); |
| 1444 | return; |
| 1445 | } |
| 1446 | flush (); |
| 1447 | return; |
| 1448 | } catch (MelderError) { |
| 1449 | Melder_throw (U"16-bit audio not played."); |
| 1450 | } |
| 1451 | #else |
| 1452 | Melder_throw (U"Cannot play a sound on this computer.\n16-bit audio not played."); |
| 1453 | #endif |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | /* End of file melder_audio.cpp */ |