@kmamal/sdl 1.0.0-2 → 1.0.0-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -37,15 +37,16 @@ class AudioStream extends EventsViaPoll {
37
37
 
38
38
  this._id = id
39
39
  this._recording = recording
40
+ const helper = AudioFormatHelpers[format]
41
+
40
42
  this._device = device
41
43
  this._channels = channels
42
- this._format = format
44
+ this._format = helper.name
43
45
  this._frequency = frequency
44
46
 
45
47
  this._playing = false
46
48
  this._closed = false
47
49
 
48
- const helper = AudioFormatHelpers[this._format]
49
50
  this._bytesPerSample = helper.bytesPerSample
50
51
  this._minSampleValue = helper.minSampleValue
51
52
  this._maxSampleValue = helper.maxSampleValue
@@ -118,8 +119,10 @@ class AudioStream extends EventsViaPoll {
118
119
  // We might be inside an event listener
119
120
  this._retire(() => Object.assign(new Error("stream is closed"), { id: this._id }))
120
121
 
121
- try { this.emit('close', { type: 'close' }) }
122
- catch (error) { this.emit('error', error) }
122
+ Globals.events.withoutPolling(() => {
123
+ try { this.emit('close', { type: 'close' }) }
124
+ catch (error) { this.emit('error', error) }
125
+ })
123
126
  }
124
127
  }
125
128
 
@@ -64,6 +64,10 @@ const AudioFormatHelpers = Object.assign(Object.create(null), {
64
64
  },
65
65
  })
66
66
 
