channels/rdpsnd: fix stop/start
[platform/upstream/freerdp.git] / channels / rdpsnd / client / rdpsnd_main.c
index eb2b3d1..a04d9d6 100644 (file)
@@ -32,6 +32,7 @@
 
 #include <winpr/crt.h>
 #include <winpr/synch.h>
+#include <winpr/print.h>
 #include <winpr/cmdline.h>
 #include <winpr/sysinfo.h>
 #include <winpr/collections.h>
 #include <freerdp/addin.h>
 #include <freerdp/constants.h>
 #include <freerdp/utils/stream.h>
-#include <freerdp/utils/list.h>
+#include <freerdp/utils/signal.h>
 #include <freerdp/utils/svc_plugin.h>
 
 #include "rdpsnd_main.h"
 
+#define TIME_DELAY_MS  65
+
 struct rdpsnd_plugin
 {
        rdpSvcPlugin plugin;
 
-       wMessageQueue* OutQueue;
+       HANDLE thread;
+       wMessageQueue* queue;
 
        BYTE cBlockNo;
-       rdpsndFormat* supported_formats;
-       int n_supported_formats;
-       int current_format;
+       int wCurrentFormatNo;
+
+       AUDIO_FORMAT* ServerFormats;
+       UINT16 NumberOfServerFormats;
+
+       AUDIO_FORMAT* ClientFormats;
+       UINT16 NumberOfClientFormats;
 
        BOOL expectingWave;
        BYTE waveData[4];
        UINT16 waveDataSize;
-       UINT32 wTimeStamp; /* server timestamp */
-       UINT32 wave_timestamp; /* client timestamp */
-
-       BOOL is_open;
-       UINT32 close_timestamp;
+       UINT32 wTimeStamp;
 
-       UINT16 fixed_format;
-       UINT16 fixed_channel;
-       UINT32 fixed_rate;
        int latency;
+       BOOL isOpen;
+       UINT16 fixedFormat;
+       UINT16 fixedChannel;
+       UINT32 fixedRate;
 
        char* subsystem;
        char* device_name;
@@ -77,324 +82,429 @@ struct rdpsnd_plugin
        rdpsndDevicePlugin* device;
 };
 
-/* process the linked list of data that has queued to be sent */
-static void rdpsnd_process_interval(rdpSvcPlugin* plugin)
+void rdpsnd_send_wave_confirm_pdu(rdpsndPlugin* rdpsnd, UINT16 wTimeStamp, BYTE cConfirmedBlockNo);
+
+static void* rdpsnd_schedule_thread(void* arg)
 {
-       STREAM* data;
        wMessage message;
+       UINT16 wTimeDiff;
        UINT16 wTimeStamp;
        UINT16 wCurrentTime;
-       rdpsndPlugin* rdpsnd = (rdpsndPlugin*) plugin;
+       RDPSND_WAVE* wave;
+       rdpsndPlugin* rdpsnd = (rdpsndPlugin*) arg;
 
-       while (MessageQueue_Peek(rdpsnd->OutQueue, &message, FALSE))
+       while (1)
        {
+               if (!MessageQueue_Wait(rdpsnd->queue))
+                       break;
+
+               if (!MessageQueue_Peek(rdpsnd->queue, &message, TRUE))
+                       break;
+
                if (message.id == WMQ_QUIT)
                        break;
 
-               wTimeStamp = (UINT16) (size_t) message.lParam;
+               wave = (RDPSND_WAVE*) message.wParam;
                wCurrentTime = (UINT16) GetTickCount();
+               wTimeStamp = wave->wLocalTimeB;
 
                if (wCurrentTime <= wTimeStamp)
-                       break;
+               {
+                       wTimeDiff = wTimeStamp - wCurrentTime;
+                       Sleep(wTimeDiff);
+               }
+
+               rdpsnd_send_wave_confirm_pdu(rdpsnd, wave->wTimeStampB, wave->cBlockNo);
+               free(wave);
+       }
+
+       return NULL;
+}
+
+void rdpsnd_send_quality_mode_pdu(rdpsndPlugin* rdpsnd)
+{
+       STREAM* pdu;
+
+       pdu = stream_new(8);
+       stream_write_BYTE(pdu, SNDC_QUALITYMODE); /* msgType */
+       stream_write_BYTE(pdu, 0); /* bPad */
+       stream_write_UINT16(pdu, 4); /* BodySize */
+       stream_write_UINT16(pdu, HIGH_QUALITY); /* wQualityMode */
+       stream_write_UINT16(pdu, 0); /* Reserved */
+
+       svc_plugin_send((rdpSvcPlugin*) rdpsnd, pdu);
+}
+
+void rdpsnd_free_audio_formats(AUDIO_FORMAT* formats, UINT16 count)
+{
+       int index;
+       AUDIO_FORMAT* format;
 
-               if (MessageQueue_Peek(rdpsnd->OutQueue, &message, TRUE))
+       if (formats)
+       {
+               for (index = 0; index < (int) count; index++)
                {
-                       data = (STREAM*) message.wParam;
-                       svc_plugin_send(plugin, data);
+                       format = &formats[index];
 
-                       DEBUG_SVC("processed output data");
+                       if (format->cbSize)
+                               free(format->data);
                }
+
+               free(formats);
        }
+}
 
