Debian Codegraph @

foned/SoundRecorder.cpp

raw
1 /* SoundRecorder.cpp
2 *
3 * Copyright (C) 1992-2026 Paul Boersma
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 /* Linux code originally by Darryl Purnell, Pretoria */
19 /* GTK conversion includes work by Franz Brauße */
20
21 /* This source file describes interactive sound recorders for the following systems:
22 * MacOS
23 * Linux
24 * Windows
25 * Because the behaviour of these sound recorders is partly similar, partly different,
26 * this would seem a good candidate for object-oriented programming
27 * (one audio manager and several audio drivers).
28 * However, the places where sound recorders are similar and where they are different,
29 * are hard to predict. For this reason, everything is done with platform #ifdefs.
30 */
31
32 #include <errno.h>
33 #include "SoundRecorder.h"
34 #include "Sound_and_Spectrum.h"
35 #include "machine.h"
36 #include "EditorM.h"
37 #if defined (macintosh)
38 #include "pa_mac_core.h"
39 #endif
40
41 #include "enums_getText.h"
42 #include "SoundRecorder_enums.h"
43 #include "enums_getValue.h"
44 #include "SoundRecorder_enums.h"
45
46 Thing_implement (SoundRecorder, Editor, 0);
47
48 #include "Prefs_define.h"
49 #include "SoundRecorder_prefs.h"
50 #include "Prefs_install.h"
51 #include "SoundRecorder_prefs.h"
52 #include "Prefs_copyToInstance.h"
53 #include "SoundRecorder_prefs.h"
54
55 static struct {
56 integer bufferSizeInMegabytes;
57 } preferences;
58
59 void SoundRecorder_preferences () {
60 Preferences_addInteger (U"SoundRecorder.bufferSizeInMegabytes", & preferences.bufferSizeInMegabytes, 60);
61 }
62
63 integer SoundRecorder_getBufferSizePref_MB () {
64 return preferences.bufferSizeInMegabytes;
65 }
66 void SoundRecorder_setBufferSizePref_MB (integer size) {
67 preferences.bufferSizeInMegabytes = Melder_clipped (1_integer, size, 1000_integer);
68 }
69
70 #define step 1000
71
72 /* For those systems that do not have a pollable audio control panel, */
73 /* the settings are saved only here, so that they are remembered across */
74 /* subsequent creations of a SoundRecorder. Also, this is then the way */
75 /* in which two simultaneously open SoundRecorders would communicate. */
76
77 static struct {
78 int inputSource; // 1 = microphone, 2 = line, 3 = digital
79 int leftGain, rightGain; // 0..255
80 double sampleRate;
81 } theControlPanel =
82 #if defined (linux)
83 { 1, 200, 200, 44100.0 };
84 #elif defined (macintosh)
85 { 1, 26, 26, 44100.0 };
86 #else
87 { 1, 26, 26, 44100.0 };
88 #endif
89
90 /********** ERROR HANDLING **********/
91
92 #if defined (_WIN32)
93 static void win_fillFormat (SoundRecorder me) {
94 my waveFormat. nSamplesPerSec = (int) theControlPanel. sampleRate;
95 my waveFormat. nChannels = my numberOfChannels;
96 my waveFormat. wFormatTag = WAVE_FORMAT_PCM;
97 my waveFormat. wBitsPerSample = 16;
98 my waveFormat. nBlockAlign = my waveFormat. nChannels * my waveFormat. wBitsPerSample / 8;
99 my waveFormat. nAvgBytesPerSec = my waveFormat. nBlockAlign * my waveFormat. nSamplesPerSec;
100 my waveFormat. cbSize = 0;
101 }
102 static void win_fillHeader (SoundRecorder me, int which) {
103 my waveHeader [which]. dwFlags = 0;
104 my waveHeader [which]. lpData =
105 ( which == 0 ? (char *) my recordBuffer.asArgumentToFunctionThatExpectsZeroBasedArray() :
106 which == 1 ? (char *) my buffertje1: (char *) my buffertje2 );
107 my waveHeader [which]. dwBufferLength =
108 ( which == 0 ? my nmax * my waveFormat. nChannels * 2 : 1000 * my waveFormat. nChannels * 2 );
109 my waveHeader [which]. dwLoops = 0;
110 my waveHeader [which]. lpNext = nullptr;
111 my waveHeader [which]. reserved = 0;
112 }
113 static void win_waveInCheck (SoundRecorder me) {
114 wchar_t messageText [MAXERRORLENGTH];
115 MMRESULT err;
116 if (my err == MMSYSERR_NOERROR) return;
117 err = waveInGetErrorText (my err, messageText, MAXERRORLENGTH);
118 if (err == MMSYSERR_NOERROR)
119 Melder_throw (Melder_peekWto32 (messageText));
120 else if (err == MMSYSERR_BADERRNUM)
121 Melder_throw (U"Error number ", my err, U" out of range.");
122 else if (err == MMSYSERR_NODRIVER)
123 Melder_throw (U"No sound driver present.");
124 else if (err == MMSYSERR_NOMEM)
125 Melder_throw (U"Out of memory.");
126 else
127 Melder_throw (U"Unknown sound error.");
128 }
129 static void win_waveInOpen (SoundRecorder me) {
130 try {
131 my err = waveInOpen (& my hWaveIn, WAVE_MAPPER, & my waveFormat, 0, 0, CALLBACK_NULL);
132 win_waveInCheck (me);
133 if (! (Melder_debug == 8))
134 waveInReset (my hWaveIn);
135 } catch (MelderError) {
136 Melder_throw (U"Audio input not opened.");
137 }
138 }
139 static void win_waveInPrepareHeader (SoundRecorder me, int which) {
140 try {
141 my err = waveInPrepareHeader (my hWaveIn, & my waveHeader [which], sizeof (WAVEHDR));
142 win_waveInCheck (me);
143 } catch (MelderError) {
144 Melder_throw (U"Audio input: cannot prepare header.\nQuit some other programs or go to \"Sound input prefs\" in the Preferences menu.");
145 }
146 }
147 static void win_waveInAddBuffer (SoundRecorder me, int which) {
148 try {
149 my err = waveInAddBuffer (my hWaveIn, & my waveHeader [which], sizeof (WAVEHDR));
150 win_waveInCheck (me);
151 } catch (MelderError) {
152 Melder_throw (U"Audio input: cannot add buffer.");
153 }
154 }
155 static void win_waveInStart (SoundRecorder me) {
156 try {
157 my err = waveInStart (my hWaveIn); // asynchronous
158 win_waveInCheck (me);
159 } catch (MelderError) {
160 Melder_throw (U"Audio input not started.");
161 }
162 }
163 static void win_waveInStop (SoundRecorder me) {
164 try {
165 my err = waveInStop (my hWaveIn);
166 win_waveInCheck (me);
167 } catch (MelderError) {
168 Melder_throw (U"Audio input not stopped.");
169 }
170 }
171 static void win_waveInReset (SoundRecorder me) {
172 try {
173 my err = waveInReset (my hWaveIn);
174 win_waveInCheck (me);
175 } catch (MelderError) {
176 Melder_throw (U"Audio input not reset.");
177 }
178 }
179 static void win_waveInUnprepareHeader (SoundRecorder me, int which) {
180 try {
181 my err = waveInUnprepareHeader (my hWaveIn, & my waveHeader [which], sizeof (WAVEHDR));
182 win_waveInCheck (me);
183 } catch (MelderError) {
184 Melder_throw (U"Audio input: cannot unprepare header.");
185 }
186 }
187 static void win_waveInClose (SoundRecorder me) {
188 try {
189 my err = waveInClose (my hWaveIn);
190 my hWaveIn = 0;
191 win_waveInCheck (me);
192 } catch (MelderError) {
193 Melder_throw (U"Audio input not closed.");
194 }
195 }
196 #endif
197
198 static void stopRecording (SoundRecorder me) {
199 if (! my recording) return;
200 try {
201 my recording = false;
202 if (! my synchronous) {
203 if (my inputUsesPortAudio) {
204 Pa_StopStream (my portaudioStream);
205 Pa_CloseStream (my portaudioStream);
206 my portaudioStream = nullptr;
207 } else {
208 #if defined (_WIN32)
209 /*
210 * On newer systems, waveInStop waits until the buffer is full.
211 * Wrong behaviour!
212 * Therefore, we call waveInReset instead.
213 * But on these same newer systems, waveInReset causes the dwBytesRecorded
214 * attribute to go to zero, so we cannot do
215 * my nsamp = my waveHeader [0]. dwBytesRecorded / (sizeof (short) * my numberOfChannels);
216 */
217 MMTIME mmtime;
218 mmtime. wType = TIME_BYTES;
219 my nsamp = 0;
220 if (waveInGetPosition (my hWaveIn, & mmtime, sizeof (MMTIME)) == MMSYSERR_NOERROR)
221 my nsamp = mmtime. u.cb / (sizeof (short) * my numberOfChannels);
222 win_waveInReset (me);
223 if (my nsamp == 0)
224 my nsamp = my waveHeader [0]. dwBytesRecorded / (sizeof (short) * my numberOfChannels);
225 if (my nsamp > my nmax)
226 my nsamp = my nmax;
227 win_waveInUnprepareHeader (me, 0);
228 win_waveInClose (me);
229 #endif
230 }
231 }
232 } catch (MelderError) {
233 Melder_flushError (U"Cannot stop recording.");
234 }
235 }
236
237 void structSoundRecorder :: v9_destroy () noexcept {
238 stopRecording (this); // must occur before freeing our buffer
239 MelderAudio_stopPlaying (MelderAudio_IMPLICIT); // must also occur before freeing our buffer
240 #if cocoa
241 if (our d_cocoaTimer)
242 CFRunLoopTimerInvalidate (our d_cocoaTimer);
243 #elif gtk
244 g_idle_remove_by_data (this);
245 #elif motif
246 if (our workProcId)
247 XtRemoveWorkProc (our workProcId);
248 #endif
249
250 if (our inputUsesPortAudio) {
251 if (our portaudioStream)
252 Pa_StopStream (our portaudioStream);
253 if (our portaudioStream)
254 Pa_CloseStream (our portaudioStream);
255 } else {
256 #if defined (_WIN32)
257 if (our hWaveIn != 0) {
258 waveInReset (our hWaveIn);
259 waveInUnprepareHeader (our hWaveIn, & our waveHeader [0], sizeof (WAVEHDR));
260 waveInClose (our hWaveIn);
261 }
262 #elif defined (macintosh)
263 #elif defined (UNIX)
264 if (our fd != -1)
265 close (our fd);
266 #endif
267 }
268 our SoundRecorder_Parent :: v9_destroy ();
269 }
270
271 static void showMaximum (SoundRecorder me, int channel, double maximum) {
272 maximum /= 32768.0;
273 Graphics_setWindow (my graphics.get(),
274 my numberOfChannels == 1 || channel == 1 ? 0.0 : -1.0,
275 my numberOfChannels == 1 || channel == 2 ? 1.0 : 2.0,
276 -0.1, 1.1);
277 Graphics_setGrey (my graphics.get(), 0.9);
278 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, maximum, 1.0);
279 Graphics_setColour (my graphics.get(), Melder_GREEN);
280 if (maximum < 0.75) {
281 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, 0.0, maximum);
282 } else {
283 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, 0.0, 0.75);
284 Graphics_setColour (my graphics.get(), Melder_YELLOW);
285 if (maximum < 0.92) {
286 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, 0.75, maximum);
287 } else {
288 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, 0.75, 0.92);
289 Graphics_setColour (my graphics.get(), Melder_RED);
290 Graphics_fillRectangle (my graphics.get(), 0.0, 1.0, 0.92, maximum);
291 }
292 }
293 }
294
295 static void showMeter (SoundRecorder me, const short *buffertje, integer nsamp) {
296 Melder_assert (my graphics);
297 Graphics_clearWs (my graphics.get());
298 if (nsamp < 1) {
299 Graphics_setWindow (my graphics.get(), 0.0, 1.0, 0.0, 1.0);
300 #if defined (macintosh)
301 Graphics_setColour (my graphics.get(), Melder_WHITE);
302 Graphics_fillRectangle (my graphics.get(), 0.2, 0.8, 0.3, 0.7);
303 #endif
304 Graphics_setTextAlignment (my graphics.get(), Graphics_CENTRE, Graphics_HALF);
305 Graphics_setColour (my graphics.get(), Melder_BLACK);
306 Graphics_text (my graphics.get(), 0.5, 0.5, U"Not recording.");
307 return;
308 }
309 if (my instancePref_meter_which() == kSoundRecorder_meter::INTENSITY) {
310 int leftMaximum = 0, rightMaximum = 0;
311 if (my numberOfChannels == 1) {
312 for (integer i = 0; i < nsamp; i ++) {
313 int value = buffertje [i];
314 if (abs (value) > leftMaximum)
315 leftMaximum = abs (value);
316 }
317 } else {
318 for (integer i = 0; i < nsamp; i ++) {
319 int left = buffertje [2 * i], right = buffertje [2 * i + 1];
320 if (abs (left) > leftMaximum)
321 leftMaximum = abs (left);
322 if (abs (right) > rightMaximum)
323 rightMaximum = abs (right);
324 }
325 }
326 if (my lastLeftMaximum > 30000) {
327 int leak = my lastLeftMaximum - Melder_ifloor (2000000.0 / theControlPanel. sampleRate);
328 if (leftMaximum < leak)
329 leftMaximum = leak;
330 }
331 showMaximum (me, 1, leftMaximum);
332 my lastLeftMaximum = leftMaximum;
333 if (my numberOfChannels == 2) {
334 if (my lastRightMaximum > 30000) {
335 int leak = my lastRightMaximum - Melder_ifloor (2000000.0 / theControlPanel. sampleRate);
336 if (rightMaximum < leak)
337 rightMaximum = leak;
338 }
339 showMaximum (me, 2, rightMaximum);
340 my lastRightMaximum = rightMaximum;
341 }
342 } else if (my instancePref_meter_which() == kSoundRecorder_meter::CENTRE_OF_GRAVITY_VERSUS_INTENSITY) {
343 autoSound sound = Sound_create (my numberOfChannels,
344 0.0, nsamp / theControlPanel. sampleRate,
345 nsamp, 1.0 / theControlPanel. sampleRate, 0.5 / theControlPanel. sampleRate);
346 const short *p = & buffertje [0];
347 for (integer isamp = 1; isamp <= nsamp; isamp ++)
348 for (integer ichan = 1; ichan <= my numberOfChannels; ichan ++)
349 sound -> z [ichan] [isamp] = * (p ++) / 32768.0;
350 Sound_multiplyByWindow (sound.get(), kSound_windowShape::KAISER_2);
351 const double intensity = Sound_getIntensity_dB (sound.get());
352 autoSpectrum spectrum = Sound_to_Spectrum (sound.get(), true);
353 const double centreOfGravity = Spectrum_getCentreOfGravity (spectrum.get(), 1.0);
354 trace (nsamp, U" samples, intensity ", intensity, U" dB, centre of gravity ", centreOfGravity, U" Hz");
355 Graphics_setWindow (my graphics.get(),
356 my instancePref_meter_centreOfGravity_minimum(), my instancePref_meter_centreOfGravity_maximum(),
357 my instancePref_meter_intensity_minimum(), my instancePref_meter_intensity_maximum()
358 );
359 Graphics_setColour (my graphics.get(), Melder_WHITE);
360 Graphics_fillRectangle (my graphics.get(),
361 my instancePref_meter_centreOfGravity_minimum(), my instancePref_meter_centreOfGravity_maximum(),
362 my instancePref_meter_intensity_minimum(), my instancePref_meter_intensity_maximum()
363 );
364 Graphics_setColour (my graphics.get(), Melder_BLACK);
365 Graphics_fillCircle_mm (my graphics.get(), centreOfGravity, intensity, 3.0);
366 }
367 }
368
369 static bool tooManySamplesInBufferToReturnToGui (SoundRecorder me) {
370 (void) me;
371 return false;
372 }
373
374 static integer getMyNsamp (SoundRecorder me) {
375 volatile integer nsamp = my nsamp; // Prevent inlining.
376 return nsamp;
377 }
378
379 #if cocoa
380 #define WORKPROC_RETURN void
381 #define WORKPROC_ARGS CFRunLoopTimerRef /*timer*/, void *void_SoundRecorder
382 #elif gtk
383 #define WORKPROC_RETURN gboolean
384 #define WORKPROC_ARGS void *void_SoundRecorder
385 #else
386 #define WORKPROC_RETURN bool
387 #define WORKPROC_ARGS void *void_SoundRecorder
388 #endif
389
390 static WORKPROC_RETURN workProc (WORKPROC_ARGS) {
391 SoundRecorder me = static_cast <SoundRecorder> (void_SoundRecorder);
392 try {
393 short buffertje [step*2];
394 int stepje = 0;
395
396 /*
397 Determine global audio parameters (may have been changed by an external control panel):
398 1. input source;
399 2. left and right gain;
400 3. sampling frequency.
401 */
402 if (my inputUsesPortAudio) {
403 } else {
404 }
405
406 /*
407 Set the buttons according to the audio parameters.
408 */
409 if (my recordButton)
410 GuiThing_setSensitive (my recordButton, ! my recording);
411 if (my stopButton)
412 GuiThing_setSensitive (my stopButton, my recording);
413 if (my playButton)
414 GuiThing_setSensitive (my playButton, ! my recording && my nsamp > 0);
415 if (my applyButton)
416 GuiThing_setSensitive (my applyButton, ! my recording && my nsamp > 0);
417 if (my okButton)
418 GuiThing_setSensitive (my okButton, ! my recording && my nsamp > 0);
419 if (my monoButton && my numberOfChannels == 1)
420 GuiRadioButton_set (my monoButton);
421 if (my stereoButton && my numberOfChannels == 2)
422 GuiRadioButton_set (my stereoButton);
423 for (integer i = 1; i <= SoundRecorder_IFSAMP_MAX; i ++)
424 if (my fsamps [i]. button && theControlPanel. sampleRate == my fsamps [i]. fsamp)
425 GuiRadioButton_set (my fsamps [i]. button);
426 if (my devices [theControlPanel. inputSource]. button)
427 GuiRadioButton_set (my devices [theControlPanel. inputSource]. button);
428 if (my monoButton) GuiThing_setSensitive (my monoButton, ! my recording);
429 if (my stereoButton) GuiThing_setSensitive (my stereoButton, ! my recording);
430 for (integer i = 1; i <= SoundRecorder_IFSAMP_MAX; i ++)
431 if (my fsamps [i]. button)
432 GuiThing_setSensitive (my fsamps [i]. button, ! my recording);
433 for (integer i = 1; i <= SoundRecorder_IDEVICE_MAX; i ++)
434 if (my devices [i]. button)
435 GuiThing_setSensitive (my devices [i]. button, ! my recording);
436
437 /*Graphics_setGrey (my graphics, 0.9);
438 Graphics_fillRectangle (my graphics, 0.0, 1.0, 0.0, 32768.0);
439 Graphics_setGrey (my graphics, 0.9);
440 Graphics_fillRectangle (my graphics, 0.0, 1.0, 0.0, 32768.0);*/
441
442 if (my synchronous) {
443 /*
444 Read some samples into 'buffertje'.
445 */
446 do {
447 if (my inputUsesPortAudio) {
448 /*
449 Asynchronous recording: do nothing.
450 */
451 } else {
452 #if defined (macintosh) || defined (_WIN32)
453 /*
454 Asynchronous recording on these systems: do nothing.
455 */
456 #else
457 // linux
458 if (my fd != -1)
459 stepje = read (my fd, (void *) buffertje, step * (sizeof (short) * my numberOfChannels)) / (sizeof (short) * my numberOfChannels);
460 #endif
461 }
462
463 if (my recording)
464 memcpy (& my recordBuffer [1 + my nsamp * my numberOfChannels], buffertje, stepje * (sizeof (short) * my numberOfChannels));
465 //showMeter (me, buffertje, stepje);
466 if (my recording) {
467 my nsamp += stepje;
468 if (my nsamp > my nmax - step)
469 my recording = false;
470 GuiScale_setValue (my progressScale, 1000.0 * ((double) my nsamp / (double) my nmax));
471 }
472 } while (my recording && tooManySamplesInBufferToReturnToGui (me));
473 } else {
474 if (my recording) {
475 /*
476 We have to know how far the buffer has been filled.
477 However, the buffer may be filled at interrupt time,
478 so that the buffer may be being filled during this workproc.
479 So we ask for the buffer filling just once, namely here at the beginning.
480 */
481 my lastSample = 0;
482 if (my inputUsesPortAudio) {
483 /*
484 The buffer filling is contained in my nsamp,
485 which has been set during interrupt time and may again be updated behind our backs during this workproc.
486 So we do it in such a way that the compiler cannot ask for my nsamp twice.
487 */
488 my lastSample = getMyNsamp (me);
489 Pa_Sleep (10);
490 } else {
491 #if defined (_WIN32)
492 MMTIME mmtime;
493 mmtime. wType = TIME_BYTES;
494 if (waveInGetPosition (my hWaveIn, & mmtime, sizeof (MMTIME)) == MMSYSERR_NOERROR)
495 my lastSample = mmtime. u.cb / (sizeof (short) * my numberOfChannels);
496 #elif defined (macintosh)
497 #endif
498 }
499 my firstSample = my lastSample - 3000;
500 Melder_clipLeft (0_integer, & my firstSample);
501 GuiScale_setValue (my progressScale, 1000.0 * ((double) my lastSample / (double) my nmax));
502 Graphics_updateWs (my graphics.get());
503 } else {
504 #if defined (_WIN32)
505 if (my inputUsesPortAudio) {
506 Pa_Sleep (10);
507 }
508 #endif
509 }
510 }
511 } catch (MelderError) {
512 Melder_flushError ();
513 }
514 #if cocoa
515 return;
516 #elif gtk
517 return true;
518 #else
519 return false;
520 #endif
521 }
522
523 static int portaudioStreamCallback (
524 const void *input, void * /* output */,
525 unsigned long frameCount,
526 const PaStreamCallbackTimeInfo* /* timeInfo */,
527 PaStreamCallbackFlags /* statusFlags */,
528 void *void_SoundRecorder)
529 {
530 /*
531 This procedure may be called at interrupt time.
532 It therefore accesses only data that is constant during recording,
533 namely me, my buffer, my numberOfChannels, and my nmax.
534 The only thing it changes is my nsamp;
535 the workProc will therefore have to take some care in accessing my nsamp (see there).
536 */
537 SoundRecorder me = static_cast <SoundRecorder> (void_SoundRecorder);
538 if (Melder_debug == 20)
539 Melder_casual (U"The PortAudio stream callback receives ", frameCount, U" frames.");
540 Melder_assert (my nsamp <= my nmax);
541 uinteger samplesLeft = my nmax - my nsamp;
542 if (samplesLeft > 0) {
543 uinteger dsamples = samplesLeft > frameCount ? frameCount : samplesLeft;
544 if (Melder_debug == 20)
545 Melder_casual (U"play ", dsamples, U" ", Pa_GetStreamCpuLoad (my portaudioStream));
546 memcpy (& my recordBuffer [1 + my nsamp * my numberOfChannels], input, 2 * dsamples * my numberOfChannels);
547 my nsamp += dsamples;
548 if (my nsamp >= my nmax)
549 return paComplete;
550 } else /*if (my nsamp >= my nmax)*/ {
551 my nsamp = my nmax;
552 return paComplete;
553 }
554 return paContinue;
555 }
556
557 static void gui_button_cb_record (SoundRecorder me, GuiButtonEvent /* event */) {
558 try {
559 if (my recording)
560 return;
561 my nsamp = 0;
562 my recording = true;
563 my lastLeftMaximum = 0;
564 my lastRightMaximum = 0;
565 if (! my synchronous) {
566 if (my inputUsesPortAudio) {
567 PaStreamParameters streamParameters = { };
568 streamParameters. device = my deviceIndices [theControlPanel. inputSource];
569 streamParameters. channelCount = my numberOfChannels;
570 streamParameters. sampleFormat = paInt16;
571 streamParameters. suggestedLatency = my deviceInfos [theControlPanel. inputSource] -> defaultLowInputLatency;
572 #if defined (macintosh)
573 PaMacCoreStreamInfo macCoreStreamInfo = { };
574 macCoreStreamInfo. size = sizeof (PaMacCoreStreamInfo);
575 macCoreStreamInfo. hostApiType = paCoreAudio;
576 macCoreStreamInfo. version = 0x01;
577 macCoreStreamInfo. flags = paMacCoreChangeDeviceParameters | paMacCoreFailIfConversionRequired;
578 streamParameters. hostApiSpecificStreamInfo = & macCoreStreamInfo;
579 #endif
580 if (Melder_debug == 20)
581 Melder_casual (U"Before Pa_OpenStream");
582 PaError err = Pa_OpenStream (& my portaudioStream, & streamParameters, nullptr,
583 theControlPanel. sampleRate, 0, paNoFlag, portaudioStreamCallback, (void *) me);
584 if (Melder_debug == 20)
585 Melder_casual (U"Pa_OpenStream returns ", (int) err);
586 if (err) {
587 conststring32 errorText = Melder_peek8to32_u (Pa_GetErrorText (err));
588 if (Melder_equ (errorText, U"Invalid number of channels"))
589 if (my numberOfChannels == 1)
590 Melder_throw (U"You are trying to record in mono, but your microphone does not seem to support that.\nPerhaps you could try to record in stereo instead.");
591 else
592 Melder_throw (U"You are trying to record in stereo, but you do not seem to have a stereo microphone.\nPerhaps you could try to record in mono instead.");
593 else
594 Melder_throw (U"Error opening audio input stream: ", errorText, U".");
595 }
596 Pa_StartStream (my portaudioStream);
597 if (Melder_debug == 20)
598 Melder_casual (U"Pa_StartStream returns ", (int) err);
599 if (err)
600 Melder_throw (U"Error starting audio input stream: ", Melder_peek8to32_u (Pa_GetErrorText (err)), U".");
601 } else {
602 #if defined (_WIN32)
603 win_fillFormat (me);
604 win_fillHeader (me, 0);
605 win_waveInOpen (me);
606 win_waveInPrepareHeader (me, 0);
607 win_waveInAddBuffer (me, 0);
608 win_waveInStart (me);
609 #elif defined (macintosh)
610 #endif
611 }
612 }
613 Graphics_updateWs (my graphics.get());
614 } catch (MelderError) {
615 my recording = false;
616 Graphics_updateWs (my graphics.get());
617 Melder_flushError (U"The recording was not started.");
618 }
619 }
620
621 static void gui_button_cb_stop (SoundRecorder me, GuiButtonEvent /* event */) {
622 stopRecording (me);
623 Graphics_updateWs (my graphics.get());
624 }
625
626 static void gui_button_cb_play (SoundRecorder me, GuiButtonEvent /* event */) {
627 if (my recording || my nsamp == 0)
628 return;
629 MelderAudio_play16 (my recordBuffer.asArgumentToFunctionThatExpectsZeroBasedArray(),
630 theControlPanel. sampleRate, my nsamp, my numberOfChannels, nullptr, nullptr);
631 }
632
633 static void publish (SoundRecorder me) {
634 autoSound sound;
635 if (my nsamp == 0)
636 return;
637 double fsamp = theControlPanel. sampleRate;
638 if (fsamp <= 0.0)
639 fsamp = 44100.0; // safe
640 try {
641 sound = Sound_createSimple (my numberOfChannels, (double) my nsamp / fsamp, fsamp);
642 } catch (MelderError) {
643 Melder_flushError (U"You can still save to file.");
644 return;
645 }
646 if (my numberOfChannels == 1) {
647 for (integer i = 1; i <= my nsamp; i ++)
648 sound -> z [1] [i] = my recordBuffer [i] * (1.0 / 32768);
649 } else {
650 for (integer i = 1; i <= my nsamp; i ++) {
651 sound -> z [1] [i] = my recordBuffer [i + i - 1] * (1.0 / 32768);
652 sound -> z [2] [i] = my recordBuffer [i + i] * (1.0 / 32768);
653 }
654 }
655 if (my soundName) {
656 autostring32 name = GuiText_getString (my soundName);
657 Thing_setName (sound.get(), name.get());
658 }
659 Editor_broadcastPublication (me, sound.move());
660 }
661
662 static void gui_button_cb_cancel (SoundRecorder me, GuiButtonEvent /* event */) {
663 stopRecording (me);
664 forget (me);
665 }
666
667 static void gui_button_cb_apply (SoundRecorder me, GuiButtonEvent /* event */) {
668 stopRecording (me);
669 publish (me);
670 }
671
672 static void gui_button_cb_ok (SoundRecorder me, GuiButtonEvent /* event */) {
673 stopRecording (me);
674 publish (me);
675 forget (me);
676 }
677
678 static void initialize (SoundRecorder me) {
679 try {
680 if (my inputUsesPortAudio) {
681 #if defined (macintoshXXX)
682 my fsamps [SoundRecorder_IFSAMP_8000]. canDo = false;
683 my fsamps [SoundRecorder_IFSAMP_11025]. canDo = false;
684 my fsamps [SoundRecorder_IFSAMP_12000]. canDo = false;
685 my fsamps [SoundRecorder_IFSAMP_16000]. canDo = false;
686 my fsamps [SoundRecorder_IFSAMP_22050]. canDo = false;
687 my fsamps [SoundRecorder_IFSAMP_24000]. canDo = false;
688 my fsamps [SoundRecorder_IFSAMP_32000]. canDo = false;
689 my fsamps [SoundRecorder_IFSAMP_64000]. canDo = false;
690 #else
691 // Accept all standard sample rates.
692 (void) me;
693 #endif
694 } else {
695 #if defined (macintosh)
696 #elif defined (_WIN32)
697 (void) me;
698 #elif defined (linux) && ! defined (NO_AUDIO)
699 int sampleRate = (int) theControlPanel. sampleRate, sampleSize = 16;
700 int channels = my numberOfChannels, stereo = ( my numberOfChannels == 2 ), val;
701 #if __BYTE_ORDER == __BIG_ENDIAN
702 int format = AFMT_S16_BE;
703 #else
704 int format = AFMT_S16_LE;
705 #endif
706 int fd_mixer;
707 my fd = open ("/dev/dsp", O_RDONLY);
708 if (my fd == -1) {
709 if (errno == EBUSY)
710 Melder_throw (U"Audio device already in use.");
711 else
712 Melder_throw (U"Cannot open audio device.\n"
713 U"Please switch on PortAudio in the Sound Recording Preferences.");
714 }
715 ioctl (my fd, SNDCTL_DSP_RESET, nullptr);
716 ioctl (my fd, SNDCTL_DSP_SPEED, & sampleRate);
717 ioctl (my fd, SNDCTL_DSP_SAMPLESIZE, & sampleSize);
718 ioctl (my fd, SNDCTL_DSP_CHANNELS, (val = channels, & val));
719 if (channels == 1 && val == 2) {
720 close (my fd);
721 Melder_throw (U"This sound card does not support mono.");
722 }
723 ioctl (my fd, SNDCTL_DSP_STEREO, & stereo);
724 ioctl (my fd, SNDCTL_DSP_SETFMT, & format);
725 fd_mixer = open ("/dev/mixer", O_WRONLY);
726 if (fd_mixer == -1) {
727 Melder_throw (U"Cannot open /dev/mixer.");
728 } else {
729 int dev_mask = theControlPanel. inputSource == 2 ? SOUND_MASK_LINE : SOUND_MASK_MIC;
730 if (ioctl (fd_mixer, SOUND_MIXER_WRITE_RECSRC, & dev_mask) == -1) {
731 close (fd_mixer);
732 Melder_throw (U"Can't set recording device in mixer.");
733 }
734 close (fd_mixer);
735 }
736 #endif
737 }
738 } catch (MelderError) {
739 Melder_throw (U"16-bit audio recording not initialized.");
740 }
741 }
742
743 static void gui_radiobutton_cb_input (SoundRecorder me, GuiRadioButtonEvent event) {
744 Melder_casual (U"SoundRecorder:"
745 U" setting the input source from ", theControlPanel. inputSource,
746 U" to ", event -> position, U".");
747 theControlPanel. inputSource = event -> position;
748
749 /* Set system's input source. */
750 if (my inputUsesPortAudio) {
751 // deferred to the start of recording
752 } else {
753 #if defined (_WIN32)
754 // deferred to the start of recording
755 #elif defined (macintosh)
756 //SPBCloseDevice (my refNum);
757 try {
758 initialize (me);
759 } catch (MelderError) {
760 Melder_flushError ();
761 }
762 #elif defined (linux) && ! defined (NO_AUDIO)
763 int fd_mixer = open ("/dev/mixer", O_WRONLY);
764 if (fd_mixer == -1)
765 Melder_flushError (U"(Sound_record:) Cannot open /dev/mixer.");
766 int dev_mask = theControlPanel.inputSource == 2 ? SOUND_MASK_LINE : SOUND_MASK_MIC;
767 if (ioctl (fd_mixer, SOUND_MIXER_WRITE_RECSRC, & dev_mask) == -1)
768 Melder_flushError (U"(Sound_record:) Can't set recording device in mixer");
769 close (fd_mixer);
770 #endif
771 }
772 }
773
774 static void gui_radiobutton_cb_fsamp (SoundRecorder me, GuiRadioButtonEvent event) {
775 if (my recording)
776 return;
777 try {
778 double fsamp = undefined;
779 for (integer i = 1; i <= SoundRecorder_IFSAMP_MAX; i ++)
780 if (event -> toggle == my fsamps [i]. button)
781 fsamp = my fsamps [i]. fsamp;
782 Melder_assert (isdefined (fsamp));
783 /*
784 If we push the 48000 button while the sampling frequency is 22050,
785 we first get a message that the 22050 button has changed,
786 and then we get a message that the 48000 button has changed.
787 So the following will work (it used to be different with old Motif versions on Linux):
788 */
789 Melder_casual (U"SoundRecorder:"
790 U" setting the sample rate from ", (integer) theControlPanel. sampleRate,
791 U" to ", (integer) fsamp, U" Hz.");
792 if (fsamp == theControlPanel. sampleRate)
793 return;
794 /*
795 Now we know, hopefully, that the message is from the button that was clicked,
796 not the one that was unset by the radio box, so we can take action.
797 */
798 theControlPanel. sampleRate = fsamp;
799 /*
800 Set the system's sampling frequency.
801 On some systems, we cannot do this without closing the audio device,
802 and reopening it with a new sampling frequency.
803 */
804 if (my inputUsesPortAudio) {
805 // deferred to the start of recording
806 } else {
807 #if defined (_WIN32)
808 // deferred to the start of recording
809 #elif defined (macintosh)
810 //SPBCloseDevice (my refNum);
811 initialize (me);
812 #elif defined (linux) && ! defined (NO_AUDIO)
813 close (my fd);
814 initialize (me);
815 #endif
816 }
817 } catch (MelderError) {
818 Melder_throw (U"Sampling frequency not changed.");
819 }
820 }
821
822 static void gui_drawingarea_cb_expose (SoundRecorder me, GuiDrawingArea_ExposeEvent event) {
823 if (! my graphics)
824 return; // could be the case in the very beginning
825 if (my recording)
826 showMeter (me, & my recordBuffer [1 + my firstSample * my numberOfChannels], my lastSample - my firstSample);
827 else
828 showMeter (me, nullptr, 0);
829 }
830
831 static void gui_drawingarea_cb_resize (SoundRecorder me, GuiDrawingArea_ResizeEvent event) {
832 if (! my graphics)
833 return; // could be the case in the very beginning
834 Graphics_setWsViewport (my graphics.get(), 0, event -> width, 0, event -> height);
835 Graphics_setWsWindow (my graphics.get(), 0, event -> width, 0, event -> height);
836 Graphics_setViewport (my graphics.get(), 0, event -> width, 0, event -> height);
837 Graphics_updateWs (my graphics.get());
838 }
839
840 void structSoundRecorder :: v_createChildren ()
841 {
842 /*
843 Channels.
844 */
845 #if 0
846 integer y = Machine_getMenuBarBottom () + 20;
847 GuiLabel_createShown (our windowForm, 10, 160, y, y + Gui_LABEL_HEIGHT, U"Channels:", 0);
848
849 GuiRadioGroup_begin ();
850 y += Gui_RADIOBUTTON_HEIGHT + Gui_RADIOBUTTON_SPACING;
851 our monoButton = GuiRadioButton_createShown (our windowForm, 20, 170, y, y + Gui_RADIOBUTTON_HEIGHT,
852 U"Mono", nullptr, nullptr, 0);
853 y += Gui_RADIOBUTTON_HEIGHT + Gui_RADIOBUTTON_SPACING;
854 our stereoButton = GuiRadioButton_createShown (our windowForm, 20, 170, y, y + Gui_RADIOBUTTON_HEIGHT,
855 U"Stereo", nullptr, nullptr, 0);
856 GuiRadioGroup_end ();
857 #endif
858
859 /*
860 Input source.
861 */
862 //y = Machine_getMenuBarBottom () + 140;
863 integer y = Machine_getMenuBarBottom () + 20;
864 #if defined (_WIN32)
865 GuiLabel_createShown (our windowForm, 10, 320, y, y + Gui_LABEL_HEIGHT, U"(use Windows mixer", 0);
866 y += Gui_LABEL_HEIGHT + 10;
867 GuiLabel_createShown (our windowForm, 10, 320, y, y + Gui_LABEL_HEIGHT, U" without meters)", 0);
868 #else
869 GuiLabel_createShown (our windowForm, 10, 320, y, y + Gui_LABEL_HEIGHT, U"Input source:", 0);
870 GuiRadioGroup_begin ();
871 for (integer i = 1; i <= SoundRecorder_IDEVICE_MAX; i ++) {
872 if (our devices [i]. canDo) {
873 y += Gui_RADIOBUTTON_HEIGHT + Gui_RADIOBUTTON_SPACING;
874 our devices [i]. button = GuiRadioButton_createShown (our windowForm, 20, 320, y, y + Gui_RADIOBUTTON_HEIGHT,
875 our devices [i]. fullName, gui_radiobutton_cb_input, this, 0);
876 }
877 }
878 GuiRadioGroup_end ();
879 #endif
880
881 /*
882 Meter box.
883 */
884 y = Machine_getMenuBarBottom () + 20;
885 GuiLabel_createShown (our windowForm, 320, -170, y, y + Gui_LABEL_HEIGHT, U"Meter", GuiLabel_CENTRE);
886 y += Gui_LABEL_HEIGHT;
887 our meter = GuiDrawingArea_createShown (our windowForm, 320, -170, y, -150,
888 gui_drawingarea_cb_expose, nullptr,
889 nullptr, gui_drawingarea_cb_resize, nullptr, this, GuiDrawingArea_BORDER
890 );
891
892 /*
893 Sampling frequency.
894 */
895 y = Machine_getMenuBarBottom () + 20;
896 GuiLabel_createShown (our windowForm, -160, -10, y, y + Gui_LABEL_HEIGHT, U"Sampling frequency:", 0);
897 GuiRadioGroup_begin ();
898 for (integer i = 1; i <= SoundRecorder_IFSAMP_MAX; i ++) {
899 if (our fsamps [i]. canDo) {
900 double fsamp = our fsamps [i]. fsamp;
901 y += Gui_RADIOBUTTON_HEIGHT + Gui_RADIOBUTTON_SPACING;
902 our fsamps [i]. button = GuiRadioButton_createShown (our windowForm,
903 -150, -10, y, y + Gui_RADIOBUTTON_HEIGHT,
904 Melder_cat (fsamp == Melder_roundDown (fsamp) ? Melder_integer ((integer) fsamp) : Melder_fixed (fsamp, 5), U" Hz"),
905 gui_radiobutton_cb_fsamp, this, fsamp == theControlPanel. sampleRate ? GuiRadioButton_SET : 0
906 );
907 }
908 }
909 GuiRadioGroup_end ();
910
911 our progressScale = GuiScale_createShown (our windowForm,
912 10, -10, -130, -90,
913 0, 1000, 0, 0);
914
915 y = 60;
916 our recordButton = GuiButton_createShown (our windowForm, 20, 90, -y - Gui_PUSHBUTTON_HEIGHT, -y,
917 U"Record", gui_button_cb_record, this, 0);
918 our stopButton = GuiButton_createShown (our windowForm, 100, 170, -y - Gui_PUSHBUTTON_HEIGHT, -y,
919 U"Stop", gui_button_cb_stop, this, 0);
920 if (inputUsesPortAudio) {
921 our playButton = GuiButton_createShown (our windowForm, 180, 250, -y - Gui_PUSHBUTTON_HEIGHT, -y,
922 U"Play", gui_button_cb_play, this, 0);
923 } else {
924 #if defined (_WIN32) || defined (macintosh)
925 our playButton = GuiButton_createShown (our windowForm, 180, 250, -y - Gui_PUSHBUTTON_HEIGHT, -y,
926 U"Play", gui_button_cb_play, this, 0);
927 #endif
928 }
929
930 GuiLabel_createShown (our windowForm, -200, -130, -y - 2 - Gui_TEXTFIELD_HEIGHT, -y - 2, U"Name:", GuiLabel_RIGHT);
931 our soundName = GuiText_createShown (our windowForm, -120, -20, -y - 2 - Gui_TEXTFIELD_HEIGHT, -y - 2, 0);
932 GuiText_setString (our soundName, U"untitled");
933
934 y = 20;
935 our cancelButton = GuiButton_createShown (our windowForm, -350, -280, -y - Gui_PUSHBUTTON_HEIGHT, -y,
936 U"Close", gui_button_cb_cancel, this, 0);
937 our applyButton = GuiButton_createShown (our windowForm, -270, -170, -y - Gui_PUSHBUTTON_HEIGHT, -y,
938 U"Save to list", gui_button_cb_apply, this, GuiButton_DEFAULT);
939 our okButton = GuiButton_createShown (our windowForm, -160, -20, -y - Gui_PUSHBUTTON_HEIGHT, -y,
940 U"Save to list & Close", gui_button_cb_ok, this, 0);
941 }
942
943 static void writeAudioFile (SoundRecorder me, MelderFile file, int audioFileType) {
944 try {
945 MelderFile_writeAudioFile (file, audioFileType, my recordBuffer.asArgumentToFunctionThatExpectsZeroBasedArray(),
946 Melder_iround (theControlPanel. sampleRate), my nsamp, my numberOfChannels, 16);
947 } catch (MelderError) {
948 Melder_throw (U"Audio file not written.");
949 }
950 }
951
952 static void menu_cb_writeWav (SoundRecorder me, EDITOR_ARGS) {
953 EDITOR_FORM_SAVE (U"Save as WAV file", nullptr)
954 autostring32 name = GuiText_getString (my soundName);
955 Melder_sprint (defaultName,300, name.get(), U".wav");
956 EDITOR_DO_SAVE
957 writeAudioFile (me, file, Melder_WAV);
958 EDITOR_END
959 }
960
961 static void menu_cb_writeAifc (SoundRecorder me, EDITOR_ARGS) {
962 EDITOR_FORM_SAVE (U"Save as AIFC file", nullptr)
963 autostring32 name = GuiText_getString (my soundName);
964 Melder_sprint (defaultName,300, name.get(), U".aifc");
965 EDITOR_DO_SAVE
966 writeAudioFile (me, file, Melder_AIFC);
967 EDITOR_END
968 }
969
970 static void menu_cb_writeNextSun (SoundRecorder me, EDITOR_ARGS) {
971 EDITOR_FORM_SAVE (U"Save as NeXT/Sun file", nullptr)
972 autostring32 name = GuiText_getString (my soundName);
973 Melder_sprint (defaultName,300, name.get(), U".au");
974 EDITOR_DO_SAVE
975 writeAudioFile (me, file, Melder_NEXT_SUN);
976 EDITOR_END
977 }
978
979 static void menu_cb_writeNist (SoundRecorder me, EDITOR_ARGS) {
980 EDITOR_FORM_SAVE (U"Save as NIST file", nullptr)
981 autostring32 name = GuiText_getString (my soundName);
982 Melder_sprint (defaultName,300, name.get(), U".nist");
983 EDITOR_DO_SAVE
984 writeAudioFile (me, file, Melder_NIST);
985 EDITOR_END
986 }
987
988 static void updateMenus (SoundRecorder me) {
989 GuiMenuItem_check (my meterIntensityButton,
990 my instancePref_meter_which() == kSoundRecorder_meter::INTENSITY);
991 GuiMenuItem_check (my meterCentreOfGravityVersusIntensityButton,
992 my instancePref_meter_which() == kSoundRecorder_meter::CENTRE_OF_GRAVITY_VERSUS_INTENSITY);
993 }
994
995 static void menu_cb_intensity (SoundRecorder me, EDITOR_ARGS) {
996 my setInstancePref_meter_which (kSoundRecorder_meter::INTENSITY);
997 updateMenus (me);
998 }
999 static void menu_cb_centreOfGravityVersusIntensity (SoundRecorder me, EDITOR_ARGS) {
1000 my setInstancePref_meter_which (kSoundRecorder_meter::CENTRE_OF_GRAVITY_VERSUS_INTENSITY);
1001 updateMenus (me);
1002 }
1003
1004 static void menu_cb_SoundRecorder_help (SoundRecorder, EDITOR_ARGS) { Melder_help (U"SoundRecorder"); }
1005
1006 void structSoundRecorder :: v_createMenus () {
1007 SoundRecorder_Parent :: v_createMenus ();
1008 Editor_addCommand (this, U"File", U"Save as WAV file...", 0, menu_cb_writeWav);
1009 Editor_addCommand (this, U"File", U"Save as AIFC file...", 0, menu_cb_writeAifc);
1010 Editor_addCommand (this, U"File", U"Save as NeXT/Sun file...", 0, menu_cb_writeNextSun);
1011 Editor_addCommand (this, U"File", U"Save as NIST file...", 0, menu_cb_writeNist);
1012 Editor_addCommand (this, U"File", U"-- write --", 0, nullptr);
1013 Editor_addMenu (this, U"Meter", 0);
1014 our meterIntensityButton =
1015 Editor_addCommand (this, U"Meter", U"Intensity", GuiMenu_RADIO_FIRST, menu_cb_intensity);
1016 our meterCentreOfGravityVersusIntensityButton =
1017 Editor_addCommand (this, U"Meter", U"Centre of gravity ~ intensity", GuiMenu_RADIO_NEXT, menu_cb_centreOfGravityVersusIntensity);
1018 }
1019
1020 void structSoundRecorder :: v_createMenuItems_help (EditorMenu menu) {
1021 SoundRecorder_Parent :: v_createMenuItems_help (menu);
1022 EditorMenu_addCommand (menu, U"SoundRecorder help", '?', menu_cb_SoundRecorder_help);
1023 }
1024
1025 autoSoundRecorder SoundRecorder_create (int numberOfChannels) {
1026 try {
1027 autoSoundRecorder me = Thing_new (SoundRecorder);
1028 my inputUsesPortAudio =
1029 #if defined (_WIN32)
1030 MelderAudio_getInputSoundSystem () == kMelder_inputSoundSystem::MME_VIA_PORTAUDIO;
1031 #elif defined (macintosh)
1032 MelderAudio_getInputSoundSystem () == kMelder_inputSoundSystem::COREAUDIO_VIA_PORTAUDIO;
1033 #elif defined (raspberrypi)
1034 MelderAudio_getInputSoundSystem () == kMelder_inputSoundSystem::JACK_VIA_PORTAUDIO;
1035 #else
1036 MelderAudio_getInputSoundSystem () == kMelder_inputSoundSystem::ALSA_OR_JACK_VIA_PORTAUDIO;
1037 #endif
1038
1039 if (my inputUsesPortAudio) {
1040 } else {
1041 #if defined (_WIN32)
1042 UINT numberOfDevices = waveInGetNumDevs ();
1043 if (numberOfDevices == 0)
1044 Melder_throw (U"No sound input devices available.");
1045 WAVEINCAPS caps;
1046 MMRESULT err = waveInGetDevCaps (WAVE_MAPPER, & caps, sizeof (WAVEINCAPS));
1047 if (numberOfChannels == 2 && caps. wChannels < 2)
1048 Melder_throw (U"Your computer does not support stereo sound input.");
1049 /* BUG: should we ask whether 16 bit is supported? */
1050 for (UINT i = 0; i < numberOfDevices; i ++) {
1051 waveInGetDevCaps (i, & caps, sizeof (WAVEINCAPS));
1052 /*Melder_casual (U"Name of device ", i, U": ", Melder_peek16to32 (aps. szPname));*/
1053 }
1054 #elif defined (macintosh)
1055 SInt32 soundFeatures;
1056 if (Gestalt (gestaltSoundAttr, & soundFeatures) ||
1057 ! (soundFeatures & (1 << gestaltSoundIOMgrPresent)) ||
1058 ! (soundFeatures & (1 << gestaltBuiltInSoundInput)) ||
1059 ! (soundFeatures & (1 << gestaltHasSoundInputDevice)))
1060 Melder_throw (U"Your computer does not support sound input.");
1061 if (! (soundFeatures & (1 << gestalt16BitSoundIO)) || // hardware
1062 ! (soundFeatures & (1 << gestaltStereoInput)) || // hardware
1063 ! (soundFeatures & (1 << gestalt16BitAudioSupport))) // software
1064 Melder_throw (U"Your computer does not support stereo sound input.");
1065 #endif
1066 }
1067 my numberOfChannels = numberOfChannels;
1068 if (sizeof (short) != 2)
1069 Melder_throw (U"Long shorts!!!!!");
1070 if (my inputUsesPortAudio) {
1071 my synchronous = false;
1072 } else {
1073 #if defined (macintosh) || defined (_WIN32)
1074 my synchronous = false;
1075 #else
1076 my synchronous = true;
1077 #endif
1078 }
1079 /*
1080 Allocate the maximum buffer.
1081 */
1082 Melder_clip (1_integer, & preferences.bufferSizeInMegabytes, 1000_integer);
1083 if (NUMisEmpty (my recordBuffer.get())) {
1084 integer nmax_bytes_pref = preferences.bufferSizeInMegabytes * 1000000;
1085 integer nmax_bytes = ( my inputUsesPortAudio ? nmax_bytes_pref :
1086 #if defined (_WIN32)
1087 66150000 ); // the maximum physical buffer on Windows XP; shorter than in Windows 98, alas.
1088 #else
1089 nmax_bytes_pref );
1090 #endif
1091 my nmax = nmax_bytes / (sizeof (short) * numberOfChannels);
1092 for (;;) {
1093 try {
1094 my recordBuffer = newvectorzero <short> (my nmax * numberOfChannels);
1095 break; // success
1096 } catch (MelderError) {
1097 if (my nmax < 100000) {
1098 throw; // failure, with error message
1099 } else {
1100 Melder_clearError ();
1101 my nmax /= 2; // retry with less application memory
1102 }
1103 }
1104 }
1105 }
1106
1107 /*
1108 Count the number of input devices and sources.
1109 */
1110 if (my inputUsesPortAudio) {
1111 if (! MelderAudio_hasBeenInitialized) {
1112 PaError err = Pa_Initialize ();
1113 if (Melder_debug == 20)
1114 Melder_casual (U"init ", Melder_peek8to32_u (Pa_GetErrorText (err)));
1115 MelderAudio_hasBeenInitialized = true;
1116 if (Melder_debug == 20) {
1117 PaHostApiIndex hostApiCount = Pa_GetHostApiCount ();
1118 Melder_casual (U"host API count ", hostApiCount);
1119 for (PaHostApiIndex iHostApi = 0; iHostApi < hostApiCount; iHostApi ++) {
1120 const PaHostApiInfo *hostApiInfo = Pa_GetHostApiInfo (iHostApi);
1121 PaHostApiTypeId type = hostApiInfo -> type;
1122 Melder_casual (U"host API ", iHostApi, U": ", type, U", \"", Melder_peek8to32_u (hostApiInfo -> name), U"\" ", hostApiInfo -> deviceCount);
1123 }
1124 PaHostApiIndex defaultHostApi = Pa_GetDefaultHostApi ();
1125 Melder_casual (U"default host API ", defaultHostApi);
1126 PaDeviceIndex deviceCount = Pa_GetDeviceCount ();
1127 Melder_casual (U"device count ", deviceCount);
1128 }
1129 }
1130 PaDeviceIndex deviceCount = Pa_GetDeviceCount ();
1131 for (PaDeviceIndex idevice = 0; idevice < deviceCount; idevice ++) {
1132 const PaDeviceInfo *deviceInfo = Pa_GetDeviceInfo (idevice);
1133 if (Melder_debug == 20)
1134 Melder_casual (
1135 U"Device \"", Melder_peek8to32_u (deviceInfo -> name),
1136 U"\", input ", deviceInfo -> maxInputChannels,
1137 U", output ", deviceInfo -> maxOutputChannels,
1138 U", sample rate ", deviceInfo -> defaultSampleRate
1139 );
1140 if (deviceInfo -> maxInputChannels > 0 && my numberOfInputDevices < SoundRecorder_IDEVICE_MAX) {
1141 my devices [++ my numberOfInputDevices]. canDo = true;
1142 #if defined (macintosh) || defined (_WIN32) // only one host API
1143 str32ncpy (my devices [my numberOfInputDevices]. fullName, Melder_peek8to32_u (deviceInfo -> name), SoundRecorder_Device :: maximumLengthOfFullName);
1144 #else
1145 const PaHostApiIndex hostApiIndex = deviceInfo -> hostApi;
1146 const PaHostApiInfo * const hostApiInfo = Pa_GetHostApiInfo (hostApiIndex);
1147 Melder_assert (hostApiInfo);
1148 const conststring8 shortHostApiName8 = ( strstr (hostApiInfo -> name, "JACK") == hostApiInfo -> name ? "JACK" : hostApiInfo -> name );
1149 str32ncpy (my devices [my numberOfInputDevices]. fullName,
1150 Melder_cat (U"(", Melder_peek8to32_u (shortHostApiName8), U":) ", Melder_peek8to32_u (deviceInfo -> name)),
1151 SoundRecorder_Device :: maximumLengthOfFullName
1152 );
1153 #endif
1154 my devices [my numberOfInputDevices]. fullName [SoundRecorder_Device :: maximumLengthOfFullName] = U'\0';
1155 my deviceInfos [my numberOfInputDevices] = deviceInfo;
1156 my deviceIndices [my numberOfInputDevices] = idevice;
1157 }
1158 }
1159 if (my numberOfInputDevices == 0)
1160 Melder_throw (U"No input devices available.");
1161 } else {
1162 #if defined (macintosh)
1163 #elif defined (_WIN32)
1164 // No device info: use Windows mixer.
1165 #else
1166 my devices [1]. canDo = true;
1167 str32cpy (my devices [1]. fullName, U"Microphone");
1168 my devices [2]. canDo = true;
1169 str32cpy (my devices [2]. fullName, U"Line");
1170 #endif
1171 }
1172
1173 /*
1174 Sampling frequency constants.
1175 */
1176 my fsamps [SoundRecorder_IFSAMP_8000]. fsamp = 8000.0;
1177 my fsamps [SoundRecorder_IFSAMP_9800]. fsamp = 9800.0;
1178 my fsamps [SoundRecorder_IFSAMP_11025]. fsamp = 11025.0;
1179 my fsamps [SoundRecorder_IFSAMP_12000]. fsamp = 12000.0;
1180 my fsamps [SoundRecorder_IFSAMP_16000]. fsamp = 16000.0;
1181 my fsamps [SoundRecorder_IFSAMP_22050]. fsamp = 22050.0;
1182 my fsamps [SoundRecorder_IFSAMP_22254]. fsamp = 22254.54545;
1183 my fsamps [SoundRecorder_IFSAMP_24000]. fsamp = 24000.0;
1184 my fsamps [SoundRecorder_IFSAMP_32000]. fsamp = 32000.0;
1185 my fsamps [SoundRecorder_IFSAMP_44100]. fsamp = 44100.0;
1186 my fsamps [SoundRecorder_IFSAMP_48000]. fsamp = 48000.0;
1187 my fsamps [SoundRecorder_IFSAMP_64000]. fsamp = 64000.0;
1188 my fsamps [SoundRecorder_IFSAMP_96000]. fsamp = 96000.0;
1189 my fsamps [SoundRecorder_IFSAMP_192000]. fsamp = 192000.0;
1190
1191 /*
1192 The default set of possible sampling frequencies, to be modified in the initialize () procedure.
1193 */
1194 for (integer i = 1; i <= SoundRecorder_IFSAMP_MAX; i ++)
1195 my fsamps [i]. canDo = true; // optimistic: can do all, except two:
1196 my fsamps [SoundRecorder_IFSAMP_9800]. canDo = false; // sgi only
1197 my fsamps [SoundRecorder_IFSAMP_22254]. canDo = false; // old Mac only
1198
1199 /*
1200 Initialize system-dependent structures.
1201 On all systems: stereo 16-bit linear encoding.
1202 Some systems take initial values from the system control panel
1203 (automatically in the workProc), other systems from theControlPanel.
1204 */
1205 initialize (me.get());
1206
1207 autoMelderString title;
1208 MelderString_copy (& title, U"SoundRecorder (", ( numberOfChannels == 1 ? U"mono" : U"stereo" ), U")");
1209 Editor_init (me.get(), 100, 100, 800, 600, title.string, nullptr);
1210 my graphics = Graphics_create_xmdrawingarea (my meter);
1211 Melder_assert (my graphics);
1212
1213 struct structGuiDrawingArea_ResizeEvent event { my meter, 0 };
1214 event. width = GuiControl_getWidth (my meter);
1215 event. height = GuiControl_getHeight (my meter);
1216 gui_drawingarea_cb_resize (me.get(), & event);
1217
1218 #if cocoa
1219 CFRunLoopTimerContext context = { 0, me.get(), nullptr, nullptr, nullptr };
1220 my d_cocoaTimer = CFRunLoopTimerCreate (nullptr, CFAbsoluteTimeGetCurrent () + 0.02,
1221 0.02, 0, 0, workProc, & context);
1222 CFRunLoopAddTimer (CFRunLoopGetCurrent (), my d_cocoaTimer, kCFRunLoopCommonModes);
1223 #elif gtk
1224 g_idle_add (workProc, me.get());
1225 #elif motif
1226 my workProcId = XtAddWorkProc (workProc, me.get());
1227 #endif
1228 updateMenus (me.get());
1229 return me;
1230 } catch (MelderError) {
1231 Melder_throw (U"SoundRecorder not created.");
1232 }
1233 }
1234
1235 /* End of file SoundRecorder.cpp */