67
+ for (const [ key, value ] of Object.entries(AudioFormatHelpers)) {
68
+ value.name = key
69
+ }
70
+
67
71
  if (Os.endianness() === 'LE') {
68
72
  AudioFormatHelpers.s16 = AudioFormatHelpers.s16le
69
73
  AudioFormatHelpers.s32 = AudioFormatHelpers.s32le
@@ -489,6 +489,12 @@ const poll = () => {
489
489
  finally { polling = false }
490
490
  }
491
491
 
492
+ const withoutPolling = (fn) => {
493
+ const prevValue = polling
494
+ try { fn() }
495
+ finally { polling = prevValue }
496
+ }
497
+
492
498
  let pollInterval = null
493
499
 
494
500
  const switchToPollingFast = () => {
@@ -509,6 +515,7 @@ const stopPolling = () => {
509
515
 
510
516
  Globals.events = {
511
517
  poll,
518
+ withoutPolling,
512
519
  switchToPollingFast,
513
520
  switchToPollingSlow,
514
521
  stopPolling,
@@ -133,7 +133,7 @@ class GamepadInstance extends EventsViaPoll {
133
133
  if (highFreqRumble < 0 || highFreqRumble > 1) { throw Object.assign(new Error("highFreqRumble must be between 0 and 1"), { highFreqRumble }) }
134
134
  if (duration !== null) {
135
135
  if (!Number.isInteger(duration)) { throw Object.assign(new Error("duration must be an integer"), { duration }) }
136
- if (duration < 1 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a positive 32-bit integer"), { duration }) }
136
+ if (duration < 0 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a non-negative 32-bit integer"), { duration }) }
137
137
  }
138
138
 
139
139
  if (!this.hasRumble) { throw Object.assign(new Error("device has no rumble"), { id: this._device.id }) }
@@ -164,7 +164,7 @@ class GamepadInstance extends EventsViaPoll {
164
164
  if (rightRumble < 0 || rightRumble > 1) { throw Object.assign(new Error("rightRumble must be between 0 and 1"), { rightRumble }) }
165
165
  if (duration !== null) {
166
166
  if (!Number.isInteger(duration)) { throw Object.assign(new Error("duration must be an integer"), { duration }) }
167
- if (duration < 1 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a positive 32-bit integer"), { duration }) }
167
+ if (duration < 0 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a non-negative 32-bit integer"), { duration }) }
168
168
  }
169
169
 
170
170
  if (!this.hasRumbleTriggers) { throw Object.assign(new Error("device has no trigger rumble"), { id: this._device.id }) }
@@ -201,8 +201,10 @@ class GamepadInstance extends EventsViaPoll {
201
201
  // We might be inside an event listener
202
202
  this._retire(() => Object.assign(new Error("instance is closed"), { id: this._device.id }))
203
203
 
204
- try { this.emit('close', { type: 'close' }) }
205
- catch (error) { this.emit('error', error) }
204
+ Globals.events.withoutPolling(() => {
205
+ try { this.emit('close', { type: 'close' }) }
206
+ catch (error) { this.emit('error', error) }
207
+ })
206
208
  }
207
209
  }
208
210
 
@@ -1,5 +1,5 @@
1
1
  const { isMainThread } = require('node:worker_threads')
2
- if (!isMainThread) { throw new Error('@kmamal/sdl can only be used in the main thread') }
2
+ if (!isMainThread) { throw new Error("@kmamal/sdl can only be used in the main thread, import @kmamal/sdl/worker in workers") }
3
3
 
4
4
  const Bindings = require('./bindings')
5
5
  const Globals = require('./globals')
@@ -133,7 +133,7 @@ class JoystickInstance extends EventsViaPoll {
133
133
  if (highFreqRumble < 0 || highFreqRumble > 1) { throw Object.assign(new Error("highFreqRumble must be between 0 and 1"), { highFreqRumble }) }
134
134
  if (duration !== null) {
135
135
  if (!Number.isInteger(duration)) { throw Object.assign(new Error("duration must be an integer"), { duration }) }
136
- if (duration < 1 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a positive 32-bit integer"), { duration }) }
136
+ if (duration < 0 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a non-negative 32-bit integer"), { duration }) }
137
137
  }
138
138
 
139
139
  if (!this.hasRumble) { throw Object.assign(new Error("device has no rumble"), { id: this._device.id }) }
@@ -164,7 +164,7 @@ class JoystickInstance extends EventsViaPoll {
164
164
  if (rightRumble < 0 || rightRumble > 1) { throw Object.assign(new Error("rightRumble must be between 0 and 1"), { rightRumble }) }
165
165
  if (duration !== null) {
166
166
  if (!Number.isInteger(duration)) { throw Object.assign(new Error("duration must be an integer"), { duration }) }
167
- if (duration < 1 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a positive 32-bit integer"), { duration }) }
167
+ if (duration < 0 || duration > 2 ** 31 - 1) { throw Object.assign(new Error("duration must be a non-negative 32-bit integer"), { duration }) }
168
168
  }
169
169
 
170
170
  if (!this.hasRumbleTriggers) { throw Object.assign(new Error("device has no trigger rumble"), { id: this._device.id }) }
@@ -199,8 +199,10 @@ class JoystickInstance extends EventsViaPoll {
199
199
  // We might be inside an event listener
200
200
  this._retire(() => Object.assign(new Error("instance is closed"), { id: this._device.id }))
201
201
 
202
- try { this.emit('close', { type: 'close' }) }
203
- catch (error) { this.emit('error', error) }
202
+ Globals.events.withoutPolling(() => {
203
+ try { this.emit('close', { type: 'close' }) }
204
+ catch (error) { this.emit('error', error) }
205
+ })
204
206
  }
205
207
  }
206
208
 
@@ -20,6 +20,8 @@ const clearEffectTimeout = (effect, id) => {
20
20
  const MAX_DURATION = 0xFFFF
21
21
 
22
22
  const startEffect = (kind, id, a, b, duration) => {
23
+ if (duration === 0) { return stopEffect(kind, id) }
24
+
23
25
  const effect = effects[kind]
24
26
  a = Math.round(a * 0xFFFF)
25
27
  b = Math.round(b * 0xFFFF)
@@ -59,8 +59,10 @@ class SensorInstance extends EventsViaPoll {
59
59
  // We might be inside an event listener
60
60
  this._retire(() => Object.assign(new Error("instance is closed"), { id: this._device.id }))
61
61
 
62
- try { this.emit('close', { type: 'close' }) }
63
- catch (error) { this.emit('error', error) }
62
+ Globals.events.withoutPolling(() => {
63
+ try { this.emit('close', { type: 'close' }) }
64
+ catch (error) { this.emit('error', error) }
65
+ })
64
66
  }
65
67
  }
66
68
 
@@ -1,3 +1,4 @@
1
+ const Os = require('node:os')
1
2
 
2
3
  const minStride = (bytesPerPixel) => (width) => width * bytesPerPixel
3
4
  const minStridePacked = (width) => 4 * Math.ceil(width / 2)
@@ -9,18 +10,18 @@ const rgb = (bytesPerPixel) => ({
9
10
  bytesPerPixel,
10
11
  isYuv: false,
11
12
  isPlanarYuv: false,
12
- isRenderable: true,
13
13
  minStride: minStride(bytesPerPixel),
14
14
  minBufferSize,
15
+ isRenderable: true,
15
16
  })
16
17
 
17
18
  const yuv = (bytesPerPixel, isPlanarYuv, isRenderable = true) => ({
18
19
  bytesPerPixel,
19
20
  isYuv: true,
20
21
  isPlanarYuv,
21
- isRenderable,
22
22
  minStride: isPlanarYuv ? minStride(bytesPerPixel) : minStridePacked,
23
23
  minBufferSize: isPlanarYuv ? minBufferSizePlanar : minBufferSize,
24
+ isRenderable,
24
25
  })
25
26
 
26
27
  const VideoFormatHelpers = Object.assign(Object.create(null), {
@@ -71,14 +72,6 @@ const VideoFormatHelpers = Object.assign(Object.create(null), {
71
72
  argb128f: rgb(16),
72
73
  bgra128f: rgb(16),
73
74
  abgr128f: rgb(16),
74
- rgba32: rgb(4),
75
- argb32: rgb(4),
76
- bgra32: rgb(4),
77
- abgr32: rgb(4),
78
- rgbx32: rgb(4),
79
- xrgb32: rgb(4),
80
- bgrx32: rgb(4),
81
- xbgr32: rgb(4),
82
75
  yv12: yuv(1, true),
83
76
  iyuv: yuv(1, true),
84
77
  yuy2: yuv(2, false),
@@ -89,6 +82,31 @@ const VideoFormatHelpers = Object.assign(Object.create(null), {
89
82
  p010: { ...yuv(2, true, false), minStride: minStridePacked },
90
83
  })
91
84
 
85
+ for (const [ key, value ] of Object.entries(VideoFormatHelpers)) {
86
+ value.name = key
87
+ }
88
+
89
+ if (Os.endianness() === 'LE') {
90
+ VideoFormatHelpers.rgba32 = VideoFormatHelpers.abgr8888
91
+ VideoFormatHelpers.argb32 = VideoFormatHelpers.bgra8888
92
+ VideoFormatHelpers.bgra32 = VideoFormatHelpers.argb8888
93
+ VideoFormatHelpers.abgr32 = VideoFormatHelpers.rgba8888
94
+ VideoFormatHelpers.rgbx32 = VideoFormatHelpers.xbgr8888
95
+ VideoFormatHelpers.xrgb32 = VideoFormatHelpers.bgrx8888
96
+ VideoFormatHelpers.bgrx32 = VideoFormatHelpers.xrgb8888
97
+ VideoFormatHelpers.xbgr32 = VideoFormatHelpers.rgbx8888
98
+ }
99
+ else {
100
+ VideoFormatHelpers.rgba32 = VideoFormatHelpers.rgba8888
101
+ VideoFormatHelpers.argb32 = VideoFormatHelpers.argb8888
102
+ VideoFormatHelpers.bgra32 = VideoFormatHelpers.bgra8888
103
+ VideoFormatHelpers.abgr32 = VideoFormatHelpers.abgr8888
104
+ VideoFormatHelpers.rgbx32 = VideoFormatHelpers.rgbx8888
105
+ VideoFormatHelpers.xrgb32 = VideoFormatHelpers.xrgb8888
106
+ VideoFormatHelpers.bgrx32 = VideoFormatHelpers.bgrx8888
107
+ VideoFormatHelpers.xbgr32 = VideoFormatHelpers.xbgr8888
108
+ }
109
+
92
110
  const getFormatHelpers = (format) => {
93
111
  if (typeof format !== 'string') { throw Object.assign(new Error("format must be a string"), { format }) }
94
112
  const helpers = VideoFormatHelpers[format]
@@ -46,6 +46,13 @@ const video = new class extends EventsViaPoll {
46
46
  isYuv (format) { return getFormatHelpers(format).isYuv }
47
47
  isPlanarYuv (format) { return getFormatHelpers(format).isPlanarYuv }
48
48
 
49
+ minStride (format, width) {
50
+ const helpers = getFormatHelpers(format)
51
+ if (!Number.isInteger(width)) { throw Object.assign(new Error("width must be an integer"), { width }) }
52
+ if (width < 0) { throw Object.assign(new Error("width must be non-negative"), { width }) }
53
+ return helpers.minStride(width)
54
+ }
55
+
49
56
  minBufferSize (format, stride, height) {
50
57
  const helpers = getFormatHelpers(format)
51
58
  if (!Number.isInteger(stride)) { throw Object.assign(new Error("stride must be an integer"), { stride }) }
@@ -82,7 +82,10 @@ class Window extends EventsViaPoll {
82
82
  if (typeof borderless !== 'boolean') { throw Object.assign(new Error("borderless must be a boolean"), { borderless }) }
83
83
  if (typeof alwaysOnTop !== 'boolean') { throw Object.assign(new Error("alwaysOnTop must be a boolean"), { alwaysOnTop }) }
84
84
  if (hasAccelerated && typeof accelerated !== 'boolean') { throw Object.assign(new Error("accelerated must be a boolean"), { accelerated }) }
85
- if (hasVsync && typeof vsync !== 'boolean') { throw Object.assign(new Error("vsync must be a boolean"), { vsync }) }
85
+ if (hasVsync) {
86
+ if (!Number.isInteger(vsync)) { throw Object.assign(new Error("vsync must be an integer"), { vsync }) }
87
+ if (vsync < -1 || vsync > 2 ** 31 - 1) { throw Object.assign(new Error("vsync must be -1 or a non-negative 32-bit integer"), { vsync }) }
88
+ }
86
89
  if (typeof opengl !== 'boolean') { throw Object.assign(new Error("opengl must be a boolean"), { opengl }) }
87
90
  if (typeof webgpu !== 'boolean') { throw Object.assign(new Error("webgpu must be a boolean"), { webgpu }) }
88
91
  if (display !== null && (x !== null || y !== null)) { throw Object.assign(new Error("display and x/y are mutually exclusive"), { display, x, y }) }
@@ -111,7 +114,7 @@ class Window extends EventsViaPoll {
111
114
  borderless,
112
115
  alwaysOnTop,
113
116
  accelerated ?? true,
114
- vsync ?? true,
117
+ vsync ?? 1,
115
118
  opengl,
116
119
  webgpu,
117
120
  )
@@ -154,32 +157,34 @@ class Window extends EventsViaPoll {
154
157
  // Manually emit some initial events for convenience
155
158
  process.nextTick(() => {
156
159
  if (this._destroyed) { return }
157
- try {
158
- this.emit('move', {
159
- x: this._x,
160
- y: this._y,
161
- type: 'move',
162
- })
163
- }
164
- catch (error) { this.emit('error', error) }
165
- try {
166
- this.emit('resize', {
167
- width: this._width,
168
- height: this._height,
169
- pixelWidth: this._pixelWidth,
170
- pixelHeight: this._pixelHeight,
171
- type: 'resize',
172
- })
173
- }
174
- catch (error) { this.emit('error', error) }
175
- if (this._visible) {
160
+ Globals.events.withoutPolling(() => {
176
161
  try {
177
- this.emit('expose', {
178
- type: 'expose',
162
+ this.emit('move', {
163
+ x: this._x,
164
+ y: this._y,
165
+ type: 'move',
179
166
  })
180
167
  }
181
168
  catch (error) { this.emit('error', error) }
182
- }
169
+ try {
170
+ this.emit('resize', {
171
+ width: this._width,
172
+ height: this._height,
173
+ pixelWidth: this._pixelWidth,
174
+ pixelHeight: this._pixelHeight,
175
+ type: 'resize',
176
+ })
177
+ }
178
+ catch (error) { this.emit('error', error) }
179
+ if (this._visible) {
180
+ try {
181
+ this.emit('expose', {
182
+ type: 'expose',
183
+ })
184
+ }
185
+ catch (error) { this.emit('error', error) }
186
+ }
187
+ })
183
188
  })
184
189
  }
185
190
 
@@ -378,7 +383,8 @@ class Window extends EventsViaPoll {
378
383
  if (this._opengl) { throw new Error("can't call setVsync in opengl mode") }
379
384
  if (this._webgpu) { throw new Error("can't call setVsync in webgpu mode") }
380
385
 
381
- if (typeof vsync !== 'boolean') { throw Object.assign(new Error("vsync must be a boolean"), { vsync }) }
386
+ if (!Number.isInteger(vsync)) { throw Object.assign(new Error("vsync must be an integer"), { vsync }) }
387
+ if (vsync < -1 || vsync > 2 ** 31 - 1) { throw Object.assign(new Error("vsync must be -1 or a non-negative 32-bit integer"), { vsync }) }
382
388
 
383
389
  const result = Bindings.window_setAcceleratedAndVsync(this._id, this._accelerated, vsync)
384
390
  this._accelerated = result.accelerated
@@ -583,21 +589,25 @@ class Window extends EventsViaPoll {
583
589
  // We might be inside an event listener
584
590
  this._retire(() => Object.assign(new Error("window is destroyed"), { id: this._id }))
585
591
 
586
- try { this.emit('close', { type: 'close' }) }
587
- catch (error) { this.emit('error', error) }
592
+ Globals.events.withoutPolling(() => {
593
+ try { this.emit('close', { type: 'close' }) }
594
+ catch (error) { this.emit('error', error) }
595
+ })
588
596
  }
589
597
 
590
598
  destroyGently () {
591
599
  if (this._destroyed) { throw Object.assign(new Error("window is destroyed"), { id: this._id }) }
592
600
 
593
601
  let shouldPrevent = false
594
- try {
595
- this.emit('beforeClose', {
596
- type: 'beforeClose',
597
- prevent: () => { shouldPrevent = true },
598
- })
599
- }
600
- catch (error) { this.emit('error', error) }
602
+ Globals.events.withoutPolling(() => {
603
+ try {
604
+ this.emit('beforeClose', {
605
+ type: 'beforeClose',
606
+ prevent: () => { shouldPrevent = true },
607
+ })
608
+ }
609
+ catch (error) { this.emit('error', error) }
610
+ })
601
611
  if (shouldPrevent) { return }
602
612
 
603
613
  // A listener may have already destroyed the window
@@ -1,6 +1,39 @@
1
+ const { isMainThread } = require('node:worker_threads')
2
+ if (isMainThread) { throw new Error("@kmamal/sdl/worker can only be used in worker threads, import @kmamal/sdl in the main thread") }
3
+
4
+ const Globals = require('./globals')
5
+
6
+ Globals.events = {
7
+ poll () {},
8
+ withoutPolling (fn) { fn() },
9
+ switchToPollingFast () {},
10
+ switchToPollingSlow () {},
11
+ }
12
+
1
13
  const Enums = require('./enums')
2
14
  const { getFormatHelpers: getAudioFormatHelpers } = require('./audio/format-helpers')
3
15
  const { getFormatHelpers: getVideoFormatHelpers } = require('./video/format-helpers')
16
+ const { AudioPlaybackStream } = require('./audio/audio-playback-stream')
17
+ const { AudioRecordingStream } = require('./audio/audio-recording-stream')
18
+ const { makeDefault: makeDefaultDevice } = require('./audio/device')
19
+
20
+ const makeModule = (type, Stream) => {
21
+ const defaultDevice = makeDefaultDevice()
22
+
23
+ return {
24
+ openDevice (device = null, options = {}) {
25
+ if (device === null) { device = defaultDevice }
26
+ else {
27
+ if (typeof device !== 'object') { throw Object.assign(new Error("device must be an object"), { device }) }
28
+ const { id } = device
29
+ if (id !== null && !Number.isInteger(id)) { throw Object.assign(new Error("device.id must be an integer or null"), { id }) }
30
+ if (id !== null && (id < 0 || id > 2 ** 32 - 1)) { throw Object.assign(new Error("device.id must be an unsigned 32-bit integer"), { id }) }
31
+ }
32
+
33
+ return new Stream(device, options)
34
+ },
35
+ }
36
+ }
4
37
 
5
38
  module.exports = {
6
39
  video: {
@@ -8,6 +41,13 @@ module.exports = {
8
41
  isYuv (format) { return getVideoFormatHelpers(format).isYuv },
9
42
  isPlanarYuv (format) { return getVideoFormatHelpers(format).isPlanarYuv },
10
43
 
44
+ minStride (format, width) {
45
+ const helpers = getVideoFormatHelpers(format)
46
+ if (!Number.isInteger(width)) { throw Object.assign(new Error("width must be an integer"), { width }) }
47
+ if (width < 0) { throw Object.assign(new Error("width must be non-negative"), { width }) }
48
+ return helpers.minStride(width)
49
+ },
50
+
11
51
  minBufferSize (format, stride, height) {
12
52
  const helpers = getVideoFormatHelpers(format)
13
53
  if (!Number.isInteger(stride)) { throw Object.assign(new Error("stride must be an integer"), { stride }) }
@@ -41,5 +81,8 @@ module.exports = {
41
81
  if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
42
82
  return getAudioFormatHelpers(format).writer.call(buffer, value, offset)
43
83
  },
84
+
85
+ playback: makeModule('playback', AudioPlaybackStream),
86
+ recording: makeModule('recording', AudioRecordingStream),
44
87
  },
45
88
  }
@@ -1,12 +1,19 @@
1
1
  #include "audio.h"
2
+ #include "global.h"
2
3
  #include <SDL3/SDL.h>
3
4
  #include <string>
4
5
  #include <sstream>
6
+ #include <mutex>
5
7
 
6
8
  std::map<bool, std::string> audio::device_types;
7
9
  std::map<SDL_AudioFormat, std::string> audio::formats;
8
10
 
9
- static std::map<SDL_AudioDeviceID, SDL_AudioStream *> open_streams;
11
+ struct OpenStream {
12
+ SDL_AudioStream *stream;
13
+ napi_env env;
14
+ };
15
+
16
+ static std::map<SDL_AudioDeviceID, OpenStream> open_streams;
10
17
 
11
18
  static SDL_AudioStream *
12
19
  _getStream (Napi::Env &env, SDL_AudioDeviceID audio_id)
@@ -17,7 +24,32 @@ _getStream (Napi::Env &env, SDL_AudioDeviceID audio_id)
17
24
  message << "getAudioStream(" << audio_id << ") error: invalid audio stream id";
18
25
  throw Napi::Error::New(env, message.str());
19
26
  }
20
- return entry->second;
27
+ return entry->second.stream;
28
+ }
29
+
30
+ void
31
+ audio::closeEnvStreams (Napi::Env env)
32
+ {
33
+ std::lock_guard<std::mutex> guard(global::lock());
34
+
35
+ for (auto it = open_streams.begin(); it != open_streams.end();) {
36
+ if (it->second.env == (napi_env) env) {
37
+ SDL_DestroyAudioStream(it->second.stream);
38
+ it = open_streams.erase(it);
39
+ }
40
+ else {
41
+ it++;
42
+ }
43
+ }
44
+ }
45
+
46
+ void
47
+ audio::closeAllStreams ()
48
+ {
49
+ for (auto &entry : open_streams) {
50
+ SDL_DestroyAudioStream(entry.second.stream);
51
+ }
52
+ open_streams.clear();
21
53
  }
22
54
 
23
55
 
@@ -82,6 +114,9 @@ audio::getDevices(const Napi::CallbackInfo &info)
82
114
  {
83
115
  Napi::Env env = info.Env();
84
116
 
117
+ std::lock_guard<std::mutex> guard(global::lock());
118
+ global::assertReady(env);
119
+
85
120
  bool is_recording = info[0].As<Napi::Boolean>().Value();
86
121
 
87
122
  return audio::_getDevices(env, is_recording);
@@ -92,6 +127,9 @@ audio::open (const Napi::CallbackInfo &info)
92
127
  {
93
128
  Napi::Env env = info.Env();
94
129
 
130
+ std::lock_guard<std::mutex> guard(global::lock());
131
+ global::assertReady(env);
132
+
95
133
  bool has_id = !info[0].IsNull();
96
134
  bool is_recording = info[1].As<Napi::Boolean>().Value();
97
135
  int freq = info[2].As<Napi::Number>().Int32Value();
@@ -132,7 +170,7 @@ audio::open (const Napi::CallbackInfo &info)
132
170
  throw Napi::Error::New(env, message.str());
133
171
  }
134
172
 
135
- open_streams[audio_id] = stream;
173
+ open_streams[audio_id] = { stream, env };
136
174
 
137
175
  return Napi::Number::New(env, audio_id);
138
176
  }
@@ -142,6 +180,9 @@ audio::getDeviceFormat (const Napi::CallbackInfo &info)
142
180
  {
143
181
  Napi::Env env = info.Env();
144
182
 
183
+ std::lock_guard<std::mutex> guard(global::lock());
184
+ global::assertReady(env);
185
+
145
186
  int audio_id = info[0].As<Napi::Number>().Int32Value();
146
187
 
147
188
  SDL_AudioSpec spec;
@@ -172,6 +213,9 @@ audio::play (const Napi::CallbackInfo &info)
172
213
  {
173
214
  Napi::Env env = info.Env();
174
215
 
216
+ std::lock_guard<std::mutex> guard(global::lock());
217
+ global::assertReady(env);
218
+
175
219
  int audio_id = info[0].As<Napi::Number>().Int32Value();
176
220
  bool should_play = info[1].As<Napi::Boolean>().Value();
177
221
 
@@ -195,6 +239,9 @@ audio::getQueued (const Napi::CallbackInfo &info)
195
239
  {
196
240
  Napi::Env env = info.Env();
197
241
 
242
+ std::lock_guard<std::mutex> guard(global::lock());
243
+ global::assertReady(env);
244
+
198
245
  int audio_id = info[0].As<Napi::Number>().Int32Value();
199
246
 
200
247
  SDL_AudioStream *stream = _getStream(env, audio_id);
@@ -215,6 +262,9 @@ audio::getAvailable (const Napi::CallbackInfo &info)
215
262
  {
216
263
  Napi::Env env = info.Env();
217
264
 
265
+ std::lock_guard<std::mutex> guard(global::lock());
266
+ global::assertReady(env);
267
+
218
268
  int audio_id = info[0].As<Napi::Number>().Int32Value();
219
269
 
220
270
  SDL_AudioStream *stream = _getStream(env, audio_id);
@@ -235,6 +285,9 @@ audio::clear (const Napi::CallbackInfo &info)
235
285
  {
236
286
  Napi::Env env = info.Env();
237
287
 
288
+ std::lock_guard<std::mutex> guard(global::lock());
289
+ global::assertReady(env);
290
+
238
291
  int audio_id = info[0].As<Napi::Number>().Int32Value();
239
292
 
240
293
  SDL_AudioStream *stream = _getStream(env, audio_id);
@@ -254,6 +307,9 @@ audio::putData (const Napi::CallbackInfo &info)
254
307
  {
255
308
  Napi::Env env = info.Env();
256
309
 
310
+ std::lock_guard<std::mutex> guard(global::lock());
311
+ global::assertReady(env);
312
+
257
313
  int audio_id = info[0].As<Napi::Number>().Int32Value();
258
314
  void *src = info[1].As<Napi::Buffer<char>>().Data();
259
315
  int size = info[2].As<Napi::Number>().Int32Value();
@@ -275,6 +331,9 @@ audio::getData (const Napi::CallbackInfo &info)
275
331
  {
276
332
  Napi::Env env = info.Env();
277
333
 
334
+ std::lock_guard<std::mutex> guard(global::lock());
335
+ global::assertReady(env);
336
+
278
337
  int audio_id = info[0].As<Napi::Number>().Int32Value();
279
338
  void *dst = info[1].As<Napi::Buffer<char>>().Data();
280
339
  int size = info[2].As<Napi::Number>().Int32Value();
@@ -297,6 +356,9 @@ audio::close (const Napi::CallbackInfo &info)
297
356
  {
298
357
  Napi::Env env = info.Env();
299
358
 
359
+ std::lock_guard<std::mutex> guard(global::lock());
360
+ global::assertReady(env);
361
+
300
362
  int audio_id = info[0].As<Napi::Number>().Int32Value();
301
363
 
302
364
  SDL_AudioStream *stream = _getStream(env, audio_id);
@@ -11,6 +11,9 @@ namespace audio {
11
11
  extern std::map<bool, std::string> device_types;
12
12
  extern std::map<SDL_AudioFormat, std::string> formats;
13
13
 
14
+ void closeEnvStreams(Napi::Env env);
15
+ void closeAllStreams();
16
+
14
17
  Napi::Value _getDevice(Napi::Env &env, SDL_AudioDeviceID id);
15
18
  Napi::Array _getDevices(Napi::Env &env, bool is_recording);
16
19
 
@@ -28,7 +28,7 @@ gamepad::getSteamHandle (Napi::Env &env, SDL_Gamepad *gamepad)
28
28
  {
29
29
  Uint64 _steam_handle = SDL_GetGamepadSteamHandle(gamepad);
30
30
  return _steam_handle != 0
31
- ? Napi::Buffer<Uint64>::Copy(env, &_steam_handle, 1)
31
+ ? Napi::BigInt::New(env, _steam_handle)
32
32
  : env.Null();
33
33
  }
34
34
 
@@ -12,6 +12,7 @@
12
12
  #include <string>
13
13
  #include <sstream>
14
14
  #include <vector>
15
+ #include <atomic>
15
16
 
16
17
  #if defined(SDL_PLATFORM_MACOS)
17
18
  #include "cocoa-global.h"
@@ -19,6 +20,28 @@
19
20
 
20
21
 
21
22
  static SDL_ThreadID mainThreadId;
23
+ static std::atomic<bool> ready { false };
24
+
25
+ std::mutex &
26
+ global::lock()
27
+ {
28
+ static std::mutex mutex;
29
+ return mutex;
30
+ }
31
+
32
+ void
33
+ global::assertReady(Napi::Env &env)
34
+ {
35
+ if (!ready.load(std::memory_order_acquire)) {
36
+ throw Napi::Error::New(env, "SDL is not initialized, import @kmamal/sdl in the main thread first");
37
+ }
38
+ }
39
+
40
+ void
41
+ global::registerEnv(Napi::Env env)
42
+ {
43
+ env.AddCleanupHook([env]() { audio::closeEnvStreams(env); });
44
+ }
22
45
 
23
46
  bool watchEvents(void*, SDL_Event *event) {
24
47
  if (true
@@ -395,6 +418,8 @@ global::initialize(const Napi::CallbackInfo &info)
395
418
 
396
419
  SDL_memset(&joystick::zero_guid, 0, sizeof(joystick::zero_guid));
397
420
 
421
+ ready.store(true, std::memory_order_release);
422
+
398
423
  Napi::Object result = Napi::Object::New(env);
399
424
  result.Set("version", versions);
400
425
  result.Set("platform", platform);
@@ -410,6 +435,10 @@ global::cleanup(const Napi::CallbackInfo &info)
410
435
  {
411
436
  Napi::Env env = info.Env();
412
437
 
438
+ std::lock_guard<std::mutex> guard(global::lock());
439
+
440
+ audio::closeAllStreams();
441
+ ready.store(false, std::memory_order_release);
413
442
  SDL_Quit();
414
443
 
415
444
  return env.Undefined();