-       if (rdpsnd->is_open && (rdpsnd->close_timestamp > 0))
+char* rdpsnd_get_audio_tag_string(UINT16 wFormatTag)
+{
+       switch (wFormatTag)
        {
-               if (GetTickCount() > rdpsnd->close_timestamp)
-               {
-                       if (rdpsnd->device)
-                               IFCALL(rdpsnd->device->Close, rdpsnd->device);
+               case WAVE_FORMAT_PCM:
+                       return "WAVE_FORMAT_PCM";
 
-                       rdpsnd->is_open = FALSE;
-                       rdpsnd->close_timestamp = 0;
+               case WAVE_FORMAT_ADPCM:
+                       return "WAVE_FORMAT_ADPCM";
 
-                       DEBUG_SVC("processed close");
-               }
+               case WAVE_FORMAT_ALAW:
+                       return "WAVE_FORMAT_ALAW";
+
+               case WAVE_FORMAT_MULAW:
+                       return "WAVE_FORMAT_MULAW";
+
+               case WAVE_FORMAT_DVI_ADPCM:
+                       return "WAVE_FORMAT_DVI_ADPCM";
        }
 
-       if ((MessageQueue_Size(rdpsnd->OutQueue) == 0) && !rdpsnd->is_open)
-               rdpsnd->plugin.interval_ms = 0;
+       return "WAVE_FORMAT_UNKNOWN";
 }
 
-static void rdpsnd_free_supported_formats(rdpsndPlugin* rdpsnd)
+void rdpsnd_print_audio_format(AUDIO_FORMAT* format)
 {
-       UINT16 i;
+       printf("%s: wFormatTag: 0x%04X nChannels: %d nSamplesPerSec: %d nAvgBytesPerSec: %d nBlockAlign: %d wBitsPerSample: %d\n",
+                       rdpsnd_get_audio_tag_string(format->wFormatTag), format->wFormatTag,
+                       format->nChannels, format->nSamplesPerSec, format->nAvgBytesPerSec,
+                       format->nBlockAlign, format->wBitsPerSample);
+}
+
+UINT32 rdpsnd_compute_audio_time_length(AUDIO_FORMAT* format, int size)
+{
+       UINT32 mstime;
+       UINT32 wSamples;
 
-       for (i = 0; i < rdpsnd->n_supported_formats; i++)
-               free(rdpsnd->supported_formats[i].data);
+       /**
+        * [MSDN-AUDIOFORMAT]:
+        * http://msdn.microsoft.com/en-us/library/ms713497.aspx
+        */
 
-       free(rdpsnd->supported_formats);
+       wSamples = (size * 8) / format->wBitsPerSample;
+       mstime = (((wSamples * 1000) / format->nSamplesPerSec) / format->nChannels);
 
-       rdpsnd->supported_formats = NULL;
-       rdpsnd->n_supported_formats = 0;
+       return mstime;
 }
 
