summaryrefslogtreecommitdiffstats
path: root/channels/rdpsnd/client/mac/rdpsnd_mac.m
blob: 648ded4a9405c896e17eb109ef78e3ef080a38fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
 * FreeRDP: A Remote Desktop Protocol Implementation
 * Audio Output Virtual Channel
 *
 * Copyright 2012 Laxmikant Rashinkar <LK.Rashinkar@gmail.com>
 * Copyright 2015 Thincast Technologies GmbH
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 * Copyright 2016 Inuvika Inc.
 * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <freerdp/config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <winpr/crt.h>
#include <winpr/sysinfo.h>

#include <freerdp/types.h>

#include <AVFoundation/AVAudioBuffer.h>
#include <AVFoundation/AVFoundation.h>

#include "rdpsnd_main.h"

typedef struct
{
	rdpsndDevicePlugin device;

	BOOL isOpen;
	BOOL isPlaying;

	UINT32 latency;
	AUDIO_FORMAT format;

	AVAudioEngine *engine;
	AVAudioPlayerNode *player;
	UINT64 diff;
} rdpsndMacPlugin;

static BOOL rdpsnd_mac_set_format(rdpsndDevicePlugin *device, const AUDIO_FORMAT *format,
                                  UINT32 latency)
{
	rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;
	if (!mac || !format)
		return FALSE;

	mac->latency = latency;
	mac->format = *format;

	audio_format_print(WLog_Get(TAG), WLOG_DEBUG, format);
	return TRUE;
}

static char *FormatError(OSStatus st)
{
	switch (st)
	{
		case kAudioFileUnspecifiedError:
			return "kAudioFileUnspecifiedError";

		case kAudioFileUnsupportedFileTypeError:
			return "kAudioFileUnsupportedFileTypeError";

		case kAudioFileUnsupportedDataFormatError:
			return "kAudioFileUnsupportedDataFormatError";

		case kAudioFileUnsupportedPropertyError:
			return "kAudioFileUnsupportedPropertyError";

		case kAudioFileBadPropertySizeError:
			return "kAudioFileBadPropertySizeError";

		case kAudioFilePermissionsError:
			return "kAudioFilePermissionsError";

		case kAudioFileNotOptimizedError:
			return "kAudioFileNotOptimizedError";

		case kAudioFileInvalidChunkError:
			return "kAudioFileInvalidChunkError";

		case kAudioFileDoesNotAllow64BitDataSizeError:
			return "kAudioFileDoesNotAllow64BitDataSizeError";

		case kAudioFileInvalidPacketOffsetError:
			return "kAudioFileInvalidPacketOffsetError";

		case kAudioFileInvalidFileError:
			return "kAudioFileInvalidFileError";

		case kAudioFileOperationNotSupportedError:
			return "kAudioFileOperationNotSupportedError";

		case kAudioFileNotOpenError:
			return "kAudioFileNotOpenError";

		case kAudioFileEndOfFileError:
			return "kAudioFileEndOfFileError";

		case kAudioFilePositionError:
			return "kAudioFilePositionError";

		case kAudioFileFileNotFoundError:
			return "kAudioFileFileNotFoundError";

		default:
			return "unknown error";
	}
}

static void rdpsnd_mac_release(rdpsndMacPlugin *mac)
{
	if (mac->player)
		[mac->player release];
	mac->player = NULL;

	if (mac->engine)
		[mac->engine release];
	mac->engine = NULL;
}

static BOOL rdpsnd_mac_open(rdpsndDevicePlugin *device, const AUDIO_FORMAT *format, UINT32 latency)
{
	@autoreleasepool
	{
		AudioDeviceID outputDeviceID;
		UInt32 propertySize;
		OSStatus err;
		NSError *error;
		rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;
		AudioObjectPropertyAddress propertyAddress = {
			kAudioHardwarePropertyDefaultOutputDevice,
			kAudioObjectPropertyScopeGlobal,
#if defined(MAC_OS_VERSION_12_0)
			kAudioObjectPropertyElementMain
#else
			kAudioObjectPropertyElementMaster
#endif
		};

		if (mac->isOpen)
			return TRUE;

		if (!rdpsnd_mac_set_format(device, format, latency))
			return FALSE;

		propertySize = sizeof(outputDeviceID);
		err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL,
		                                 &propertySize, &outputDeviceID);
		if (err)
		{
			WLog_ERR(TAG, "AudioHardwareGetProperty: %s", FormatError(err));
			return FALSE;
		}

		mac->engine = [[AVAudioEngine alloc] init];
		if (!mac->engine)
			return FALSE;

		err = AudioUnitSetProperty(mac->engine.outputNode.audioUnit,
		                           kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global,
		                           0, &outputDeviceID, sizeof(outputDeviceID));
		if (err)
		{
			rdpsnd_mac_release(mac);
			WLog_ERR(TAG, "AudioUnitSetProperty: %s", FormatError(err));
			return FALSE;
		}

		mac->player = [[AVAudioPlayerNode alloc] init];
		if (!mac->player)
		{
			rdpsnd_mac_release(mac);
			WLog_ERR(TAG, "AVAudioPlayerNode::init() failed");
			return FALSE;
		}

		[mac->engine attachNode:mac->player];

		[mac->engine connect:mac->player to:mac->engine.mainMixerNode format:nil];

		[mac->engine prepare];

		if (![mac->engine startAndReturnError:&error])
		{
			device->Close(device);
			WLog_ERR(TAG, "Failed to start audio player %s",
			         [error.localizedDescription UTF8String]);
			return FALSE;
		}

		mac->isOpen = TRUE;
		return TRUE;
	}
}

