🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

395 lines
13 KiB

  1. /*
  2. * OpenAL Recording Example
  3. *
  4. * Copyright (c) 2017 by Chris Robinson <chris.kcat@gmail.com>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /* This file contains a relatively simple recorder. */
  25. #include <string.h>
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <errno.h>
  29. #include <math.h>
  30. #include "AL/al.h"
  31. #include "AL/alc.h"
  32. #include "AL/alext.h"
  33. #include "common/alhelpers.h"
  34. #if defined(_WIN64)
  35. #define SZFMT "%I64u"
  36. #elif defined(_WIN32)
  37. #define SZFMT "%u"
  38. #else
  39. #define SZFMT "%zu"
  40. #endif
  41. #if defined(_MSC_VER) && (_MSC_VER < 1900)
  42. static float msvc_strtof(const char *str, char **end)
  43. { return (float)strtod(str, end); }
  44. #define strtof msvc_strtof
  45. #endif
  46. static void fwrite16le(ALushort val, FILE *f)
  47. {
  48. ALubyte data[2] = { val&0xff, (val>>8)&0xff };
  49. fwrite(data, 1, 2, f);
  50. }
  51. static void fwrite32le(ALuint val, FILE *f)
  52. {
  53. ALubyte data[4] = { val&0xff, (val>>8)&0xff, (val>>16)&0xff, (val>>24)&0xff };
  54. fwrite(data, 1, 4, f);
  55. }
  56. typedef struct Recorder {
  57. ALCdevice *mDevice;
  58. FILE *mFile;
  59. long mDataSizeOffset;
  60. ALuint mDataSize;
  61. float mRecTime;
  62. int mChannels;
  63. int mBits;
  64. int mSampleRate;
  65. ALuint mFrameSize;
  66. ALbyte *mBuffer;
  67. ALsizei mBufferSize;
  68. } Recorder;
  69. int main(int argc, char **argv)
  70. {
  71. static const char optlist[] =
  72. " --channels/-c <channels> Set channel count (1 or 2)\n"
  73. " --bits/-b <bits> Set channel count (8, 16, or 32)\n"
  74. " --rate/-r <rate> Set sample rate (8000 to 96000)\n"
  75. " --time/-t <time> Time in seconds to record (1 to 10)\n"
  76. " --outfile/-o <filename> Output filename (default: record.wav)";
  77. const char *fname = "record.wav";
  78. const char *devname = NULL;
  79. const char *progname;
  80. Recorder recorder;
  81. long total_size;
  82. ALenum format;
  83. ALCenum err;
  84. progname = argv[0];
  85. if(argc < 2)
  86. {
  87. fprintf(stderr, "Record from a device to a wav file.\n\n"
  88. "Usage: %s [-device <name>] [options...]\n\n"
  89. "Available options:\n%s\n", progname, optlist);
  90. return 0;
  91. }
  92. recorder.mDevice = NULL;
  93. recorder.mFile = NULL;
  94. recorder.mDataSizeOffset = 0;
  95. recorder.mDataSize = 0;
  96. recorder.mRecTime = 4.0f;
  97. recorder.mChannels = 1;
  98. recorder.mBits = 16;
  99. recorder.mSampleRate = 44100;
  100. recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
  101. recorder.mBuffer = NULL;
  102. recorder.mBufferSize = 0;
  103. argv++; argc--;
  104. if(argc > 1 && strcmp(argv[0], "-device") == 0)
  105. {
  106. devname = argv[1];
  107. argv += 2;
  108. argc -= 2;
  109. }
  110. while(argc > 0)
  111. {
  112. char *end;
  113. if(strcmp(argv[0], "--") == 0)
  114. break;
  115. else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0)
  116. {
  117. if(argc < 2)
  118. {
  119. fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
  120. return 1;
  121. }
  122. recorder.mChannels = strtol(argv[1], &end, 0);
  123. if((recorder.mChannels != 1 && recorder.mChannels != 2) || (end && *end != '\0'))
  124. {
  125. fprintf(stderr, "Invalid channels: %s\n", argv[1]);
  126. return 1;
  127. }
  128. argv += 2;
  129. argc -= 2;
  130. }
  131. else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0)
  132. {
  133. if(argc < 2)
  134. {
  135. fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
  136. return 1;
  137. }
  138. recorder.mBits = strtol(argv[1], &end, 0);
  139. if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) ||
  140. (end && *end != '\0'))
  141. {
  142. fprintf(stderr, "Invalid bit count: %s\n", argv[1]);
  143. return 1;
  144. }
  145. argv += 2;
  146. argc -= 2;
  147. }
  148. else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0)
  149. {
  150. if(argc < 2)
  151. {
  152. fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
  153. return 1;
  154. }
  155. recorder.mSampleRate = strtol(argv[1], &end, 0);
  156. if(!(recorder.mSampleRate >= 8000 && recorder.mSampleRate <= 96000) || (end && *end != '\0'))
  157. {
  158. fprintf(stderr, "Invalid sample rate: %s\n", argv[1]);
  159. return 1;
  160. }
  161. argv += 2;
  162. argc -= 2;
  163. }
  164. else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0)
  165. {
  166. if(argc < 2)
  167. {
  168. fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
  169. return 1;
  170. }
  171. recorder.mRecTime = strtof(argv[1], &end);
  172. if(!(recorder.mRecTime >= 1.0f && recorder.mRecTime <= 10.0f) || (end && *end != '\0'))
  173. {
  174. fprintf(stderr, "Invalid record time: %s\n", argv[1]);
  175. return 1;
  176. }
  177. argv += 2;
  178. argc -= 2;
  179. }
  180. else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0)
  181. {
  182. if(argc < 2)
  183. {
  184. fprintf(stderr, "Missing argument for option: %s\n", argv[0]);
  185. return 1;
  186. }
  187. fname = argv[1];
  188. argv += 2;
  189. argc -= 2;
  190. }
  191. else if(strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0)
  192. {
  193. fprintf(stderr, "Record from a device to a wav file.\n\n"
  194. "Usage: %s [-device <name>] [options...]\n\n"
  195. "Available options:\n%s\n", progname, optlist);
  196. return 0;
  197. }
  198. else
  199. {
  200. fprintf(stderr, "Invalid option '%s'.\n\n"
  201. "Usage: %s [-device <name>] [options...]\n\n"
  202. "Available options:\n%s\n", argv[0], progname, optlist);
  203. return 0;
  204. }
  205. }
  206. recorder.mFrameSize = recorder.mChannels * recorder.mBits / 8;
  207. format = AL_NONE;
  208. if(recorder.mChannels == 1)
  209. {
  210. if(recorder.mBits == 8)
  211. format = AL_FORMAT_MONO8;
  212. else if(recorder.mBits == 16)
  213. format = AL_FORMAT_MONO16;
  214. else if(recorder.mBits == 32)
  215. format = AL_FORMAT_MONO_FLOAT32;
  216. }
  217. else if(recorder.mChannels == 2)
  218. {
  219. if(recorder.mBits == 8)
  220. format = AL_FORMAT_STEREO8;
  221. else if(recorder.mBits == 16)
  222. format = AL_FORMAT_STEREO16;
  223. else if(recorder.mBits == 32)
  224. format = AL_FORMAT_STEREO_FLOAT32;
  225. }
  226. recorder.mDevice = alcCaptureOpenDevice(devname, recorder.mSampleRate, format, 32768);
  227. if(!recorder.mDevice)
  228. {
  229. fprintf(stderr, "Failed to open %s, %s %d-bit, %s, %dhz (%d samples)\n",
  230. devname ? devname : "default device",
  231. (recorder.mBits == 32) ? "Float" :
  232. (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
  233. (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
  234. 32768
  235. );
  236. return 1;
  237. }
  238. fprintf(stderr, "Opened \"%s\"\n", alcGetString(
  239. recorder.mDevice, ALC_CAPTURE_DEVICE_SPECIFIER
  240. ));
  241. recorder.mFile = fopen(fname, "wb");
  242. if(!recorder.mFile)
  243. {
  244. fprintf(stderr, "Failed to open '%s' for writing\n", fname);
  245. alcCaptureCloseDevice(recorder.mDevice);
  246. return 1;
  247. }
  248. fputs("RIFF", recorder.mFile);
  249. fwrite32le(0xFFFFFFFF, recorder.mFile); // 'RIFF' header len; filled in at close
  250. fputs("WAVE", recorder.mFile);
  251. fputs("fmt ", recorder.mFile);
  252. fwrite32le(18, recorder.mFile); // 'fmt ' header len
  253. // 16-bit val, format type id (1 = integer PCM, 3 = float PCM)
  254. fwrite16le((recorder.mBits == 32) ? 0x0003 : 0x0001, recorder.mFile);
  255. // 16-bit val, channel count
  256. fwrite16le(recorder.mChannels, recorder.mFile);
  257. // 32-bit val, frequency
  258. fwrite32le(recorder.mSampleRate, recorder.mFile);
  259. // 32-bit val, bytes per second
  260. fwrite32le(recorder.mSampleRate * recorder.mFrameSize, recorder.mFile);
  261. // 16-bit val, frame size
  262. fwrite16le(recorder.mFrameSize, recorder.mFile);
  263. // 16-bit val, bits per sample
  264. fwrite16le(recorder.mBits, recorder.mFile);
  265. // 16-bit val, extra byte count
  266. fwrite16le(0, recorder.mFile);
  267. fputs("data", recorder.mFile);
  268. fwrite32le(0xFFFFFFFF, recorder.mFile); // 'data' header len; filled in at close
  269. recorder.mDataSizeOffset = ftell(recorder.mFile) - 4;
  270. if(ferror(recorder.mFile) || recorder.mDataSizeOffset < 0)
  271. {
  272. fprintf(stderr, "Error writing header: %s\n", strerror(errno));
  273. fclose(recorder.mFile);
  274. alcCaptureCloseDevice(recorder.mDevice);
  275. return 1;
  276. }
  277. fprintf(stderr, "Recording '%s', %s %d-bit, %s, %dhz (%g second%s)\n", fname,
  278. (recorder.mBits == 32) ? "Float" :
  279. (recorder.mBits != 8) ? "Signed" : "Unsigned", recorder.mBits,
  280. (recorder.mChannels == 1) ? "Mono" : "Stereo", recorder.mSampleRate,
  281. recorder.mRecTime, (recorder.mRecTime != 1.0f) ? "s" : ""
  282. );
  283. alcCaptureStart(recorder.mDevice);
  284. while((double)recorder.mDataSize/(double)recorder.mSampleRate < recorder.mRecTime &&
  285. (err=alcGetError(recorder.mDevice)) == ALC_NO_ERROR && !ferror(recorder.mFile))
  286. {
  287. ALCint count = 0;
  288. fprintf(stderr, "\rCaptured %u samples", recorder.mDataSize);
  289. alcGetIntegerv(recorder.mDevice, ALC_CAPTURE_SAMPLES, 1, &count);
  290. if(count < 1)
  291. {
  292. al_nssleep(10000000);
  293. continue;
  294. }
  295. if(count > recorder.mBufferSize)
  296. {
  297. ALbyte *data = calloc(recorder.mFrameSize, count);
  298. free(recorder.mBuffer);
  299. recorder.mBuffer = data;
  300. recorder.mBufferSize = count;
  301. }
  302. alcCaptureSamples(recorder.mDevice, recorder.mBuffer, count);
  303. #if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN
  304. /* Byteswap multibyte samples on big-endian systems (wav needs little-
  305. * endian, and OpenAL gives the system's native-endian).
  306. */
  307. if(recorder.mBits == 16)
  308. {
  309. ALCint i;
  310. for(i = 0;i < count*recorder.mChannels;i++)
  311. {
  312. ALbyte b = recorder.mBuffer[i*2 + 0];
  313. recorder.mBuffer[i*2 + 0] = recorder.mBuffer[i*2 + 1];
  314. recorder.mBuffer[i*2 + 1] = b;
  315. }
  316. }
  317. else if(recorder.mBits == 32)
  318. {
  319. ALCint i;
  320. for(i = 0;i < count*recorder.mChannels;i++)
  321. {
  322. ALbyte b0 = recorder.mBuffer[i*4 + 0];
  323. ALbyte b1 = recorder.mBuffer[i*4 + 1];
  324. recorder.mBuffer[i*4 + 0] = recorder.mBuffer[i*4 + 3];
  325. recorder.mBuffer[i*4 + 1] = recorder.mBuffer[i*4 + 2];
  326. recorder.mBuffer[i*4 + 2] = b1;
  327. recorder.mBuffer[i*4 + 3] = b0;
  328. }
  329. }
  330. #endif
  331. recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, count,
  332. recorder.mFile);
  333. }
  334. alcCaptureStop(recorder.mDevice);
  335. fprintf(stderr, "\rCaptured %u samples\n", recorder.mDataSize);
  336. if(err != ALC_NO_ERROR)
  337. fprintf(stderr, "Got device error 0x%04x: %s\n", err, alcGetString(recorder.mDevice, err));
  338. alcCaptureCloseDevice(recorder.mDevice);
  339. recorder.mDevice = NULL;
  340. free(recorder.mBuffer);
  341. recorder.mBuffer = NULL;
  342. recorder.mBufferSize = 0;
  343. total_size = ftell(recorder.mFile);
  344. if(fseek(recorder.mFile, recorder.mDataSizeOffset, SEEK_SET) == 0)
  345. {
  346. fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile);
  347. if(fseek(recorder.mFile, 4, SEEK_SET) == 0)
  348. fwrite32le(total_size - 8, recorder.mFile);
  349. }
  350. fclose(recorder.mFile);
  351. recorder.mFile = NULL;
  352. return 0;
  353. }