-/* receives a list of server supported formats and returns a list
-   of client supported formats */
-static void rdpsnd_process_message_formats(rdpsndPlugin* rdpsnd, STREAM* data_in)
+void rdpsnd_select_supported_audio_formats(rdpsndPlugin* rdpsnd)
 {
-       UINT32 dwVolume;
-       UINT16 dwVolumeLeft;
-       UINT16 dwVolumeRight;
-       UINT16 wNumberOfFormats;
-       UINT16 nFormat;
-       UINT16 wVersion;
-       STREAM* data_out;
-       rdpsndFormat* out_formats;
-       UINT16 n_out_formats;
-       rdpsndFormat* format;
-       BYTE* format_mark;
-       BYTE* data_mark;
-       int pos;
-
-       rdpsnd_free_supported_formats(rdpsnd);
-
-       stream_seek_UINT32(data_in); /* dwFlags */
-       stream_seek_UINT32(data_in); /* dwVolume */
-       stream_seek_UINT32(data_in); /* dwPitch */
-       stream_seek_UINT16(data_in); /* wDGramPort */
-       stream_read_UINT16(data_in, wNumberOfFormats);
-       stream_read_BYTE(data_in, rdpsnd->cBlockNo); /* cLastBlockConfirmed */
-       stream_read_UINT16(data_in, wVersion);
-       stream_seek_BYTE(data_in); /* bPad */
-
-       DEBUG_SVC("wNumberOfFormats %d wVersion %d", wNumberOfFormats, wVersion);
-
-       if (wNumberOfFormats < 1)
-       {
-               DEBUG_WARN("wNumberOfFormats is 0");
-               return;
-       }
+       int index;
+       AUDIO_FORMAT* serverFormat;
+       AUDIO_FORMAT* clientFormat;
 
-       out_formats = (rdpsndFormat*) malloc(wNumberOfFormats * sizeof(rdpsndFormat));
-       ZeroMemory(out_formats, wNumberOfFormats * sizeof(rdpsndFormat));
-       n_out_formats = 0;
+       rdpsnd_free_audio_formats(rdpsnd->ClientFormats, rdpsnd->NumberOfClientFormats);
+       rdpsnd->NumberOfClientFormats = 0;
+       rdpsnd->ClientFormats = NULL;
 
-       dwVolumeLeft = (0xFFFF / 2); /* 50% ? */
-       dwVolumeRight = (0xFFFF / 2); /* 50% ? */
-       dwVolume = (dwVolumeLeft << 16) | dwVolumeRight;
+       rdpsnd->ClientFormats = (AUDIO_FORMAT*) malloc(sizeof(AUDIO_FORMAT) * rdpsnd->NumberOfServerFormats);
 
-       data_out = stream_new(24);
-       stream_write_BYTE(data_out, SNDC_FORMATS); /* msgType */
-       stream_write_BYTE(data_out, 0); /* bPad */
-       stream_seek_UINT16(data_out); /* BodySize */
-       stream_write_UINT32(data_out, TSSNDCAPS_ALIVE | TSSNDCAPS_VOLUME); /* dwFlags */
-       stream_write_UINT32(data_out, dwVolume); /* dwVolume */
-       stream_write_UINT32(data_out, 0); /* dwPitch */
-       stream_write_UINT16_be(data_out, 0); /* wDGramPort */
-       stream_seek_UINT16(data_out); /* wNumberOfFormats */
-       stream_write_BYTE(data_out, 0); /* cLastBlockConfirmed */
-       stream_write_UINT16(data_out, 6); /* wVersion */
-       stream_write_BYTE(data_out, 0); /* bPad */
-
-       for (nFormat = 0; nFormat < wNumberOfFormats; nFormat++)
+       for (index = 0; index < (int) rdpsnd->NumberOfServerFormats; index++)
        {
-               stream_get_mark(data_in, format_mark);
-               format = &out_formats[n_out_formats];
-               stream_read_UINT16(data_in, format->wFormatTag);
-               stream_read_UINT16(data_in, format->nChannels);
-               stream_read_UINT32(data_in, format->nSamplesPerSec);
-               stream_seek_UINT32(data_in); /* nAvgBytesPerSec */
-               stream_read_UINT16(data_in, format->nBlockAlign);
-               stream_read_UINT16(data_in, format->wBitsPerSample);
-               stream_read_UINT16(data_in, format->cbSize);
-               stream_get_mark(data_in, data_mark);
-               stream_seek(data_in, format->cbSize);
-               format->data = NULL;
-
-               DEBUG_SVC("wFormatTag=%d nChannels=%d nSamplesPerSec=%d nBlockAlign=%d wBitsPerSample=%d",
-                       format->wFormatTag, format->nChannels, format->nSamplesPerSec,
-                       format->nBlockAlign, format->wBitsPerSample);
+               serverFormat = &rdpsnd->ServerFormats[index];
 
-               if (rdpsnd->fixed_format > 0 && rdpsnd->fixed_format != format->wFormatTag)
+               if (rdpsnd->fixedFormat > 0 && (rdpsnd->fixedFormat != serverFormat->wFormatTag))
                        continue;
 
-               if (rdpsnd->fixed_channel > 0 && rdpsnd->fixed_channel != format->nChannels)
+               if (rdpsnd->fixedChannel > 0 && (rdpsnd->fixedChannel != serverFormat->nChannels))
                        continue;
 
-               if (rdpsnd->fixed_rate > 0 && rdpsnd->fixed_rate != format->nSamplesPerSec)
+               if (rdpsnd->fixedRate > 0 && (rdpsnd->fixedRate != serverFormat->nSamplesPerSec))
                        continue;
 
-               if (rdpsnd->device && rdpsnd->device->FormatSupported(rdpsnd->device, format))
+               if (rdpsnd->device && rdpsnd->device->FormatSupported(rdpsnd->device, serverFormat))
                {
-                       DEBUG_SVC("format supported.");
+                       clientFormat = &rdpsnd->ClientFormats[rdpsnd->NumberOfClientFormats++];
 
-                       stream_check_size(data_out, 18 + format->cbSize);
-                       stream_write(data_out, format_mark, 18 + format->cbSize);
+                       CopyMemory(clientFormat, serverFormat, sizeof(AUDIO_FORMAT));
+                       clientFormat->cbSize = 0;
 
-                       if (format->cbSize > 0)
+                       if (serverFormat->cbSize > 0)
                        {
-                               format->data = malloc(format->cbSize);
-                               CopyMemory(format->data, data_mark, format->cbSize);
+                               clientFormat->data = (BYTE*) malloc(serverFormat->cbSize);
+                               CopyMemory(clientFormat->data, serverFormat->data, serverFormat->cbSize);
+                               clientFormat->cbSize = serverFormat->cbSize;
                        }
-
-                       n_out_formats++;
                }
        }
+}
 
