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
35 #define MAX_BUFFER_TIME 0.1 // max time of a buffer in seconds
37 void CEngineStats::Reset(unsigned int sampleRate)
39 CSingleLock lock(m_lock);
40 m_sinkUpdate = XbmcThreads::SystemClockMillis();
42 m_sinkSampleRate = sampleRate;
43 m_bufferedSamples = 0;
47 void CEngineStats::UpdateSinkDelay(double delay, int samples)
49 CSingleLock lock(m_lock);
50 m_sinkUpdate = XbmcThreads::SystemClockMillis();
52 if (samples > m_bufferedSamples)
54 CLog::Log(LOGERROR, "CEngineStats::UpdateSinkDelay - inconsistency in buffer time");
57 m_bufferedSamples -= samples;
60 void CEngineStats::AddSamples(int samples, std::list<CActiveAEStream*> &streams)
62 CSingleLock lock(m_lock);
63 m_bufferedSamples += samples;
65 //update buffered time of streams
66 std::list<CActiveAEStream*>::iterator it;
67 for(it=streams.begin(); it!=streams.end(); ++it)
70 std::deque<CSampleBuffer*>::iterator itBuf;
71 for(itBuf=(*it)->m_processingSamples.begin(); itBuf!=(*it)->m_processingSamples.end(); ++itBuf)
73 delay += (float)(*itBuf)->pkt->nb_samples / (*itBuf)->pkt->config.sample_rate;
75 delay += (*it)->m_resampleBuffers->GetDelay();
76 (*it)->m_bufferedTime = delay;
80 float CEngineStats::GetDelay()
82 CSingleLock lock(m_lock);
83 unsigned int now = XbmcThreads::SystemClockMillis();
84 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
85 delay += (float)m_bufferedSamples / m_sinkSampleRate;
93 // this is used to sync a/v so we need to add sink latency here
94 float CEngineStats::GetDelay(CActiveAEStream *stream)
96 CSingleLock lock(m_lock);
97 unsigned int now = XbmcThreads::SystemClockMillis();
98 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
99 delay += m_sinkLatency;
100 delay += (float)m_bufferedSamples / m_sinkSampleRate;
105 delay += stream->m_bufferedTime;
109 float CEngineStats::GetCacheTime(CActiveAEStream *stream)
111 CSingleLock lock(m_lock);
112 float delay = (float)m_bufferedSamples / m_sinkSampleRate;
114 delay += stream->m_bufferedTime;
118 float CEngineStats::GetCacheTotal(CActiveAEStream *stream)
120 return MAX_CACHE_LEVEL + m_sinkCacheTotal;
123 float CEngineStats::GetWaterLevel()
125 return (float)m_bufferedSamples / m_sinkSampleRate;
128 void CEngineStats::SetSuspended(bool state)
130 CSingleLock lock(m_lock);
134 bool CEngineStats::IsSuspended()
136 CSingleLock lock(m_lock);
140 CActiveAE::CActiveAE() :
142 m_controlPort("OutputControlPort", &m_inMsgEvent, &m_outMsgEvent),
143 m_dataPort("OutputDataPort", &m_inMsgEvent, &m_outMsgEvent),
144 m_sink(&m_outMsgEvent)
146 m_sinkBuffers = NULL;
147 m_silenceBuffers = NULL;
148 m_encoderBuffers = NULL;
150 m_vizBuffersInput = NULL;
157 m_audioCallback = NULL;
158 m_vizInitialized = false;
159 m_sinkHasVolume = false;
162 CActiveAE::~CActiveAE()
167 void CActiveAE::Dispose()
169 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
170 g_Windowing.Unregister(this);
176 m_controlPort.Purge();
180 m_dllAvFormat.Unload();
181 m_dllAvCodec.Unload();
182 m_dllAvUtil.Unload();
185 //-----------------------------------------------------------------------------
187 //-----------------------------------------------------------------------------
193 AE_TOP_UNCONFIGURED, // 2
194 AE_TOP_RECONFIGURING, // 3
195 AE_TOP_CONFIGURED, // 4
196 AE_TOP_CONFIGURED_SUSPEND, // 5
197 AE_TOP_CONFIGURED_IDLE, // 6
198 AE_TOP_CONFIGURED_PLAY, // 7
201 int AE_parentStates[] = {
204 0, //TOP_UNCONFIGURED
206 0, //TOP_RECONFIGURING
207 4, //TOP_CONFIGURED_SUSPEND
208 4, //TOP_CONFIGURED_IDLE
209 4, //TOP_CONFIGURED_PLAY
212 void CActiveAE::StateMachine(int signal, Protocol *port, Message *msg)
214 for (int state = m_state; ; state = AE_parentStates[state])
219 if (port == &m_controlPort)
223 case CActiveAEControlProtocol::GETSTATE:
224 msg->Reply(CActiveAEControlProtocol::ACC, &m_state, sizeof(m_state));
226 case CActiveAEControlProtocol::VOLUME:
227 m_volume = *(float*)msg->data;
229 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
231 case CActiveAEControlProtocol::MUTE:
232 m_muted = *(bool*)msg->data;
234 case CActiveAEControlProtocol::KEEPCONFIG:
235 m_extKeepConfig = *(unsigned int*)msg->data;
237 case CActiveAEControlProtocol::DISPLAYRESET:
239 case CActiveAEControlProtocol::APPFOCUSED:
240 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::APPFOCUSED, msg->data, sizeof(bool));
246 else if (port == &m_dataPort)
250 case CActiveAEDataProtocol::NEWSOUND:
251 CActiveAESound *sound;
252 sound = *(CActiveAESound**)msg->data;
255 m_sounds.push_back(sound);
259 case CActiveAEDataProtocol::FREESTREAM:
260 CActiveAEStream *stream;
261 stream = *(CActiveAEStream**)msg->data;
262 DiscardStream(stream);
264 case CActiveAEDataProtocol::FREESOUND:
265 sound = *(CActiveAESound**)msg->data;
268 case CActiveAEDataProtocol::DRAINSTREAM:
269 stream = *(CActiveAEStream**)msg->data;
270 stream->m_drain = true;
271 stream->m_resampleBuffers->m_drain = true;
272 msg->Reply(CActiveAEDataProtocol::ACC);
273 stream->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
279 else if (port == &m_sink.m_dataPort)
283 case CSinkDataProtocol::RETURNSAMPLE:
284 CSampleBuffer **buffer;
285 buffer = (CSampleBuffer**)msg->data;
296 std::string portName = port == NULL ? "timer" : port->portName;
297 CLog::Log(LOGWARNING, "CActiveAE::%s - signal: %d from port: %s not handled for state: %d", __FUNCTION__, signal, portName.c_str(), m_state);
302 if (port == NULL) // timeout
306 case CActiveAEControlProtocol::TIMEOUT:
312 m_state = AE_TOP_CONFIGURED_IDLE;
317 m_state = AE_TOP_ERROR;
327 case AE_TOP_UNCONFIGURED:
328 if (port == &m_controlPort)
332 case CActiveAEControlProtocol::INIT:
334 m_sink.EnumerateSinkList(false);
337 msg->Reply(CActiveAEControlProtocol::ACC);
340 m_state = AE_TOP_CONFIGURED_IDLE;
345 m_state = AE_TOP_ERROR;
356 case AE_TOP_RECONFIGURING:
357 if (port == NULL) // timeout
361 case CActiveAEControlProtocol::TIMEOUT:
368 if (!m_sinkBuffers->m_inputSamples.empty() || !m_sinkBuffers->m_outputSamples.empty())
373 if (NeedReconfigureSink())
380 m_state = AE_TOP_CONFIGURED_PLAY;
385 m_state = AE_TOP_ERROR;
388 m_extDeferData = false;
396 case AE_TOP_CONFIGURED:
397 if (port == &m_controlPort)
402 case CActiveAEControlProtocol::RECONFIGURE:
403 if (m_streams.empty())
406 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
410 if (!NeedReconfigureBuffers() && !NeedReconfigureSink())
412 m_state = AE_TOP_RECONFIGURING;
414 // don't accept any data until we are reconfigured
415 m_extDeferData = true;
417 case CActiveAEControlProtocol::SUSPEND:
419 m_stats.SetSuspended(true);
420 m_state = AE_TOP_CONFIGURED_SUSPEND;
421 m_extDeferData = true;
423 case CActiveAEControlProtocol::DISPLAYLOST:
424 if (m_sink.GetDeviceType(m_mode == MODE_PCM ? m_settings.device : m_settings.passthoughdevice) == AE_DEVTYPE_HDMI)
427 m_stats.SetSuspended(true);
428 m_state = AE_TOP_CONFIGURED_SUSPEND;
429 m_extDeferData = true;
431 msg->Reply(CActiveAEControlProtocol::ACC);
433 case CActiveAEControlProtocol::DEVICECHANGE:
436 while (!m_extLastDeviceChange.empty() && (now - m_extLastDeviceChange.front() > 0))
438 m_extLastDeviceChange.pop();
440 if (m_extLastDeviceChange.size() > 2)
442 CLog::Log(LOGWARNING,"CActiveAE - received %ld device change events within one second", m_extLastDeviceChange.size());
445 m_extLastDeviceChange.push(now);
447 m_sink.EnumerateSinkList(true);
453 m_state = AE_TOP_CONFIGURED_PLAY;
458 m_state = AE_TOP_ERROR;
461 m_controlPort.PurgeOut(CActiveAEControlProtocol::DEVICECHANGE);
463 case CActiveAEControlProtocol::PAUSESTREAM:
464 CActiveAEStream *stream;
465 stream = *(CActiveAEStream**)msg->data;
466 if (stream->m_paused != true && m_streams.size() == 1)
470 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
472 stream->m_paused = true;
474 case CActiveAEControlProtocol::RESUMESTREAM:
475 stream = *(CActiveAEStream**)msg->data;
476 stream->m_paused = false;
478 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
481 case CActiveAEControlProtocol::FLUSHSTREAM:
482 stream = *(CActiveAEStream**)msg->data;
483 SFlushStream(stream);
484 msg->Reply(CActiveAEControlProtocol::ACC);
487 case CActiveAEControlProtocol::STREAMAMP:
488 MsgStreamParameter *par;
489 par = (MsgStreamParameter*)msg->data;
490 par->stream->m_limiter.SetAmplification(par->parameter.float_par);
491 par->stream->m_amplify = par->parameter.float_par;
493 case CActiveAEControlProtocol::STREAMVOLUME:
494 par = (MsgStreamParameter*)msg->data;
495 par->stream->m_volume = par->parameter.float_par;
497 case CActiveAEControlProtocol::STREAMRGAIN:
498 par = (MsgStreamParameter*)msg->data;
499 par->stream->m_rgain = par->parameter.float_par;
501 case CActiveAEControlProtocol::STREAMRESAMPLERATIO:
502 par = (MsgStreamParameter*)msg->data;
503 if (par->stream->m_resampleBuffers)
505 par->stream->m_resampleBuffers->m_resampleRatio = par->parameter.double_par;
508 case CActiveAEControlProtocol::STREAMFADE:
510 fade = (MsgStreamFade*)msg->data;
511 fade->stream->m_fadingBase = fade->from;
512 fade->stream->m_fadingTarget = fade->target;
513 fade->stream->m_fadingTime = fade->millis;
514 fade->stream->m_fadingSamples = -1;
516 case CActiveAEControlProtocol::STOPSOUND:
517 CActiveAESound *sound;
518 sound = *(CActiveAESound**)msg->data;
525 else if (port == &m_dataPort)
529 case CActiveAEDataProtocol::PLAYSOUND:
530 CActiveAESound *sound;
531 sound = *(CActiveAESound**)msg->data;
532 if (m_settings.guisoundmode == AE_SOUND_OFF ||
533 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
537 SoundState st = {sound, 0};
538 m_sounds_playing.push_back(st);
540 m_state = AE_TOP_CONFIGURED_PLAY;
543 case CActiveAEDataProtocol::NEWSTREAM:
544 MsgStreamNew *streamMsg;
545 CActiveAEStream *stream;
546 streamMsg = (MsgStreamNew*)msg->data;
547 stream = CreateStream(streamMsg);
550 msg->Reply(CActiveAEDataProtocol::ACC, &stream, sizeof(CActiveAEStream*));
555 m_state = AE_TOP_CONFIGURED_PLAY;
560 m_state = AE_TOP_ERROR;
565 msg->Reply(CActiveAEDataProtocol::ERR);
567 case CActiveAEDataProtocol::STREAMSAMPLE:
568 MsgStreamSample *msgData;
569 CSampleBuffer *samples;
570 msgData = (MsgStreamSample*)msg->data;
571 samples = msgData->stream->m_processingSamples.front();
572 msgData->stream->m_processingSamples.pop_front();
573 if (samples != msgData->buffer)
574 CLog::Log(LOGERROR, "CActiveAE - inconsistency in stream sample message");
575 if (msgData->buffer->pkt->nb_samples == 0)
576 msgData->buffer->Return();
578 msgData->stream->m_resampleBuffers->m_inputSamples.push_back(msgData->buffer);
580 m_state = AE_TOP_CONFIGURED_PLAY;
582 case CActiveAEDataProtocol::FREESTREAM:
583 stream = *(CActiveAEStream**)msg->data;
584 DiscardStream(stream);
585 if (m_streams.empty())
588 m_extDrainTimer.Set(m_extKeepConfig);
590 m_extDrainTimer.Set(m_stats.GetDelay() * 1000);
594 m_state = AE_TOP_CONFIGURED_PLAY;
596 case CActiveAEDataProtocol::DRAINSTREAM:
597 stream = *(CActiveAEStream**)msg->data;
598 stream->m_drain = true;
599 stream->m_resampleBuffers->m_drain = true;
601 m_state = AE_TOP_CONFIGURED_PLAY;
602 msg->Reply(CActiveAEDataProtocol::ACC);
608 else if (port == &m_sink.m_dataPort)
612 case CSinkDataProtocol::RETURNSAMPLE:
613 CSampleBuffer **buffer;
614 buffer = (CSampleBuffer**)msg->data;
620 m_state = AE_TOP_CONFIGURED_PLAY;
628 case AE_TOP_CONFIGURED_SUSPEND:
629 if (port == &m_controlPort)
631 bool displayReset = false;
634 case CActiveAEControlProtocol::DISPLAYRESET:
636 case CActiveAEControlProtocol::INIT:
640 m_sink.EnumerateSinkList(true);
645 msg->Reply(CActiveAEControlProtocol::ACC);
648 m_state = AE_TOP_CONFIGURED_PLAY;
653 m_state = AE_TOP_ERROR;
656 m_stats.SetSuspended(false);
657 m_extDeferData = false;
659 case CActiveAEControlProtocol::DEVICECHANGE:
665 else if (port == &m_sink.m_dataPort)
669 case CSinkDataProtocol::RETURNSAMPLE:
670 CSampleBuffer **buffer;
671 buffer = (CSampleBuffer**)msg->data;
681 else if (port == NULL) // timeout
685 case CActiveAEControlProtocol::TIMEOUT:
694 case AE_TOP_CONFIGURED_IDLE:
695 if (port == &m_controlPort)
699 case CActiveAEControlProtocol::RESUMESTREAM:
700 CActiveAEStream *stream;
701 stream = *(CActiveAEStream**)msg->data;
702 stream->m_paused = false;
703 m_state = AE_TOP_CONFIGURED_PLAY;
706 case CActiveAEControlProtocol::FLUSHSTREAM:
707 stream = *(CActiveAEStream**)msg->data;
708 SFlushStream(stream);
709 msg->Reply(CActiveAEControlProtocol::ACC);
710 m_state = AE_TOP_CONFIGURED_PLAY;
717 else if (port == NULL) // timeout
721 case CActiveAEControlProtocol::TIMEOUT:
723 ClearDiscardedBuffers();
726 if (m_extDrainTimer.IsTimePast())
731 m_state = AE_TOP_CONFIGURED_PLAY;
736 m_state = AE_TOP_ERROR;
741 m_extTimeout = m_extDrainTimer.MillisLeft();
752 case AE_TOP_CONFIGURED_PLAY:
753 if (port == NULL) // timeout
757 case CActiveAEControlProtocol::TIMEOUT:
760 m_state = AE_TOP_ERROR;
769 if (!m_extDrain && HasWork())
771 ClearDiscardedBuffers();
776 m_state = AE_TOP_CONFIGURED_IDLE;
784 default: // we are in no state, should not happen
785 CLog::Log(LOGERROR, "CActiveAE::%s - no valid state: %d", __FUNCTION__, m_state);
791 void CActiveAE::Process()
794 Protocol *port = NULL;
796 XbmcThreads::EndTime timer;
798 m_state = AE_TOP_UNCONFIGURED;
800 m_bStateMachineSelfTrigger = false;
802 m_extDeferData = false;
811 timer.Set(m_extTimeout);
813 if (m_bStateMachineSelfTrigger)
815 m_bStateMachineSelfTrigger = false;
816 // self trigger state machine
817 StateMachine(msg->signal, port, msg);
818 if (!m_bStateMachineSelfTrigger)
825 // check control port
826 else if (m_controlPort.ReceiveOutMessage(&msg))
829 port = &m_controlPort;
831 // check sink data port
832 else if (m_sink.m_dataPort.ReceiveInMessage(&msg))
835 port = &m_sink.m_dataPort;
837 else if (!m_extDeferData)
840 if (m_dataPort.ReceiveOutMessage(&msg))
848 std::list<CActiveAEStream*>::iterator it;
849 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
851 if((*it)->m_streamPort->ReceiveOutMessage(&msg))
863 StateMachine(msg->signal, port, msg);
864 if (!m_bStateMachineSelfTrigger)
873 else if (m_outMsgEvent.WaitMSec(m_extTimeout))
875 m_extTimeout = timer.MillisLeft();
881 msg = m_controlPort.GetMessage();
882 msg->signal = CActiveAEControlProtocol::TIMEOUT;
884 // signal timeout to state machine
885 StateMachine(msg->signal, port, msg);
886 if (!m_bStateMachineSelfTrigger)
895 AEAudioFormat CActiveAE::GetInputFormat(AEAudioFormat *desiredFmt)
897 AEAudioFormat inputFormat;
899 if (m_streams.empty())
901 inputFormat.m_dataFormat = AE_FMT_FLOAT;
902 inputFormat.m_sampleRate = 44100;
903 inputFormat.m_encodedRate = 0;
904 inputFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
905 inputFormat.m_frames = 0;
906 inputFormat.m_frameSamples = 0;
907 inputFormat.m_frameSize = 0;
909 // force input format after unpausing slave
910 else if (desiredFmt != NULL)
912 inputFormat = *desiredFmt;
914 // keep format when having multiple streams
915 else if (m_streams.size() > 1 && m_silenceBuffers == NULL)
917 inputFormat = m_inputFormat;
921 inputFormat = m_streams.front()->m_format;
922 m_inputFormat = inputFormat;
928 void CActiveAE::Configure(AEAudioFormat *desiredFmt)
930 bool initSink = false;
932 AEAudioFormat sinkInputFormat, inputFormat;
933 AEAudioFormat oldInternalFormat = m_internalFormat;
934 AEAudioFormat oldSinkRequestFormat = m_sinkRequestFormat;
936 inputFormat = GetInputFormat(desiredFmt);
938 m_sinkRequestFormat = inputFormat;
939 ApplySettingsToFormat(m_sinkRequestFormat, m_settings, (int*)&m_mode);
942 std::string device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
944 CAESinkFactory::ParseDevice(device, driver);
945 if ((!CompareFormat(m_sinkRequestFormat, m_sinkFormat) && !CompareFormat(m_sinkRequestFormat, oldSinkRequestFormat)) ||
946 m_currDevice.compare(device) != 0 ||
947 m_settings.driver.compare(driver) != 0)
951 m_settings.driver = driver;
952 m_currDevice = device;
954 m_stats.Reset(m_sinkFormat.m_sampleRate);
955 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
957 // limit buffer size in case of sink returns large buffer
958 unsigned int buffertime = m_sinkFormat.m_frames / m_sinkFormat.m_sampleRate;
959 if (buffertime > MAX_BUFFER_TIME)
961 CLog::Log(LOGWARNING, "ActiveAE::%s - sink returned large buffer of %d ms, reducing to %d ms", __FUNCTION__, buffertime, (int)(MAX_BUFFER_TIME*1000));
962 m_sinkFormat.m_frames = MAX_BUFFER_TIME * m_sinkFormat.m_sampleRate;
966 if (m_silenceBuffers)
968 m_discardBufferPools.push_back(m_silenceBuffers);
969 m_silenceBuffers = NULL;
972 // buffers for driving gui sounds if no streams are active
973 if (m_streams.empty())
975 inputFormat = m_sinkFormat;
976 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
978 inputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
979 inputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
981 inputFormat.m_dataFormat = AE_FMT_FLOAT;
982 inputFormat.m_frameSize = inputFormat.m_channelLayout.Count() *
983 (CAEUtil::DataFormatToBits(inputFormat.m_dataFormat) >> 3);
984 m_silenceBuffers = new CActiveAEBufferPool(inputFormat);
985 m_silenceBuffers->Create(MAX_WATER_LEVEL*1000);
986 sinkInputFormat = inputFormat;
987 m_internalFormat = inputFormat;
989 bool streaming = false;
990 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
995 if (m_encoderBuffers)
997 m_discardBufferPools.push_back(m_encoderBuffers);
998 m_encoderBuffers = NULL;
1002 m_discardBufferPools.push_back(m_vizBuffers);
1003 m_vizBuffers = NULL;
1005 if (m_vizBuffersInput)
1007 m_discardBufferPools.push_back(m_vizBuffersInput);
1008 m_vizBuffersInput = NULL;
1011 // resample buffers for streams
1014 bool streaming = true;
1015 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
1017 AEAudioFormat outputFormat;
1018 if (m_mode == MODE_RAW)
1020 inputFormat.m_frames = m_sinkFormat.m_frames;
1021 outputFormat = inputFormat;
1022 sinkInputFormat = m_sinkFormat;
1024 // transcode everything with more than 2 channels
1025 else if (m_mode == MODE_TRANSCODE)
1027 outputFormat = inputFormat;
1028 outputFormat.m_dataFormat = AE_FMT_FLOATP;
1029 outputFormat.m_sampleRate = 48000;
1034 m_encoder = new CAEEncoderFFmpeg();
1035 m_encoder->Initialize(outputFormat, true);
1036 m_encoderFormat = outputFormat;
1039 outputFormat = m_encoderFormat;
1041 outputFormat.m_channelLayout = m_encoderFormat.m_channelLayout;
1042 outputFormat.m_frames = m_encoderFormat.m_frames;
1045 if (m_encoder->GetCodecID() == AV_CODEC_ID_AC3)
1047 AEAudioFormat format;
1048 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1049 format.m_dataFormat = AE_FMT_S16NE;
1050 format.m_frameSize = 2* (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
1051 format.m_frames = AC3_FRAME_SIZE;
1052 format.m_sampleRate = 48000;
1053 format.m_encodedRate = m_encoderFormat.m_sampleRate;
1054 if (m_encoderBuffers && initSink)
1056 m_discardBufferPools.push_back(m_encoderBuffers);
1057 m_encoderBuffers = NULL;
1059 if (!m_encoderBuffers)
1061 m_encoderBuffers = new CActiveAEBufferPool(format);
1062 m_encoderBuffers->Create(MAX_WATER_LEVEL*1000);
1066 sinkInputFormat = m_sinkFormat;
1070 outputFormat = m_sinkFormat;
1071 outputFormat.m_dataFormat = AE_FMT_FLOAT;
1072 outputFormat.m_frameSize = outputFormat.m_channelLayout.Count() *
1073 (CAEUtil::DataFormatToBits(outputFormat.m_dataFormat) >> 3);
1075 // due to channel ordering of the driver, a sink may return more channels than
1076 // requested, i.e. 2.1 request returns FL,FR,BL,BR,FC,LFE for ALSA
1077 // in this case we need to downmix to requested format
1078 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
1080 outputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
1081 outputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
1084 // TODO: adjust to decoder
1085 sinkInputFormat = outputFormat;
1087 m_internalFormat = outputFormat;
1089 std::list<CActiveAEStream*>::iterator it;
1090 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1092 // check if we support input format of stream
1093 if (!AE_IS_RAW((*it)->m_format.m_dataFormat) &&
1094 CActiveAEResample::GetAVSampleFormat((*it)->m_format.m_dataFormat) == AV_SAMPLE_FMT_FLT &&
1095 (*it)->m_format.m_dataFormat != AE_FMT_FLOAT)
1097 (*it)->m_convertFn = CAEConvert::ToFloat((*it)->m_format.m_dataFormat);
1098 (*it)->m_format.m_dataFormat = AE_FMT_FLOAT;
1101 if (!(*it)->m_inputBuffers)
1103 // align input buffers with period of sink or encoder
1104 (*it)->m_format.m_frames = m_internalFormat.m_frames * ((float)(*it)->m_format.m_sampleRate / m_internalFormat.m_sampleRate);
1106 // create buffer pool
1107 (*it)->m_inputBuffers = new CActiveAEBufferPool((*it)->m_format);
1108 (*it)->m_inputBuffers->Create(MAX_CACHE_LEVEL*1000);
1109 (*it)->m_streamSpace = (*it)->m_format.m_frameSize * (*it)->m_format.m_frames;
1111 // if input format does not follow ffmpeg channel mask, we may need to remap channels
1112 (*it)->InitRemapper();
1114 if (initSink && (*it)->m_resampleBuffers)
1116 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1117 (*it)->m_resampleBuffers = NULL;
1119 if (!(*it)->m_resampleBuffers)
1121 (*it)->m_resampleBuffers = new CActiveAEBufferPoolResample((*it)->m_inputBuffers->m_format, outputFormat, m_settings.resampleQuality);
1122 (*it)->m_resampleBuffers->m_changeResampler = (*it)->m_forceResampler;
1123 (*it)->m_resampleBuffers->Create(MAX_CACHE_LEVEL*1000, false, m_settings.stereoupmix, m_settings.normalizelevels);
1125 if (m_mode == MODE_TRANSCODE || m_streams.size() > 1)
1126 (*it)->m_resampleBuffers->m_fillPackets = true;
1129 (*it)->m_limiter.SetSamplerate(outputFormat.m_sampleRate);
1132 // update buffered time of streams
1133 m_stats.AddSamples(0, m_streams);
1136 if (!AE_IS_RAW(inputFormat.m_dataFormat))
1138 if (initSink && m_vizBuffers)
1140 m_discardBufferPools.push_back(m_vizBuffers);
1141 m_vizBuffers = NULL;
1142 m_discardBufferPools.push_back(m_vizBuffersInput);
1143 m_vizBuffersInput = NULL;
1147 AEAudioFormat vizFormat = m_internalFormat;
1148 vizFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
1149 vizFormat.m_dataFormat = AE_FMT_FLOAT;
1152 m_vizBuffersInput = new CActiveAEBufferPool(m_internalFormat);
1153 m_vizBuffersInput->Create(2000);
1156 m_vizBuffers = new CActiveAEBufferPoolResample(m_internalFormat, vizFormat, m_settings.resampleQuality);
1157 // TODO use cache of sync + water level
1158 m_vizBuffers->Create(2000, false, false);
1159 m_vizInitialized = false;
1164 // resample buffers for sink
1165 if (m_sinkBuffers &&
1166 (!CompareFormat(m_sinkBuffers->m_format,m_sinkFormat) || !CompareFormat(m_sinkBuffers->m_inputFormat, sinkInputFormat)))
1168 m_discardBufferPools.push_back(m_sinkBuffers);
1169 m_sinkBuffers = NULL;
1173 m_sinkBuffers = new CActiveAEBufferPoolResample(sinkInputFormat, m_sinkFormat, m_settings.resampleQuality);
1174 m_sinkBuffers->Create(MAX_WATER_LEVEL*1000, true, false);
1178 if (!CompareFormat(oldInternalFormat, m_internalFormat))
1180 if (m_settings.guisoundmode == AE_SOUND_ALWAYS ||
1181 (m_settings.guisoundmode == AE_SOUND_IDLE && m_streams.empty()))
1183 std::vector<CActiveAESound*>::iterator it;
1184 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
1186 (*it)->SetConverted(false);
1189 m_sounds_playing.clear();
1192 ClearDiscardedBuffers();
1196 CActiveAEStream* CActiveAE::CreateStream(MsgStreamNew *streamMsg)
1198 // we only can handle a single pass through stream
1199 bool hasRawStream = false;
1200 bool hasStream = false;
1201 std::list<CActiveAEStream*>::iterator it;
1202 for(it = m_streams.begin(); it != m_streams.end(); ++it)
1204 if((*it)->IsDrained())
1206 if(AE_IS_RAW((*it)->m_format.m_dataFormat))
1207 hasRawStream = true;
1210 if (hasRawStream || (hasStream && AE_IS_RAW(streamMsg->format.m_dataFormat)))
1215 // create the stream
1216 CActiveAEStream *stream;
1217 stream = new CActiveAEStream(&streamMsg->format);
1218 stream->m_streamPort = new CActiveAEDataProtocol("stream",
1219 &stream->m_inMsgEvent, &m_outMsgEvent);
1221 // create buffer pool
1222 stream->m_inputBuffers = NULL; // create in Configure when we know the sink format
1223 stream->m_resampleBuffers = NULL; // create in Configure when we know the sink format
1224 stream->m_statsLock = m_stats.GetLock();
1225 stream->m_fadingSamples = 0;
1226 stream->m_started = false;
1228 if (streamMsg->options & AESTREAM_PAUSED)
1229 stream->m_paused = true;
1231 if (streamMsg->options & AESTREAM_FORCE_RESAMPLE)
1232 stream->m_forceResampler = true;
1234 m_streams.push_back(stream);
1239 void CActiveAE::DiscardStream(CActiveAEStream *stream)
1241 std::list<CActiveAEStream*>::iterator it;
1242 for (it=m_streams.begin(); it!=m_streams.end(); )
1244 if (stream == (*it))
1246 while (!(*it)->m_processingSamples.empty())
1248 (*it)->m_processingSamples.front()->Return();
1249 (*it)->m_processingSamples.pop_front();
1251 m_discardBufferPools.push_back((*it)->m_inputBuffers);
1252 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1253 CLog::Log(LOGDEBUG, "CActiveAE::DiscardStream - audio stream deleted");
1254 delete (*it)->m_streamPort;
1256 it = m_streams.erase(it);
1262 ClearDiscardedBuffers();
1265 void CActiveAE::SFlushStream(CActiveAEStream *stream)
1267 while (!stream->m_processingSamples.empty())
1269 stream->m_processingSamples.front()->Return();
1270 stream->m_processingSamples.pop_front();
1272 stream->m_resampleBuffers->Flush();
1273 stream->m_streamPort->Purge();
1274 stream->m_bufferedTime = 0.0;
1275 stream->m_paused = false;
1277 // flush the engine if we only have a single stream
1278 if (m_streams.size() == 1)
1284 void CActiveAE::FlushEngine()
1287 m_sinkBuffers->Flush();
1289 m_vizBuffers->Flush();
1291 // send message to sink
1293 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::FLUSH,
1296 bool success = reply->signal == CSinkControlProtocol::ACC;
1299 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on flush", __FUNCTION__);
1306 CLog::Log(LOGERROR, "ActiveAE::%s - failed to flush", __FUNCTION__);
1309 m_stats.Reset(m_sinkFormat.m_sampleRate);
1312 void CActiveAE::ClearDiscardedBuffers()
1314 std::list<CActiveAEBufferPool*>::iterator it;
1315 for (it=m_discardBufferPools.begin(); it!=m_discardBufferPools.end(); ++it)
1317 CActiveAEBufferPoolResample *rbuf = dynamic_cast<CActiveAEBufferPoolResample*>(*it);
1322 // if all buffers have returned, we can delete the buffer pool
1323 if ((*it)->m_allSamples.size() == (*it)->m_freeSamples.size())
1326 CLog::Log(LOGDEBUG, "CActiveAE::ClearDiscardedBuffers - buffer pool deleted");
1327 m_discardBufferPools.erase(it);
1333 void CActiveAE::SStopSound(CActiveAESound *sound)
1335 std::list<SoundState>::iterator it;
1336 for (it=m_sounds_playing.begin(); it!=m_sounds_playing.end(); ++it)
1338 if (it->sound == sound)
1340 m_sounds_playing.erase(it);
1346 void CActiveAE::DiscardSound(CActiveAESound *sound)
1350 std::vector<CActiveAESound*>::iterator it;
1351 for (it=m_sounds.begin(); it!=m_sounds.end(); ++it)
1361 void CActiveAE::ChangeResamplers()
1363 std::list<CActiveAEStream*>::iterator it;
1364 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1366 bool normalize = true;
1367 if (((*it)->m_resampleBuffers->m_format.m_channelLayout.Count() <
1368 (*it)->m_resampleBuffers->m_inputFormat.m_channelLayout.Count()) &&
1369 !m_settings.normalizelevels)
1372 if ((*it)->m_resampleBuffers && (*it)->m_resampleBuffers->m_resampler &&
1373 (((*it)->m_resampleBuffers->m_resampleQuality != m_settings.resampleQuality) ||
1374 (((*it)->m_resampleBuffers->m_stereoUpmix != m_settings.stereoupmix)) ||
1375 ((*it)->m_resampleBuffers->m_normalize != normalize)))
1377 (*it)->m_resampleBuffers->m_changeResampler = true;
1379 (*it)->m_resampleBuffers->m_resampleQuality = m_settings.resampleQuality;
1380 (*it)->m_resampleBuffers->m_stereoUpmix = m_settings.stereoupmix;
1381 (*it)->m_resampleBuffers->m_normalize = normalize;
1385 void CActiveAE::ApplySettingsToFormat(AEAudioFormat &format, AudioSettings &settings, int *mode)
1387 int oldMode = m_mode;
1392 if (AE_IS_RAW(format.m_dataFormat))
1394 if ((format.m_dataFormat == AE_FMT_AC3 && !settings.ac3passthrough) ||
1395 (format.m_dataFormat == AE_FMT_EAC3 && !settings.eac3passthrough) ||
1396 (format.m_dataFormat == AE_FMT_TRUEHD && !settings.truehdpassthrough) ||
1397 (format.m_dataFormat == AE_FMT_DTS && !settings.dtspassthrough) ||
1398 (format.m_dataFormat == AE_FMT_DTSHD && !settings.dtshdpassthrough))
1400 CLog::Log(LOGERROR, "CActiveAE::ApplySettingsToFormat - input audio format is wrong");
1406 else if (settings.channels <= AE_CH_LAYOUT_2_0 && // no multichannel pcm
1407 settings.passthrough &&
1408 settings.ac3passthrough &&
1409 settings.ac3transcode &&
1410 !m_streams.empty() &&
1411 (format.m_channelLayout.Count() > 2 || settings.stereoupmix))
1413 format.m_dataFormat = AE_FMT_AC3;
1414 format.m_sampleRate = 48000;
1415 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1417 *mode = MODE_TRANSCODE;
1421 format.m_dataFormat = AE_FMT_FLOAT;
1422 // consider user channel layout for those cases
1423 // 1. input stream is multichannel
1424 // 2. stereo upmix is selected
1426 if ((format.m_channelLayout.Count() > 2) ||
1427 settings.stereoupmix ||
1428 (settings.config == AE_CONFIG_FIXED))
1430 CAEChannelInfo stdLayout;
1431 switch (settings.channels)
1434 case 0: stdLayout = AE_CH_LAYOUT_2_0; break;
1435 case 1: stdLayout = AE_CH_LAYOUT_2_0; break;
1436 case 2: stdLayout = AE_CH_LAYOUT_2_1; break;
1437 case 3: stdLayout = AE_CH_LAYOUT_3_0; break;
1438 case 4: stdLayout = AE_CH_LAYOUT_3_1; break;
1439 case 5: stdLayout = AE_CH_LAYOUT_4_0; break;
1440 case 6: stdLayout = AE_CH_LAYOUT_4_1; break;
1441 case 7: stdLayout = AE_CH_LAYOUT_5_0; break;
1442 case 8: stdLayout = AE_CH_LAYOUT_5_1; break;
1443 case 9: stdLayout = AE_CH_LAYOUT_7_0; break;
1444 case 10: stdLayout = AE_CH_LAYOUT_7_1; break;
1447 if (m_settings.config == AE_CONFIG_FIXED || (settings.stereoupmix && format.m_channelLayout.Count() <= 2))
1448 format.m_channelLayout = stdLayout;
1449 else if (m_extKeepConfig && (settings.config == AE_CONFIG_AUTO) && (oldMode != MODE_RAW))
1450 format.m_channelLayout = m_internalFormat.m_channelLayout;
1452 format.m_channelLayout.ResolveChannels(stdLayout);
1454 // don't change from multi to stereo in AUTO mode
1455 else if ((settings.config == AE_CONFIG_AUTO) &&
1456 m_stats.GetWaterLevel() > 0 && m_internalFormat.m_channelLayout.Count() > 2)
1458 format.m_channelLayout = m_internalFormat.m_channelLayout;
1461 if (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958)
1463 if (format.m_sampleRate > m_settings.samplerate)
1465 format.m_sampleRate = m_settings.samplerate;
1466 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - limit samplerate for SPDIF to %d", format.m_sampleRate);
1468 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1471 if (m_settings.config == AE_CONFIG_FIXED)
1473 format.m_sampleRate = m_settings.samplerate;
1474 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - Forcing samplerate to %d", format.m_sampleRate);
1477 // sinks may not support mono
1478 if (format.m_channelLayout.Count() == 1)
1480 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1485 bool CActiveAE::NeedReconfigureBuffers()
1487 AEAudioFormat newFormat = GetInputFormat();
1488 ApplySettingsToFormat(newFormat, m_settings);
1490 if (newFormat.m_dataFormat != m_sinkRequestFormat.m_dataFormat ||
1491 newFormat.m_channelLayout != m_sinkRequestFormat.m_channelLayout ||
1492 newFormat.m_sampleRate != m_sinkRequestFormat.m_sampleRate)
1498 bool CActiveAE::NeedReconfigureSink()
1500 AEAudioFormat newFormat = GetInputFormat();
1501 ApplySettingsToFormat(newFormat, m_settings);
1503 std::string device = AE_IS_RAW(newFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
1505 CAESinkFactory::ParseDevice(device, driver);
1507 if (!CompareFormat(newFormat, m_sinkFormat) ||
1508 m_currDevice.compare(device) != 0 ||
1509 m_settings.driver.compare(driver) != 0)
1515 bool CActiveAE::InitSink()
1518 config.format = m_sinkRequestFormat;
1519 config.stats = &m_stats;
1520 config.device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? &m_settings.passthoughdevice :
1523 // send message to sink
1525 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::CONFIGURE,
1528 &config, sizeof(config)))
1530 bool success = reply->signal == CSinkControlProtocol::ACC;
1534 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1539 data = (SinkReply*)reply->data;
1542 m_sinkFormat = data->format;
1543 m_sinkHasVolume = data->hasVolume;
1544 m_stats.SetSinkCacheTotal(data->cacheTotal);
1545 m_stats.SetSinkLatency(data->latency);
1551 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
1552 m_stats.SetSinkCacheTotal(0);
1553 m_stats.SetSinkLatency(0);
1558 m_inMsgEvent.Reset();
1562 void CActiveAE::DrainSink()
1564 // send message to sink
1566 if (m_sink.m_dataPort.SendOutMessageSync(CSinkDataProtocol::DRAIN,
1570 bool success = reply->signal == CSinkDataProtocol::ACC;
1574 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on drain", __FUNCTION__);
1582 CLog::Log(LOGERROR, "ActiveAE::%s - failed to drain", __FUNCTION__);
1588 void CActiveAE::UnconfigureSink()
1590 // send message to sink
1592 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::UNCONFIGURE,
1596 bool success = reply->signal == CSinkControlProtocol::ACC;
1599 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1606 CLog::Log(LOGERROR, "ActiveAE::%s - failed to unconfigure", __FUNCTION__);
1610 // make sure we open sink on next configure
1613 m_inMsgEvent.Reset();
1617 bool CActiveAE::RunStages()
1621 // serve input streams
1622 std::list<CActiveAEStream*>::iterator it;
1623 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1625 if ((*it)->m_resampleBuffers && !(*it)->m_paused)
1626 busy = (*it)->m_resampleBuffers->ResampleBuffers();
1627 else if ((*it)->m_resampleBuffers &&
1628 ((*it)->m_resampleBuffers->m_inputSamples.size() > (*it)->m_resampleBuffers->m_allSamples.size() * 0.5))
1630 CSingleLock lock((*it)->m_streamLock);
1631 (*it)->m_streamIsBuffering = false;
1634 // provide buffers to stream
1635 float time = m_stats.GetCacheTime((*it));
1636 CSampleBuffer *buffer;
1637 if (!(*it)->m_drain)
1639 while (time < MAX_CACHE_LEVEL && !(*it)->m_inputBuffers->m_freeSamples.empty())
1641 buffer = (*it)->m_inputBuffers->GetFreeBuffer();
1642 (*it)->m_processingSamples.push_back(buffer);
1643 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMBUFFER, &buffer, sizeof(CSampleBuffer*));
1644 (*it)->IncFreeBuffers();
1645 time += (float)buffer->pkt->max_nb_samples / buffer->pkt->config.sample_rate;
1650 if ((*it)->m_resampleBuffers->m_inputSamples.empty() &&
1651 (*it)->m_resampleBuffers->m_outputSamples.empty() &&
1652 (*it)->m_processingSamples.empty())
1654 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
1655 (*it)->m_drain = false;
1656 (*it)->m_resampleBuffers->m_drain = false;
1657 (*it)->m_started = false;
1659 // set variables being polled via stream interface
1660 CSingleLock lock((*it)->m_streamLock);
1661 if ((*it)->m_streamSlave)
1663 CActiveAEStream *slave = (CActiveAEStream*)((*it)->m_streamSlave);
1664 slave->m_paused = false;
1666 // TODO: find better solution for this
1667 // gapless bites audiophile
1668 if (m_settings.config == AE_CONFIG_MATCH)
1669 Configure(&slave->m_format);
1671 (*it)->m_streamSlave = NULL;
1673 (*it)->m_streamDrained = true;
1674 (*it)->m_streamDraining = false;
1675 (*it)->m_streamFading = false;
1680 if (m_stats.GetWaterLevel() < MAX_WATER_LEVEL &&
1681 (m_mode != MODE_TRANSCODE || (m_encoderBuffers && !m_encoderBuffers->m_freeSamples.empty())))
1683 // mix streams and sounds sounds
1684 if (m_mode != MODE_RAW)
1686 CSampleBuffer *out = NULL;
1687 if (!m_sounds_playing.empty() && m_streams.empty())
1689 if (m_silenceBuffers && !m_silenceBuffers->m_freeSamples.empty())
1691 out = m_silenceBuffers->GetFreeBuffer();
1692 for (int i=0; i<out->pkt->planes; i++)
1694 memset(out->pkt->data[i], 0, out->pkt->linesize);
1696 out->pkt->nb_samples = out->pkt->max_nb_samples;
1701 std::list<CActiveAEStream*>::iterator it;
1703 // if we deal with more than a single stream, all streams
1704 // must provide samples for mixing
1705 bool allStreamsReady = true;
1706 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1708 if ((*it)->m_paused || !(*it)->m_started || !(*it)->m_resampleBuffers)
1711 if ((*it)->m_resampleBuffers->m_outputSamples.empty())
1712 allStreamsReady = false;
1715 bool needClamp = false;
1716 for (it = m_streams.begin(); it != m_streams.end() && allStreamsReady; ++it)
1718 if ((*it)->m_paused || !(*it)->m_resampleBuffers)
1721 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1723 (*it)->m_started = true;
1727 out = (*it)->m_resampleBuffers->m_outputSamples.front();
1728 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1730 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1732 float fadingStep = 0.0f;
1735 if ((*it)->m_fadingSamples == -1)
1737 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1738 (*it)->m_volume = (*it)->m_fadingBase;
1740 if ((*it)->m_fadingSamples > 0)
1742 nb_floats = out->pkt->config.channels / out->pkt->planes;
1743 nb_loops = out->pkt->nb_samples;
1744 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1745 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1746 fadingStep = delta / samples;
1749 // for stream amplification,
1750 // turned off downmix normalization,
1751 // or if sink format is float (in order to prevent from clipping)
1752 // we need to run on a per sample basis
1753 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize || (m_sinkFormat.m_dataFormat == AE_FMT_FLOAT))
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**)out->pkt->data, out->pkt->config.channels, i*nb_floats, out->pkt->planes > 1);
1779 for(int j=0; j<out->pkt->planes; j++)
1782 CAEUtil::SSEMulArray((float*)out->pkt->data[j]+i*nb_floats, volume, nb_floats);
1784 float* fbuffer = (float*) out->pkt->data[j]+i*nb_floats;
1785 for (int k = 0; k < nb_floats; ++k)
1787 fbuffer[k] *= volume;
1795 CSampleBuffer *mix = NULL;
1796 mix = (*it)->m_resampleBuffers->m_outputSamples.front();
1797 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1799 int nb_floats = mix->pkt->nb_samples * mix->pkt->config.channels / mix->pkt->planes;
1801 float fadingStep = 0.0f;
1804 if ((*it)->m_fadingSamples == -1)
1806 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1807 (*it)->m_volume = (*it)->m_fadingBase;
1809 if ((*it)->m_fadingSamples > 0)
1811 nb_floats = mix->pkt->config.channels / mix->pkt->planes;
1812 nb_loops = mix->pkt->nb_samples;
1813 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1814 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1815 fadingStep = delta / samples;
1818 // for streams amplification of turned off downmix normalization
1819 // we need to run on a per sample basis
1820 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize)
1822 nb_floats = out->pkt->config.channels / out->pkt->planes;
1823 nb_loops = out->pkt->nb_samples;
1826 for(int i=0; i<nb_loops; i++)
1828 if ((*it)->m_fadingSamples > 0)
1830 (*it)->m_volume += fadingStep;
1831 (*it)->m_fadingSamples--;
1833 if ((*it)->m_fadingSamples == 0)
1835 // set variables being polled via stream interface
1836 CSingleLock lock((*it)->m_streamLock);
1837 (*it)->m_streamFading = false;
1841 // volume for stream
1842 float volume = (*it)->m_volume * (*it)->m_rgain;
1844 volume *= (*it)->m_limiter.Run((float**)mix->pkt->data, mix->pkt->config.channels, i*nb_floats, mix->pkt->planes > 1);
1846 for(int j=0; j<out->pkt->planes && j<mix->pkt->planes; j++)
1848 float *dst = (float*)out->pkt->data[j]+i*nb_floats;
1849 float *src = (float*)mix->pkt->data[j]+i*nb_floats;
1851 CAEUtil::SSEMulAddArray(dst, src, volume, nb_floats);
1852 for (int k = 0; k < nb_floats; ++k)
1854 if (fabs(dst[k]) > 1.0f)
1861 for (int k = 0; k < nb_floats; ++k)
1863 dst[k] += src[k] * volume;
1864 if (fabs(dst[k]) > 1.0f)
1876 // finally clamp samples
1877 if(out && needClamp)
1879 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1880 for(int i=0; i<out->pkt->planes; i++)
1882 CAEUtil::ClampArray((float*)out->pkt->data[i], nb_floats);
1886 // process output buffer, gui sounds, encode, viz
1891 CSingleLock lock(m_vizLock);
1892 if (m_audioCallback && m_vizBuffers && !m_streams.empty())
1894 if (!m_vizInitialized)
1896 m_audioCallback->OnInitialize(2, m_vizBuffers->m_format.m_sampleRate, 32);
1897 m_vizInitialized = true;
1900 if (!m_vizBuffersInput->m_freeSamples.empty())
1902 // copy the samples into the viz input buffer
1903 CSampleBuffer *viz = m_vizBuffersInput->GetFreeBuffer();
1904 int samples = std::min(512, out->pkt->nb_samples);
1905 int bytes = samples * out->pkt->config.channels / out->pkt->planes * out->pkt->bytes_per_sample;
1906 for(int i= 0; i < out->pkt->planes; i++)
1908 memcpy(viz->pkt->data[i], out->pkt->data[i], bytes);
1910 viz->pkt->nb_samples = samples;
1911 m_vizBuffers->m_inputSamples.push_back(viz);
1914 CLog::Log(LOGWARNING,"ActiveAE::%s - viz ran out of free buffers", __FUNCTION__);
1915 unsigned int now = XbmcThreads::SystemClockMillis();
1916 unsigned int timestamp = now + m_stats.GetDelay() * 1000;
1917 busy |= m_vizBuffers->ResampleBuffers(timestamp);
1918 while(!m_vizBuffers->m_outputSamples.empty())
1920 CSampleBuffer *buf = m_vizBuffers->m_outputSamples.front();
1921 if ((now - buf->timestamp) & 0x80000000)
1926 samples = std::min(512, buf->pkt->nb_samples);
1927 m_audioCallback->OnAudioData((float*)(buf->pkt->data[0]), samples);
1929 m_vizBuffers->m_outputSamples.pop_front();
1933 else if (m_vizBuffers)
1934 m_vizBuffers->Flush();
1938 MixSounds(*(out->pkt));
1939 if (!m_sinkHasVolume || m_muted)
1940 Deamplify(*(out->pkt));
1942 if (m_mode == MODE_TRANSCODE && m_encoder)
1944 CSampleBuffer *buf = m_encoderBuffers->GetFreeBuffer();
1945 m_encoder->Encode(out->pkt->data[0], out->pkt->planes*out->pkt->linesize,
1946 buf->pkt->data[0], buf->pkt->planes*buf->pkt->linesize);
1947 buf->pkt->nb_samples = buf->pkt->max_nb_samples;
1957 m_stats.AddSamples(out->pkt->nb_samples, m_streams);
1958 m_sinkBuffers->m_inputSamples.push_back(out);
1964 std::list<CActiveAEStream*>::iterator it;
1965 CSampleBuffer *buffer;
1966 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1968 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1970 buffer = (*it)->m_resampleBuffers->m_outputSamples.front();
1971 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1972 m_stats.AddSamples(buffer->pkt->nb_samples, m_streams);
1973 m_sinkBuffers->m_inputSamples.push_back(buffer);
1978 // serve sink buffers
1979 busy = m_sinkBuffers->ResampleBuffers();
1980 while(!m_sinkBuffers->m_outputSamples.empty())
1982 CSampleBuffer *out = NULL;
1983 out = m_sinkBuffers->m_outputSamples.front();
1984 m_sinkBuffers->m_outputSamples.pop_front();
1985 m_sink.m_dataPort.SendOutMessage(CSinkDataProtocol::SAMPLE,
1986 &out, sizeof(CSampleBuffer*));
1994 bool CActiveAE::HasWork()
1996 if (!m_sounds_playing.empty())
1998 if (!m_sinkBuffers->m_inputSamples.empty())
2000 if (!m_sinkBuffers->m_outputSamples.empty())
2003 std::list<CActiveAEStream*>::iterator it;
2004 for (it = m_streams.begin(); it != m_streams.end(); ++it)
2006 if (!(*it)->m_resampleBuffers->m_inputSamples.empty())
2008 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
2010 if (!(*it)->m_processingSamples.empty())
2017 void CActiveAE::MixSounds(CSoundPacket &dstSample)
2019 if (m_sounds_playing.empty())
2024 float *sample_buffer;
2025 int max_samples = dstSample.nb_samples;
2027 std::list<SoundState>::iterator it;
2028 for (it = m_sounds_playing.begin(); it != m_sounds_playing.end(); )
2030 if (!it->sound->IsConverted())
2031 ResampleSound(it->sound);
2032 int available_samples = it->sound->GetSound(false)->nb_samples - it->samples_played;
2033 int mix_samples = std::min(max_samples, available_samples);
2034 int start = it->samples_played *
2035 m_dllAvUtil.av_get_bytes_per_sample(it->sound->GetSound(false)->config.fmt) *
2036 it->sound->GetSound(false)->config.channels /
2037 it->sound->GetSound(false)->planes;
2039 for(int j=0; j<dstSample.planes; j++)
2041 volume = it->sound->GetVolume();
2042 out = (float*)dstSample.data[j];
2043 sample_buffer = (float*)(it->sound->GetSound(false)->data[j]+start);
2044 int nb_floats = mix_samples * dstSample.config.channels / dstSample.planes;
2046 CAEUtil::SSEMulAddArray(out, sample_buffer, volume, nb_floats);
2048 for (int k = 0; k < nb_floats; ++k)
2049 *out++ += *sample_buffer++ * volume;
2053 it->samples_played += mix_samples;
2055 // no more frames, so remove it from the list
2056 if (it->samples_played >= it->sound->GetSound(false)->nb_samples)
2058 it = m_sounds_playing.erase(it);
2065 void CActiveAE::Deamplify(CSoundPacket &dstSample)
2067 if (m_volume < 1.0 || m_muted)
2070 int nb_floats = dstSample.nb_samples * dstSample.config.channels / dstSample.planes;
2071 float volume = m_muted ? 0.0f : m_volume;
2073 for(int j=0; j<dstSample.planes; j++)
2075 buffer = (float*)dstSample.data[j];
2077 CAEUtil::SSEMulArray(buffer, volume, nb_floats);
2079 float *fbuffer = buffer;
2080 for (int i = 0; i < nb_floats; i++)
2081 *fbuffer++ *= volume;
2087 //-----------------------------------------------------------------------------
2089 //-----------------------------------------------------------------------------
2091 void CActiveAE::LoadSettings()
2093 m_settings.device = CSettings::Get().GetString("audiooutput.audiodevice");
2094 m_settings.passthoughdevice = CSettings::Get().GetString("audiooutput.passthroughdevice");
2096 m_settings.config = CSettings::Get().GetInt("audiooutput.config");
2097 m_settings.channels = (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958) ? AE_CH_LAYOUT_2_0 : CSettings::Get().GetInt("audiooutput.channels");
2098 m_settings.samplerate = CSettings::Get().GetInt("audiooutput.samplerate");
2100 m_settings.stereoupmix = IsSettingVisible("audiooutput.stereoupmix") ? CSettings::Get().GetBool("audiooutput.stereoupmix") : false;
2101 m_settings.normalizelevels = CSettings::Get().GetBool("audiooutput.normalizelevels");
2102 m_settings.guisoundmode = CSettings::Get().GetInt("audiooutput.guisoundmode");
2104 m_settings.passthrough = m_settings.config == AE_CONFIG_FIXED ? false : CSettings::Get().GetBool("audiooutput.passthrough");
2105 if (!m_sink.HasPassthroughDevice())
2106 m_settings.passthrough = false;
2107 m_settings.ac3passthrough = CSettings::Get().GetBool("audiooutput.ac3passthrough");
2108 m_settings.ac3transcode = CSettings::Get().GetBool("audiooutput.ac3transcode");
2109 m_settings.eac3passthrough = CSettings::Get().GetBool("audiooutput.eac3passthrough");
2110 m_settings.truehdpassthrough = CSettings::Get().GetBool("audiooutput.truehdpassthrough");
2111 m_settings.dtspassthrough = CSettings::Get().GetBool("audiooutput.dtspassthrough");
2112 m_settings.dtshdpassthrough = CSettings::Get().GetBool("audiooutput.dtshdpassthrough");
2114 m_settings.resampleQuality = static_cast<AEQuality>(CSettings::Get().GetInt("audiooutput.processquality"));
2117 bool CActiveAE::Initialize()
2119 if (!m_dllAvUtil.Load() || !m_dllAvCodec.Load() || !m_dllAvFormat.Load())
2121 CLog::Log(LOGERROR,"CActiveAE::Initialize - failed to load ffmpeg libraries");
2124 m_dllAvFormat.av_register_all();
2128 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2132 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2136 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2143 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2148 // hook into windowing for receiving display reset events
2149 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
2150 g_Windowing.Register(this);
2153 m_inMsgEvent.Reset();
2157 void CActiveAE::EnumerateOutputDevices(AEDeviceList &devices, bool passthrough)
2159 m_sink.EnumerateOutputDevices(devices, passthrough);
2162 std::string CActiveAE::GetDefaultDevice(bool passthrough)
2164 return m_sink.GetDefaultDevice(passthrough);
2167 void CActiveAE::OnSettingsChange(const std::string& setting)
2169 if (setting == "audiooutput.passthroughdevice" ||
2170 setting == "audiooutput.audiodevice" ||
2171 setting == "audiooutput.config" ||
2172 setting == "audiooutput.ac3passthrough" ||
2173 setting == "audiooutput.ac3transcode" ||
2174 setting == "audiooutput.eac3passthrough" ||
2175 setting == "audiooutput.dtspassthrough" ||
2176 setting == "audiooutput.truehdpassthrough" ||
2177 setting == "audiooutput.dtshdpassthrough" ||
2178 setting == "audiooutput.channels" ||
2179 setting == "audiooutput.stereoupmix" ||
2180 setting == "audiooutput.streamsilence" ||
2181 setting == "audiooutput.processquality" ||
2182 setting == "audiooutput.passthrough" ||
2183 setting == "audiooutput.samplerate" ||
2184 setting == "audiooutput.normalizelevels" ||
2185 setting == "audiooutput.guisoundmode")
2187 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RECONFIGURE);
2191 bool CActiveAE::SupportsRaw(AEDataFormat format, int samplerate)
2193 if (!m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), format, samplerate))
2199 bool CActiveAE::SupportsSilenceTimeout()
2204 bool CActiveAE::SupportsQualityLevel(enum AEQuality level)
2206 if (level == AE_QUALITY_LOW || level == AE_QUALITY_MID || level == AE_QUALITY_HIGH)
2212 bool CActiveAE::IsSettingVisible(const std::string &settingId)
2214 if (settingId == "audiooutput.samplerate")
2216 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958)
2218 if (CSettings::Get().GetInt("audiooutput.config") == AE_CONFIG_FIXED)
2221 else if (settingId == "audiooutput.channels")
2223 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) != AE_DEVTYPE_IEC958)
2226 else if (settingId == "audiooutput.passthrough")
2228 if (m_sink.HasPassthroughDevice() && CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2231 else if (settingId == "audiooutput.truehdpassthrough")
2233 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_TRUEHD, 192000) &&
2234 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2237 else if (settingId == "audiooutput.dtshdpassthrough")
2239 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_DTSHD, 192000) &&
2240 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2243 else if (settingId == "audiooutput.eac3passthrough")
2245 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_EAC3, 192000) &&
2246 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2249 else if (settingId == "audiooutput.stereoupmix")
2251 if (m_sink.HasPassthroughDevice() ||
2252 CSettings::Get().GetInt("audiooutput.channels") > AE_CH_LAYOUT_2_0)
2255 else if (settingId == "audiooutput.ac3transcode")
2257 if (m_sink.HasPassthroughDevice() &&
2258 CSettings::Get().GetBool("audiooutput.ac3passthrough") &&
2259 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2260 (CSettings::Get().GetInt("audiooutput.channels") <= AE_CH_LAYOUT_2_0 || m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958))
2266 void CActiveAE::Shutdown()
2271 bool CActiveAE::Suspend()
2273 return m_controlPort.SendOutMessage(CActiveAEControlProtocol::SUSPEND);
2276 bool CActiveAE::Resume()
2279 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2283 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2287 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2293 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2297 m_inMsgEvent.Reset();
2301 bool CActiveAE::IsSuspended()
2303 return m_stats.IsSuspended();
2306 float CActiveAE::GetVolume()
2311 void CActiveAE::SetVolume(const float volume)
2313 m_aeVolume = std::max( 0.0f, std::min(1.0f, volume));
2314 m_controlPort.SendOutMessage(CActiveAEControlProtocol::VOLUME, &m_aeVolume, sizeof(float));
2317 void CActiveAE::SetMute(const bool enabled)
2319 m_aeMuted = enabled;
2320 m_controlPort.SendOutMessage(CActiveAEControlProtocol::MUTE, &m_aeMuted, sizeof(bool));
2323 bool CActiveAE::IsMuted()
2328 void CActiveAE::SetSoundMode(const int mode)
2333 void CActiveAE::KeepConfiguration(unsigned int millis)
2335 unsigned int timeMs = millis;
2336 m_controlPort.SendOutMessage(CActiveAEControlProtocol::KEEPCONFIG, &timeMs, sizeof(unsigned int));
2339 void CActiveAE::DeviceChange()
2341 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DEVICECHANGE);
2344 void CActiveAE::OnLostDevice()
2347 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::DISPLAYLOST,
2351 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2355 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2360 CLog::Log(LOGERROR, "ActiveAE::%s - timed out", __FUNCTION__);
2364 void CActiveAE::OnResetDevice()
2366 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DISPLAYRESET);
2369 void CActiveAE::OnAppFocusChange(bool focus)
2371 m_controlPort.SendOutMessage(CActiveAEControlProtocol::APPFOCUSED, &focus, sizeof(focus));
2374 //-----------------------------------------------------------------------------
2376 //-----------------------------------------------------------------------------
2378 uint8_t **CActiveAE::AllocSoundSample(SampleConfig &config, int &samples, int &bytes_per_sample, int &planes, int &linesize)
2381 planes = m_dllAvUtil.av_sample_fmt_is_planar(config.fmt) ? config.channels : 1;
2382 buffer = new uint8_t*[planes];
2384 // align buffer to 16 in order to be compatible with sse in CAEConvert
2385 m_dllAvUtil.av_samples_alloc(buffer, &linesize, config.channels,
2386 samples, config.fmt, 16);
2387 bytes_per_sample = m_dllAvUtil.av_get_bytes_per_sample(config.fmt);
2391 void CActiveAE::FreeSoundSample(uint8_t **data)
2393 m_dllAvUtil.av_freep(data);
2397 bool CActiveAE::CompareFormat(AEAudioFormat &lhs, AEAudioFormat &rhs)
2399 if (lhs.m_channelLayout != rhs.m_channelLayout ||
2400 lhs.m_dataFormat != rhs.m_dataFormat ||
2401 lhs.m_sampleRate != rhs.m_sampleRate)
2407 //-----------------------------------------------------------------------------
2409 //-----------------------------------------------------------------------------
2412 * load sound from an audio file and store original format
2413 * register the sound in ActiveAE
2414 * later when the engine is idle it will convert the sound to sink format
2417 #define SOUNDBUFFER_SIZE 20480
2419 IAESound *CActiveAE::MakeSound(const std::string& file)
2421 AVFormatContext *fmt_ctx = NULL;
2422 AVCodecContext *dec_ctx = NULL;
2423 AVIOContext *io_ctx;
2424 AVInputFormat *io_fmt;
2425 AVCodec *dec = NULL;
2426 CActiveAESound *sound = NULL;
2427 SampleConfig config;
2429 sound = new CActiveAESound(file);
2430 if (!sound->Prepare())
2435 int fileSize = sound->GetFileSize();
2437 fmt_ctx = m_dllAvFormat.avformat_alloc_context();
2438 unsigned char* buffer = (unsigned char*)m_dllAvUtil.av_malloc(SOUNDBUFFER_SIZE+FF_INPUT_BUFFER_PADDING_SIZE);
2439 io_ctx = m_dllAvFormat.avio_alloc_context(buffer, SOUNDBUFFER_SIZE, 0,
2440 sound, CActiveAESound::Read, NULL, CActiveAESound::Seek);
2441 io_ctx->max_packet_size = sound->GetChunkSize();
2442 if(io_ctx->max_packet_size)
2443 io_ctx->max_packet_size *= SOUNDBUFFER_SIZE / io_ctx->max_packet_size;
2445 if(!sound->IsSeekPosible())
2446 io_ctx->seekable = 0;
2448 fmt_ctx->pb = io_ctx;
2450 m_dllAvFormat.av_probe_input_buffer(io_ctx, &io_fmt, file.c_str(), NULL, 0, 0);
2453 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2459 if (m_dllAvFormat.avformat_open_input(&fmt_ctx, file.c_str(), NULL, NULL) == 0)
2461 fmt_ctx->flags |= AVFMT_FLAG_NOPARSE;
2462 if (m_dllAvFormat.avformat_find_stream_info(fmt_ctx, NULL) >= 0)
2464 dec_ctx = fmt_ctx->streams[0]->codec;
2465 dec = m_dllAvCodec.avcodec_find_decoder(dec_ctx->codec_id);
2466 config.sample_rate = dec_ctx->sample_rate;
2467 config.channels = dec_ctx->channels;
2468 config.channel_layout = dec_ctx->channel_layout;
2473 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2478 dec_ctx = m_dllAvCodec.avcodec_alloc_context3(dec);
2479 dec_ctx->sample_rate = config.sample_rate;
2480 dec_ctx->channels = config.channels;
2481 if (!config.channel_layout)
2482 config.channel_layout = m_dllAvUtil.av_get_default_channel_layout(config.channels);
2483 dec_ctx->channel_layout = config.channel_layout;
2486 AVFrame *decoded_frame = NULL;
2487 decoded_frame = m_dllAvCodec.avcodec_alloc_frame();
2489 if (m_dllAvCodec.avcodec_open2(dec_ctx, dec, NULL) >= 0)
2494 m_dllAvCodec.av_init_packet(&avpkt);
2496 while (m_dllAvFormat.av_read_frame(fmt_ctx, &avpkt) >= 0)
2499 len = m_dllAvCodec.avcodec_decode_audio4(dec_ctx, decoded_frame, &got_frame, &avpkt);
2502 m_dllAvCodec.avcodec_close(dec_ctx);
2503 m_dllAvUtil.av_free(dec_ctx);
2504 m_dllAvUtil.av_free(&decoded_frame);
2505 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2513 int samples = fileSize / m_dllAvUtil.av_get_bytes_per_sample(dec_ctx->sample_fmt) / config.channels;
2514 config.fmt = dec_ctx->sample_fmt;
2515 config.bits_per_sample = dec_ctx->bits_per_coded_sample;
2516 sound->InitSound(true, config, samples);
2519 sound->StoreSound(true, decoded_frame->extended_data,
2520 decoded_frame->nb_samples, decoded_frame->linesize[0]);
2523 m_dllAvCodec.avcodec_close(dec_ctx);
2526 m_dllAvUtil.av_free(dec_ctx);
2527 m_dllAvUtil.av_free(decoded_frame);
2528 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2533 m_dataPort.SendOutMessage(CActiveAEDataProtocol::NEWSOUND, &sound, sizeof(CActiveAESound*));
2538 void CActiveAE::FreeSound(IAESound *sound)
2540 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESOUND, &sound, sizeof(CActiveAESound*));
2543 void CActiveAE::PlaySound(CActiveAESound *sound)
2545 m_dataPort.SendOutMessage(CActiveAEDataProtocol::PLAYSOUND, &sound, sizeof(CActiveAESound*));
2548 void CActiveAE::StopSound(CActiveAESound *sound)
2550 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STOPSOUND, &sound, sizeof(CActiveAESound*));
2554 * resample sounds to destination format for mixing
2555 * destination format is either format of stream or
2556 * default sink format when no stream is playing
2558 void CActiveAE::ResampleSounds()
2560 if (m_settings.guisoundmode == AE_SOUND_OFF ||
2561 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
2564 std::vector<CActiveAESound*>::iterator it;
2565 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
2567 if (!(*it)->IsConverted())
2570 // only do one sound, then yield to main loop
2576 bool CActiveAE::ResampleSound(CActiveAESound *sound)
2578 SampleConfig orig_config, dst_config;
2579 uint8_t **dst_buffer;
2582 if (m_mode == MODE_RAW || m_internalFormat.m_dataFormat == AE_FMT_INVALID)
2585 if (!sound->GetSound(true))
2588 orig_config = sound->GetSound(true)->config;
2590 dst_config.channel_layout = CActiveAEResample::GetAVChannelLayout(m_internalFormat.m_channelLayout);
2591 dst_config.channels = m_internalFormat.m_channelLayout.Count();
2592 dst_config.sample_rate = m_internalFormat.m_sampleRate;
2593 dst_config.fmt = CActiveAEResample::GetAVSampleFormat(m_internalFormat.m_dataFormat);
2594 dst_config.bits_per_sample = CAEUtil::DataFormatToUsedBits(m_internalFormat.m_dataFormat);
2596 CActiveAEResample *resampler = new CActiveAEResample();
2597 resampler->Init(dst_config.channel_layout,
2598 dst_config.channels,
2599 dst_config.sample_rate,
2601 dst_config.bits_per_sample,
2602 orig_config.channel_layout,
2603 orig_config.channels,
2604 orig_config.sample_rate,
2606 orig_config.bits_per_sample,
2610 m_settings.resampleQuality);
2612 dst_samples = resampler->CalcDstSampleCount(sound->GetSound(true)->nb_samples,
2613 m_internalFormat.m_sampleRate,
2614 orig_config.sample_rate);
2616 dst_buffer = sound->InitSound(false, dst_config, dst_samples);
2622 int samples = resampler->Resample(dst_buffer, dst_samples,
2623 sound->GetSound(true)->data,
2624 sound->GetSound(true)->nb_samples,
2627 sound->GetSound(false)->nb_samples = samples;
2630 sound->SetConverted(true);
2634 //-----------------------------------------------------------------------------
2636 //-----------------------------------------------------------------------------
2638 IAEStream *CActiveAE::MakeStream(enum AEDataFormat dataFormat, unsigned int sampleRate, unsigned int encodedSampleRate, CAEChannelInfo channelLayout, unsigned int options)
2640 //TODO: pass number of samples in audio packet
2642 AEAudioFormat format;
2643 format.m_dataFormat = dataFormat;
2644 format.m_sampleRate = sampleRate;
2645 format.m_encodedRate = encodedSampleRate;
2646 format.m_channelLayout = channelLayout;
2647 format.m_frames = format.m_sampleRate / 10;
2648 format.m_frameSize = format.m_channelLayout.Count() *
2649 (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
2652 msg.format = format;
2653 msg.options = options;
2656 if (m_dataPort.SendOutMessageSync(CActiveAEDataProtocol::NEWSTREAM,
2658 &msg, sizeof(MsgStreamNew)))
2660 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2663 CActiveAEStream *stream = *(CActiveAEStream**)reply->data;
2670 CLog::Log(LOGERROR, "ActiveAE::%s - could not create stream", __FUNCTION__);
2674 IAEStream *CActiveAE::FreeStream(IAEStream *stream)
2676 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESTREAM, &stream, sizeof(IAEStream*));
2680 void CActiveAE::FlushStream(CActiveAEStream *stream)
2683 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::FLUSHSTREAM,
2685 &stream, sizeof(CActiveAEStream*)))
2687 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2691 CLog::Log(LOGERROR, "CActiveAE::FlushStream - failed");
2696 void CActiveAE::PauseStream(CActiveAEStream *stream, bool pause)
2698 // TODO pause sink, needs api change
2700 m_controlPort.SendOutMessage(CActiveAEControlProtocol::PAUSESTREAM,
2701 &stream, sizeof(CActiveAEStream*));
2703 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RESUMESTREAM,
2704 &stream, sizeof(CActiveAEStream*));
2707 void CActiveAE::SetStreamAmplification(CActiveAEStream *stream, float amplify)
2709 MsgStreamParameter msg;
2710 msg.stream = stream;
2711 msg.parameter.float_par = amplify;
2712 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMAMP,
2713 &msg, sizeof(MsgStreamParameter));
2716 void CActiveAE::SetStreamReplaygain(CActiveAEStream *stream, float rgain)
2718 MsgStreamParameter msg;
2719 msg.stream = stream;
2720 msg.parameter.float_par = rgain;
2721 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRGAIN,
2722 &msg, sizeof(MsgStreamParameter));
2725 void CActiveAE::SetStreamVolume(CActiveAEStream *stream, float volume)
2727 MsgStreamParameter msg;
2728 msg.stream = stream;
2729 msg.parameter.float_par = volume;
2730 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMVOLUME,
2731 &msg, sizeof(MsgStreamParameter));
2734 void CActiveAE::SetStreamResampleRatio(CActiveAEStream *stream, double ratio)
2736 MsgStreamParameter msg;
2737 msg.stream = stream;
2738 msg.parameter.double_par = ratio;
2739 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRESAMPLERATIO,
2740 &msg, sizeof(MsgStreamParameter));
2743 void CActiveAE::SetStreamFade(CActiveAEStream *stream, float from, float target, unsigned int millis)
2746 msg.stream = stream;
2748 msg.target = target;
2749 msg.millis = millis;
2750 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMFADE,
2751 &msg, sizeof(MsgStreamFade));
2754 void CActiveAE::RegisterAudioCallback(IAudioCallback* pCallback)
2756 CSingleLock lock(m_vizLock);
2757 m_audioCallback = pCallback;
2758 m_vizInitialized = false;
2761 void CActiveAE::UnregisterAudioCallback()
2763 CSingleLock lock(m_vizLock);
2764 m_audioCallback = NULL;