2 * Copyright (C) 2010-2013 Team XBMC
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)
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.
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/>.
23 using namespace ActiveAE;
24 #include "ActiveAESound.h"
25 #include "ActiveAEStream.h"
26 #include "cores/AudioEngine/Utils/AEUtil.h"
27 #include "cores/AudioEngine/Encoders/AEEncoderFFmpeg.h"
29 #include "settings/Settings.h"
30 #include "settings/AdvancedSettings.h"
31 #include "windowing/WindowingFactory.h"
33 #define MAX_CACHE_LEVEL 0.5 // total cache time of stream in seconds
34 #define MAX_WATER_LEVEL 0.25 // buffered time after stream stages in seconds
36 void CEngineStats::Reset(unsigned int sampleRate)
38 CSingleLock lock(m_lock);
39 m_sinkUpdate = XbmcThreads::SystemClockMillis();
41 m_sinkSampleRate = sampleRate;
42 m_bufferedSamples = 0;
46 void CEngineStats::UpdateSinkDelay(double delay, int samples)
48 CSingleLock lock(m_lock);
49 m_sinkUpdate = XbmcThreads::SystemClockMillis();
51 if (samples > m_bufferedSamples)
53 CLog::Log(LOGERROR, "CEngineStats::UpdateSinkDelay - inconsistency in buffer time");
56 m_bufferedSamples -= samples;
59 void CEngineStats::AddSamples(int samples, std::list<CActiveAEStream*> &streams)
61 CSingleLock lock(m_lock);
62 m_bufferedSamples += samples;
64 //update buffered time of streams
65 std::list<CActiveAEStream*>::iterator it;
66 for(it=streams.begin(); it!=streams.end(); ++it)
69 std::deque<CSampleBuffer*>::iterator itBuf;
70 for(itBuf=(*it)->m_processingSamples.begin(); itBuf!=(*it)->m_processingSamples.end(); ++itBuf)
72 delay += (float)(*itBuf)->pkt->nb_samples / (*itBuf)->pkt->config.sample_rate;
74 delay += (*it)->m_resampleBuffers->GetDelay();
75 (*it)->m_bufferedTime = delay;
79 float CEngineStats::GetDelay()
81 CSingleLock lock(m_lock);
82 unsigned int now = XbmcThreads::SystemClockMillis();
83 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
84 delay += (float)m_bufferedSamples / m_sinkSampleRate;
92 // this is used to sync a/v so we need to add sink latency here
93 float CEngineStats::GetDelay(CActiveAEStream *stream)
95 CSingleLock lock(m_lock);
96 unsigned int now = XbmcThreads::SystemClockMillis();
97 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
98 delay += m_sinkLatency;
99 delay += (float)m_bufferedSamples / m_sinkSampleRate;
104 delay += stream->m_bufferedTime;
108 float CEngineStats::GetCacheTime(CActiveAEStream *stream)
110 CSingleLock lock(m_lock);
111 float delay = (float)m_bufferedSamples / m_sinkSampleRate;
113 delay += stream->m_bufferedTime;
117 float CEngineStats::GetCacheTotal(CActiveAEStream *stream)
119 return MAX_CACHE_LEVEL + m_sinkCacheTotal;
122 float CEngineStats::GetWaterLevel()
124 return (float)m_bufferedSamples / m_sinkSampleRate;
127 void CEngineStats::SetSuspended(bool state)
129 CSingleLock lock(m_lock);
133 bool CEngineStats::IsSuspended()
135 CSingleLock lock(m_lock);
139 CActiveAE::CActiveAE() :
141 m_controlPort("OutputControlPort", &m_inMsgEvent, &m_outMsgEvent),
142 m_dataPort("OutputDataPort", &m_inMsgEvent, &m_outMsgEvent),
143 m_sink(&m_outMsgEvent)
145 m_sinkBuffers = NULL;
146 m_silenceBuffers = NULL;
147 m_encoderBuffers = NULL;
149 m_vizBuffersInput = NULL;
156 m_audioCallback = NULL;
157 m_vizInitialized = false;
158 m_sinkHasVolume = false;
161 CActiveAE::~CActiveAE()
166 void CActiveAE::Dispose()
168 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
169 g_Windowing.Unregister(this);
175 m_controlPort.Purge();
179 m_dllAvFormat.Unload();
180 m_dllAvCodec.Unload();
181 m_dllAvUtil.Unload();
184 //-----------------------------------------------------------------------------
186 //-----------------------------------------------------------------------------
192 AE_TOP_UNCONFIGURED, // 2
193 AE_TOP_RECONFIGURING, // 3
194 AE_TOP_CONFIGURED, // 4
195 AE_TOP_CONFIGURED_SUSPEND, // 5
196 AE_TOP_CONFIGURED_IDLE, // 6
197 AE_TOP_CONFIGURED_PLAY, // 7
200 int AE_parentStates[] = {
203 0, //TOP_UNCONFIGURED
205 0, //TOP_RECONFIGURING
206 4, //TOP_CONFIGURED_SUSPEND
207 4, //TOP_CONFIGURED_IDLE
208 4, //TOP_CONFIGURED_PLAY
211 void CActiveAE::StateMachine(int signal, Protocol *port, Message *msg)
213 for (int state = m_state; ; state = AE_parentStates[state])
218 if (port == &m_controlPort)
222 case CActiveAEControlProtocol::GETSTATE:
223 msg->Reply(CActiveAEControlProtocol::ACC, &m_state, sizeof(m_state));
225 case CActiveAEControlProtocol::VOLUME:
226 m_volume = *(float*)msg->data;
228 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
230 case CActiveAEControlProtocol::MUTE:
231 m_muted = *(bool*)msg->data;
233 case CActiveAEControlProtocol::KEEPCONFIG:
234 m_extKeepConfig = *(unsigned int*)msg->data;
236 case CActiveAEControlProtocol::DISPLAYRESET:
242 else if (port == &m_dataPort)
246 case CActiveAEDataProtocol::NEWSOUND:
247 CActiveAESound *sound;
248 sound = *(CActiveAESound**)msg->data;
251 m_sounds.push_back(sound);
255 case CActiveAEDataProtocol::FREESTREAM:
256 CActiveAEStream *stream;
257 stream = *(CActiveAEStream**)msg->data;
258 DiscardStream(stream);
260 case CActiveAEDataProtocol::FREESOUND:
261 sound = *(CActiveAESound**)msg->data;
264 case CActiveAEDataProtocol::DRAINSTREAM:
265 stream = *(CActiveAEStream**)msg->data;
266 stream->m_drain = true;
267 stream->m_resampleBuffers->m_drain = true;
268 msg->Reply(CActiveAEDataProtocol::ACC);
269 stream->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
275 else if (port == &m_sink.m_dataPort)
279 case CSinkDataProtocol::RETURNSAMPLE:
280 CSampleBuffer **buffer;
281 buffer = (CSampleBuffer**)msg->data;
292 std::string portName = port == NULL ? "timer" : port->portName;
293 CLog::Log(LOGWARNING, "CActiveAE::%s - signal: %d from port: %s not handled for state: %d", __FUNCTION__, signal, portName.c_str(), m_state);
298 if (port == NULL) // timeout
302 case CActiveAEControlProtocol::TIMEOUT:
308 m_state = AE_TOP_CONFIGURED_IDLE;
313 m_state = AE_TOP_ERROR;
323 case AE_TOP_UNCONFIGURED:
324 if (port == &m_controlPort)
328 case CActiveAEControlProtocol::INIT:
330 m_sink.EnumerateSinkList(false);
333 msg->Reply(CActiveAEControlProtocol::ACC);
336 m_state = AE_TOP_CONFIGURED_IDLE;
341 m_state = AE_TOP_ERROR;
352 case AE_TOP_RECONFIGURING:
353 if (port == NULL) // timeout
357 case CActiveAEControlProtocol::TIMEOUT:
364 if (!m_sinkBuffers->m_inputSamples.empty() || !m_sinkBuffers->m_outputSamples.empty())
369 if (NeedReconfigureSink())
376 m_state = AE_TOP_CONFIGURED_PLAY;
381 m_state = AE_TOP_ERROR;
384 m_extDeferData = false;
392 case AE_TOP_CONFIGURED:
393 if (port == &m_controlPort)
397 case CActiveAEControlProtocol::RECONFIGURE:
398 if (m_streams.empty())
400 bool silence = false;
401 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
405 if (!NeedReconfigureBuffers() && !NeedReconfigureSink())
407 m_state = AE_TOP_RECONFIGURING;
409 // don't accept any data until we are reconfigured
410 m_extDeferData = true;
412 case CActiveAEControlProtocol::SUSPEND:
414 m_stats.SetSuspended(true);
415 m_state = AE_TOP_CONFIGURED_SUSPEND;
416 m_extDeferData = true;
418 case CActiveAEControlProtocol::DISPLAYLOST:
419 if (m_sink.GetDeviceType(m_mode == MODE_PCM ? m_settings.device : m_settings.passthoughdevice) == AE_DEVTYPE_HDMI)
422 m_stats.SetSuspended(true);
423 m_state = AE_TOP_CONFIGURED_SUSPEND;
424 m_extDeferData = true;
426 msg->Reply(CActiveAEControlProtocol::ACC);
428 case CActiveAEControlProtocol::PAUSESTREAM:
429 CActiveAEStream *stream;
430 stream = *(CActiveAEStream**)msg->data;
431 if (stream->m_paused != true && m_streams.size() == 1)
433 stream->m_paused = true;
435 case CActiveAEControlProtocol::RESUMESTREAM:
436 stream = *(CActiveAEStream**)msg->data;
437 stream->m_paused = false;
440 case CActiveAEControlProtocol::FLUSHSTREAM:
441 stream = *(CActiveAEStream**)msg->data;
442 SFlushStream(stream);
443 msg->Reply(CActiveAEControlProtocol::ACC);
446 case CActiveAEControlProtocol::STREAMAMP:
447 MsgStreamParameter *par;
448 par = (MsgStreamParameter*)msg->data;
449 par->stream->m_limiter.SetAmplification(par->parameter.float_par);
450 par->stream->m_amplify = par->parameter.float_par;
452 case CActiveAEControlProtocol::STREAMVOLUME:
453 par = (MsgStreamParameter*)msg->data;
454 par->stream->m_volume = par->parameter.float_par;
456 case CActiveAEControlProtocol::STREAMRGAIN:
457 par = (MsgStreamParameter*)msg->data;
458 par->stream->m_rgain = par->parameter.float_par;
460 case CActiveAEControlProtocol::STREAMRESAMPLERATIO:
461 par = (MsgStreamParameter*)msg->data;
462 if (par->stream->m_resampleBuffers)
464 par->stream->m_resampleBuffers->m_resampleRatio = par->parameter.double_par;
467 case CActiveAEControlProtocol::STREAMFADE:
469 fade = (MsgStreamFade*)msg->data;
470 fade->stream->m_fadingBase = fade->from;
471 fade->stream->m_fadingTarget = fade->target;
472 fade->stream->m_fadingTime = fade->millis;
473 fade->stream->m_fadingSamples = -1;
475 case CActiveAEControlProtocol::STOPSOUND:
476 CActiveAESound *sound;
477 sound = *(CActiveAESound**)msg->data;
484 else if (port == &m_dataPort)
488 case CActiveAEDataProtocol::PLAYSOUND:
489 CActiveAESound *sound;
490 sound = *(CActiveAESound**)msg->data;
491 if (m_settings.guisoundmode == AE_SOUND_OFF ||
492 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
496 SoundState st = {sound, 0};
497 m_sounds_playing.push_back(st);
499 m_state = AE_TOP_CONFIGURED_PLAY;
502 case CActiveAEDataProtocol::NEWSTREAM:
503 MsgStreamNew *streamMsg;
504 CActiveAEStream *stream;
505 streamMsg = (MsgStreamNew*)msg->data;
506 stream = CreateStream(streamMsg);
509 msg->Reply(CActiveAEDataProtocol::ACC, &stream, sizeof(CActiveAEStream*));
514 m_state = AE_TOP_CONFIGURED_PLAY;
519 m_state = AE_TOP_ERROR;
524 msg->Reply(CActiveAEDataProtocol::ERR);
526 case CActiveAEDataProtocol::STREAMSAMPLE:
527 MsgStreamSample *msgData;
528 CSampleBuffer *samples;
529 msgData = (MsgStreamSample*)msg->data;
530 samples = msgData->stream->m_processingSamples.front();
531 msgData->stream->m_processingSamples.pop_front();
532 if (samples != msgData->buffer)
533 CLog::Log(LOGERROR, "CActiveAE - inconsistency in stream sample message");
534 if (msgData->buffer->pkt->nb_samples == 0)
535 msgData->buffer->Return();
537 msgData->stream->m_resampleBuffers->m_inputSamples.push_back(msgData->buffer);
539 m_state = AE_TOP_CONFIGURED_PLAY;
541 case CActiveAEDataProtocol::FREESTREAM:
542 stream = *(CActiveAEStream**)msg->data;
543 DiscardStream(stream);
544 if (m_streams.empty())
547 m_extDrainTimer.Set(m_extKeepConfig);
549 m_extDrainTimer.Set(m_stats.GetDelay() * 1000);
553 m_state = AE_TOP_CONFIGURED_PLAY;
555 case CActiveAEDataProtocol::DRAINSTREAM:
556 stream = *(CActiveAEStream**)msg->data;
557 stream->m_drain = true;
558 stream->m_resampleBuffers->m_drain = true;
560 m_state = AE_TOP_CONFIGURED_PLAY;
561 msg->Reply(CActiveAEDataProtocol::ACC);
567 else if (port == &m_sink.m_dataPort)
571 case CSinkDataProtocol::RETURNSAMPLE:
572 CSampleBuffer **buffer;
573 buffer = (CSampleBuffer**)msg->data;
579 m_state = AE_TOP_CONFIGURED_PLAY;
587 case AE_TOP_CONFIGURED_SUSPEND:
588 if (port == &m_controlPort)
590 bool displayReset = false;
593 case CActiveAEControlProtocol::DISPLAYRESET:
595 case CActiveAEControlProtocol::INIT:
599 m_sink.EnumerateSinkList(true);
604 msg->Reply(CActiveAEControlProtocol::ACC);
607 m_state = AE_TOP_CONFIGURED_PLAY;
612 m_state = AE_TOP_ERROR;
615 m_stats.SetSuspended(false);
616 m_extDeferData = false;
622 else if (port == &m_sink.m_dataPort)
626 case CSinkDataProtocol::RETURNSAMPLE:
627 CSampleBuffer **buffer;
628 buffer = (CSampleBuffer**)msg->data;
638 else if (port == NULL) // timeout
642 case CActiveAEControlProtocol::TIMEOUT:
651 case AE_TOP_CONFIGURED_IDLE:
652 if (port == NULL) // timeout
656 case CActiveAEControlProtocol::RESUMESTREAM:
657 CActiveAEStream *stream;
658 stream = *(CActiveAEStream**)msg->data;
659 stream->m_paused = false;
660 m_state = AE_TOP_CONFIGURED_PLAY;
663 case CActiveAEControlProtocol::FLUSHSTREAM:
664 stream = *(CActiveAEStream**)msg->data;
665 SFlushStream(stream);
666 msg->Reply(CActiveAEControlProtocol::ACC);
667 m_state = AE_TOP_CONFIGURED_PLAY;
670 case CActiveAEControlProtocol::TIMEOUT:
672 ClearDiscardedBuffers();
675 if (m_extDrainTimer.IsTimePast())
680 m_state = AE_TOP_CONFIGURED_PLAY;
685 m_state = AE_TOP_ERROR;
690 m_extTimeout = m_extDrainTimer.MillisLeft();
701 case AE_TOP_CONFIGURED_PLAY:
702 if (port == NULL) // timeout
706 case CActiveAEControlProtocol::TIMEOUT:
709 m_state = AE_TOP_ERROR;
718 if (!m_extDrain && HasWork())
720 ClearDiscardedBuffers();
725 m_state = AE_TOP_CONFIGURED_IDLE;
733 default: // we are in no state, should not happen
734 CLog::Log(LOGERROR, "CActiveAE::%s - no valid state: %d", __FUNCTION__, m_state);
740 void CActiveAE::Process()
743 Protocol *port = NULL;
745 XbmcThreads::EndTime timer;
747 m_state = AE_TOP_UNCONFIGURED;
749 m_bStateMachineSelfTrigger = false;
751 m_extDeferData = false;
760 timer.Set(m_extTimeout);
762 if (m_bStateMachineSelfTrigger)
764 m_bStateMachineSelfTrigger = false;
765 // self trigger state machine
766 StateMachine(msg->signal, port, msg);
767 if (!m_bStateMachineSelfTrigger)
774 // check control port
775 else if (m_controlPort.ReceiveOutMessage(&msg))
778 port = &m_controlPort;
780 // check sink data port
781 else if (m_sink.m_dataPort.ReceiveInMessage(&msg))
784 port = &m_sink.m_dataPort;
786 else if (!m_extDeferData)
789 if (m_dataPort.ReceiveOutMessage(&msg))
797 std::list<CActiveAEStream*>::iterator it;
798 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
800 if((*it)->m_streamPort->ReceiveOutMessage(&msg))
812 StateMachine(msg->signal, port, msg);
813 if (!m_bStateMachineSelfTrigger)
822 else if (m_outMsgEvent.WaitMSec(m_extTimeout))
824 m_extTimeout = timer.MillisLeft();
830 msg = m_controlPort.GetMessage();
831 msg->signal = CActiveAEControlProtocol::TIMEOUT;
833 // signal timeout to state machine
834 StateMachine(msg->signal, port, msg);
835 if (!m_bStateMachineSelfTrigger)
844 AEAudioFormat CActiveAE::GetInputFormat(AEAudioFormat *desiredFmt)
846 AEAudioFormat inputFormat;
848 if (m_streams.empty())
850 inputFormat.m_dataFormat = AE_FMT_FLOAT;
851 inputFormat.m_sampleRate = 44100;
852 inputFormat.m_encodedRate = 0;
853 inputFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
854 inputFormat.m_frames = 0;
855 inputFormat.m_frameSamples = 0;
856 inputFormat.m_frameSize = 0;
858 // force input format after unpausing slave
859 else if (desiredFmt != NULL)
861 inputFormat = *desiredFmt;
863 // keep format when having multiple streams
864 else if (m_streams.size() > 1 && m_silenceBuffers == NULL)
866 inputFormat = m_inputFormat;
870 inputFormat = m_streams.front()->m_format;
871 m_inputFormat = inputFormat;
877 void CActiveAE::Configure(AEAudioFormat *desiredFmt)
879 bool initSink = false;
881 AEAudioFormat sinkInputFormat, inputFormat;
882 AEAudioFormat oldInternalFormat = m_internalFormat;
883 AEAudioFormat oldSinkRequestFormat = m_sinkRequestFormat;
885 inputFormat = GetInputFormat(desiredFmt);
887 m_sinkRequestFormat = inputFormat;
888 ApplySettingsToFormat(m_sinkRequestFormat, m_settings, (int*)&m_mode);
891 std::string device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
893 CAESinkFactory::ParseDevice(device, driver);
894 if ((!CompareFormat(m_sinkRequestFormat, m_sinkFormat) && !CompareFormat(m_sinkRequestFormat, oldSinkRequestFormat)) ||
895 m_currDevice.compare(device) != 0 ||
896 m_settings.driver.compare(driver) != 0)
900 m_settings.driver = driver;
901 m_currDevice = device;
903 m_stats.Reset(m_sinkFormat.m_sampleRate);
904 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
906 // limit buffer size in case of sink returns large buffer
907 unsigned int buffertime = (m_sinkFormat.m_frames*1000) / m_sinkFormat.m_sampleRate;
910 CLog::Log(LOGWARNING, "ActiveAE::%s - sink returned large buffer of %d ms, reducing to 80 ms", __FUNCTION__, buffertime);
911 m_sinkFormat.m_frames = 80 * m_sinkFormat.m_sampleRate / 1000;
915 if (m_silenceBuffers)
917 m_discardBufferPools.push_back(m_silenceBuffers);
918 m_silenceBuffers = NULL;
921 // buffers for driving gui sounds if no streams are active
922 if (m_streams.empty())
924 inputFormat = m_sinkFormat;
925 inputFormat.m_dataFormat = AE_FMT_FLOAT;
926 inputFormat.m_frameSize = inputFormat.m_channelLayout.Count() *
927 (CAEUtil::DataFormatToBits(inputFormat.m_dataFormat) >> 3);
928 m_silenceBuffers = new CActiveAEBufferPool(inputFormat);
929 m_silenceBuffers->Create(MAX_WATER_LEVEL*1000);
930 sinkInputFormat = inputFormat;
931 m_internalFormat = inputFormat;
933 bool silence = false;
934 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
939 if (m_encoderBuffers)
941 m_discardBufferPools.push_back(m_encoderBuffers);
942 m_encoderBuffers = NULL;
946 m_discardBufferPools.push_back(m_vizBuffers);
949 if (m_vizBuffersInput)
951 m_discardBufferPools.push_back(m_vizBuffersInput);
952 m_vizBuffersInput = NULL;
955 // resample buffers for streams
959 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
961 AEAudioFormat outputFormat;
962 if (m_mode == MODE_RAW)
964 outputFormat = inputFormat;
965 sinkInputFormat = m_sinkFormat;
967 // transcode everything with more than 2 channels
968 else if (m_mode == MODE_TRANSCODE)
970 outputFormat = inputFormat;
971 outputFormat.m_dataFormat = AE_FMT_FLOATP;
972 outputFormat.m_sampleRate = 48000;
977 m_encoder = new CAEEncoderFFmpeg();
978 m_encoder->Initialize(outputFormat, true);
979 m_encoderFormat = outputFormat;
982 outputFormat = m_encoderFormat;
984 outputFormat.m_channelLayout = m_encoderFormat.m_channelLayout;
985 outputFormat.m_frames = m_encoderFormat.m_frames;
988 if (m_encoder->GetCodecID() == AV_CODEC_ID_AC3)
990 AEAudioFormat format;
991 format.m_channelLayout = AE_CH_LAYOUT_2_0;
992 format.m_dataFormat = AE_FMT_S16NE;
993 format.m_frameSize = 2* (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
994 format.m_frames = AC3_FRAME_SIZE;
995 format.m_sampleRate = 48000;
996 format.m_encodedRate = m_encoderFormat.m_sampleRate;
997 if (m_encoderBuffers && initSink)
999 m_discardBufferPools.push_back(m_encoderBuffers);
1000 m_encoderBuffers = NULL;
1002 if (!m_encoderBuffers)
1004 m_encoderBuffers = new CActiveAEBufferPool(format);
1005 m_encoderBuffers->Create(MAX_WATER_LEVEL*1000);
1009 sinkInputFormat = m_sinkFormat;
1013 outputFormat = m_sinkFormat;
1014 outputFormat.m_dataFormat = AE_FMT_FLOAT;
1015 outputFormat.m_frameSize = outputFormat.m_channelLayout.Count() *
1016 (CAEUtil::DataFormatToBits(outputFormat.m_dataFormat) >> 3);
1017 // TODO: adjust to decoder
1018 sinkInputFormat = outputFormat;
1020 m_internalFormat = outputFormat;
1022 std::list<CActiveAEStream*>::iterator it;
1023 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1025 // check if we support input format of stream
1026 if (!AE_IS_RAW((*it)->m_format.m_dataFormat) &&
1027 CActiveAEResample::GetAVSampleFormat((*it)->m_format.m_dataFormat) == AV_SAMPLE_FMT_FLT &&
1028 (*it)->m_format.m_dataFormat != AE_FMT_FLOAT)
1030 (*it)->m_convertFn = CAEConvert::ToFloat((*it)->m_format.m_dataFormat);
1031 (*it)->m_format.m_dataFormat = AE_FMT_FLOAT;
1034 if (!(*it)->m_inputBuffers)
1036 // align input buffers with period of sink or encoder
1037 (*it)->m_format.m_frames = m_internalFormat.m_frames * ((float)(*it)->m_format.m_sampleRate / m_internalFormat.m_sampleRate);
1039 // create buffer pool
1040 (*it)->m_inputBuffers = new CActiveAEBufferPool((*it)->m_format);
1041 (*it)->m_inputBuffers->Create(MAX_CACHE_LEVEL*1000);
1042 (*it)->m_streamSpace = (*it)->m_format.m_frameSize * (*it)->m_format.m_frames;
1044 // if input format does not follow ffmpeg channel mask, we may need to remap channels
1045 (*it)->InitRemapper();
1047 if (initSink && (*it)->m_resampleBuffers)
1049 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1050 (*it)->m_resampleBuffers = NULL;
1052 if (!(*it)->m_resampleBuffers)
1054 (*it)->m_resampleBuffers = new CActiveAEBufferPoolResample((*it)->m_inputBuffers->m_format, outputFormat, m_settings.resampleQuality);
1055 (*it)->m_resampleBuffers->m_changeResampler = (*it)->m_forceResampler;
1056 (*it)->m_resampleBuffers->Create(MAX_CACHE_LEVEL*1000, false, m_settings.stereoupmix, m_settings.normalizelevels);
1058 if (m_mode == MODE_TRANSCODE || m_streams.size() > 1)
1059 (*it)->m_resampleBuffers->m_fillPackets = true;
1062 (*it)->m_limiter.SetSamplerate(outputFormat.m_sampleRate);
1065 // update buffered time of streams
1066 m_stats.AddSamples(0, m_streams);
1069 if (!AE_IS_RAW(inputFormat.m_dataFormat))
1071 if (initSink && m_vizBuffers)
1073 m_discardBufferPools.push_back(m_vizBuffers);
1074 m_vizBuffers = NULL;
1075 m_discardBufferPools.push_back(m_vizBuffersInput);
1076 m_vizBuffersInput = NULL;
1080 AEAudioFormat vizFormat = m_internalFormat;
1081 vizFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
1082 vizFormat.m_dataFormat = AE_FMT_FLOAT;
1085 m_vizBuffersInput = new CActiveAEBufferPool(m_internalFormat);
1086 m_vizBuffersInput->Create(2000);
1089 m_vizBuffers = new CActiveAEBufferPoolResample(m_internalFormat, vizFormat, m_settings.resampleQuality);
1090 // TODO use cache of sync + water level
1091 m_vizBuffers->Create(2000, false, false);
1092 m_vizInitialized = false;
1097 // resample buffers for sink
1098 if (m_sinkBuffers &&
1099 (!CompareFormat(m_sinkBuffers->m_format,m_sinkFormat) || !CompareFormat(m_sinkBuffers->m_inputFormat, sinkInputFormat)))
1101 m_discardBufferPools.push_back(m_sinkBuffers);
1102 m_sinkBuffers = NULL;
1106 m_sinkBuffers = new CActiveAEBufferPoolResample(sinkInputFormat, m_sinkFormat, m_settings.resampleQuality);
1107 m_sinkBuffers->Create(MAX_WATER_LEVEL*1000, true, false);
1111 if (!CompareFormat(oldInternalFormat, m_internalFormat))
1113 if (m_settings.guisoundmode == AE_SOUND_ALWAYS ||
1114 (m_settings.guisoundmode == AE_SOUND_IDLE && m_streams.empty()))
1116 std::vector<CActiveAESound*>::iterator it;
1117 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
1119 (*it)->SetConverted(false);
1122 m_sounds_playing.clear();
1125 ClearDiscardedBuffers();
1129 CActiveAEStream* CActiveAE::CreateStream(MsgStreamNew *streamMsg)
1131 // we only can handle a single pass through stream
1132 bool hasRawStream = false;
1133 bool hasStream = false;
1134 std::list<CActiveAEStream*>::iterator it;
1135 for(it = m_streams.begin(); it != m_streams.end(); ++it)
1137 if((*it)->IsDrained())
1139 if(AE_IS_RAW((*it)->m_format.m_dataFormat))
1140 hasRawStream = true;
1143 if (hasRawStream || (hasStream && AE_IS_RAW(streamMsg->format.m_dataFormat)))
1148 // create the stream
1149 CActiveAEStream *stream;
1150 stream = new CActiveAEStream(&streamMsg->format);
1151 stream->m_streamPort = new CActiveAEDataProtocol("stream",
1152 &stream->m_inMsgEvent, &m_outMsgEvent);
1154 // create buffer pool
1155 stream->m_inputBuffers = NULL; // create in Configure when we know the sink format
1156 stream->m_resampleBuffers = NULL; // create in Configure when we know the sink format
1157 stream->m_statsLock = m_stats.GetLock();
1158 stream->m_fadingSamples = 0;
1159 stream->m_started = false;
1161 if (streamMsg->options & AESTREAM_PAUSED)
1162 stream->m_paused = true;
1164 if (streamMsg->options & AESTREAM_FORCE_RESAMPLE)
1165 stream->m_forceResampler = true;
1167 m_streams.push_back(stream);
1172 void CActiveAE::DiscardStream(CActiveAEStream *stream)
1174 std::list<CActiveAEStream*>::iterator it;
1175 for (it=m_streams.begin(); it!=m_streams.end(); )
1177 if (stream == (*it))
1179 while (!(*it)->m_processingSamples.empty())
1181 (*it)->m_processingSamples.front()->Return();
1182 (*it)->m_processingSamples.pop_front();
1184 m_discardBufferPools.push_back((*it)->m_inputBuffers);
1185 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1186 CLog::Log(LOGDEBUG, "CActiveAE::DiscardStream - audio stream deleted");
1187 delete (*it)->m_streamPort;
1189 it = m_streams.erase(it);
1195 ClearDiscardedBuffers();
1198 void CActiveAE::SFlushStream(CActiveAEStream *stream)
1200 while (!stream->m_processingSamples.empty())
1202 stream->m_processingSamples.front()->Return();
1203 stream->m_processingSamples.pop_front();
1205 stream->m_resampleBuffers->Flush();
1206 stream->m_streamPort->Purge();
1207 stream->m_bufferedTime = 0.0;
1208 stream->m_paused = false;
1210 // flush the engine if we only have a single stream
1211 if (m_streams.size() == 1)
1217 void CActiveAE::FlushEngine()
1220 m_sinkBuffers->Flush();
1222 m_vizBuffers->Flush();
1224 // send message to sink
1226 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::FLUSH,
1229 bool success = reply->signal == CSinkControlProtocol::ACC;
1232 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on flush", __FUNCTION__);
1239 CLog::Log(LOGERROR, "ActiveAE::%s - failed to flush", __FUNCTION__);
1242 m_stats.Reset(m_sinkFormat.m_sampleRate);
1245 void CActiveAE::ClearDiscardedBuffers()
1247 std::list<CActiveAEBufferPool*>::iterator it;
1248 for (it=m_discardBufferPools.begin(); it!=m_discardBufferPools.end(); ++it)
1250 CActiveAEBufferPoolResample *rbuf = dynamic_cast<CActiveAEBufferPoolResample*>(*it);
1255 // if all buffers have returned, we can delete the buffer pool
1256 if ((*it)->m_allSamples.size() == (*it)->m_freeSamples.size())
1259 CLog::Log(LOGDEBUG, "CActiveAE::ClearDiscardedBuffers - buffer pool deleted");
1260 m_discardBufferPools.erase(it);
1266 void CActiveAE::SStopSound(CActiveAESound *sound)
1268 std::list<SoundState>::iterator it;
1269 for (it=m_sounds_playing.begin(); it!=m_sounds_playing.end(); ++it)
1271 if (it->sound == sound)
1273 m_sounds_playing.erase(it);
1279 void CActiveAE::DiscardSound(CActiveAESound *sound)
1283 std::vector<CActiveAESound*>::iterator it;
1284 for (it=m_sounds.begin(); it!=m_sounds.end(); ++it)
1294 void CActiveAE::ChangeResamplers()
1296 std::list<CActiveAEStream*>::iterator it;
1297 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1299 bool normalize = true;
1300 if (((*it)->m_resampleBuffers->m_format.m_channelLayout.Count() <
1301 (*it)->m_resampleBuffers->m_inputFormat.m_channelLayout.Count()) &&
1302 !m_settings.normalizelevels)
1305 if ((*it)->m_resampleBuffers && (*it)->m_resampleBuffers->m_resampler &&
1306 (((*it)->m_resampleBuffers->m_resampleQuality != m_settings.resampleQuality) ||
1307 (((*it)->m_resampleBuffers->m_stereoUpmix != m_settings.stereoupmix)) ||
1308 ((*it)->m_resampleBuffers->m_normalize != normalize)))
1310 (*it)->m_resampleBuffers->m_changeResampler = true;
1312 (*it)->m_resampleBuffers->m_resampleQuality = m_settings.resampleQuality;
1313 (*it)->m_resampleBuffers->m_stereoUpmix = m_settings.stereoupmix;
1314 (*it)->m_resampleBuffers->m_normalize = normalize;
1318 void CActiveAE::ApplySettingsToFormat(AEAudioFormat &format, AudioSettings &settings, int *mode)
1320 int oldMode = m_mode;
1325 if (AE_IS_RAW(format.m_dataFormat))
1327 if ((format.m_dataFormat == AE_FMT_AC3 && !settings.ac3passthrough) ||
1328 (format.m_dataFormat == AE_FMT_EAC3 && !settings.eac3passthrough) ||
1329 (format.m_dataFormat == AE_FMT_TRUEHD && !settings.truehdpassthrough) ||
1330 (format.m_dataFormat == AE_FMT_DTS && !settings.dtspassthrough) ||
1331 (format.m_dataFormat == AE_FMT_DTSHD && !settings.dtshdpassthrough))
1333 CLog::Log(LOGERROR, "CActiveAE::ApplySettingsToFormat - input audio format is wrong");
1339 else if (settings.channels <= AE_CH_LAYOUT_2_0 && // no multichannel pcm
1340 settings.passthrough &&
1341 settings.ac3passthrough &&
1342 settings.ac3transcode &&
1343 !m_streams.empty() &&
1344 (format.m_channelLayout.Count() > 2 || settings.stereoupmix))
1346 format.m_dataFormat = AE_FMT_AC3;
1347 format.m_sampleRate = 48000;
1348 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1350 *mode = MODE_TRANSCODE;
1354 format.m_dataFormat = AE_FMT_FLOAT;
1355 // consider user channel layout for those cases
1356 // 1. input stream is multichannel
1357 // 2. stereo upmix is selected
1359 if ((format.m_channelLayout.Count() > 2) ||
1360 settings.stereoupmix ||
1361 (settings.config == AE_CONFIG_FIXED))
1363 CAEChannelInfo stdLayout;
1364 switch (settings.channels)
1367 case 0: stdLayout = AE_CH_LAYOUT_2_0; break;
1368 case 1: stdLayout = AE_CH_LAYOUT_2_0; break;
1369 case 2: stdLayout = AE_CH_LAYOUT_2_1; break;
1370 case 3: stdLayout = AE_CH_LAYOUT_3_0; break;
1371 case 4: stdLayout = AE_CH_LAYOUT_3_1; break;
1372 case 5: stdLayout = AE_CH_LAYOUT_4_0; break;
1373 case 6: stdLayout = AE_CH_LAYOUT_4_1; break;
1374 case 7: stdLayout = AE_CH_LAYOUT_5_0; break;
1375 case 8: stdLayout = AE_CH_LAYOUT_5_1; break;
1376 case 9: stdLayout = AE_CH_LAYOUT_7_0; break;
1377 case 10: stdLayout = AE_CH_LAYOUT_7_1; break;
1380 if (m_settings.config == AE_CONFIG_FIXED || (settings.stereoupmix && format.m_channelLayout.Count() <= 2))
1381 format.m_channelLayout = stdLayout;
1382 else if (m_extKeepConfig && (settings.config == AE_CONFIG_AUTO) && (oldMode != MODE_RAW))
1383 format.m_channelLayout = m_internalFormat.m_channelLayout;
1385 format.m_channelLayout.ResolveChannels(stdLayout);
1387 // don't change from multi to stereo in AUTO mode
1388 else if ((settings.config == AE_CONFIG_AUTO) &&
1389 m_stats.GetWaterLevel() > 0 && m_internalFormat.m_channelLayout.Count() > 2)
1391 format.m_channelLayout = m_internalFormat.m_channelLayout;
1394 if (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958)
1396 if (format.m_sampleRate > m_settings.samplerate)
1398 format.m_sampleRate = m_settings.samplerate;
1399 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - limit samplerate for SPDIF to %d", format.m_sampleRate);
1401 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1404 if (m_settings.config == AE_CONFIG_FIXED)
1406 format.m_sampleRate = m_settings.samplerate;
1407 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - Forcing samplerate to %d", format.m_sampleRate);
1410 // sinks may not support mono
1411 if (format.m_channelLayout.Count() == 1)
1413 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1418 bool CActiveAE::NeedReconfigureBuffers()
1420 AEAudioFormat newFormat = GetInputFormat();
1421 ApplySettingsToFormat(newFormat, m_settings);
1423 if (newFormat.m_dataFormat != m_sinkRequestFormat.m_dataFormat ||
1424 newFormat.m_channelLayout != m_sinkRequestFormat.m_channelLayout ||
1425 newFormat.m_sampleRate != m_sinkRequestFormat.m_sampleRate)
1431 bool CActiveAE::NeedReconfigureSink()
1433 AEAudioFormat newFormat = GetInputFormat();
1434 ApplySettingsToFormat(newFormat, m_settings);
1436 std::string device = AE_IS_RAW(newFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
1438 CAESinkFactory::ParseDevice(device, driver);
1440 if (!CompareFormat(newFormat, m_sinkFormat) ||
1441 m_currDevice.compare(device) != 0 ||
1442 m_settings.driver.compare(driver) != 0)
1448 bool CActiveAE::InitSink()
1451 config.format = m_sinkRequestFormat;
1452 config.stats = &m_stats;
1453 config.device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? &m_settings.passthoughdevice :
1456 // send message to sink
1458 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::CONFIGURE,
1461 &config, sizeof(config)))
1463 bool success = reply->signal == CSinkControlProtocol::ACC;
1467 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1472 data = (SinkReply*)reply->data;
1475 m_sinkFormat = data->format;
1476 m_sinkHasVolume = data->hasVolume;
1477 m_stats.SetSinkCacheTotal(data->cacheTotal);
1478 m_stats.SetSinkLatency(data->latency);
1484 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
1485 m_stats.SetSinkCacheTotal(0);
1486 m_stats.SetSinkLatency(0);
1491 m_inMsgEvent.Reset();
1495 void CActiveAE::DrainSink()
1497 // send message to sink
1499 if (m_sink.m_dataPort.SendOutMessageSync(CSinkDataProtocol::DRAIN,
1503 bool success = reply->signal == CSinkDataProtocol::ACC;
1507 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on drain", __FUNCTION__);
1515 CLog::Log(LOGERROR, "ActiveAE::%s - failed to drain", __FUNCTION__);
1521 void CActiveAE::UnconfigureSink()
1523 // send message to sink
1525 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::UNCONFIGURE,
1529 bool success = reply->signal == CSinkControlProtocol::ACC;
1532 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1539 CLog::Log(LOGERROR, "ActiveAE::%s - failed to unconfigure", __FUNCTION__);
1543 // make sure we open sink on next configure
1546 m_inMsgEvent.Reset();
1550 bool CActiveAE::RunStages()
1554 // serve input streams
1555 std::list<CActiveAEStream*>::iterator it;
1556 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1558 if ((*it)->m_resampleBuffers && !(*it)->m_paused)
1559 busy = (*it)->m_resampleBuffers->ResampleBuffers();
1560 else if ((*it)->m_resampleBuffers &&
1561 ((*it)->m_resampleBuffers->m_inputSamples.size() > (*it)->m_resampleBuffers->m_allSamples.size() * 0.5))
1563 CSingleLock lock((*it)->m_streamLock);
1564 (*it)->m_streamIsBuffering = false;
1567 // provide buffers to stream
1568 float time = m_stats.GetCacheTime((*it));
1569 CSampleBuffer *buffer;
1570 if (!(*it)->m_drain)
1572 while (time < MAX_CACHE_LEVEL && !(*it)->m_inputBuffers->m_freeSamples.empty())
1574 buffer = (*it)->m_inputBuffers->GetFreeBuffer();
1575 (*it)->m_processingSamples.push_back(buffer);
1576 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMBUFFER, &buffer, sizeof(CSampleBuffer*));
1577 (*it)->IncFreeBuffers();
1578 time += (float)buffer->pkt->max_nb_samples / buffer->pkt->config.sample_rate;
1583 if ((*it)->m_resampleBuffers->m_inputSamples.empty() &&
1584 (*it)->m_resampleBuffers->m_outputSamples.empty() &&
1585 (*it)->m_processingSamples.empty())
1587 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
1588 (*it)->m_drain = false;
1589 (*it)->m_resampleBuffers->m_drain = false;
1590 (*it)->m_started = false;
1592 // set variables being polled via stream interface
1593 CSingleLock lock((*it)->m_streamLock);
1594 if ((*it)->m_streamSlave)
1596 CActiveAEStream *slave = (CActiveAEStream*)((*it)->m_streamSlave);
1597 slave->m_paused = false;
1599 // TODO: find better solution for this
1600 // gapless bites audiophile
1601 if (m_settings.config == AE_CONFIG_MATCH)
1602 Configure(&slave->m_format);
1604 (*it)->m_streamSlave = NULL;
1606 (*it)->m_streamDrained = true;
1607 (*it)->m_streamDraining = false;
1608 (*it)->m_streamFading = false;
1613 if (m_stats.GetWaterLevel() < MAX_WATER_LEVEL &&
1614 (m_mode != MODE_TRANSCODE || (m_encoderBuffers && !m_encoderBuffers->m_freeSamples.empty())))
1616 // mix streams and sounds sounds
1617 if (m_mode != MODE_RAW)
1619 CSampleBuffer *out = NULL;
1620 if (!m_sounds_playing.empty() && m_streams.empty())
1622 if (m_silenceBuffers && !m_silenceBuffers->m_freeSamples.empty())
1624 out = m_silenceBuffers->GetFreeBuffer();
1625 for (int i=0; i<out->pkt->planes; i++)
1627 memset(out->pkt->data[i], 0, out->pkt->linesize);
1629 out->pkt->nb_samples = out->pkt->max_nb_samples;
1634 std::list<CActiveAEStream*>::iterator it;
1636 // if we deal with more than a single stream, all streams
1637 // must provide samples for mixing
1638 bool allStreamsReady = true;
1639 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1641 if ((*it)->m_paused || !(*it)->m_started || !(*it)->m_resampleBuffers)
1644 if ((*it)->m_resampleBuffers->m_outputSamples.empty())
1645 allStreamsReady = false;
1648 bool needClamp = false;
1649 for (it = m_streams.begin(); it != m_streams.end() && allStreamsReady; ++it)
1651 if ((*it)->m_paused || !(*it)->m_resampleBuffers)
1654 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1656 (*it)->m_started = true;
1660 out = (*it)->m_resampleBuffers->m_outputSamples.front();
1661 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1663 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1665 float fadingStep = 0.0f;
1668 if ((*it)->m_fadingSamples == -1)
1670 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1671 (*it)->m_volume = (*it)->m_fadingBase;
1673 if ((*it)->m_fadingSamples > 0)
1675 nb_floats = out->pkt->config.channels / out->pkt->planes;
1676 nb_loops = out->pkt->nb_samples;
1677 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1678 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1679 fadingStep = delta / samples;
1682 // for stream amplification,
1683 // turned off downmix normalization,
1684 // or if sink format is float (in order to prevent from clipping)
1685 // we need to run on a per sample basis
1686 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize || (m_sinkFormat.m_dataFormat == AE_FMT_FLOAT))
1688 nb_floats = out->pkt->config.channels / out->pkt->planes;
1689 nb_loops = out->pkt->nb_samples;
1692 for(int i=0; i<nb_loops; i++)
1694 if ((*it)->m_fadingSamples > 0)
1696 (*it)->m_volume += fadingStep;
1697 (*it)->m_fadingSamples--;
1699 if ((*it)->m_fadingSamples == 0)
1701 // set variables being polled via stream interface
1702 CSingleLock lock((*it)->m_streamLock);
1703 (*it)->m_streamFading = false;
1707 // volume for stream
1708 float volume = (*it)->m_volume * (*it)->m_rgain;
1710 volume *= (*it)->m_limiter.Run((float**)out->pkt->data, out->pkt->config.channels, i*nb_floats, out->pkt->planes > 1);
1712 for(int j=0; j<out->pkt->planes; j++)
1715 CAEUtil::SSEMulArray((float*)out->pkt->data[j]+i*nb_floats, volume, nb_floats);
1717 float* fbuffer = (float*) out->pkt->data[j]+i*nb_floats;
1718 for (int k = 0; k < nb_floats; ++k)
1720 fbuffer[k] *= volume;
1728 CSampleBuffer *mix = NULL;
1729 mix = (*it)->m_resampleBuffers->m_outputSamples.front();
1730 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1732 int nb_floats = mix->pkt->nb_samples * mix->pkt->config.channels / mix->pkt->planes;
1734 float fadingStep = 0.0f;
1737 if ((*it)->m_fadingSamples == -1)
1739 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1740 (*it)->m_volume = (*it)->m_fadingBase;
1742 if ((*it)->m_fadingSamples > 0)
1744 nb_floats = mix->pkt->config.channels / mix->pkt->planes;
1745 nb_loops = mix->pkt->nb_samples;
1746 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1747 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1748 fadingStep = delta / samples;
1751 // for streams amplification of turned off downmix normalization
1752 // we need to run on a per sample basis
1753 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize)
1755 nb_floats = out->pkt->config.channels / out->pkt->planes;
1756 nb_loops = out->pkt->nb_samples;
1759 for(int i=0; i<nb_loops; i++)
1761 if ((*it)->m_fadingSamples > 0)
1763 (*it)->m_volume += fadingStep;
1764 (*it)->m_fadingSamples--;
1766 if ((*it)->m_fadingSamples == 0)
1768 // set variables being polled via stream interface
1769 CSingleLock lock((*it)->m_streamLock);
1770 (*it)->m_streamFading = false;
1774 // volume for stream
1775 float volume = (*it)->m_volume * (*it)->m_rgain;
1777 volume *= (*it)->m_limiter.Run((float**)mix->pkt->data, mix->pkt->config.channels, i*nb_floats, mix->pkt->planes > 1);
1779 for(int j=0; j<out->pkt->planes && j<mix->pkt->planes; j++)
1781 float *dst = (float*)out->pkt->data[j]+i*nb_floats;
1782 float *src = (float*)mix->pkt->data[j]+i*nb_floats;
1784 CAEUtil::SSEMulAddArray(dst, src, volume, nb_floats);
1785 for (int k = 0; k < nb_floats; ++k)
1787 if (fabs(dst[k]) > 1.0f)
1794 for (int k = 0; k < nb_floats; ++k)
1796 dst[k] += src[k] * volume;
1797 if (fabs(dst[k]) > 1.0f)
1809 // finally clamp samples
1810 if(out && needClamp)
1812 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1813 for(int i=0; i<out->pkt->planes; i++)
1815 CAEUtil::ClampArray((float*)out->pkt->data[i], nb_floats);
1819 // process output buffer, gui sounds, encode, viz
1824 CSingleLock lock(m_vizLock);
1825 if (m_audioCallback && m_vizBuffers && !m_streams.empty())
1827 if (!m_vizInitialized)
1829 m_audioCallback->OnInitialize(2, m_vizBuffers->m_format.m_sampleRate, 32);
1830 m_vizInitialized = true;
1833 if (!m_vizBuffersInput->m_freeSamples.empty())
1835 // copy the samples into the viz input buffer
1836 CSampleBuffer *viz = m_vizBuffersInput->GetFreeBuffer();
1837 int samples = std::min(512, out->pkt->nb_samples);
1838 int bytes = samples * out->pkt->config.channels / out->pkt->planes * out->pkt->bytes_per_sample;
1839 for(int i= 0; i < out->pkt->planes; i++)
1841 memcpy(viz->pkt->data[i], out->pkt->data[i], bytes);
1843 viz->pkt->nb_samples = samples;
1844 m_vizBuffers->m_inputSamples.push_back(viz);
1847 CLog::Log(LOGWARNING,"ActiveAE::%s - viz ran out of free buffers", __FUNCTION__);
1848 unsigned int now = XbmcThreads::SystemClockMillis();
1849 unsigned int timestamp = now + m_stats.GetDelay() * 1000;
1850 busy |= m_vizBuffers->ResampleBuffers(timestamp);
1851 while(!m_vizBuffers->m_outputSamples.empty())
1853 CSampleBuffer *buf = m_vizBuffers->m_outputSamples.front();
1854 if ((now - buf->timestamp) & 0x80000000)
1859 samples = std::min(512, buf->pkt->nb_samples);
1860 m_audioCallback->OnAudioData((float*)(buf->pkt->data[0]), samples);
1862 m_vizBuffers->m_outputSamples.pop_front();
1866 else if (m_vizBuffers)
1867 m_vizBuffers->Flush();
1871 MixSounds(*(out->pkt));
1872 if (!m_sinkHasVolume || m_muted)
1873 Deamplify(*(out->pkt));
1875 if (m_mode == MODE_TRANSCODE && m_encoder)
1877 CSampleBuffer *buf = m_encoderBuffers->GetFreeBuffer();
1878 m_encoder->Encode(out->pkt->data[0], out->pkt->planes*out->pkt->linesize,
1879 buf->pkt->data[0], buf->pkt->planes*buf->pkt->linesize);
1880 buf->pkt->nb_samples = buf->pkt->max_nb_samples;
1890 m_stats.AddSamples(out->pkt->nb_samples, m_streams);
1891 m_sinkBuffers->m_inputSamples.push_back(out);
1897 std::list<CActiveAEStream*>::iterator it;
1898 CSampleBuffer *buffer;
1899 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1901 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1903 buffer = (*it)->m_resampleBuffers->m_outputSamples.front();
1904 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1905 m_stats.AddSamples(buffer->pkt->nb_samples, m_streams);
1906 m_sinkBuffers->m_inputSamples.push_back(buffer);
1911 // serve sink buffers
1912 busy = m_sinkBuffers->ResampleBuffers();
1913 while(!m_sinkBuffers->m_outputSamples.empty())
1915 CSampleBuffer *out = NULL;
1916 out = m_sinkBuffers->m_outputSamples.front();
1917 m_sinkBuffers->m_outputSamples.pop_front();
1918 m_sink.m_dataPort.SendOutMessage(CSinkDataProtocol::SAMPLE,
1919 &out, sizeof(CSampleBuffer*));
1927 bool CActiveAE::HasWork()
1929 if (!m_sounds_playing.empty())
1931 if (!m_sinkBuffers->m_inputSamples.empty())
1933 if (!m_sinkBuffers->m_outputSamples.empty())
1936 std::list<CActiveAEStream*>::iterator it;
1937 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1939 if (!(*it)->m_resampleBuffers->m_inputSamples.empty())
1941 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1943 if (!(*it)->m_processingSamples.empty())
1950 void CActiveAE::MixSounds(CSoundPacket &dstSample)
1952 if (m_sounds_playing.empty())
1957 float *sample_buffer;
1958 int max_samples = dstSample.nb_samples;
1960 std::list<SoundState>::iterator it;
1961 for (it = m_sounds_playing.begin(); it != m_sounds_playing.end(); )
1963 if (!it->sound->IsConverted())
1964 ResampleSound(it->sound);
1965 int available_samples = it->sound->GetSound(false)->nb_samples - it->samples_played;
1966 int mix_samples = std::min(max_samples, available_samples);
1967 int start = it->samples_played *
1968 m_dllAvUtil.av_get_bytes_per_sample(it->sound->GetSound(false)->config.fmt) *
1969 it->sound->GetSound(false)->config.channels /
1970 it->sound->GetSound(false)->planes;
1972 for(int j=0; j<dstSample.planes; j++)
1974 volume = it->sound->GetVolume();
1975 out = (float*)dstSample.data[j];
1976 sample_buffer = (float*)(it->sound->GetSound(false)->data[j]+start);
1977 int nb_floats = mix_samples * dstSample.config.channels / dstSample.planes;
1979 CAEUtil::SSEMulAddArray(out, sample_buffer, volume, nb_floats);
1981 for (int k = 0; k < nb_floats; ++k)
1982 *out++ += *sample_buffer++ * volume;
1986 it->samples_played += mix_samples;
1988 // no more frames, so remove it from the list
1989 if (it->samples_played >= it->sound->GetSound(false)->nb_samples)
1991 it = m_sounds_playing.erase(it);
1998 void CActiveAE::Deamplify(CSoundPacket &dstSample)
2000 if (m_volume < 1.0 || m_muted)
2003 int nb_floats = dstSample.nb_samples * dstSample.config.channels / dstSample.planes;
2005 for(int j=0; j<dstSample.planes; j++)
2007 buffer = (float*)dstSample.data[j];
2009 CAEUtil::SSEMulArray(buffer, m_muted ? 0.0 : m_volume, nb_floats);
2011 float *fbuffer = buffer;
2012 for (int i = 0; i < nb_floats; i++)
2013 *fbuffer++ *= m_volume;
2019 //-----------------------------------------------------------------------------
2021 //-----------------------------------------------------------------------------
2023 void CActiveAE::LoadSettings()
2025 m_settings.device = CSettings::Get().GetString("audiooutput.audiodevice");
2026 m_settings.passthoughdevice = CSettings::Get().GetString("audiooutput.passthroughdevice");
2028 m_settings.config = CSettings::Get().GetInt("audiooutput.config");
2029 m_settings.channels = (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958) ? AE_CH_LAYOUT_2_0 : CSettings::Get().GetInt("audiooutput.channels");
2030 m_settings.samplerate = CSettings::Get().GetInt("audiooutput.samplerate");
2032 m_settings.stereoupmix = IsSettingVisible("audiooutput.stereoupmix") ? CSettings::Get().GetBool("audiooutput.stereoupmix") : false;
2033 m_settings.normalizelevels = CSettings::Get().GetBool("audiooutput.normalizelevels");
2034 m_settings.guisoundmode = CSettings::Get().GetInt("audiooutput.guisoundmode");
2036 m_settings.passthrough = m_settings.config == AE_CONFIG_FIXED ? false : CSettings::Get().GetBool("audiooutput.passthrough");
2037 m_settings.ac3passthrough = CSettings::Get().GetBool("audiooutput.ac3passthrough");
2038 m_settings.ac3transcode = CSettings::Get().GetBool("audiooutput.ac3transcode");
2039 m_settings.eac3passthrough = CSettings::Get().GetBool("audiooutput.eac3passthrough");
2040 m_settings.truehdpassthrough = CSettings::Get().GetBool("audiooutput.truehdpassthrough");
2041 m_settings.dtspassthrough = CSettings::Get().GetBool("audiooutput.dtspassthrough");
2042 m_settings.dtshdpassthrough = CSettings::Get().GetBool("audiooutput.dtshdpassthrough");
2044 m_settings.resampleQuality = static_cast<AEQuality>(CSettings::Get().GetInt("audiooutput.processquality"));
2047 bool CActiveAE::Initialize()
2049 if (!m_dllAvUtil.Load() || !m_dllAvCodec.Load() || !m_dllAvFormat.Load())
2051 CLog::Log(LOGERROR,"CActiveAE::Initialize - failed to load ffmpeg libraries");
2054 m_dllAvFormat.av_register_all();
2058 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2062 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2066 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2073 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2078 // hook into windowing for receiving display reset events
2079 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
2080 g_Windowing.Register(this);
2083 m_inMsgEvent.Reset();
2087 void CActiveAE::EnumerateOutputDevices(AEDeviceList &devices, bool passthrough)
2089 m_sink.EnumerateOutputDevices(devices, passthrough);
2092 std::string CActiveAE::GetDefaultDevice(bool passthrough)
2094 return m_sink.GetDefaultDevice(passthrough);
2097 void CActiveAE::OnSettingsChange(const std::string& setting)
2099 if (setting == "audiooutput.passthroughdevice" ||
2100 setting == "audiooutput.audiodevice" ||
2101 setting == "audiooutput.config" ||
2102 setting == "audiooutput.ac3passthrough" ||
2103 setting == "audiooutput.ac3transcode" ||
2104 setting == "audiooutput.eac3passthrough" ||
2105 setting == "audiooutput.dtspassthrough" ||
2106 setting == "audiooutput.truehdpassthrough" ||
2107 setting == "audiooutput.dtshdpassthrough" ||
2108 setting == "audiooutput.channels" ||
2109 setting == "audiooutput.stereoupmix" ||
2110 setting == "audiooutput.streamsilence" ||
2111 setting == "audiooutput.processquality" ||
2112 setting == "audiooutput.passthrough" ||
2113 setting == "audiooutput.samplerate" ||
2114 setting == "audiooutput.normalizelevels" ||
2115 setting == "audiooutput.guisoundmode")
2117 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RECONFIGURE);
2121 bool CActiveAE::SupportsRaw(AEDataFormat format)
2123 if (!m_sink.HasPassthroughDevice())
2126 // those formats require HDMI
2127 if (format == AE_FMT_DTSHD || format == AE_FMT_TRUEHD)
2129 if(m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.passthroughdevice")) != AE_DEVTYPE_HDMI)
2137 bool CActiveAE::SupportsSilenceTimeout()
2142 bool CActiveAE::SupportsQualityLevel(enum AEQuality level)
2144 if (level == AE_QUALITY_LOW || level == AE_QUALITY_MID || level == AE_QUALITY_HIGH)
2150 bool CActiveAE::IsSettingVisible(const std::string &settingId)
2152 if (settingId == "audiooutput.samplerate")
2154 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958)
2156 if (CSettings::Get().GetInt("audiooutput.config") == AE_CONFIG_FIXED)
2159 else if (settingId == "audiooutput.channels")
2161 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) != AE_DEVTYPE_IEC958)
2164 else if (settingId == "audiooutput.passthrough")
2166 if (m_sink.HasPassthroughDevice() && CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2169 else if (settingId == "audiooutput.truehdpassthrough")
2171 if (m_sink.HasPassthroughDevice() &&
2172 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2173 m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.passthroughdevice")) == AE_DEVTYPE_HDMI)
2176 else if (settingId == "audiooutput.dtshdpassthrough")
2178 if (m_sink.HasPassthroughDevice() &&
2179 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2180 m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.passthroughdevice")) == AE_DEVTYPE_HDMI)
2183 else if (settingId == "audiooutput.stereoupmix")
2185 if (m_sink.HasPassthroughDevice() ||
2186 CSettings::Get().GetInt("audiooutput.channels") > AE_CH_LAYOUT_2_0)
2189 else if (settingId == "audiooutput.ac3transcode")
2191 if (m_sink.HasPassthroughDevice() &&
2192 CSettings::Get().GetBool("audiooutput.ac3passthrough") &&
2193 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2194 (CSettings::Get().GetInt("audiooutput.channels") <= AE_CH_LAYOUT_2_0 || m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958))
2200 void CActiveAE::Shutdown()
2205 bool CActiveAE::Suspend()
2207 return m_controlPort.SendOutMessage(CActiveAEControlProtocol::SUSPEND);
2210 bool CActiveAE::Resume()
2213 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2217 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2221 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2227 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2231 m_inMsgEvent.Reset();
2235 bool CActiveAE::IsSuspended()
2237 return m_stats.IsSuspended();
2240 float CActiveAE::GetVolume()
2245 void CActiveAE::SetVolume(const float volume)
2247 m_aeVolume = std::max( 0.0f, std::min(1.0f, volume));
2248 m_controlPort.SendOutMessage(CActiveAEControlProtocol::VOLUME, &m_aeVolume, sizeof(float));
2251 void CActiveAE::SetMute(const bool enabled)
2253 m_aeMuted = enabled;
2254 m_controlPort.SendOutMessage(CActiveAEControlProtocol::MUTE, &m_aeMuted, sizeof(bool));
2257 bool CActiveAE::IsMuted()
2262 void CActiveAE::SetSoundMode(const int mode)
2267 void CActiveAE::KeepConfiguration(unsigned int millis)
2269 unsigned int timeMs = millis;
2270 m_controlPort.SendOutMessage(CActiveAEControlProtocol::KEEPCONFIG, &timeMs, sizeof(unsigned int));
2273 void CActiveAE::OnLostDevice()
2276 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::DISPLAYLOST,
2280 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2284 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2289 CLog::Log(LOGERROR, "ActiveAE::%s - timed out", __FUNCTION__);
2293 void CActiveAE::OnResetDevice()
2295 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DISPLAYRESET);
2298 //-----------------------------------------------------------------------------
2300 //-----------------------------------------------------------------------------
2302 uint8_t **CActiveAE::AllocSoundSample(SampleConfig &config, int &samples, int &bytes_per_sample, int &planes, int &linesize)
2305 planes = m_dllAvUtil.av_sample_fmt_is_planar(config.fmt) ? config.channels : 1;
2306 buffer = new uint8_t*[planes];
2308 // align buffer to 16 in order to be compatible with sse in CAEConvert
2309 m_dllAvUtil.av_samples_alloc(buffer, &linesize, config.channels,
2310 samples, config.fmt, 16);
2311 bytes_per_sample = m_dllAvUtil.av_get_bytes_per_sample(config.fmt);
2315 void CActiveAE::FreeSoundSample(uint8_t **data)
2317 m_dllAvUtil.av_freep(data);
2321 bool CActiveAE::CompareFormat(AEAudioFormat &lhs, AEAudioFormat &rhs)
2323 if (lhs.m_channelLayout != rhs.m_channelLayout ||
2324 lhs.m_dataFormat != rhs.m_dataFormat ||
2325 lhs.m_sampleRate != rhs.m_sampleRate)
2331 //-----------------------------------------------------------------------------
2333 //-----------------------------------------------------------------------------
2336 * load sound from an audio file and store original format
2337 * register the sound in ActiveAE
2338 * later when the engine is idle it will convert the sound to sink format
2341 #define SOUNDBUFFER_SIZE 20480
2343 IAESound *CActiveAE::MakeSound(const std::string& file)
2345 AVFormatContext *fmt_ctx = NULL;
2346 AVCodecContext *dec_ctx = NULL;
2347 AVIOContext *io_ctx;
2348 AVInputFormat *io_fmt;
2349 AVCodec *dec = NULL;
2350 CActiveAESound *sound = NULL;
2351 SampleConfig config;
2353 sound = new CActiveAESound(file);
2354 if (!sound->Prepare())
2359 int fileSize = sound->GetFileSize();
2361 fmt_ctx = m_dllAvFormat.avformat_alloc_context();
2362 unsigned char* buffer = (unsigned char*)m_dllAvUtil.av_malloc(SOUNDBUFFER_SIZE+FF_INPUT_BUFFER_PADDING_SIZE);
2363 io_ctx = m_dllAvFormat.avio_alloc_context(buffer, SOUNDBUFFER_SIZE, 0,
2364 sound, CActiveAESound::Read, NULL, CActiveAESound::Seek);
2365 io_ctx->max_packet_size = sound->GetChunkSize();
2366 if(io_ctx->max_packet_size)
2367 io_ctx->max_packet_size *= SOUNDBUFFER_SIZE / io_ctx->max_packet_size;
2369 if(!sound->IsSeekPosible())
2370 io_ctx->seekable = 0;
2372 fmt_ctx->pb = io_ctx;
2374 m_dllAvFormat.av_probe_input_buffer(io_ctx, &io_fmt, file.c_str(), NULL, 0, 0);
2377 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2383 if (m_dllAvFormat.avformat_open_input(&fmt_ctx, file.c_str(), NULL, NULL) == 0)
2385 fmt_ctx->flags |= AVFMT_FLAG_NOPARSE;
2386 if (m_dllAvFormat.avformat_find_stream_info(fmt_ctx, NULL) >= 0)
2388 dec_ctx = fmt_ctx->streams[0]->codec;
2389 dec = m_dllAvCodec.avcodec_find_decoder(dec_ctx->codec_id);
2390 config.sample_rate = dec_ctx->sample_rate;
2391 config.channels = dec_ctx->channels;
2392 config.channel_layout = dec_ctx->channel_layout;
2397 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2402 dec_ctx = m_dllAvCodec.avcodec_alloc_context3(dec);
2403 dec_ctx->sample_rate = config.sample_rate;
2404 dec_ctx->channels = config.channels;
2405 if (!config.channel_layout)
2406 config.channel_layout = m_dllAvUtil.av_get_default_channel_layout(config.channels);
2407 dec_ctx->channel_layout = config.channel_layout;
2410 AVFrame *decoded_frame = NULL;
2411 decoded_frame = m_dllAvCodec.avcodec_alloc_frame();
2413 if (m_dllAvCodec.avcodec_open2(dec_ctx, dec, NULL) >= 0)
2418 m_dllAvCodec.av_init_packet(&avpkt);
2420 while (m_dllAvFormat.av_read_frame(fmt_ctx, &avpkt) >= 0)
2423 len = m_dllAvCodec.avcodec_decode_audio4(dec_ctx, decoded_frame, &got_frame, &avpkt);
2426 m_dllAvCodec.avcodec_close(dec_ctx);
2427 m_dllAvUtil.av_free(dec_ctx);
2428 m_dllAvUtil.av_free(&decoded_frame);
2429 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2437 int samples = fileSize / m_dllAvUtil.av_get_bytes_per_sample(dec_ctx->sample_fmt) / config.channels;
2438 config.fmt = dec_ctx->sample_fmt;
2439 config.bits_per_sample = dec_ctx->bits_per_coded_sample;
2440 sound->InitSound(true, config, samples);
2443 sound->StoreSound(true, decoded_frame->extended_data,
2444 decoded_frame->nb_samples, decoded_frame->linesize[0]);
2447 m_dllAvCodec.avcodec_close(dec_ctx);
2450 m_dllAvUtil.av_free(dec_ctx);
2451 m_dllAvUtil.av_free(decoded_frame);
2452 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2457 m_dataPort.SendOutMessage(CActiveAEDataProtocol::NEWSOUND, &sound, sizeof(CActiveAESound*));
2462 void CActiveAE::FreeSound(IAESound *sound)
2464 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESOUND, &sound, sizeof(CActiveAESound*));
2467 void CActiveAE::PlaySound(CActiveAESound *sound)
2469 m_dataPort.SendOutMessage(CActiveAEDataProtocol::PLAYSOUND, &sound, sizeof(CActiveAESound*));
2472 void CActiveAE::StopSound(CActiveAESound *sound)
2474 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STOPSOUND, &sound, sizeof(CActiveAESound*));
2478 * resample sounds to destination format for mixing
2479 * destination format is either format of stream or
2480 * default sink format when no stream is playing
2482 void CActiveAE::ResampleSounds()
2484 if (m_settings.guisoundmode == AE_SOUND_OFF ||
2485 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
2488 std::vector<CActiveAESound*>::iterator it;
2489 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
2491 if (!(*it)->IsConverted())
2494 // only do one sound, then yield to main loop
2500 bool CActiveAE::ResampleSound(CActiveAESound *sound)
2502 SampleConfig orig_config, dst_config;
2503 uint8_t **dst_buffer;
2506 if (m_mode == MODE_RAW || m_internalFormat.m_dataFormat == AE_FMT_INVALID)
2509 if (!sound->GetSound(true))
2512 orig_config = sound->GetSound(true)->config;
2514 dst_config.channel_layout = CActiveAEResample::GetAVChannelLayout(m_internalFormat.m_channelLayout);
2515 dst_config.channels = m_internalFormat.m_channelLayout.Count();
2516 dst_config.sample_rate = m_internalFormat.m_sampleRate;
2517 dst_config.fmt = CActiveAEResample::GetAVSampleFormat(m_internalFormat.m_dataFormat);
2518 dst_config.bits_per_sample = CAEUtil::DataFormatToUsedBits(m_internalFormat.m_dataFormat);
2520 CActiveAEResample *resampler = new CActiveAEResample();
2521 resampler->Init(dst_config.channel_layout,
2522 dst_config.channels,
2523 dst_config.sample_rate,
2525 dst_config.bits_per_sample,
2526 orig_config.channel_layout,
2527 orig_config.channels,
2528 orig_config.sample_rate,
2530 orig_config.bits_per_sample,
2534 m_settings.resampleQuality);
2536 dst_samples = resampler->CalcDstSampleCount(sound->GetSound(true)->nb_samples,
2537 m_internalFormat.m_sampleRate,
2538 orig_config.sample_rate);
2540 dst_buffer = sound->InitSound(false, dst_config, dst_samples);
2546 int samples = resampler->Resample(dst_buffer, dst_samples,
2547 sound->GetSound(true)->data,
2548 sound->GetSound(true)->nb_samples,
2551 sound->GetSound(false)->nb_samples = samples;
2554 sound->SetConverted(true);
2558 //-----------------------------------------------------------------------------
2560 //-----------------------------------------------------------------------------
2562 IAEStream *CActiveAE::MakeStream(enum AEDataFormat dataFormat, unsigned int sampleRate, unsigned int encodedSampleRate, CAEChannelInfo channelLayout, unsigned int options)
2564 //TODO: pass number of samples in audio packet
2566 AEAudioFormat format;
2567 format.m_dataFormat = dataFormat;
2568 format.m_sampleRate = sampleRate;
2569 format.m_encodedRate = encodedSampleRate;
2570 format.m_channelLayout = channelLayout;
2571 format.m_frames = format.m_sampleRate / 10;
2572 format.m_frameSize = format.m_channelLayout.Count() *
2573 (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
2576 msg.format = format;
2577 msg.options = options;
2580 if (m_dataPort.SendOutMessageSync(CActiveAEDataProtocol::NEWSTREAM,
2582 &msg, sizeof(MsgStreamNew)))
2584 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2587 CActiveAEStream *stream = *(CActiveAEStream**)reply->data;
2594 CLog::Log(LOGERROR, "ActiveAE::%s - could not create stream", __FUNCTION__);
2598 IAEStream *CActiveAE::FreeStream(IAEStream *stream)
2600 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESTREAM, &stream, sizeof(IAEStream*));
2604 void CActiveAE::FlushStream(CActiveAEStream *stream)
2607 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::FLUSHSTREAM,
2609 &stream, sizeof(CActiveAEStream*)))
2611 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2615 CLog::Log(LOGERROR, "CActiveAE::FlushStream - failed");
2620 void CActiveAE::PauseStream(CActiveAEStream *stream, bool pause)
2622 // TODO pause sink, needs api change
2624 m_controlPort.SendOutMessage(CActiveAEControlProtocol::PAUSESTREAM,
2625 &stream, sizeof(CActiveAEStream*));
2627 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RESUMESTREAM,
2628 &stream, sizeof(CActiveAEStream*));
2631 void CActiveAE::SetStreamAmplification(CActiveAEStream *stream, float amplify)
2633 MsgStreamParameter msg;
2634 msg.stream = stream;
2635 msg.parameter.float_par = amplify;
2636 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMAMP,
2637 &msg, sizeof(MsgStreamParameter));
2640 void CActiveAE::SetStreamReplaygain(CActiveAEStream *stream, float rgain)
2642 MsgStreamParameter msg;
2643 msg.stream = stream;
2644 msg.parameter.float_par = rgain;
2645 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRGAIN,
2646 &msg, sizeof(MsgStreamParameter));
2649 void CActiveAE::SetStreamVolume(CActiveAEStream *stream, float volume)
2651 MsgStreamParameter msg;
2652 msg.stream = stream;
2653 msg.parameter.float_par = volume;
2654 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMVOLUME,
2655 &msg, sizeof(MsgStreamParameter));
2658 void CActiveAE::SetStreamResampleRatio(CActiveAEStream *stream, double ratio)
2660 MsgStreamParameter msg;
2661 msg.stream = stream;
2662 msg.parameter.double_par = ratio;
2663 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRESAMPLERATIO,
2664 &msg, sizeof(MsgStreamParameter));
2667 void CActiveAE::SetStreamFade(CActiveAEStream *stream, float from, float target, unsigned int millis)
2670 msg.stream = stream;
2672 msg.target = target;
2673 msg.millis = millis;
2674 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMFADE,
2675 &msg, sizeof(MsgStreamFade));
2678 void CActiveAE::RegisterAudioCallback(IAudioCallback* pCallback)
2680 CSingleLock lock(m_vizLock);
2681 m_audioCallback = pCallback;
2682 m_vizInitialized = false;
2685 void CActiveAE::UnregisterAudioCallback()
2687 CSingleLock lock(m_vizLock);
2688 m_audioCallback = NULL;