-       rdpsnd->n_supported_formats = n_out_formats;
+void rdpsnd_send_client_audio_formats(rdpsndPlugin* rdpsnd)
+{
+       int index;
+       STREAM* pdu;
+       UINT16 length;
+       UINT32 dwVolume;
+       UINT16 dwVolumeLeft;
+       UINT16 dwVolumeRight;
+       UINT16 wNumberOfFormats;
+       AUDIO_FORMAT* clientFormat;
+
+       dwVolumeLeft = (0xFFFF); /* 100% */
+       dwVolumeRight = (0xFFFF); /* 100% */
+       dwVolume = (dwVolumeLeft << 16) | dwVolumeRight;
+
+       wNumberOfFormats = rdpsnd->NumberOfClientFormats;
 
-       if (n_out_formats > 0)
+       length = 4 + 20;
+
+       for (index = 0; index < (int) wNumberOfFormats; index++)
+               length += (18 + rdpsnd->ClientFormats[index].cbSize);
+
+       pdu = stream_new(length);
+
+       stream_write_BYTE(pdu, SNDC_FORMATS); /* msgType */
+       stream_write_BYTE(pdu, 0); /* bPad */
+       stream_write_UINT16(pdu, length - 4); /* BodySize */
+
+       stream_write_UINT32(pdu, TSSNDCAPS_ALIVE | TSSNDCAPS_VOLUME); /* dwFlags */
+       stream_write_UINT32(pdu, dwVolume); /* dwVolume */
+       stream_write_UINT32(pdu, 0); /* dwPitch */
+       stream_write_UINT16(pdu, 0); /* wDGramPort */
+       stream_write_UINT16(pdu, wNumberOfFormats); /* wNumberOfFormats */
+       stream_write_BYTE(pdu, 0); /* cLastBlockConfirmed */
+       stream_write_UINT16(pdu, 6); /* wVersion */
+       stream_write_BYTE(pdu, 0); /* bPad */
+
+       for (index = 0; index < (int) wNumberOfFormats; index++)
        {
-               rdpsnd->supported_formats = out_formats;
+               clientFormat = &rdpsnd->ClientFormats[index];
+
+               stream_write_UINT16(pdu, clientFormat->wFormatTag);
+               stream_write_UINT16(pdu, clientFormat->nChannels);
+               stream_write_UINT32(pdu, clientFormat->nSamplesPerSec);
+               stream_write_UINT32(pdu, clientFormat->nAvgBytesPerSec);
+               stream_write_UINT16(pdu, clientFormat->nBlockAlign);
+               stream_write_UINT16(pdu, clientFormat->wBitsPerSample);
+               stream_write_UINT16(pdu, clientFormat->cbSize);
+
+               if (clientFormat->cbSize > 0)
+                       stream_write(pdu, clientFormat->data, clientFormat->cbSize);
        }
-       else
+
+       svc_plugin_send((rdpSvcPlugin*) rdpsnd, pdu);
+}
+
+void rdpsnd_recv_server_audio_formats_pdu(rdpsndPlugin* rdpsnd, STREAM* s)
+{
+       int index;
+       UINT16 wVersion;
+       AUDIO_FORMAT* format;
+       UINT16 wNumberOfFormats;
+
+       rdpsnd_free_audio_formats(rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
+       rdpsnd->NumberOfServerFormats = 0;
+       rdpsnd->ServerFormats = NULL;
+
+       stream_seek_UINT32(s); /* dwFlags */
+       stream_seek_UINT32(s); /* dwVolume */
+       stream_seek_UINT32(s); /* dwPitch */
+       stream_seek_UINT16(s); /* wDGramPort */
+       stream_read_UINT16(s, wNumberOfFormats);
+       stream_read_BYTE(s, rdpsnd->cBlockNo); /* cLastBlockConfirmed */
+       stream_read_UINT16(s, wVersion); /* wVersion */
+       stream_seek_BYTE(s); /* bPad */
+
+       rdpsnd->NumberOfServerFormats = wNumberOfFormats;
+       rdpsnd->ServerFormats = (AUDIO_FORMAT*) malloc(sizeof(AUDIO_FORMAT) * wNumberOfFormats);
+
+       for (index = 0; index < (int) wNumberOfFormats; index++)
        {
-               free(out_formats);
-               DEBUG_WARN("no formats supported");
+               format = &rdpsnd->ServerFormats[index];
+
+               stream_read_UINT16(s, format->wFormatTag); /* wFormatTag */
+               stream_read_UINT16(s, format->nChannels); /* nChannels */
+               stream_read_UINT32(s, format->nSamplesPerSec); /* nSamplesPerSec */
+               stream_read_UINT32(s, format->nAvgBytesPerSec); /* nAvgBytesPerSec */
+               stream_read_UINT16(s, format->nBlockAlign); /* nBlockAlign */
+               stream_read_UINT16(s, format->wBitsPerSample); /* wBitsPerSample */
+               stream_read_UINT16(s, format->cbSize); /* cbSize */
+
+               format->data = (BYTE*) malloc(format->cbSize);
+               stream_read(s, format->data, format->cbSize);
        }
 
-       pos = stream_get_pos(data_out);
-       stream_set_pos(data_out, 2);
-       stream_write_UINT16(data_out, pos - 4);
-       stream_set_pos(data_out, 18);
-       stream_write_UINT16(data_out, n_out_formats);
-       stream_set_pos(data_out, pos);
+       rdpsnd_select_supported_audio_formats(rdpsnd);
 
-       svc_plugin_send((rdpSvcPlugin*) rdpsnd, data_out);
+       rdpsnd_send_client_audio_formats(rdpsnd);
 
        if (wVersion >= 6)
-       {
-               data_out = stream_new(8);
-               stream_write_BYTE(data_out, SNDC_QUALITYMODE); /* msgType */
-               stream_write_BYTE(data_out, 0); /* bPad */
-               stream_write_UINT16(data_out, 4); /* BodySize */
-               stream_write_UINT16(data_out, HIGH_QUALITY); /* wQualityMode */
-               stream_write_UINT16(data_out, 0); /* Reserved */
-
-               svc_plugin_send((rdpSvcPlugin*) rdpsnd, data_out);
-       }
+               rdpsnd_send_quality_mode_pdu(rdpsnd);
+}
+
+void rdpsnd_send_training_confirm_pdu(rdpsndPlugin* rdpsnd, UINT16 wTimeStamp, UINT16 wPackSize)
+{
+       STREAM* pdu;
+
+       pdu = stream_new(8);
+       stream_write_BYTE(pdu, SNDC_TRAINING); /* msgType */
+       stream_write_BYTE(pdu, 0); /* bPad */
+       stream_write_UINT16(pdu, 4); /* BodySize */
+       stream_write_UINT16(pdu, wTimeStamp);
+       stream_write_UINT16(pdu, wPackSize);
+
+       svc_plugin_send((rdpSvcPlugin*) rdpsnd, pdu);
 }
 
-/* server is getting a feel of the round trip time */
-static void rdpsnd_process_message_training(rdpsndPlugin* rdpsnd, STREAM* data_in)
+static void rdpsnd_recv_training_pdu(rdpsndPlugin* rdpsnd, STREAM* s)
 {
        UINT16 wTimeStamp;
        UINT16 wPackSize;
-       STREAM* data_out;
 
-       stream_read_UINT16(data_in, wTimeStamp);
-       stream_read_UINT16(data_in, wPackSize);
+       stream_read_UINT16(s, wTimeStamp);
+       stream_read_UINT16(s, wPackSize);
 
-       data_out = stream_new(8);
-       stream_write_BYTE(data_out, SNDC_TRAINING); /* msgType */
-       stream_write_BYTE(data_out, 0); /* bPad */
-       stream_write_UINT16(data_out, 4); /* BodySize */
-       stream_write_UINT16(data_out, wTimeStamp);
-       stream_write_UINT16(data_out, wPackSize);
-
-       svc_plugin_send((rdpSvcPlugin*) rdpsnd, data_out);
+       rdpsnd_send_training_confirm_pdu(rdpsnd, wTimeStamp, wPackSize);
 }
 
-static void rdpsnd_process_message_wave_info(rdpsndPlugin* rdpsnd, STREAM* data_in, UINT16 BodySize)
+static void rdpsnd_recv_wave_info_pdu(rdpsndPlugin* rdpsnd, STREAM* s, UINT16 BodySize)
 {
        UINT16 wFormatNo;
+       AUDIO_FORMAT* format;
 
-       stream_read_UINT16(data_in, rdpsnd->wTimeStamp);
-       stream_read_UINT16(data_in, wFormatNo);
-       stream_read_BYTE(data_in, rdpsnd->cBlockNo);
-       stream_seek(data_in, 3); /* bPad */
-       stream_read(data_in, rdpsnd->waveData, 4);
-
-       rdpsnd->waveDataSize = BodySize - 8;
-       rdpsnd->wave_timestamp = GetTickCount();
        rdpsnd->expectingWave = TRUE;
 
-       DEBUG_SVC("waveDataSize %d wFormatNo %d", rdpsnd->waveDataSize, wFormatNo);
+       stream_read_UINT16(s, rdpsnd->wTimeStamp);
+       stream_read_UINT16(s, wFormatNo);
+       stream_read_BYTE(s, rdpsnd->cBlockNo);
+       stream_seek(s, 3); /* bPad */
+       stream_read(s, rdpsnd->waveData, 4);
+
+       rdpsnd->waveDataSize = BodySize - 8;
 
-       rdpsnd->close_timestamp = 0;
+       format = &rdpsnd->ClientFormats[wFormatNo];
 
-       if (!rdpsnd->is_open)
+       if (!rdpsnd->isOpen)
        {
-               rdpsnd->current_format = wFormatNo;
-               rdpsnd->is_open = TRUE;
+               rdpsnd->isOpen = TRUE;
+               rdpsnd->wCurrentFormatNo = wFormatNo;
 
                if (rdpsnd->device)
                {
-                       IFCALL(rdpsnd->device->Open, rdpsnd->device, &rdpsnd->supported_formats[wFormatNo],
-                               rdpsnd->latency);
+                       IFCALL(rdpsnd->device->Open, rdpsnd->device, format, rdpsnd->latency);
                }
        }
-       else if (wFormatNo != rdpsnd->current_format)
+       else if (wFormatNo != rdpsnd->wCurrentFormatNo)
        {
-               rdpsnd->current_format = wFormatNo;
+               rdpsnd->wCurrentFormatNo = wFormatNo;
 
                if (rdpsnd->device)
                {
-                       IFCALL(rdpsnd->device->SetFormat, rdpsnd->device, &rdpsnd->supported_formats[wFormatNo],
-                               rdpsnd->latency);
+                       IFCALL(rdpsnd->device->SetFormat, rdpsnd->device, format, rdpsnd->latency);
                }
        }
 }
 
-/* header is not removed from data in this function */
-static void rdpsnd_process_message_wave(rdpsndPlugin* rdpsnd, STREAM* data_in)
+void rdpsnd_send_wave_confirm_pdu(rdpsndPlugin* rdpsnd, UINT16 wTimeStamp, BYTE cConfirmedBlockNo)
 {
-       STREAM* data;
-       UINT32 delay_ms;
-       UINT16 wTimeStamp;
+       STREAM* pdu;
 
-       rdpsnd->expectingWave = 0;
+       pdu = stream_new(8);
+       stream_write_BYTE(pdu, SNDC_WAVECONFIRM);
+       stream_write_BYTE(pdu, 0);
+       stream_write_UINT16(pdu, 4);
+       stream_write_UINT16(pdu, wTimeStamp);
+       stream_write_BYTE(pdu, cConfirmedBlockNo); /* cConfirmedBlockNo */
+       stream_write_BYTE(pdu, 0); /* bPad */
 
-       CopyMemory(stream_get_head(data_in), rdpsnd->waveData, 4);
+       svc_plugin_send((rdpSvcPlugin*) rdpsnd, pdu);
+}
 
-       if (stream_get_size(data_in) != rdpsnd->waveDataSize)
-       {
-               DEBUG_WARN("size error");
-               return;
-       }
+void rdpsnd_device_send_wave_confirm_pdu(rdpsndDevicePlugin* device, RDPSND_WAVE* wave)
+{
+       MessageQueue_Post(device->rdpsnd->queue, NULL, 0, (void*) wave, NULL);
+}
 
-       if (rdpsnd->device)
-       {
-               IFCALL(rdpsnd->device->Play, rdpsnd->device, stream_get_head(data_in), stream_get_size(data_in));
-       }
+static void rdpsnd_recv_wave_pdu(rdpsndPlugin* rdpsnd, STREAM* s)
+{
+       int size;
+       BYTE* data;
+       RDPSND_WAVE* wave;
+       AUDIO_FORMAT* format;
 
-       delay_ms = 250;
-       wTimeStamp = rdpsnd->wTimeStamp + delay_ms;
+       rdpsnd->expectingWave = FALSE;
 
-       DEBUG_SVC("data_size %d delay_ms %u process_ms %u",
-               stream_get_size(data_in), delay_ms, process_ms);
+       /**
+        * The Wave PDU is a special case: it is always sent after a Wave Info PDU,
+        * and we do not process its header. Instead, the header is pad that needs
+        * to be filled with the first four bytes of the audio sample data sent as
+        * part of the preceding Wave Info PDU.
+        */
 
-       data = stream_new(8);
-       stream_write_BYTE(data, SNDC_WAVECONFIRM);
-       stream_write_BYTE(data, 0);
-       stream_write_UINT16(data, 4);
-       stream_write_UINT16(data, wTimeStamp);
-       stream_write_BYTE(data, rdpsnd->cBlockNo); /* cConfirmedBlockNo */
-       stream_write_BYTE(data, 0); /* bPad */
+       CopyMemory(stream_get_head(s), rdpsnd->waveData, 4);
 
-       wTimeStamp = rdpsnd->wave_timestamp + delay_ms;
-       MessageQueue_Post(rdpsnd->OutQueue, NULL, 0, (void*) data, (void*) (size_t) wTimeStamp);
+       data = stream_get_head(s);
+       size = stream_get_size(s);
 
-       rdpsnd->plugin.interval_ms = 10;
+       wave = (RDPSND_WAVE*) malloc(sizeof(RDPSND_WAVE));
+
+       wave->wLocalTimeA = GetTickCount();
+       wave->wTimeStampA = rdpsnd->wTimeStamp;
+       wave->wFormatNo = rdpsnd->wCurrentFormatNo;
+       wave->cBlockNo = rdpsnd->cBlockNo;
+
+       wave->data = data;
+       wave->length = size;
+
+       format = &rdpsnd->ClientFormats[rdpsnd->wCurrentFormatNo];
+       wave->wAudioLength = rdpsnd_compute_audio_time_length(format, size);
+
+       if (!rdpsnd->device)
+               return;
+
+       if (rdpsnd->device->WaveDecode)
+       {
+               IFCALL(rdpsnd->device->WaveDecode, rdpsnd->device, wave);
+       }
+
+       if (rdpsnd->device->WavePlay)
+       {
+               IFCALL(rdpsnd->device->WavePlay, rdpsnd->device, wave);
+       }
+       else
+       {
+               IFCALL(rdpsnd->device->Play, rdpsnd->device, data, size);
+       }
+
+       if (!rdpsnd->device->WavePlay)
+       {
+               wave->wTimeStampB = rdpsnd->wTimeStamp + wave->wAudioLength + TIME_DELAY_MS;
+               wave->wLocalTimeB = wave->wLocalTimeA + wave->wAudioLength + TIME_DELAY_MS;
+               rdpsnd->device->WaveConfirm(rdpsnd->device, wave);
+       }
 }
 
-static void rdpsnd_process_message_close(rdpsndPlugin* rdpsnd)
+static void rdpsnd_recv_close_pdu(rdpsndPlugin* rdpsnd)
 {
        DEBUG_SVC("server closes.");
 
        if (rdpsnd->device)
        {
-               IFCALL(rdpsnd->device->Start, rdpsnd->device);
+               IFCALL(rdpsnd->device->Close, rdpsnd->device);
        }
 
-       rdpsnd->close_timestamp = GetTickCount() + 2000;
-       rdpsnd->plugin.interval_ms = 10;
+       rdpsnd->isOpen = FALSE;
 }
 
-static void rdpsnd_process_message_setvolume(rdpsndPlugin* rdpsnd, STREAM* data_in)
+static void rdpsnd_recv_volume_pdu(rdpsndPlugin* rdpsnd, STREAM* s)
 {
        UINT32 dwVolume;
 
-       stream_read_UINT32(data_in, dwVolume);
+       stream_read_UINT32(s, dwVolume);
        DEBUG_SVC("dwVolume 0x%X", dwVolume);
 
        if (rdpsnd->device)
@@ -403,45 +513,45 @@ static void rdpsnd_process_message_setvolume(rdpsndPlugin* rdpsnd, STREAM* data_
        }
 }
 
-static void rdpsnd_process_receive(rdpSvcPlugin* plugin, STREAM* data_in)
+static void rdpsnd_recv_pdu(rdpSvcPlugin* plugin, STREAM* s)
 {
-       rdpsndPlugin* rdpsnd = (rdpsndPlugin*)plugin;
        BYTE msgType;
        UINT16 BodySize;
+       rdpsndPlugin* rdpsnd = (rdpsndPlugin*) plugin;
 
        if (rdpsnd->expectingWave)
        {
-               rdpsnd_process_message_wave(rdpsnd, data_in);
-               stream_free(data_in);
+               rdpsnd_recv_wave_pdu(rdpsnd, s);
+               stream_free(s);
                return;
        }
 
-       stream_read_BYTE(data_in, msgType); /* msgType */
-       stream_seek_BYTE(data_in); /* bPad */
-       stream_read_UINT16(data_in, BodySize);
+       stream_read_BYTE(s, msgType); /* msgType */
+       stream_seek_BYTE(s); /* bPad */
+       stream_read_UINT16(s, BodySize);
 
-       DEBUG_SVC("msgType %d BodySize %d", msgType, BodySize);
+       //printf("msgType %d BodySize %d\n", msgType, BodySize);
 
        switch (msgType)
        {
                case SNDC_FORMATS:
-                       rdpsnd_process_message_formats(rdpsnd, data_in);
+                       rdpsnd_recv_server_audio_formats_pdu(rdpsnd, s);
                        break;
 
                case SNDC_TRAINING:
-                       rdpsnd_process_message_training(rdpsnd, data_in);
+                       rdpsnd_recv_training_pdu(rdpsnd, s);
                        break;
 
                case SNDC_WAVE:
-                       rdpsnd_process_message_wave_info(rdpsnd, data_in, BodySize);
+                       rdpsnd_recv_wave_info_pdu(rdpsnd, s, BodySize);
                        break;
 
                case SNDC_CLOSE:
-                       rdpsnd_process_message_close(rdpsnd);
+                       rdpsnd_recv_close_pdu(rdpsnd);
                        break;
 
                case SNDC_SETVOLUME:
-                       rdpsnd_process_message_setvolume(rdpsnd, data_in);
+                       rdpsnd_recv_volume_pdu(rdpsnd, s);
                        break;
 
                default:
@@ -449,7 +559,7 @@ static void rdpsnd_process_receive(rdpSvcPlugin* plugin, STREAM* data_in)
                        break;
        }
 
-       stream_free(data_in);
+       stream_free(s);
 }
 
 static void rdpsnd_register_device_plugin(rdpsndPlugin* rdpsnd, rdpsndDevicePlugin* device)
@@ -459,7 +569,11 @@ static void rdpsnd_register_device_plugin(rdpsndPlugin* rdpsnd, rdpsndDevicePlug
                DEBUG_WARN("existing device, abort.");
                return;
        }
+
        rdpsnd->device = device;
+       device->rdpsnd = rdpsnd;
+
+       device->WaveConfirm = rdpsnd_device_send_wave_confirm_pdu;
 }
 
 static BOOL rdpsnd_load_device_plugin(rdpsndPlugin* rdpsnd, const char* name, ADDIN_ARGV* args)
