changed: Improve (fallback) logic for subtitle downloading
[vuplus_xbmc] / xbmc / cores / AudioEngine / Sinks / AESinkPULSE.cpp
1 /*
2  *      Copyright (C) 2010-2013 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program 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 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20 #include "system.h"
21 #ifdef HAS_PULSEAUDIO
22 #include "AESinkPULSE.h"
23 #include "utils/log.h"
24 #include "Util.h"
25 #include "guilib/LocalizeStrings.h"
26
27 using namespace std;
28
29 static const char *ContextStateToString(pa_context_state s)
30 {
31   switch (s)
32   {
33     case PA_CONTEXT_UNCONNECTED:
34       return "unconnected";
35     case PA_CONTEXT_CONNECTING:
36       return "connecting";
37     case PA_CONTEXT_AUTHORIZING:
38       return "authorizing";
39     case PA_CONTEXT_SETTING_NAME:
40       return "setting name";
41     case PA_CONTEXT_READY:
42       return "ready";
43     case PA_CONTEXT_FAILED:
44       return "failed";
45     case PA_CONTEXT_TERMINATED:
46       return "terminated";
47     default:
48       return "none";
49   }
50 }
51
52 static const char *StreamStateToString(pa_stream_state s)
53 {
54   switch(s)
55   {
56     case PA_STREAM_UNCONNECTED:
57       return "unconnected";
58     case PA_STREAM_CREATING:
59       return "creating";
60     case PA_STREAM_READY:
61       return "ready";
62     case PA_STREAM_FAILED:
63       return "failed";
64     case PA_STREAM_TERMINATED:
65       return "terminated";
66     default:
67       return "none";
68   }
69 }
70
71 static pa_sample_format AEFormatToPulseFormat(AEDataFormat format)
72 {
73   switch (format)
74   {
75     case AE_FMT_U8    : return PA_SAMPLE_U8;
76     case AE_FMT_S16LE : return PA_SAMPLE_S16LE;
77     case AE_FMT_S16BE : return PA_SAMPLE_S16BE;
78     case AE_FMT_S16NE : return PA_SAMPLE_S16NE;
79     case AE_FMT_S24LE3: return PA_SAMPLE_S24LE;
80     case AE_FMT_S24BE3: return PA_SAMPLE_S24BE;
81     case AE_FMT_S24NE3: return PA_SAMPLE_S24NE;
82     case AE_FMT_S24LE4: return PA_SAMPLE_S24_32LE;
83     case AE_FMT_S24BE4: return PA_SAMPLE_S24_32BE;
84     case AE_FMT_S24NE4: return PA_SAMPLE_S24_32NE;
85     case AE_FMT_S32BE : return PA_SAMPLE_S32BE;
86     case AE_FMT_S32LE : return PA_SAMPLE_S32LE;
87     case AE_FMT_S32NE : return PA_SAMPLE_S32NE;
88     case AE_FMT_FLOAT : return PA_SAMPLE_FLOAT32;
89
90     case AE_FMT_AC3:
91     case AE_FMT_DTS:
92     case AE_FMT_EAC3:
93       return PA_SAMPLE_S16NE;
94
95     default:
96       return PA_SAMPLE_INVALID;
97   }
98 }
99
100 static pa_encoding AEFormatToPulseEncoding(AEDataFormat format)
101 {
102   switch (format)
103   {
104     case AE_FMT_AC3   : return PA_ENCODING_AC3_IEC61937;
105     case AE_FMT_DTS   : return PA_ENCODING_DTS_IEC61937;
106     case AE_FMT_EAC3  : return PA_ENCODING_EAC3_IEC61937;
107
108     default:
109       return PA_ENCODING_PCM;
110   }
111 }
112
113 static AEDataFormat defaultDataFormats[] = {
114   AE_FMT_U8,
115   AE_FMT_S16LE,
116   AE_FMT_S16BE,
117   AE_FMT_S16NE,
118   AE_FMT_S24LE3,
119   AE_FMT_S24BE3,
120   AE_FMT_S24NE3,
121   AE_FMT_S24LE4,
122   AE_FMT_S24BE4,
123   AE_FMT_S24NE4,
124   AE_FMT_S32BE,
125   AE_FMT_S32LE,
126   AE_FMT_S32NE,
127   AE_FMT_FLOAT
128 };
129
130 static unsigned int defaultSampleRates[] = {
131   5512,
132   8000,
133   11025,
134   16000,
135   22050,
136   32000,
137   44100,
138   48000,
139   64000,
140   88200,
141   96000,
142   176400,
143   192000,
144   384000
145 };
146
147 /* Static callback functions */
148
149 static void ContextStateCallback(pa_context *c, void *userdata)
150 {
151   pa_threaded_mainloop *m = (pa_threaded_mainloop *)userdata;
152   switch (pa_context_get_state(c))
153   {
154     case PA_CONTEXT_READY:
155     case PA_CONTEXT_TERMINATED:
156     case PA_CONTEXT_UNCONNECTED:
157     case PA_CONTEXT_CONNECTING:
158     case PA_CONTEXT_AUTHORIZING:
159     case PA_CONTEXT_SETTING_NAME:
160     case PA_CONTEXT_FAILED:
161       pa_threaded_mainloop_signal(m, 0);
162       break;
163   }
164 }
165
166 static void StreamStateCallback(pa_stream *s, void *userdata)
167 {
168   pa_threaded_mainloop *m = (pa_threaded_mainloop *)userdata;
169   switch (pa_stream_get_state(s))
170   {
171     case PA_STREAM_UNCONNECTED:
172     case PA_STREAM_CREATING:
173     case PA_STREAM_READY:
174     case PA_STREAM_FAILED:
175     case PA_STREAM_TERMINATED:
176       pa_threaded_mainloop_signal(m, 0);
177       break;
178   }
179 }
180
181 static void StreamRequestCallback(pa_stream *s, size_t length, void *userdata)
182 {
183   pa_threaded_mainloop *m = (pa_threaded_mainloop *)userdata;
184   pa_threaded_mainloop_signal(m, 0);
185 }
186
187 static void StreamLatencyUpdateCallback(pa_stream *s, void *userdata)
188 {
189   pa_threaded_mainloop *m = (pa_threaded_mainloop *)userdata;
190   pa_threaded_mainloop_signal(m, 0);
191 }
192 struct SinkInfoStruct
193 {
194   AEDeviceInfoList *list;
195   bool isHWDevice;
196   bool device_found;
197   pa_threaded_mainloop *mainloop;
198   SinkInfoStruct()
199   {
200     list = NULL;
201     isHWDevice = false;
202     device_found = true;
203     mainloop = NULL;
204   }
205 };
206
207 static void SinkInfoCallback(pa_context *c, const pa_sink_info *i, int eol, void *userdata)
208 {
209   SinkInfoStruct *sinkStruct = (SinkInfoStruct *)userdata;
210   if(i)
211   {
212     if (i->flags && (i->flags & PA_SINK_HARDWARE))
213       sinkStruct->isHWDevice = true;
214
215     sinkStruct->device_found = true;
216   }
217   pa_threaded_mainloop_signal(sinkStruct->mainloop, 0);
218 }
219
220 static AEChannel PAChannelToAEChannel(pa_channel_position_t channel)
221 {
222   AEChannel ae_channel;
223   switch (channel)
224   {
225     case PA_CHANNEL_POSITION_FRONT_LEFT:            ae_channel = AE_CH_FL; break;
226     case PA_CHANNEL_POSITION_FRONT_RIGHT:           ae_channel = AE_CH_FR; break;
227     case PA_CHANNEL_POSITION_FRONT_CENTER:          ae_channel = AE_CH_FC; break;
228     case PA_CHANNEL_POSITION_LFE:                   ae_channel = AE_CH_LFE; break;
229     case PA_CHANNEL_POSITION_REAR_LEFT:             ae_channel = AE_CH_BL; break;
230     case PA_CHANNEL_POSITION_REAR_RIGHT:            ae_channel = AE_CH_BR; break;
231     case PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER:  ae_channel = AE_CH_FLOC; break;
232     case PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: ae_channel = AE_CH_FROC; break;
233     case PA_CHANNEL_POSITION_REAR_CENTER:           ae_channel = AE_CH_BC; break;
234     case PA_CHANNEL_POSITION_SIDE_LEFT:             ae_channel = AE_CH_SL; break;
235     case PA_CHANNEL_POSITION_SIDE_RIGHT:            ae_channel = AE_CH_SR; break;
236     case PA_CHANNEL_POSITION_TOP_FRONT_LEFT:        ae_channel = AE_CH_TFL; break;
237     case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT:       ae_channel = AE_CH_TFR; break;
238     case PA_CHANNEL_POSITION_TOP_FRONT_CENTER:      ae_channel = AE_CH_TFC; break;
239     case PA_CHANNEL_POSITION_TOP_CENTER:            ae_channel = AE_CH_TC; break;
240     case PA_CHANNEL_POSITION_TOP_REAR_LEFT:         ae_channel = AE_CH_TBL; break;
241     case PA_CHANNEL_POSITION_TOP_REAR_RIGHT:        ae_channel = AE_CH_TBR; break;
242     case PA_CHANNEL_POSITION_TOP_REAR_CENTER:       ae_channel = AE_CH_TBC; break;
243     default:                                        ae_channel = AE_CH_NULL; break;
244   }
245   return ae_channel;
246 }
247
248 static pa_channel_position_t AEChannelToPAChannel(AEChannel ae_channel)
249 {
250   pa_channel_position_t pa_channel;
251   switch (ae_channel)
252   {
253     case AE_CH_FL:    pa_channel = PA_CHANNEL_POSITION_FRONT_LEFT; break;
254     case AE_CH_FR:    pa_channel = PA_CHANNEL_POSITION_FRONT_RIGHT; break;
255     case AE_CH_FC:    pa_channel = PA_CHANNEL_POSITION_FRONT_CENTER; break;
256     case AE_CH_LFE:   pa_channel = PA_CHANNEL_POSITION_LFE; break;
257     case AE_CH_BL:    pa_channel = PA_CHANNEL_POSITION_REAR_LEFT; break;
258     case AE_CH_BR:    pa_channel = PA_CHANNEL_POSITION_REAR_RIGHT; break;
259     case AE_CH_FLOC:  pa_channel = PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER; break;
260     case AE_CH_FROC:  pa_channel = PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER; break;
261     case AE_CH_BC:    pa_channel = PA_CHANNEL_POSITION_REAR_CENTER; break;
262     case AE_CH_SL:    pa_channel = PA_CHANNEL_POSITION_SIDE_LEFT; break;
263     case AE_CH_SR:    pa_channel = PA_CHANNEL_POSITION_SIDE_RIGHT; break;
264     case AE_CH_TFL:   pa_channel = PA_CHANNEL_POSITION_TOP_FRONT_LEFT; break;
265     case AE_CH_TFR:   pa_channel = PA_CHANNEL_POSITION_TOP_FRONT_RIGHT; break;
266     case AE_CH_TFC:   pa_channel = PA_CHANNEL_POSITION_TOP_FRONT_CENTER; break;
267     case AE_CH_TC:    pa_channel = PA_CHANNEL_POSITION_TOP_CENTER; break;
268     case AE_CH_TBL:   pa_channel = PA_CHANNEL_POSITION_TOP_REAR_LEFT; break;
269     case AE_CH_TBR:   pa_channel = PA_CHANNEL_POSITION_TOP_REAR_RIGHT; break;
270     case AE_CH_TBC:   pa_channel = PA_CHANNEL_POSITION_TOP_REAR_CENTER; break;
271     default:          pa_channel = PA_CHANNEL_POSITION_INVALID; break;
272   }
273   return pa_channel;
274 }
275
276 static pa_channel_map AEChannelMapToPAChannel(CAEChannelInfo info)
277 {
278   pa_channel_map map;
279   pa_channel_map_init(&map);
280   pa_channel_position_t pos;
281   for (unsigned int i = 0; i < info.Count(); ++i)
282   {
283     pos = AEChannelToPAChannel(info[i]);
284     if(pos != PA_CHANNEL_POSITION_INVALID)
285     {
286       // remember channel name and increase channel count
287       map.map[map.channels++] = pos;
288     }
289   }
290   return map;
291 }
292
293 static CAEChannelInfo PAChannelToAEChannelMap(pa_channel_map channels)
294 {
295   CAEChannelInfo info;
296   AEChannel ch;
297   info.Reset();
298   for (unsigned int i=0; i<channels.channels; i++)
299   {
300     ch = PAChannelToAEChannel(channels.map[i]);
301     if(ch != AE_CH_NULL)
302       info += ch;
303   }
304   return info;
305 }
306
307 static void SinkInfoRequestCallback(pa_context *c, const pa_sink_info *i, int eol, void *userdata)
308 {
309
310   SinkInfoStruct *sinkStruct = (SinkInfoStruct *)userdata;
311
312   if(sinkStruct && sinkStruct->list->empty())
313   {
314     //add a default device first
315     CAEDeviceInfo defaultDevice;
316     defaultDevice.m_deviceName = std::string("Default");
317     defaultDevice.m_displayName = std::string("Default");
318     defaultDevice.m_displayNameExtra = std::string("Default Output Device (PULSEAUDIO)");
319     defaultDevice.m_dataFormats.insert(defaultDevice.m_dataFormats.end(), defaultDataFormats, defaultDataFormats + sizeof(defaultDataFormats) / sizeof(defaultDataFormats[0]));
320     defaultDevice.m_channels = CAEChannelInfo(AE_CH_LAYOUT_2_0);
321     defaultDevice.m_sampleRates.assign(defaultSampleRates, defaultSampleRates + sizeof(defaultSampleRates) / sizeof(defaultSampleRates[0]));
322     defaultDevice.m_deviceType = AE_DEVTYPE_PCM;
323     sinkStruct->list->push_back(defaultDevice);
324   }
325   bool valid = true;
326   if (i && i->name)
327   {
328     CAEDeviceInfo device;
329
330     device.m_deviceName = string(i->name);
331     device.m_displayName = string(i->description);
332     if (i->active_port && i->active_port->description)
333       device.m_displayNameExtra = std::string((i->active_port->description)).append(" (PULSEAUDIO)");
334     else
335       device.m_displayNameExtra = std::string((i->description)).append(" (PULSEAUDIO)");
336     unsigned int device_type = AE_DEVTYPE_PCM; //0
337
338     device.m_channels = PAChannelToAEChannelMap(i->channel_map);
339
340     // Don't add devices that would not have a channel map
341     if(device.m_channels.Count() == 0)
342       valid = false;
343
344     device.m_sampleRates.assign(defaultSampleRates, defaultSampleRates + sizeof(defaultSampleRates) / sizeof(defaultSampleRates[0]));
345
346     for (unsigned int j = 0; j < i->n_formats; j++)
347     {
348       switch(i->formats[j]->encoding)
349       {
350         case PA_ENCODING_AC3_IEC61937:
351           device.m_dataFormats.push_back(AE_FMT_AC3);
352           device_type = AE_DEVTYPE_IEC958;
353           break;
354         case PA_ENCODING_DTS_IEC61937:
355           device.m_dataFormats.push_back(AE_FMT_DTS);
356           device_type = AE_DEVTYPE_IEC958;
357           break;
358         case PA_ENCODING_EAC3_IEC61937:
359           device.m_dataFormats.push_back(AE_FMT_EAC3);
360           device_type = AE_DEVTYPE_IEC958;
361           break;
362         case PA_ENCODING_PCM:
363           device.m_dataFormats.insert(device.m_dataFormats.end(), defaultDataFormats, defaultDataFormats + sizeof(defaultDataFormats) / sizeof(defaultDataFormats[0]));
364           break;
365         default:
366           break;
367       }
368     }
369     // passthrough is only working when device has Stereo channel config
370     if (device_type > AE_DEVTYPE_PCM && device.m_channels.Count() == 2)
371       device.m_deviceType = AE_DEVTYPE_IEC958;
372     else
373       device.m_deviceType = AE_DEVTYPE_PCM;
374     if(valid)
375     {
376       CLog::Log(LOGDEBUG, "PulseAudio: Found %s with devicestring %s", device.m_displayName.c_str(), device.m_deviceName.c_str());
377       sinkStruct->list->push_back(device);
378     }
379     else
380     {
381       CLog::Log(LOGDEBUG, "PulseAudio: Skipped %s with devicestring %s", device.m_displayName.c_str(), device.m_deviceName.c_str());
382     }
383  }
384   pa_threaded_mainloop_signal(sinkStruct->mainloop, 0);
385 }
386
387 /* PulseAudio class memberfunctions*/
388
389
390 CAESinkPULSE::CAESinkPULSE()
391 {
392   m_IsAllocated = false;
393   m_passthrough = false;
394   m_MainLoop = NULL;
395   m_BytesPerSecond = 0;
396   m_BufferSize = 0;
397   m_Channels = 0;
398   m_Stream = NULL;
399   m_Context = NULL;
400 }
401
402 CAESinkPULSE::~CAESinkPULSE()
403 {
404   Deinitialize();
405 }
406
407 bool CAESinkPULSE::Initialize(AEAudioFormat &format, std::string &device)
408 {
409   m_IsAllocated = false;
410   m_passthrough = false;
411   m_BytesPerSecond = 0;
412   m_BufferSize = 0;
413   m_Channels = 0;
414   m_Stream = NULL;
415   m_Context = NULL;
416
417   if (!SetupContext(NULL, &m_Context, &m_MainLoop))
418   {
419     CLog::Log(LOGNOTICE, "PulseAudio might not be running. Context was not created.");
420     Deinitialize();
421     return false;
422   }
423
424   pa_threaded_mainloop_lock(m_MainLoop);
425
426   struct pa_channel_map map;
427   pa_channel_map_init(&map);
428
429   m_passthrough = AE_IS_RAW(format.m_dataFormat);
430
431   if(m_passthrough)
432   {
433     map.channels = 2;
434     format.m_channelLayout = AE_CH_LAYOUT_2_0;
435   }
436   else
437   {
438     map = AEChannelMapToPAChannel(format.m_channelLayout);
439     // if count has changed we need to fit the AE Map
440     if(map.channels != format.m_channelLayout.Count())
441       format.m_channelLayout = PAChannelToAEChannelMap(map);
442   }
443   m_Channels = format.m_channelLayout.Count();
444
445   pa_cvolume_reset(&m_Volume, m_Channels);
446
447   pa_format_info *info[1];
448   info[0] = pa_format_info_new();
449   info[0]->encoding = AEFormatToPulseEncoding(format.m_dataFormat);
450   if(!m_passthrough)
451   {
452     pa_format_info_set_sample_format(info[0], AEFormatToPulseFormat(format.m_dataFormat));
453     pa_format_info_set_channel_map(info[0], &map);
454   }
455   pa_format_info_set_channels(info[0], m_Channels);
456
457   // PA requires m_encodedRate in order to do EAC3
458   unsigned int samplerate;
459   if (m_passthrough)
460   {
461     if (format.m_encodedRate == 0)
462     {
463       CLog::Log(LOGNOTICE, "PulseAudio: Passthrough in use but m_encodedRate is not set - fallback to m_sampleRate");
464       samplerate = format.m_sampleRate;
465     }
466     else
467       samplerate = format.m_encodedRate;
468   }
469   else
470     samplerate = format.m_sampleRate;
471
472   pa_format_info_set_rate(info[0], samplerate);
473
474   if (!pa_format_info_valid(info[0]))
475   {
476     CLog::Log(LOGERROR, "PulseAudio: Invalid format info");
477     pa_format_info_free(info[0]);
478     pa_threaded_mainloop_unlock(m_MainLoop);
479     Deinitialize();
480     return false;
481   }
482
483   pa_sample_spec spec;
484   #if PA_CHECK_VERSION(2,0,0)
485     pa_format_info_to_sample_spec(info[0], &spec, NULL);
486   #else
487     spec.rate = (AEFormatToPulseEncoding(format.m_dataFormat) == PA_ENCODING_EAC3_IEC61937) ? 4 * samplerate : samplerate;
488     spec.format = AEFormatToPulseFormat(format.m_dataFormat);
489     spec.channels = m_Channels;
490   #endif
491   if (!pa_sample_spec_valid(&spec))
492   {
493     CLog::Log(LOGERROR, "PulseAudio: Invalid sample spec");
494     pa_format_info_free(info[0]);
495     pa_threaded_mainloop_unlock(m_MainLoop);
496     Deinitialize();
497     return false;
498   }
499
500   m_BytesPerSecond = pa_bytes_per_second(&spec);
501   unsigned int frameSize = pa_frame_size(&spec);
502
503   m_Stream = pa_stream_new_extended(m_Context, "audio stream", info, 1, NULL);
504   pa_format_info_free(info[0]);
505
506   if (m_Stream == NULL)
507   {
508     CLog::Log(LOGERROR, "PulseAudio: Could not create a stream");
509     pa_threaded_mainloop_unlock(m_MainLoop);
510     Deinitialize();
511     return false;
512   }
513
514   pa_stream_set_state_callback(m_Stream, StreamStateCallback, m_MainLoop);
515   pa_stream_set_write_callback(m_Stream, StreamRequestCallback, m_MainLoop);
516   pa_stream_set_latency_update_callback(m_Stream, StreamLatencyUpdateCallback, m_MainLoop);
517
518   bool isDefaultDevice = (device == "Default");
519
520   pa_buffer_attr buffer_attr;
521   SinkInfoStruct sinkStruct;
522   sinkStruct.mainloop = m_MainLoop;
523   sinkStruct.isHWDevice = false;
524   sinkStruct.device_found = true; // needed to get default device opened
525
526   if (!isDefaultDevice)
527   {
528     // we need to check if the device we want to open really exists
529     // default device is handled in a special manner
530     sinkStruct.device_found = false; // if sink is valid it will be set true in pa_context_get_sink_info_by_name
531     WaitForOperation(pa_context_get_sink_info_by_name(m_Context, device.c_str(),SinkInfoCallback, &sinkStruct), m_MainLoop, "Get Sink Info");
532   }
533
534   if(!sinkStruct.device_found) // ActiveAE will open us again with a valid device name
535   {
536     CLog::Log(LOGERROR, "PulseAudio: Sink %s not found", device.c_str());
537     pa_threaded_mainloop_unlock(m_MainLoop);
538     Deinitialize();
539     return false;
540   }
541
542   // 200ms max latency
543   // 50ms min packet size
544   if(sinkStruct.isHWDevice || isDefaultDevice)
545   {
546     unsigned int latency = m_BytesPerSecond / 5;
547     unsigned int process_time = latency / 4;
548     memset(&buffer_attr, 0, sizeof(buffer_attr));
549     buffer_attr.tlength = (uint32_t) latency;
550     buffer_attr.minreq = (uint32_t) process_time;
551     buffer_attr.maxlength = (uint32_t) -1;
552     buffer_attr.prebuf = (uint32_t) -1;
553     buffer_attr.fragsize = (uint32_t) latency;
554   }
555
556   if (pa_stream_connect_playback(m_Stream, isDefaultDevice ? NULL : device.c_str(), sinkStruct.isHWDevice ? &buffer_attr : NULL, ((pa_stream_flags)(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_ADJUST_LATENCY)), m_passthrough ? NULL : &m_Volume, NULL) < 0)
557   {
558     CLog::Log(LOGERROR, "PulseAudio: Failed to connect stream to output");
559     pa_threaded_mainloop_unlock(m_MainLoop);
560     Deinitialize();
561     return false;
562   }
563
564   /* Wait until the stream is ready */
565   do
566   {
567     pa_threaded_mainloop_wait(m_MainLoop);
568     CLog::Log(LOGDEBUG, "PulseAudio: Stream %s", StreamStateToString(pa_stream_get_state(m_Stream)));
569   }
570   while (pa_stream_get_state(m_Stream) != PA_STREAM_READY && pa_stream_get_state(m_Stream) != PA_STREAM_FAILED);
571
572   if (pa_stream_get_state(m_Stream) == PA_STREAM_FAILED)
573   {
574     CLog::Log(LOGERROR, "PulseAudio: Waited for the stream but it failed");
575     pa_threaded_mainloop_unlock(m_MainLoop);
576     Deinitialize();
577     return false;
578   }
579
580   const pa_buffer_attr *a;
581
582   if (!(a = pa_stream_get_buffer_attr(m_Stream)))
583   {
584     CLog::Log(LOGERROR, "PulseAudio: %s", pa_strerror(pa_context_errno(m_Context)));
585     pa_threaded_mainloop_unlock(m_MainLoop);
586     Deinitialize();
587     return false;
588   }
589   else
590   {
591     unsigned int packetSize = a->minreq;
592     m_BufferSize = a->tlength;
593
594     format.m_frames = packetSize / frameSize;
595   }
596
597   pa_threaded_mainloop_unlock(m_MainLoop);
598
599   m_IsAllocated = true;
600   format.m_frameSize = frameSize;
601   format.m_frameSamples = format.m_frames * format.m_channelLayout.Count();
602   m_format = format;
603   format.m_dataFormat = m_passthrough ? AE_FMT_S16NE : format.m_dataFormat;
604
605   Pause(false);
606
607   return true;
608 }
609
610 void CAESinkPULSE::Deinitialize()
611 {
612   m_IsAllocated = false;
613   m_passthrough = false;
614
615   if (m_Stream)
616     Drain();
617
618   if (m_MainLoop)
619     pa_threaded_mainloop_stop(m_MainLoop);
620
621   if (m_Stream)
622   {
623     pa_stream_disconnect(m_Stream);
624     pa_stream_unref(m_Stream);
625     m_Stream = NULL;
626   }
627
628   if (m_Context)
629   {
630     pa_context_disconnect(m_Context);
631     pa_context_unref(m_Context);
632     m_Context = NULL;
633   }
634
635   if (m_MainLoop)
636   {
637     pa_threaded_mainloop_free(m_MainLoop);
638     m_MainLoop = NULL;
639   }
640 }
641
642 double CAESinkPULSE::GetDelay()
643 {
644   if (!m_IsAllocated)
645     return 0;
646
647   int error = 0;
648   pa_usec_t latency = (pa_usec_t) -1;
649   pa_threaded_mainloop_lock(m_MainLoop);
650   if ((error = pa_stream_get_latency(m_Stream, &latency, NULL)) < 0)
651   {
652     if (error == -PA_ERR_NODATA)
653     {
654       WaitForOperation(pa_stream_update_timing_info(m_Stream, NULL,NULL), m_MainLoop, "Update Timing Information");
655       if ((error = pa_stream_get_latency(m_Stream, &latency, NULL)) < 0)
656       {
657         CLog::Log(LOGDEBUG, "GetDelay - Failed to get Latency %d", error); 
658       }
659     }
660   }
661   if (error < 0 )
662     latency = (pa_usec_t) 0;
663
664   pa_threaded_mainloop_unlock(m_MainLoop);
665   return latency / 1000000.0;
666 }
667
668 double CAESinkPULSE::GetCacheTotal()
669 {
670   return (float)m_BufferSize / (float)m_BytesPerSecond;
671 }
672
673 unsigned int CAESinkPULSE::AddPackets(uint8_t *data, unsigned int frames, bool hasAudio, bool blocking)
674 {
675   if (!m_IsAllocated)
676     return frames;
677
678   pa_threaded_mainloop_lock(m_MainLoop);
679
680   unsigned int available = frames * m_format.m_frameSize;
681   unsigned int length = 0;
682   // revisit me after Gotham - should use a callback for the write function
683   while ((length = pa_stream_writable_size(m_Stream)) == 0)
684     pa_threaded_mainloop_wait(m_MainLoop);
685
686   length =  std::min((unsigned int)length, available);
687
688   int error = pa_stream_write(m_Stream, data, length, NULL, 0, PA_SEEK_RELATIVE);
689   pa_threaded_mainloop_unlock(m_MainLoop);
690
691   if (error)
692   {
693     CLog::Log(LOGERROR, "CPulseAudioDirectSound::AddPackets - pa_stream_write failed\n");
694     return 0;
695   }
696
697   return (unsigned int)(length / m_format.m_frameSize);
698 }
699
700 void CAESinkPULSE::Drain()
701 {
702   if (!m_IsAllocated)
703     return;
704
705   pa_threaded_mainloop_lock(m_MainLoop);
706   WaitForOperation(pa_stream_drain(m_Stream, NULL, NULL), m_MainLoop, "Drain");
707   pa_threaded_mainloop_unlock(m_MainLoop);
708 }
709
710 void CAESinkPULSE::SetVolume(float volume)
711 {
712   if (m_IsAllocated && !m_passthrough)
713   {
714     pa_threaded_mainloop_lock(m_MainLoop);
715     pa_volume_t pavolume = pa_sw_volume_from_linear(volume);
716     if ( pavolume <= 0 )
717       pa_cvolume_mute(&m_Volume, m_Channels);
718     else
719       pa_cvolume_set(&m_Volume, m_Channels, pavolume);
720     pa_operation *op = pa_context_set_sink_input_volume(m_Context, pa_stream_get_index(m_Stream), &m_Volume, NULL, NULL);
721     if (op == NULL)
722       CLog::Log(LOGERROR, "PulseAudio: Failed to set volume");
723     else
724       pa_operation_unref(op);
725
726     pa_threaded_mainloop_unlock(m_MainLoop);
727   }
728 }
729
730 void CAESinkPULSE::EnumerateDevicesEx(AEDeviceInfoList &list, bool force)
731 {
732   pa_context *context;
733   pa_threaded_mainloop *mainloop;
734
735   if (!SetupContext(NULL, &context, &mainloop))
736   {
737     CLog::Log(LOGNOTICE, "PulseAudio might not be running. Context was not created.");
738     return;
739   }
740
741   pa_threaded_mainloop_lock(mainloop);
742
743   SinkInfoStruct sinkStruct;
744   sinkStruct.mainloop = mainloop;
745   sinkStruct.list = &list;
746   WaitForOperation(pa_context_get_sink_info_list(context, SinkInfoRequestCallback, &sinkStruct), mainloop, "EnumerateAudioSinks");
747
748   pa_threaded_mainloop_unlock(mainloop);
749
750   if (mainloop)
751     pa_threaded_mainloop_stop(mainloop);
752
753   if (context)
754   {
755     pa_context_disconnect(context);
756     pa_context_unref(context);
757     context = NULL;
758   }
759
760   if (mainloop)
761   {
762     pa_threaded_mainloop_free(mainloop);
763     mainloop = NULL;
764   }
765 }
766
767 bool CAESinkPULSE::Pause(bool pause)
768 {
769   pa_threaded_mainloop_lock(m_MainLoop);
770
771   if (!WaitForOperation(pa_stream_cork(m_Stream, pause ? 1 : 0, NULL, NULL), m_MainLoop, pause ? "Pause" : "Resume"))
772     pause = !pause;
773
774   pa_threaded_mainloop_unlock(m_MainLoop);
775
776   return pause;
777 }
778
779 inline bool CAESinkPULSE::WaitForOperation(pa_operation *op, pa_threaded_mainloop *mainloop, const char *LogEntry = "")
780 {
781   if (op == NULL)
782     return false;
783
784   bool sucess = true;
785
786   while (pa_operation_get_state(op) == PA_OPERATION_RUNNING)
787     pa_threaded_mainloop_wait(mainloop);
788
789   if (pa_operation_get_state(op) != PA_OPERATION_DONE)
790   {
791     CLog::Log(LOGERROR, "PulseAudio: %s Operation failed", LogEntry);
792     sucess = false;
793   }
794
795   pa_operation_unref(op);
796   return sucess;
797 }
798
799 bool CAESinkPULSE::SetupContext(const char *host, pa_context **context, pa_threaded_mainloop **mainloop)
800 {
801   if ((*mainloop = pa_threaded_mainloop_new()) == NULL)
802   {
803     CLog::Log(LOGERROR, "PulseAudio: Failed to allocate main loop");
804     return false;
805   }
806
807   if (((*context) = pa_context_new(pa_threaded_mainloop_get_api(*mainloop), "XBMC")) == NULL)
808   {
809     CLog::Log(LOGERROR, "PulseAudio: Failed to allocate context");
810     return false;
811   }
812
813   pa_context_set_state_callback(*context, ContextStateCallback, *mainloop);
814
815   if (pa_context_connect(*context, host, (pa_context_flags_t)0, NULL) < 0)
816   {
817     CLog::Log(LOGERROR, "PulseAudio: Failed to connect context");
818     return false;
819   }
820   pa_threaded_mainloop_lock(*mainloop);
821
822   if (pa_threaded_mainloop_start(*mainloop) < 0)
823   {
824     CLog::Log(LOGERROR, "PulseAudio: Failed to start MainLoop");
825     pa_threaded_mainloop_unlock(*mainloop);
826     return false;
827   }
828
829   /* Wait until the context is ready */
830   do
831   {
832     pa_threaded_mainloop_wait(*mainloop);
833     CLog::Log(LOGDEBUG, "PulseAudio: Context %s", ContextStateToString(pa_context_get_state(*context)));
834   }
835   while (pa_context_get_state(*context) != PA_CONTEXT_READY && pa_context_get_state(*context) != PA_CONTEXT_FAILED);
836
837   if (pa_context_get_state(*context) == PA_CONTEXT_FAILED)
838   {
839     CLog::Log(LOGERROR, "PulseAudio: Waited for the Context but it failed");
840     pa_threaded_mainloop_unlock(*mainloop);
841     return false;
842   }
843
844   pa_threaded_mainloop_unlock(*mainloop);
845   return true;
846 }
847 #endif