static void rdpsnd_mac_close(rdpsndDevicePlugin *device)
{
	@autoreleasepool
	{
		rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;

		if (mac->isPlaying)
		{
			[mac->player stop];
			mac->isPlaying = FALSE;
		}

		if (mac->isOpen)
		{
			[mac->engine stop];
			mac->isOpen = FALSE;
		}

		rdpsnd_mac_release(mac);
	}
}

static void rdpsnd_mac_free(rdpsndDevicePlugin *device)
{
	rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;
	device->Close(device);
	free(mac);
}

static BOOL rdpsnd_mac_format_supported(rdpsndDevicePlugin *device, const AUDIO_FORMAT *format)
{
	WINPR_UNUSED(device);

	switch (format->wFormatTag)
	{
		case WAVE_FORMAT_PCM:
			if (format->wBitsPerSample != 16)
				return FALSE;

			if (format->nChannels != 2)
				return FALSE;
			return TRUE;

		default:
			return FALSE;
	}
}

static BOOL rdpsnd_mac_set_volume(rdpsndDevicePlugin *device, UINT32 value)
{
	@autoreleasepool
	{
		Float32 fVolume;
		UINT16 volumeLeft;
		UINT16 volumeRight;
		rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;

		if (!mac->player)
			return FALSE;

		volumeLeft = (value & 0xFFFF);
		volumeRight = ((value >> 16) & 0xFFFF);
		fVolume = ((float)volumeLeft) / 65535.0f;

		mac->player.volume = fVolume;

		return TRUE;
	}
}

static void rdpsnd_mac_start(rdpsndDevicePlugin *device)
{
	@autoreleasepool
	{
		rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;

		if (!mac->isPlaying)
		{
			if (!mac->engine.isRunning)
			{
				NSError *error;

				if (![mac->engine startAndReturnError:&error])
				{
					device->Close(device);
					WLog_ERR(TAG, "Failed to start audio player %s",
					         [error.localizedDescription UTF8String]);
					return;
				}
			}

			[mac->player play];

			mac->isPlaying = TRUE;
			mac->diff = 100; /* Initial latency, corrected after first sample is played. */
		}
	}
}

static UINT rdpsnd_mac_play(rdpsndDevicePlugin *device, const BYTE *data, size_t size)
{
	@autoreleasepool
	{
		rdpsndMacPlugin *mac = (rdpsndMacPlugin *)device;
		AVAudioPCMBuffer *buffer;
		AVAudioFormat *format;
		float *const *db;
		size_t step;
		AVAudioFrameCount count;
		UINT64 start = GetTickCount64();

		if (!mac->isOpen)
			return 0;

		step = 2 * mac->format.nChannels;

		count = size / step;
		format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32
		                                          sampleRate:mac->format.nSamplesPerSec
		                                            channels:mac->format.nChannels
		                                         interleaved:NO];

		if (!format)
		{
			WLog_WARN(TAG, "AVAudioFormat::init() failed");
			return 0;
		}

		buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:format frameCapacity:count];
		[format release];

		if (!buffer)
		{
			WLog_WARN(TAG, "AVAudioPCMBuffer::init() failed");
			return 0;
		}

		buffer.frameLength = buffer.frameCapacity;
		db = buffer.floatChannelData;

		for (size_t pos = 0; pos < count; pos++)
		{
			const BYTE *d = &data[pos * step];
			for (size_t x = 0; x < mac->format.nChannels; x++)
			{
				const float val = (int16_t)((uint16_t)d[0] | ((uint16_t)d[1] << 8)) / 32768.0f;
				db[x][pos] = val;
				d += sizeof(int16_t);
			}
		}

		rdpsnd_mac_start(device);

		[mac->player scheduleBuffer:buffer
		          completionHandler:^{
			          UINT64 stop = GetTickCount64();
			          if (start > stop)
				          mac->diff = 0;
			          else
				          mac->diff = stop - start;
		          }];

		[buffer release];

		return mac->diff > UINT_MAX ? UINT_MAX : mac->diff;
	}
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
FREERDP_ENTRY_POINT(UINT mac_freerdp_rdpsnd_client_subsystem_entry(
    PFREERDP_RDPSND_DEVICE_ENTRY_POINTS pEntryPoints))
{
	rdpsndMacPlugin *mac;
	mac = (rdpsndMacPlugin *)calloc(1, sizeof(rdpsndMacPlugin));

	if (!mac)
		return CHANNEL_RC_NO_MEMORY;

	mac->device.Open = rdpsnd_mac_open;
	mac->device.FormatSupported = rdpsnd_mac_format_supported;
	mac->device.SetVolume = rdpsnd_mac_set_volume;
	mac->device.Play = rdpsnd_mac_play;
	mac->device.Close = rdpsnd_mac_close;
	mac->device.Free = rdpsnd_mac_free;
	pEntryPoints->pRegisterRdpsndDevice(pEntryPoints->rdpsnd, (rdpsndDevicePlugin *)mac);
	return CHANNEL_RC_OK;
}