@@ -469,7 +583,7 @@ static BOOL rdpsnd_load_device_plugin(rdpsndPlugin* rdpsnd, const char* name, AD
 
        entry = (PFREERDP_RDPSND_DEVICE_ENTRY) freerdp_load_channel_addin_entry("rdpsnd", (LPSTR) name, NULL, 0);
 
-       if (entry == NULL)
+       if (!entry)
                return FALSE;
 
        entryPoints.rdpsnd = rdpsnd;
@@ -542,15 +656,15 @@ static void rdpsnd_process_addin_args(rdpsndPlugin* rdpsnd, ADDIN_ARGV* args)
                }
                CommandLineSwitchCase(arg, "format")
                {
-                       rdpsnd->fixed_format = atoi(arg->Value);
+                       rdpsnd->fixedFormat = atoi(arg->Value);
                }
                CommandLineSwitchCase(arg, "rate")
                {
-                       rdpsnd->fixed_rate = atoi(arg->Value);
+                       rdpsnd->fixedRate = atoi(arg->Value);
                }
                CommandLineSwitchCase(arg, "channel")
                {
-                       rdpsnd->fixed_channel = atoi(arg->Value);
+                       rdpsnd->fixedChannel = atoi(arg->Value);
                }
                CommandLineSwitchCase(arg, "latency")
                {
@@ -573,11 +687,9 @@ static void rdpsnd_process_connect(rdpSvcPlugin* plugin)
 
        DEBUG_SVC("connecting");
 
-       plugin->interval_callback = rdpsnd_process_interval;
-
        rdpsnd->latency = -1;
-
-       rdpsnd->OutQueue = MessageQueue_New();
+       rdpsnd->queue = MessageQueue_New();
+       rdpsnd->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) rdpsnd_schedule_thread, (void*) plugin, 0, NULL);
 
        args = (ADDIN_ARGV*) plugin->channel_entry_points.pExtendedData;
 
@@ -620,9 +732,10 @@ static void rdpsnd_process_connect(rdpSvcPlugin* plugin)
                rdpsnd_load_device_plugin(rdpsnd, rdpsnd->subsystem, args);
        }
 
-       if (rdpsnd->device == NULL)
+       if (!rdpsnd->device)
        {
                DEBUG_WARN("no sound device.");
+               return;
        }
 }
 
@@ -638,7 +751,11 @@ static void rdpsnd_process_terminate(rdpSvcPlugin* plugin)
        if (rdpsnd->device)
                IFCALL(rdpsnd->device->Free, rdpsnd->device);
 
-       MessageQueue_Free(rdpsnd->OutQueue);
+       MessageQueue_PostQuit(rdpsnd->queue, 0);
+       WaitForSingleObject(rdpsnd->thread, INFINITE);
+
+       MessageQueue_Free(rdpsnd->queue);
+       CloseHandle(rdpsnd->thread);
 
        if (rdpsnd->subsystem)
                free(rdpsnd->subsystem);
@@ -646,9 +763,13 @@ static void rdpsnd_process_terminate(rdpSvcPlugin* plugin)
        if (rdpsnd->device_name)
                free(rdpsnd->device_name);
 
-       rdpsnd_free_supported_formats(rdpsnd);
+       rdpsnd_free_audio_formats(rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
+       rdpsnd->NumberOfServerFormats = 0;
+       rdpsnd->ServerFormats = NULL;
 
-       free(plugin);
+       rdpsnd_free_audio_formats(rdpsnd->ClientFormats, rdpsnd->NumberOfClientFormats);
+       rdpsnd->NumberOfClientFormats = 0;
+       rdpsnd->ClientFormats = NULL;
 }
 
 /* rdpsnd is always built-in */
@@ -668,10 +789,19 @@ int VirtualChannelEntry(PCHANNEL_ENTRY_POINTS pEntryPoints)
        strcpy(_p->plugin.channel_def.name, "rdpsnd");
 
        _p->plugin.connect_callback = rdpsnd_process_connect;
-       _p->plugin.receive_callback = rdpsnd_process_receive;
+       _p->plugin.receive_callback = rdpsnd_recv_pdu;
        _p->plugin.event_callback = rdpsnd_process_event;
        _p->plugin.terminate_callback = rdpsnd_process_terminate;
 
+#ifndef _WIN32
+       {
+               sigset_t mask;
+               sigemptyset(&mask);
+               sigaddset(&mask, SIGIO);
+               pthread_sigmask(SIG_BLOCK, &mask, NULL);
+       }
+#endif
+
        svc_plugin_init((rdpSvcPlugin*) _p, pEntryPoints);
 
        return 1;