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;
152 m_volumeScaled = 1.0;
158 m_audioCallback = NULL;
159 m_vizInitialized = false;
160 m_sinkHasVolume = false;
163 CActiveAE::~CActiveAE()
168 void CActiveAE::Dispose()
170 #if defined(HAS_GLX) || defined(TARGET_DARWIN)
171 g_Windowing.Unregister(this);
177 m_controlPort.Purge();
181 m_dllAvFormat.Unload();
182 m_dllAvCodec.Unload();
183 m_dllAvUtil.Unload();
186 //-----------------------------------------------------------------------------
188 //-----------------------------------------------------------------------------
194 AE_TOP_UNCONFIGURED, // 2
195 AE_TOP_RECONFIGURING, // 3
196 AE_TOP_CONFIGURED, // 4
197 AE_TOP_CONFIGURED_SUSPEND, // 5
198 AE_TOP_CONFIGURED_IDLE, // 6
199 AE_TOP_CONFIGURED_PLAY, // 7
202 int AE_parentStates[] = {
205 0, //TOP_UNCONFIGURED
207 0, //TOP_RECONFIGURING
208 4, //TOP_CONFIGURED_SUSPEND
209 4, //TOP_CONFIGURED_IDLE
210 4, //TOP_CONFIGURED_PLAY
213 void CActiveAE::StateMachine(int signal, Protocol *port, Message *msg)
215 for (int state = m_state; ; state = AE_parentStates[state])
220 if (port == &m_controlPort)
224 case CActiveAEControlProtocol::GETSTATE:
225 msg->Reply(CActiveAEControlProtocol::ACC, &m_state, sizeof(m_state));
227 case CActiveAEControlProtocol::VOLUME:
228 m_volume = *(float*)msg->data;
229 m_volumeScaled = CAEUtil::GainToScale(CAEUtil::PercentToGain(m_volume));
231 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
233 case CActiveAEControlProtocol::MUTE:
234 m_muted = *(bool*)msg->data;
236 case CActiveAEControlProtocol::KEEPCONFIG:
237 m_extKeepConfig = *(unsigned int*)msg->data;
239 case CActiveAEControlProtocol::DISPLAYRESET:
241 case CActiveAEControlProtocol::APPFOCUSED:
242 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::APPFOCUSED, msg->data, sizeof(bool));
248 else if (port == &m_dataPort)
252 case CActiveAEDataProtocol::NEWSOUND:
253 CActiveAESound *sound;
254 sound = *(CActiveAESound**)msg->data;
257 m_sounds.push_back(sound);
261 case CActiveAEDataProtocol::FREESTREAM:
262 CActiveAEStream *stream;
263 stream = *(CActiveAEStream**)msg->data;
264 DiscardStream(stream);
266 case CActiveAEDataProtocol::FREESOUND:
267 sound = *(CActiveAESound**)msg->data;
270 case CActiveAEDataProtocol::DRAINSTREAM:
271 stream = *(CActiveAEStream**)msg->data;
272 stream->m_drain = true;
273 stream->m_resampleBuffers->m_drain = true;
274 msg->Reply(CActiveAEDataProtocol::ACC);
275 stream->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
281 else if (port == &m_sink.m_dataPort)
285 case CSinkDataProtocol::RETURNSAMPLE:
286 CSampleBuffer **buffer;
287 buffer = (CSampleBuffer**)msg->data;
298 std::string portName = port == NULL ? "timer" : port->portName;
299 CLog::Log(LOGWARNING, "CActiveAE::%s - signal: %d from port: %s not handled for state: %d", __FUNCTION__, signal, portName.c_str(), m_state);
304 if (port == NULL) // timeout
308 case CActiveAEControlProtocol::TIMEOUT:
314 m_state = AE_TOP_CONFIGURED_IDLE;
319 m_state = AE_TOP_ERROR;
329 case AE_TOP_UNCONFIGURED:
330 if (port == &m_controlPort)
334 case CActiveAEControlProtocol::INIT:
336 m_sink.EnumerateSinkList(false);
339 msg->Reply(CActiveAEControlProtocol::ACC);
342 m_state = AE_TOP_CONFIGURED_IDLE;
347 m_state = AE_TOP_ERROR;
358 case AE_TOP_RECONFIGURING:
359 if (port == NULL) // timeout
363 case CActiveAEControlProtocol::TIMEOUT:
370 if (!m_sinkBuffers->m_inputSamples.empty() || !m_sinkBuffers->m_outputSamples.empty())
375 if (NeedReconfigureSink())
382 m_state = AE_TOP_CONFIGURED_PLAY;
387 m_state = AE_TOP_ERROR;
390 m_extDeferData = false;
398 case AE_TOP_CONFIGURED:
399 if (port == &m_controlPort)
404 case CActiveAEControlProtocol::RECONFIGURE:
405 if (m_streams.empty())
408 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
412 if (!NeedReconfigureBuffers() && !NeedReconfigureSink())
414 m_state = AE_TOP_RECONFIGURING;
416 // don't accept any data until we are reconfigured
417 m_extDeferData = true;
419 case CActiveAEControlProtocol::SUSPEND:
421 m_stats.SetSuspended(true);
422 m_state = AE_TOP_CONFIGURED_SUSPEND;
423 m_extDeferData = true;
425 case CActiveAEControlProtocol::DISPLAYLOST:
426 if (m_sink.GetDeviceType(m_mode == MODE_PCM ? m_settings.device : m_settings.passthoughdevice) == AE_DEVTYPE_HDMI)
429 m_stats.SetSuspended(true);
430 m_state = AE_TOP_CONFIGURED_SUSPEND;
431 m_extDeferData = true;
433 msg->Reply(CActiveAEControlProtocol::ACC);
435 case CActiveAEControlProtocol::DEVICECHANGE:
438 CLog::Log(LOGDEBUG,"CActiveAE - device change event");
439 while (!m_extLastDeviceChange.empty() && (now - m_extLastDeviceChange.front() > 0))
441 m_extLastDeviceChange.pop();
443 if (m_extLastDeviceChange.size() > 2)
445 CLog::Log(LOGWARNING,"CActiveAE - received %ld device change events within one second", m_extLastDeviceChange.size());
448 m_extLastDeviceChange.push(now);
450 m_controlPort.PurgeOut(CActiveAEControlProtocol::DEVICECHANGE);
451 m_sink.EnumerateSinkList(true);
457 m_state = AE_TOP_CONFIGURED_PLAY;
462 m_state = AE_TOP_ERROR;
466 case CActiveAEControlProtocol::PAUSESTREAM:
467 CActiveAEStream *stream;
468 stream = *(CActiveAEStream**)msg->data;
469 if (stream->m_paused != true && m_streams.size() == 1)
473 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
475 stream->m_paused = true;
477 case CActiveAEControlProtocol::RESUMESTREAM:
478 stream = *(CActiveAEStream**)msg->data;
479 stream->m_paused = false;
481 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
484 case CActiveAEControlProtocol::FLUSHSTREAM:
485 stream = *(CActiveAEStream**)msg->data;
486 SFlushStream(stream);
487 msg->Reply(CActiveAEControlProtocol::ACC);
490 case CActiveAEControlProtocol::STREAMAMP:
491 MsgStreamParameter *par;
492 par = (MsgStreamParameter*)msg->data;
493 par->stream->m_limiter.SetAmplification(par->parameter.float_par);
494 par->stream->m_amplify = par->parameter.float_par;
496 case CActiveAEControlProtocol::STREAMVOLUME:
497 par = (MsgStreamParameter*)msg->data;
498 par->stream->m_volume = par->parameter.float_par;
500 case CActiveAEControlProtocol::STREAMRGAIN:
501 par = (MsgStreamParameter*)msg->data;
502 par->stream->m_rgain = par->parameter.float_par;
504 case CActiveAEControlProtocol::STREAMRESAMPLERATIO:
505 par = (MsgStreamParameter*)msg->data;
506 if (par->stream->m_resampleBuffers)
508 par->stream->m_resampleBuffers->m_resampleRatio = par->parameter.double_par;
511 case CActiveAEControlProtocol::STREAMFADE:
513 fade = (MsgStreamFade*)msg->data;
514 fade->stream->m_fadingBase = fade->from;
515 fade->stream->m_fadingTarget = fade->target;
516 fade->stream->m_fadingTime = fade->millis;
517 fade->stream->m_fadingSamples = -1;
519 case CActiveAEControlProtocol::STOPSOUND:
520 CActiveAESound *sound;
521 sound = *(CActiveAESound**)msg->data;
528 else if (port == &m_dataPort)
532 case CActiveAEDataProtocol::PLAYSOUND:
533 CActiveAESound *sound;
534 sound = *(CActiveAESound**)msg->data;
535 if (m_settings.guisoundmode == AE_SOUND_OFF ||
536 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
540 SoundState st = {sound, 0};
541 m_sounds_playing.push_back(st);
543 m_state = AE_TOP_CONFIGURED_PLAY;
546 case CActiveAEDataProtocol::NEWSTREAM:
547 MsgStreamNew *streamMsg;
548 CActiveAEStream *stream;
549 streamMsg = (MsgStreamNew*)msg->data;
550 stream = CreateStream(streamMsg);
553 msg->Reply(CActiveAEDataProtocol::ACC, &stream, sizeof(CActiveAEStream*));
558 m_state = AE_TOP_CONFIGURED_PLAY;
563 m_state = AE_TOP_ERROR;
568 msg->Reply(CActiveAEDataProtocol::ERR);
570 case CActiveAEDataProtocol::STREAMSAMPLE:
571 MsgStreamSample *msgData;
572 CSampleBuffer *samples;
573 msgData = (MsgStreamSample*)msg->data;
574 samples = msgData->stream->m_processingSamples.front();
575 msgData->stream->m_processingSamples.pop_front();
576 if (samples != msgData->buffer)
577 CLog::Log(LOGERROR, "CActiveAE - inconsistency in stream sample message");
578 if (msgData->buffer->pkt->nb_samples == 0)
579 msgData->buffer->Return();
581 msgData->stream->m_resampleBuffers->m_inputSamples.push_back(msgData->buffer);
583 m_state = AE_TOP_CONFIGURED_PLAY;
585 case CActiveAEDataProtocol::FREESTREAM:
586 stream = *(CActiveAEStream**)msg->data;
587 DiscardStream(stream);
588 if (m_streams.empty())
591 m_extDrainTimer.Set(m_extKeepConfig);
593 m_extDrainTimer.Set(m_stats.GetDelay() * 1000);
597 m_state = AE_TOP_CONFIGURED_PLAY;
599 case CActiveAEDataProtocol::DRAINSTREAM:
600 stream = *(CActiveAEStream**)msg->data;
601 stream->m_drain = true;
602 stream->m_resampleBuffers->m_drain = true;
604 m_state = AE_TOP_CONFIGURED_PLAY;
605 msg->Reply(CActiveAEDataProtocol::ACC);
611 else if (port == &m_sink.m_dataPort)
615 case CSinkDataProtocol::RETURNSAMPLE:
616 CSampleBuffer **buffer;
617 buffer = (CSampleBuffer**)msg->data;
623 m_state = AE_TOP_CONFIGURED_PLAY;
631 case AE_TOP_CONFIGURED_SUSPEND:
632 if (port == &m_controlPort)
634 bool displayReset = false;
637 case CActiveAEControlProtocol::DISPLAYRESET:
638 CLog::Log(LOGDEBUG,"CActiveAE - display reset event");
640 case CActiveAEControlProtocol::INIT:
644 m_controlPort.PurgeOut(CActiveAEControlProtocol::DEVICECHANGE);
645 m_sink.EnumerateSinkList(true);
650 msg->Reply(CActiveAEControlProtocol::ACC);
653 m_state = AE_TOP_CONFIGURED_PLAY;
658 m_state = AE_TOP_ERROR;
661 m_stats.SetSuspended(false);
662 m_extDeferData = false;
664 case CActiveAEControlProtocol::DEVICECHANGE:
670 else if (port == &m_sink.m_dataPort)
674 case CSinkDataProtocol::RETURNSAMPLE:
675 CSampleBuffer **buffer;
676 buffer = (CSampleBuffer**)msg->data;
686 else if (port == NULL) // timeout
690 case CActiveAEControlProtocol::TIMEOUT:
699 case AE_TOP_CONFIGURED_IDLE:
700 if (port == &m_controlPort)
704 case CActiveAEControlProtocol::RESUMESTREAM:
705 CActiveAEStream *stream;
706 stream = *(CActiveAEStream**)msg->data;
707 stream->m_paused = false;
708 m_state = AE_TOP_CONFIGURED_PLAY;
711 case CActiveAEControlProtocol::FLUSHSTREAM:
712 stream = *(CActiveAEStream**)msg->data;
713 SFlushStream(stream);
714 msg->Reply(CActiveAEControlProtocol::ACC);
715 m_state = AE_TOP_CONFIGURED_PLAY;
722 else if (port == NULL) // timeout
726 case CActiveAEControlProtocol::TIMEOUT:
728 ClearDiscardedBuffers();
731 if (m_extDrainTimer.IsTimePast())
736 m_state = AE_TOP_CONFIGURED_PLAY;
741 m_state = AE_TOP_ERROR;
746 m_extTimeout = m_extDrainTimer.MillisLeft();
757 case AE_TOP_CONFIGURED_PLAY:
758 if (port == NULL) // timeout
762 case CActiveAEControlProtocol::TIMEOUT:
765 m_state = AE_TOP_ERROR;
774 if (!m_extDrain && HasWork())
776 ClearDiscardedBuffers();
781 m_state = AE_TOP_CONFIGURED_IDLE;
789 default: // we are in no state, should not happen
790 CLog::Log(LOGERROR, "CActiveAE::%s - no valid state: %d", __FUNCTION__, m_state);
796 void CActiveAE::Process()
799 Protocol *port = NULL;
801 XbmcThreads::EndTime timer;
803 m_state = AE_TOP_UNCONFIGURED;
805 m_bStateMachineSelfTrigger = false;
807 m_extDeferData = false;
816 timer.Set(m_extTimeout);
818 if (m_bStateMachineSelfTrigger)
820 m_bStateMachineSelfTrigger = false;
821 // self trigger state machine
822 StateMachine(msg->signal, port, msg);
823 if (!m_bStateMachineSelfTrigger)
830 // check control port
831 else if (m_controlPort.ReceiveOutMessage(&msg))
834 port = &m_controlPort;
836 // check sink data port
837 else if (m_sink.m_dataPort.ReceiveInMessage(&msg))
840 port = &m_sink.m_dataPort;
842 else if (!m_extDeferData)
845 if (m_dataPort.ReceiveOutMessage(&msg))
853 std::list<CActiveAEStream*>::iterator it;
854 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
856 if((*it)->m_streamPort->ReceiveOutMessage(&msg))
868 StateMachine(msg->signal, port, msg);
869 if (!m_bStateMachineSelfTrigger)
878 else if (m_outMsgEvent.WaitMSec(m_extTimeout))
880 m_extTimeout = timer.MillisLeft();
886 msg = m_controlPort.GetMessage();
887 msg->signal = CActiveAEControlProtocol::TIMEOUT;
889 // signal timeout to state machine
890 StateMachine(msg->signal, port, msg);
891 if (!m_bStateMachineSelfTrigger)
900 AEAudioFormat CActiveAE::GetInputFormat(AEAudioFormat *desiredFmt)
902 AEAudioFormat inputFormat;
904 if (m_streams.empty())
906 inputFormat.m_dataFormat = AE_FMT_FLOAT;
907 inputFormat.m_sampleRate = 44100;
908 inputFormat.m_encodedRate = 0;
909 inputFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
910 inputFormat.m_frames = 0;
911 inputFormat.m_frameSamples = 0;
912 inputFormat.m_frameSize = 0;
914 // force input format after unpausing slave
915 else if (desiredFmt != NULL)
917 inputFormat = *desiredFmt;
919 // keep format when having multiple streams
920 else if (m_streams.size() > 1 && m_silenceBuffers == NULL)
922 inputFormat = m_inputFormat;
926 inputFormat = m_streams.front()->m_format;
927 m_inputFormat = inputFormat;
933 void CActiveAE::Configure(AEAudioFormat *desiredFmt)
935 bool initSink = false;
937 AEAudioFormat sinkInputFormat, inputFormat;
938 AEAudioFormat oldInternalFormat = m_internalFormat;
939 AEAudioFormat oldSinkRequestFormat = m_sinkRequestFormat;
941 inputFormat = GetInputFormat(desiredFmt);
943 m_sinkRequestFormat = inputFormat;
944 ApplySettingsToFormat(m_sinkRequestFormat, m_settings, (int*)&m_mode);
947 std::string device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
949 CAESinkFactory::ParseDevice(device, driver);
950 if ((!CompareFormat(m_sinkRequestFormat, m_sinkFormat) && !CompareFormat(m_sinkRequestFormat, oldSinkRequestFormat)) ||
951 m_currDevice.compare(device) != 0 ||
952 m_settings.driver.compare(driver) != 0)
956 m_settings.driver = driver;
957 m_currDevice = device;
959 m_stats.Reset(m_sinkFormat.m_sampleRate);
960 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
962 // limit buffer size in case of sink returns large buffer
963 unsigned int buffertime = m_sinkFormat.m_frames / m_sinkFormat.m_sampleRate;
964 if (buffertime > MAX_BUFFER_TIME)
966 CLog::Log(LOGWARNING, "ActiveAE::%s - sink returned large buffer of %d ms, reducing to %d ms", __FUNCTION__, buffertime, (int)(MAX_BUFFER_TIME*1000));
967 m_sinkFormat.m_frames = MAX_BUFFER_TIME * m_sinkFormat.m_sampleRate;
971 if (m_silenceBuffers)
973 m_discardBufferPools.push_back(m_silenceBuffers);
974 m_silenceBuffers = NULL;
977 // buffers for driving gui sounds if no streams are active
978 if (m_streams.empty())
980 inputFormat = m_sinkFormat;
981 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
983 inputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
984 inputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
986 inputFormat.m_dataFormat = AE_FMT_FLOAT;
987 inputFormat.m_frameSize = inputFormat.m_channelLayout.Count() *
988 (CAEUtil::DataFormatToBits(inputFormat.m_dataFormat) >> 3);
989 m_silenceBuffers = new CActiveAEBufferPool(inputFormat);
990 m_silenceBuffers->Create(MAX_WATER_LEVEL*1000);
991 sinkInputFormat = inputFormat;
992 m_internalFormat = inputFormat;
994 bool streaming = false;
995 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
1000 if (m_encoderBuffers)
1002 m_discardBufferPools.push_back(m_encoderBuffers);
1003 m_encoderBuffers = NULL;
1007 m_discardBufferPools.push_back(m_vizBuffers);
1008 m_vizBuffers = NULL;
1010 if (m_vizBuffersInput)
1012 m_discardBufferPools.push_back(m_vizBuffersInput);
1013 m_vizBuffersInput = NULL;
1016 // resample buffers for streams
1019 bool streaming = true;
1020 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::STREAMING, &streaming, sizeof(bool));
1022 AEAudioFormat outputFormat;
1023 if (m_mode == MODE_RAW)
1025 inputFormat.m_frames = m_sinkFormat.m_frames;
1026 outputFormat = inputFormat;
1027 sinkInputFormat = m_sinkFormat;
1029 // transcode everything with more than 2 channels
1030 else if (m_mode == MODE_TRANSCODE)
1032 outputFormat = inputFormat;
1033 outputFormat.m_dataFormat = AE_FMT_FLOATP;
1034 outputFormat.m_sampleRate = 48000;
1035 outputFormat.m_encodedRate = 48000;
1040 m_encoder = new CAEEncoderFFmpeg();
1041 m_encoder->Initialize(outputFormat, true);
1042 m_encoderFormat = outputFormat;
1045 outputFormat = m_encoderFormat;
1047 outputFormat.m_channelLayout = m_encoderFormat.m_channelLayout;
1048 outputFormat.m_frames = m_encoderFormat.m_frames;
1051 if (m_encoder->GetCodecID() == AV_CODEC_ID_AC3)
1053 AEAudioFormat format;
1054 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1055 format.m_dataFormat = AE_FMT_S16NE;
1056 format.m_frameSize = 2* (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
1057 format.m_frames = AC3_FRAME_SIZE;
1058 format.m_sampleRate = 48000;
1059 format.m_encodedRate = m_encoderFormat.m_sampleRate;
1060 if (m_encoderBuffers && initSink)
1062 m_discardBufferPools.push_back(m_encoderBuffers);
1063 m_encoderBuffers = NULL;
1065 if (!m_encoderBuffers)
1067 m_encoderBuffers = new CActiveAEBufferPool(format);
1068 m_encoderBuffers->Create(MAX_WATER_LEVEL*1000);
1072 sinkInputFormat = m_sinkFormat;
1076 outputFormat = m_sinkFormat;
1077 outputFormat.m_dataFormat = AE_FMT_FLOAT;
1078 outputFormat.m_frameSize = outputFormat.m_channelLayout.Count() *
1079 (CAEUtil::DataFormatToBits(outputFormat.m_dataFormat) >> 3);
1081 // due to channel ordering of the driver, a sink may return more channels than
1082 // requested, i.e. 2.1 request returns FL,FR,BL,BR,FC,LFE for ALSA
1083 // in this case we need to downmix to requested format
1084 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
1086 outputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
1087 outputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
1090 // TODO: adjust to decoder
1091 sinkInputFormat = outputFormat;
1093 m_internalFormat = outputFormat;
1095 std::list<CActiveAEStream*>::iterator it;
1096 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1098 // check if we support input format of stream
1099 if (!AE_IS_RAW((*it)->m_format.m_dataFormat) &&
1100 CActiveAEResample::GetAVSampleFormat((*it)->m_format.m_dataFormat) == AV_SAMPLE_FMT_FLT &&
1101 (*it)->m_format.m_dataFormat != AE_FMT_FLOAT)
1103 (*it)->m_convertFn = CAEConvert::ToFloat((*it)->m_format.m_dataFormat);
1104 (*it)->m_format.m_dataFormat = AE_FMT_FLOAT;
1107 if (!(*it)->m_inputBuffers)
1109 // align input buffers with period of sink or encoder
1110 (*it)->m_format.m_frames = m_internalFormat.m_frames * ((float)(*it)->m_format.m_sampleRate / m_internalFormat.m_sampleRate);
1112 // create buffer pool
1113 (*it)->m_inputBuffers = new CActiveAEBufferPool((*it)->m_format);
1114 (*it)->m_inputBuffers->Create(MAX_CACHE_LEVEL*1000);
1115 (*it)->m_streamSpace = (*it)->m_format.m_frameSize * (*it)->m_format.m_frames;
1117 // if input format does not follow ffmpeg channel mask, we may need to remap channels
1118 (*it)->InitRemapper();
1120 if (initSink && (*it)->m_resampleBuffers)
1122 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1123 (*it)->m_resampleBuffers = NULL;
1125 if (!(*it)->m_resampleBuffers)
1127 (*it)->m_resampleBuffers = new CActiveAEBufferPoolResample((*it)->m_inputBuffers->m_format, outputFormat, m_settings.resampleQuality);
1128 (*it)->m_resampleBuffers->m_changeResampler = (*it)->m_forceResampler;
1129 (*it)->m_resampleBuffers->Create(MAX_CACHE_LEVEL*1000, false, m_settings.stereoupmix, m_settings.normalizelevels);
1131 if (m_mode == MODE_TRANSCODE || m_streams.size() > 1)
1132 (*it)->m_resampleBuffers->m_fillPackets = true;
1135 (*it)->m_limiter.SetSamplerate(outputFormat.m_sampleRate);
1138 // update buffered time of streams
1139 m_stats.AddSamples(0, m_streams);
1142 if (!AE_IS_RAW(inputFormat.m_dataFormat))
1144 if (initSink && m_vizBuffers)
1146 m_discardBufferPools.push_back(m_vizBuffers);
1147 m_vizBuffers = NULL;
1148 m_discardBufferPools.push_back(m_vizBuffersInput);
1149 m_vizBuffersInput = NULL;
1153 AEAudioFormat vizFormat = m_internalFormat;
1154 vizFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
1155 vizFormat.m_dataFormat = AE_FMT_FLOAT;
1158 m_vizBuffersInput = new CActiveAEBufferPool(m_internalFormat);
1159 m_vizBuffersInput->Create(2000);
1162 m_vizBuffers = new CActiveAEBufferPoolResample(m_internalFormat, vizFormat, m_settings.resampleQuality);
1163 // TODO use cache of sync + water level
1164 m_vizBuffers->Create(2000, false, false);
1165 m_vizInitialized = false;
1170 // resample buffers for sink
1171 if (m_sinkBuffers &&
1172 (!CompareFormat(m_sinkBuffers->m_format,m_sinkFormat) || !CompareFormat(m_sinkBuffers->m_inputFormat, sinkInputFormat)))
1174 m_discardBufferPools.push_back(m_sinkBuffers);
1175 m_sinkBuffers = NULL;
1179 m_sinkBuffers = new CActiveAEBufferPoolResample(sinkInputFormat, m_sinkFormat, m_settings.resampleQuality);
1180 m_sinkBuffers->Create(MAX_WATER_LEVEL*1000, true, false);
1184 if (!CompareFormat(oldInternalFormat, m_internalFormat))
1186 if (m_settings.guisoundmode == AE_SOUND_ALWAYS ||
1187 (m_settings.guisoundmode == AE_SOUND_IDLE && m_streams.empty()))
1189 std::vector<CActiveAESound*>::iterator it;
1190 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
1192 (*it)->SetConverted(false);
1195 m_sounds_playing.clear();
1198 ClearDiscardedBuffers();
1202 CActiveAEStream* CActiveAE::CreateStream(MsgStreamNew *streamMsg)
1204 // we only can handle a single pass through stream
1205 bool hasRawStream = false;
1206 bool hasStream = false;
1207 std::list<CActiveAEStream*>::iterator it;
1208 for(it = m_streams.begin(); it != m_streams.end(); ++it)
1210 if((*it)->IsDrained())
1212 if(AE_IS_RAW((*it)->m_format.m_dataFormat))
1213 hasRawStream = true;
1216 if (hasRawStream || (hasStream && AE_IS_RAW(streamMsg->format.m_dataFormat)))
1221 // create the stream
1222 CActiveAEStream *stream;
1223 stream = new CActiveAEStream(&streamMsg->format);
1224 stream->m_streamPort = new CActiveAEDataProtocol("stream",
1225 &stream->m_inMsgEvent, &m_outMsgEvent);
1227 // create buffer pool
1228 stream->m_inputBuffers = NULL; // create in Configure when we know the sink format
1229 stream->m_resampleBuffers = NULL; // create in Configure when we know the sink format
1230 stream->m_statsLock = m_stats.GetLock();
1231 stream->m_fadingSamples = 0;
1232 stream->m_started = false;
1234 if (streamMsg->options & AESTREAM_PAUSED)
1235 stream->m_paused = true;
1237 if (streamMsg->options & AESTREAM_FORCE_RESAMPLE)
1238 stream->m_forceResampler = true;
1240 m_streams.push_back(stream);
1245 void CActiveAE::DiscardStream(CActiveAEStream *stream)
1247 std::list<CActiveAEStream*>::iterator it;
1248 for (it=m_streams.begin(); it!=m_streams.end(); )
1250 if (stream == (*it))
1252 while (!(*it)->m_processingSamples.empty())
1254 (*it)->m_processingSamples.front()->Return();
1255 (*it)->m_processingSamples.pop_front();
1257 m_discardBufferPools.push_back((*it)->m_inputBuffers);
1258 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1259 CLog::Log(LOGDEBUG, "CActiveAE::DiscardStream - audio stream deleted");
1260 delete (*it)->m_streamPort;
1262 it = m_streams.erase(it);
1268 ClearDiscardedBuffers();
1271 void CActiveAE::SFlushStream(CActiveAEStream *stream)
1273 while (!stream->m_processingSamples.empty())
1275 stream->m_processingSamples.front()->Return();
1276 stream->m_processingSamples.pop_front();
1278 stream->m_resampleBuffers->Flush();
1279 stream->m_streamPort->Purge();
1280 stream->m_bufferedTime = 0.0;
1281 stream->m_paused = false;
1283 // flush the engine if we only have a single stream
1284 if (m_streams.size() == 1)
1290 void CActiveAE::FlushEngine()
1293 m_sinkBuffers->Flush();
1295 m_vizBuffers->Flush();
1297 // send message to sink
1299 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::FLUSH,
1302 bool success = reply->signal == CSinkControlProtocol::ACC;
1305 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on flush", __FUNCTION__);
1312 CLog::Log(LOGERROR, "ActiveAE::%s - failed to flush", __FUNCTION__);
1315 m_stats.Reset(m_sinkFormat.m_sampleRate);
1318 void CActiveAE::ClearDiscardedBuffers()
1320 std::list<CActiveAEBufferPool*>::iterator it;
1321 for (it=m_discardBufferPools.begin(); it!=m_discardBufferPools.end(); ++it)
1323 CActiveAEBufferPoolResample *rbuf = dynamic_cast<CActiveAEBufferPoolResample*>(*it);
1328 // if all buffers have returned, we can delete the buffer pool
1329 if ((*it)->m_allSamples.size() == (*it)->m_freeSamples.size())
1332 CLog::Log(LOGDEBUG, "CActiveAE::ClearDiscardedBuffers - buffer pool deleted");
1333 m_discardBufferPools.erase(it);
1339 void CActiveAE::SStopSound(CActiveAESound *sound)
1341 std::list<SoundState>::iterator it;
1342 for (it=m_sounds_playing.begin(); it!=m_sounds_playing.end(); ++it)
1344 if (it->sound == sound)
1346 m_sounds_playing.erase(it);
1352 void CActiveAE::DiscardSound(CActiveAESound *sound)
1356 std::vector<CActiveAESound*>::iterator it;
1357 for (it=m_sounds.begin(); it!=m_sounds.end(); ++it)
1367 void CActiveAE::ChangeResamplers()
1369 std::list<CActiveAEStream*>::iterator it;
1370 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1372 bool normalize = true;
1373 if (((*it)->m_resampleBuffers->m_format.m_channelLayout.Count() <
1374 (*it)->m_resampleBuffers->m_inputFormat.m_channelLayout.Count()) &&
1375 !m_settings.normalizelevels)
1378 if ((*it)->m_resampleBuffers && (*it)->m_resampleBuffers->m_resampler &&
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)))
1383 (*it)->m_resampleBuffers->m_changeResampler = true;
1385 (*it)->m_resampleBuffers->m_resampleQuality = m_settings.resampleQuality;
1386 (*it)->m_resampleBuffers->m_stereoUpmix = m_settings.stereoupmix;
1387 (*it)->m_resampleBuffers->m_normalize = normalize;
1391 void CActiveAE::ApplySettingsToFormat(AEAudioFormat &format, AudioSettings &settings, int *mode)
1393 int oldMode = m_mode;
1398 if (AE_IS_RAW(format.m_dataFormat))
1400 if ((format.m_dataFormat == AE_FMT_AC3 && !settings.ac3passthrough) ||
1401 (format.m_dataFormat == AE_FMT_EAC3 && !settings.eac3passthrough) ||
1402 (format.m_dataFormat == AE_FMT_TRUEHD && !settings.truehdpassthrough) ||
1403 (format.m_dataFormat == AE_FMT_DTS && !settings.dtspassthrough) ||
1404 (format.m_dataFormat == AE_FMT_DTSHD && !settings.dtshdpassthrough))
1406 CLog::Log(LOGERROR, "CActiveAE::ApplySettingsToFormat - input audio format is wrong");
1412 else if (settings.channels <= AE_CH_LAYOUT_2_0 && // no multichannel pcm
1413 settings.passthrough &&
1414 settings.ac3passthrough &&
1415 settings.ac3transcode &&
1416 !m_streams.empty() &&
1417 (format.m_channelLayout.Count() > 2 || settings.stereoupmix))
1419 format.m_dataFormat = AE_FMT_AC3;
1420 format.m_sampleRate = 48000;
1421 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1423 *mode = MODE_TRANSCODE;
1427 format.m_dataFormat = AE_FMT_FLOAT;
1428 // consider user channel layout for those cases
1429 // 1. input stream is multichannel
1430 // 2. stereo upmix is selected
1432 if ((format.m_channelLayout.Count() > 2) ||
1433 settings.stereoupmix ||
1434 (settings.config == AE_CONFIG_FIXED))
1436 CAEChannelInfo stdLayout;
1437 switch (settings.channels)
1440 case 0: stdLayout = AE_CH_LAYOUT_2_0; break;
1441 case 1: stdLayout = AE_CH_LAYOUT_2_0; break;
1442 case 2: stdLayout = AE_CH_LAYOUT_2_1; break;
1443 case 3: stdLayout = AE_CH_LAYOUT_3_0; break;
1444 case 4: stdLayout = AE_CH_LAYOUT_3_1; break;
1445 case 5: stdLayout = AE_CH_LAYOUT_4_0; break;
1446 case 6: stdLayout = AE_CH_LAYOUT_4_1; break;
1447 case 7: stdLayout = AE_CH_LAYOUT_5_0; break;
1448 case 8: stdLayout = AE_CH_LAYOUT_5_1; break;
1449 case 9: stdLayout = AE_CH_LAYOUT_7_0; break;
1450 case 10: stdLayout = AE_CH_LAYOUT_7_1; break;
1453 if (m_settings.config == AE_CONFIG_FIXED || (settings.stereoupmix && format.m_channelLayout.Count() <= 2))
1454 format.m_channelLayout = stdLayout;
1455 else if (m_extKeepConfig && (settings.config == AE_CONFIG_AUTO) && (oldMode != MODE_RAW))
1456 format.m_channelLayout = m_internalFormat.m_channelLayout;
1458 format.m_channelLayout.ResolveChannels(stdLayout);
1460 // don't change from multi to stereo in AUTO mode
1461 else if ((settings.config == AE_CONFIG_AUTO) &&
1462 m_stats.GetWaterLevel() > 0 && m_internalFormat.m_channelLayout.Count() > 2)
1464 format.m_channelLayout = m_internalFormat.m_channelLayout;
1467 if (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958)
1469 if (format.m_sampleRate > m_settings.samplerate)
1471 format.m_sampleRate = m_settings.samplerate;
1472 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - limit samplerate for SPDIF to %d", format.m_sampleRate);
1474 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1477 if (m_settings.config == AE_CONFIG_FIXED)
1479 format.m_sampleRate = m_settings.samplerate;
1480 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - Forcing samplerate to %d", format.m_sampleRate);
1483 // sinks may not support mono
1484 if (format.m_channelLayout.Count() == 1)
1486 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1491 bool CActiveAE::NeedReconfigureBuffers()
1493 AEAudioFormat newFormat = GetInputFormat();
1494 ApplySettingsToFormat(newFormat, m_settings);
1496 if (newFormat.m_dataFormat != m_sinkRequestFormat.m_dataFormat ||
1497 newFormat.m_channelLayout != m_sinkRequestFormat.m_channelLayout ||
1498 newFormat.m_sampleRate != m_sinkRequestFormat.m_sampleRate)
1504 bool CActiveAE::NeedReconfigureSink()
1506 AEAudioFormat newFormat = GetInputFormat();
1507 ApplySettingsToFormat(newFormat, m_settings);
1509 std::string device = AE_IS_RAW(newFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
1511 CAESinkFactory::ParseDevice(device, driver);
1513 if (!CompareFormat(newFormat, m_sinkFormat) ||
1514 m_currDevice.compare(device) != 0 ||
1515 m_settings.driver.compare(driver) != 0)
1521 bool CActiveAE::InitSink()
1524 config.format = m_sinkRequestFormat;
1525 config.stats = &m_stats;
1526 config.device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? &m_settings.passthoughdevice :
1529 // send message to sink
1531 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::CONFIGURE,
1534 &config, sizeof(config)))
1536 bool success = reply->signal == CSinkControlProtocol::ACC;
1540 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1545 data = (SinkReply*)reply->data;
1548 m_sinkFormat = data->format;
1549 m_sinkHasVolume = data->hasVolume;
1550 m_stats.SetSinkCacheTotal(data->cacheTotal);
1551 m_stats.SetSinkLatency(data->latency);
1557 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
1558 m_stats.SetSinkCacheTotal(0);
1559 m_stats.SetSinkLatency(0);
1564 m_inMsgEvent.Reset();
1568 void CActiveAE::DrainSink()
1570 // send message to sink
1572 if (m_sink.m_dataPort.SendOutMessageSync(CSinkDataProtocol::DRAIN,
1576 bool success = reply->signal == CSinkDataProtocol::ACC;
1580 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on drain", __FUNCTION__);
1588 CLog::Log(LOGERROR, "ActiveAE::%s - failed to drain", __FUNCTION__);
1594 void CActiveAE::UnconfigureSink()
1596 // send message to sink
1598 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::UNCONFIGURE,
1602 bool success = reply->signal == CSinkControlProtocol::ACC;
1605 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1612 CLog::Log(LOGERROR, "ActiveAE::%s - failed to unconfigure", __FUNCTION__);
1616 // make sure we open sink on next configure
1619 m_inMsgEvent.Reset();
1623 bool CActiveAE::RunStages()
1627 // serve input streams
1628 std::list<CActiveAEStream*>::iterator it;
1629 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1631 if ((*it)->m_resampleBuffers && !(*it)->m_paused)
1632 busy = (*it)->m_resampleBuffers->ResampleBuffers();
1633 else if ((*it)->m_resampleBuffers &&
1634 ((*it)->m_resampleBuffers->m_inputSamples.size() > (*it)->m_resampleBuffers->m_allSamples.size() * 0.5))
1636 CSingleLock lock((*it)->m_streamLock);
1637 (*it)->m_streamIsBuffering = false;
1640 // provide buffers to stream
1641 float time = m_stats.GetCacheTime((*it));
1642 CSampleBuffer *buffer;
1643 if (!(*it)->m_drain)
1645 while (time < MAX_CACHE_LEVEL && !(*it)->m_inputBuffers->m_freeSamples.empty())
1647 buffer = (*it)->m_inputBuffers->GetFreeBuffer();
1648 (*it)->m_processingSamples.push_back(buffer);
1649 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMBUFFER, &buffer, sizeof(CSampleBuffer*));
1650 (*it)->IncFreeBuffers();
1651 time += (float)buffer->pkt->max_nb_samples / buffer->pkt->config.sample_rate;
1656 if ((*it)->m_resampleBuffers->m_inputSamples.empty() &&
1657 (*it)->m_resampleBuffers->m_outputSamples.empty() &&
1658 (*it)->m_processingSamples.empty())
1660 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
1661 (*it)->m_drain = false;
1662 (*it)->m_resampleBuffers->m_drain = false;
1663 (*it)->m_started = false;
1665 // set variables being polled via stream interface
1666 CSingleLock lock((*it)->m_streamLock);
1667 if ((*it)->m_streamSlave)
1669 CActiveAEStream *slave = (CActiveAEStream*)((*it)->m_streamSlave);
1670 slave->m_paused = false;
1672 // TODO: find better solution for this
1673 // gapless bites audiophile
1674 if (m_settings.config == AE_CONFIG_MATCH)
1675 Configure(&slave->m_format);
1677 (*it)->m_streamSlave = NULL;
1679 (*it)->m_streamDrained = true;
1680 (*it)->m_streamDraining = false;
1681 (*it)->m_streamFading = false;
1686 if (m_stats.GetWaterLevel() < MAX_WATER_LEVEL &&
1687 (m_mode != MODE_TRANSCODE || (m_encoderBuffers && !m_encoderBuffers->m_freeSamples.empty())))
1689 // mix streams and sounds sounds
1690 if (m_mode != MODE_RAW)
1692 CSampleBuffer *out = NULL;
1693 if (!m_sounds_playing.empty() && m_streams.empty())
1695 if (m_silenceBuffers && !m_silenceBuffers->m_freeSamples.empty())
1697 out = m_silenceBuffers->GetFreeBuffer();
1698 for (int i=0; i<out->pkt->planes; i++)
1700 memset(out->pkt->data[i], 0, out->pkt->linesize);
1702 out->pkt->nb_samples = out->pkt->max_nb_samples;
1707 std::list<CActiveAEStream*>::iterator it;
1709 // if we deal with more than a single stream, all streams
1710 // must provide samples for mixing
1711 bool allStreamsReady = true;
1712 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1714 if ((*it)->m_paused || !(*it)->m_started || !(*it)->m_resampleBuffers)
1717 if ((*it)->m_resampleBuffers->m_outputSamples.empty())
1718 allStreamsReady = false;
1721 bool needClamp = false;
1722 for (it = m_streams.begin(); it != m_streams.end() && allStreamsReady; ++it)
1724 if ((*it)->m_paused || !(*it)->m_resampleBuffers)
1727 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1729 (*it)->m_started = true;
1733 out = (*it)->m_resampleBuffers->m_outputSamples.front();
1734 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1736 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1738 float fadingStep = 0.0f;
1741 if ((*it)->m_fadingSamples == -1)
1743 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1744 (*it)->m_volume = (*it)->m_fadingBase;
1746 if ((*it)->m_fadingSamples > 0)
1748 nb_floats = out->pkt->config.channels / out->pkt->planes;
1749 nb_loops = out->pkt->nb_samples;
1750 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1751 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1752 fadingStep = delta / samples;
1755 // for stream amplification,
1756 // turned off downmix normalization,
1757 // or if sink format is float (in order to prevent from clipping)
1758 // we need to run on a per sample basis
1759 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize || (m_sinkFormat.m_dataFormat == AE_FMT_FLOAT))
1761 nb_floats = out->pkt->config.channels / out->pkt->planes;
1762 nb_loops = out->pkt->nb_samples;
1765 for(int i=0; i<nb_loops; i++)
1767 if ((*it)->m_fadingSamples > 0)
1769 (*it)->m_volume += fadingStep;
1770 (*it)->m_fadingSamples--;
1772 if ((*it)->m_fadingSamples == 0)
1774 // set variables being polled via stream interface
1775 CSingleLock lock((*it)->m_streamLock);
1776 (*it)->m_streamFading = false;
1780 // volume for stream
1781 float volume = (*it)->m_volume * (*it)->m_rgain;
1783 volume *= (*it)->m_limiter.Run((float**)out->pkt->data, out->pkt->config.channels, i*nb_floats, out->pkt->planes > 1);
1785 for(int j=0; j<out->pkt->planes; j++)
1788 CAEUtil::SSEMulArray((float*)out->pkt->data[j]+i*nb_floats, volume, nb_floats);
1790 float* fbuffer = (float*) out->pkt->data[j]+i*nb_floats;
1791 for (int k = 0; k < nb_floats; ++k)
1793 fbuffer[k] *= volume;
1801 CSampleBuffer *mix = NULL;
1802 mix = (*it)->m_resampleBuffers->m_outputSamples.front();
1803 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1805 int nb_floats = mix->pkt->nb_samples * mix->pkt->config.channels / mix->pkt->planes;
1807 float fadingStep = 0.0f;
1810 if ((*it)->m_fadingSamples == -1)
1812 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1813 (*it)->m_volume = (*it)->m_fadingBase;
1815 if ((*it)->m_fadingSamples > 0)
1817 nb_floats = mix->pkt->config.channels / mix->pkt->planes;
1818 nb_loops = mix->pkt->nb_samples;
1819 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1820 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1821 fadingStep = delta / samples;
1824 // for streams amplification of turned off downmix normalization
1825 // we need to run on a per sample basis
1826 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize)
1828 nb_floats = out->pkt->config.channels / out->pkt->planes;
1829 nb_loops = out->pkt->nb_samples;
1832 for(int i=0; i<nb_loops; i++)
1834 if ((*it)->m_fadingSamples > 0)
1836 (*it)->m_volume += fadingStep;
1837 (*it)->m_fadingSamples--;
1839 if ((*it)->m_fadingSamples == 0)
1841 // set variables being polled via stream interface
1842 CSingleLock lock((*it)->m_streamLock);
1843 (*it)->m_streamFading = false;
1847 // volume for stream
1848 float volume = (*it)->m_volume * (*it)->m_rgain;
1850 volume *= (*it)->m_limiter.Run((float**)mix->pkt->data, mix->pkt->config.channels, i*nb_floats, mix->pkt->planes > 1);
1852 for(int j=0; j<out->pkt->planes && j<mix->pkt->planes; j++)
1854 float *dst = (float*)out->pkt->data[j]+i*nb_floats;
1855 float *src = (float*)mix->pkt->data[j]+i*nb_floats;
1857 CAEUtil::SSEMulAddArray(dst, src, volume, nb_floats);
1858 for (int k = 0; k < nb_floats; ++k)
1860 if (fabs(dst[k]) > 1.0f)
1867 for (int k = 0; k < nb_floats; ++k)
1869 dst[k] += src[k] * volume;
1870 if (fabs(dst[k]) > 1.0f)
1882 // finally clamp samples
1883 if(out && needClamp)
1885 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1886 for(int i=0; i<out->pkt->planes; i++)
1888 CAEUtil::ClampArray((float*)out->pkt->data[i], nb_floats);
1892 // process output buffer, gui sounds, encode, viz
1897 CSingleLock lock(m_vizLock);
1898 if (m_audioCallback && m_vizBuffers && !m_streams.empty())
1900 if (!m_vizInitialized)
1902 m_audioCallback->OnInitialize(2, m_vizBuffers->m_format.m_sampleRate, 32);
1903 m_vizInitialized = true;
1906 if (!m_vizBuffersInput->m_freeSamples.empty())
1908 // copy the samples into the viz input buffer
1909 CSampleBuffer *viz = m_vizBuffersInput->GetFreeBuffer();
1910 int samples = std::min(512, out->pkt->nb_samples);
1911 int bytes = samples * out->pkt->config.channels / out->pkt->planes * out->pkt->bytes_per_sample;
1912 for(int i= 0; i < out->pkt->planes; i++)
1914 memcpy(viz->pkt->data[i], out->pkt->data[i], bytes);
1916 viz->pkt->nb_samples = samples;
1917 m_vizBuffers->m_inputSamples.push_back(viz);
1920 CLog::Log(LOGWARNING,"ActiveAE::%s - viz ran out of free buffers", __FUNCTION__);
1921 unsigned int now = XbmcThreads::SystemClockMillis();
1922 unsigned int timestamp = now + m_stats.GetDelay() * 1000;
1923 busy |= m_vizBuffers->ResampleBuffers(timestamp);
1924 while(!m_vizBuffers->m_outputSamples.empty())
1926 CSampleBuffer *buf = m_vizBuffers->m_outputSamples.front();
1927 if ((now - buf->timestamp) & 0x80000000)
1932 samples = std::min(512, buf->pkt->nb_samples);
1933 m_audioCallback->OnAudioData((float*)(buf->pkt->data[0]), samples);
1935 m_vizBuffers->m_outputSamples.pop_front();
1939 else if (m_vizBuffers)
1940 m_vizBuffers->Flush();
1944 MixSounds(*(out->pkt));
1945 if (!m_sinkHasVolume || m_muted)
1946 Deamplify(*(out->pkt));
1948 if (m_mode == MODE_TRANSCODE && m_encoder)
1950 CSampleBuffer *buf = m_encoderBuffers->GetFreeBuffer();
1951 m_encoder->Encode(out->pkt->data[0], out->pkt->planes*out->pkt->linesize,
1952 buf->pkt->data[0], buf->pkt->planes*buf->pkt->linesize);
1953 buf->pkt->nb_samples = buf->pkt->max_nb_samples;
1963 m_stats.AddSamples(out->pkt->nb_samples, m_streams);
1964 m_sinkBuffers->m_inputSamples.push_back(out);
1970 std::list<CActiveAEStream*>::iterator it;
1971 CSampleBuffer *buffer;
1972 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1974 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1976 buffer = (*it)->m_resampleBuffers->m_outputSamples.front();
1977 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1978 m_stats.AddSamples(buffer->pkt->nb_samples, m_streams);
1979 m_sinkBuffers->m_inputSamples.push_back(buffer);
1984 // serve sink buffers
1985 busy = m_sinkBuffers->ResampleBuffers();
1986 while(!m_sinkBuffers->m_outputSamples.empty())
1988 CSampleBuffer *out = NULL;
1989 out = m_sinkBuffers->m_outputSamples.front();
1990 m_sinkBuffers->m_outputSamples.pop_front();
1991 m_sink.m_dataPort.SendOutMessage(CSinkDataProtocol::SAMPLE,
1992 &out, sizeof(CSampleBuffer*));
2000 bool CActiveAE::HasWork()
2002 if (!m_sounds_playing.empty())
2004 if (!m_sinkBuffers->m_inputSamples.empty())
2006 if (!m_sinkBuffers->m_outputSamples.empty())
2009 std::list<CActiveAEStream*>::iterator it;
2010 for (it = m_streams.begin(); it != m_streams.end(); ++it)
2012 if (!(*it)->m_resampleBuffers->m_inputSamples.empty())
2014 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
2016 if (!(*it)->m_processingSamples.empty())
2023 void CActiveAE::MixSounds(CSoundPacket &dstSample)
2025 if (m_sounds_playing.empty())
2030 float *sample_buffer;
2031 int max_samples = dstSample.nb_samples;
2033 std::list<SoundState>::iterator it;
2034 for (it = m_sounds_playing.begin(); it != m_sounds_playing.end(); )
2036 if (!it->sound->IsConverted())
2037 ResampleSound(it->sound);
2038 int available_samples = it->sound->GetSound(false)->nb_samples - it->samples_played;
2039 int mix_samples = std::min(max_samples, available_samples);
2040 int start = it->samples_played *
2041 m_dllAvUtil.av_get_bytes_per_sample(it->sound->GetSound(false)->config.fmt) *
2042 it->sound->GetSound(false)->config.channels /
2043 it->sound->GetSound(false)->planes;
2045 for(int j=0; j<dstSample.planes; j++)
2047 volume = it->sound->GetVolume();
2048 out = (float*)dstSample.data[j];
2049 sample_buffer = (float*)(it->sound->GetSound(false)->data[j]+start);
2050 int nb_floats = mix_samples * dstSample.config.channels / dstSample.planes;
2052 CAEUtil::SSEMulAddArray(out, sample_buffer, volume, nb_floats);
2054 for (int k = 0; k < nb_floats; ++k)
2055 *out++ += *sample_buffer++ * volume;
2059 it->samples_played += mix_samples;
2061 // no more frames, so remove it from the list
2062 if (it->samples_played >= it->sound->GetSound(false)->nb_samples)
2064 it = m_sounds_playing.erase(it);
2071 void CActiveAE::Deamplify(CSoundPacket &dstSample)
2073 if (m_volumeScaled < 1.0 || m_muted)
2076 int nb_floats = dstSample.nb_samples * dstSample.config.channels / dstSample.planes;
2077 float volume = m_muted ? 0.0f : m_volumeScaled;
2079 for(int j=0; j<dstSample.planes; j++)
2081 buffer = (float*)dstSample.data[j];
2083 CAEUtil::SSEMulArray(buffer, volume, nb_floats);
2085 float *fbuffer = buffer;
2086 for (int i = 0; i < nb_floats; i++)
2087 *fbuffer++ *= volume;
2093 //-----------------------------------------------------------------------------
2095 //-----------------------------------------------------------------------------
2097 void CActiveAE::LoadSettings()
2099 m_settings.device = CSettings::Get().GetString("audiooutput.audiodevice");
2100 m_settings.passthoughdevice = CSettings::Get().GetString("audiooutput.passthroughdevice");
2102 m_settings.config = CSettings::Get().GetInt("audiooutput.config");
2103 m_settings.channels = (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958) ? AE_CH_LAYOUT_2_0 : CSettings::Get().GetInt("audiooutput.channels");
2104 m_settings.samplerate = CSettings::Get().GetInt("audiooutput.samplerate");
2106 m_settings.stereoupmix = IsSettingVisible("audiooutput.stereoupmix") ? CSettings::Get().GetBool("audiooutput.stereoupmix") : false;
2107 m_settings.normalizelevels = CSettings::Get().GetBool("audiooutput.normalizelevels");
2108 m_settings.guisoundmode = CSettings::Get().GetInt("audiooutput.guisoundmode");
2110 m_settings.passthrough = m_settings.config == AE_CONFIG_FIXED ? false : CSettings::Get().GetBool("audiooutput.passthrough");
2111 if (!m_sink.HasPassthroughDevice())
2112 m_settings.passthrough = false;
2113 m_settings.ac3passthrough = CSettings::Get().GetBool("audiooutput.ac3passthrough");
2114 m_settings.ac3transcode = CSettings::Get().GetBool("audiooutput.ac3transcode");
2115 m_settings.eac3passthrough = CSettings::Get().GetBool("audiooutput.eac3passthrough");
2116 m_settings.truehdpassthrough = CSettings::Get().GetBool("audiooutput.truehdpassthrough");
2117 m_settings.dtspassthrough = CSettings::Get().GetBool("audiooutput.dtspassthrough");
2118 m_settings.dtshdpassthrough = CSettings::Get().GetBool("audiooutput.dtshdpassthrough");
2120 m_settings.resampleQuality = static_cast<AEQuality>(CSettings::Get().GetInt("audiooutput.processquality"));
2123 bool CActiveAE::Initialize()
2125 if (!m_dllAvUtil.Load() || !m_dllAvCodec.Load() || !m_dllAvFormat.Load())
2127 CLog::Log(LOGERROR,"CActiveAE::Initialize - failed to load ffmpeg libraries");
2130 m_dllAvFormat.av_register_all();
2134 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2138 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2142 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2149 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2154 // hook into windowing for receiving display reset events
2155 #if defined(HAS_GLX) || defined(TARGET_DARWIN)
2156 g_Windowing.Register(this);
2159 m_inMsgEvent.Reset();
2163 void CActiveAE::EnumerateOutputDevices(AEDeviceList &devices, bool passthrough)
2165 m_sink.EnumerateOutputDevices(devices, passthrough);
2168 std::string CActiveAE::GetDefaultDevice(bool passthrough)
2170 return m_sink.GetDefaultDevice(passthrough);
2173 void CActiveAE::OnSettingsChange(const std::string& setting)
2175 if (setting == "audiooutput.passthroughdevice" ||
2176 setting == "audiooutput.audiodevice" ||
2177 setting == "audiooutput.config" ||
2178 setting == "audiooutput.ac3passthrough" ||
2179 setting == "audiooutput.ac3transcode" ||
2180 setting == "audiooutput.eac3passthrough" ||
2181 setting == "audiooutput.dtspassthrough" ||
2182 setting == "audiooutput.truehdpassthrough" ||
2183 setting == "audiooutput.dtshdpassthrough" ||
2184 setting == "audiooutput.channels" ||
2185 setting == "audiooutput.stereoupmix" ||
2186 setting == "audiooutput.streamsilence" ||
2187 setting == "audiooutput.processquality" ||
2188 setting == "audiooutput.passthrough" ||
2189 setting == "audiooutput.samplerate" ||
2190 setting == "audiooutput.normalizelevels" ||
2191 setting == "audiooutput.guisoundmode")
2193 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RECONFIGURE);
2197 bool CActiveAE::SupportsRaw(AEDataFormat format, int samplerate)
2199 if (!m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), format, samplerate))
2205 bool CActiveAE::SupportsSilenceTimeout()
2210 bool CActiveAE::SupportsQualityLevel(enum AEQuality level)
2212 if (level == AE_QUALITY_LOW || level == AE_QUALITY_MID || level == AE_QUALITY_HIGH)
2218 bool CActiveAE::IsSettingVisible(const std::string &settingId)
2220 if (settingId == "audiooutput.samplerate")
2222 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958)
2224 if (CSettings::Get().GetInt("audiooutput.config") == AE_CONFIG_FIXED)
2227 else if (settingId == "audiooutput.channels")
2229 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) != AE_DEVTYPE_IEC958)
2232 else if (settingId == "audiooutput.passthrough")
2234 if (m_sink.HasPassthroughDevice() && CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2237 else if (settingId == "audiooutput.truehdpassthrough")
2239 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_TRUEHD, 192000) &&
2240 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2243 else if (settingId == "audiooutput.dtshdpassthrough")
2245 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_DTSHD, 192000) &&
2246 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2249 else if (settingId == "audiooutput.eac3passthrough")
2251 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_EAC3, 192000) &&
2252 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2255 else if (settingId == "audiooutput.stereoupmix")
2257 if (m_sink.HasPassthroughDevice() ||
2258 CSettings::Get().GetInt("audiooutput.channels") > AE_CH_LAYOUT_2_0)
2261 else if (settingId == "audiooutput.ac3transcode")
2263 if (m_sink.HasPassthroughDevice() &&
2264 CSettings::Get().GetBool("audiooutput.ac3passthrough") &&
2265 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2266 (CSettings::Get().GetInt("audiooutput.channels") <= AE_CH_LAYOUT_2_0 || m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958))
2272 void CActiveAE::Shutdown()
2277 bool CActiveAE::Suspend()
2279 return m_controlPort.SendOutMessage(CActiveAEControlProtocol::SUSPEND);
2282 bool CActiveAE::Resume()
2285 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2289 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2293 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2299 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2303 m_inMsgEvent.Reset();
2307 bool CActiveAE::IsSuspended()
2309 return m_stats.IsSuspended();
2312 float CActiveAE::GetVolume()
2317 void CActiveAE::SetVolume(const float volume)
2319 m_aeVolume = std::max( 0.0f, std::min(1.0f, volume));
2320 m_controlPort.SendOutMessage(CActiveAEControlProtocol::VOLUME, &m_aeVolume, sizeof(float));
2323 void CActiveAE::SetMute(const bool enabled)
2325 m_aeMuted = enabled;
2326 m_controlPort.SendOutMessage(CActiveAEControlProtocol::MUTE, &m_aeMuted, sizeof(bool));
2329 bool CActiveAE::IsMuted()
2334 void CActiveAE::SetSoundMode(const int mode)
2339 void CActiveAE::KeepConfiguration(unsigned int millis)
2341 unsigned int timeMs = millis;
2342 m_controlPort.SendOutMessage(CActiveAEControlProtocol::KEEPCONFIG, &timeMs, sizeof(unsigned int));
2345 void CActiveAE::DeviceChange()
2347 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DEVICECHANGE);
2350 void CActiveAE::OnLostDevice()
2353 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::DISPLAYLOST,
2357 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2361 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2366 CLog::Log(LOGERROR, "ActiveAE::%s - timed out", __FUNCTION__);
2370 void CActiveAE::OnResetDevice()
2372 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DISPLAYRESET);
2375 void CActiveAE::OnAppFocusChange(bool focus)
2377 m_controlPort.SendOutMessage(CActiveAEControlProtocol::APPFOCUSED, &focus, sizeof(focus));
2380 //-----------------------------------------------------------------------------
2382 //-----------------------------------------------------------------------------
2384 uint8_t **CActiveAE::AllocSoundSample(SampleConfig &config, int &samples, int &bytes_per_sample, int &planes, int &linesize)
2387 planes = m_dllAvUtil.av_sample_fmt_is_planar(config.fmt) ? config.channels : 1;
2388 buffer = new uint8_t*[planes];
2390 // align buffer to 16 in order to be compatible with sse in CAEConvert
2391 m_dllAvUtil.av_samples_alloc(buffer, &linesize, config.channels,
2392 samples, config.fmt, 16);
2393 bytes_per_sample = m_dllAvUtil.av_get_bytes_per_sample(config.fmt);
2397 void CActiveAE::FreeSoundSample(uint8_t **data)
2399 m_dllAvUtil.av_freep(data);
2403 bool CActiveAE::CompareFormat(AEAudioFormat &lhs, AEAudioFormat &rhs)
2405 if (lhs.m_channelLayout != rhs.m_channelLayout ||
2406 lhs.m_dataFormat != rhs.m_dataFormat ||
2407 lhs.m_sampleRate != rhs.m_sampleRate)
2413 //-----------------------------------------------------------------------------
2415 //-----------------------------------------------------------------------------
2418 * load sound from an audio file and store original format
2419 * register the sound in ActiveAE
2420 * later when the engine is idle it will convert the sound to sink format
2423 #define SOUNDBUFFER_SIZE 20480
2425 IAESound *CActiveAE::MakeSound(const std::string& file)
2427 AVFormatContext *fmt_ctx = NULL;
2428 AVCodecContext *dec_ctx = NULL;
2429 AVIOContext *io_ctx;
2430 AVInputFormat *io_fmt;
2431 AVCodec *dec = NULL;
2432 CActiveAESound *sound = NULL;
2433 SampleConfig config;
2435 sound = new CActiveAESound(file);
2436 if (!sound->Prepare())
2441 int fileSize = sound->GetFileSize();
2443 fmt_ctx = m_dllAvFormat.avformat_alloc_context();
2444 unsigned char* buffer = (unsigned char*)m_dllAvUtil.av_malloc(SOUNDBUFFER_SIZE+FF_INPUT_BUFFER_PADDING_SIZE);
2445 io_ctx = m_dllAvFormat.avio_alloc_context(buffer, SOUNDBUFFER_SIZE, 0,
2446 sound, CActiveAESound::Read, NULL, CActiveAESound::Seek);
2447 io_ctx->max_packet_size = sound->GetChunkSize();
2448 if(io_ctx->max_packet_size)
2449 io_ctx->max_packet_size *= SOUNDBUFFER_SIZE / io_ctx->max_packet_size;
2451 if(!sound->IsSeekPosible())
2452 io_ctx->seekable = 0;
2454 fmt_ctx->pb = io_ctx;
2456 m_dllAvFormat.av_probe_input_buffer(io_ctx, &io_fmt, file.c_str(), NULL, 0, 0);
2459 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2465 if (m_dllAvFormat.avformat_open_input(&fmt_ctx, file.c_str(), NULL, NULL) == 0)
2467 fmt_ctx->flags |= AVFMT_FLAG_NOPARSE;
2468 if (m_dllAvFormat.avformat_find_stream_info(fmt_ctx, NULL) >= 0)
2470 dec_ctx = fmt_ctx->streams[0]->codec;
2471 dec = m_dllAvCodec.avcodec_find_decoder(dec_ctx->codec_id);
2472 config.sample_rate = dec_ctx->sample_rate;
2473 config.channels = dec_ctx->channels;
2474 config.channel_layout = dec_ctx->channel_layout;
2479 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2484 dec_ctx = m_dllAvCodec.avcodec_alloc_context3(dec);
2485 dec_ctx->sample_rate = config.sample_rate;
2486 dec_ctx->channels = config.channels;
2487 if (!config.channel_layout)
2488 config.channel_layout = m_dllAvUtil.av_get_default_channel_layout(config.channels);
2489 dec_ctx->channel_layout = config.channel_layout;
2492 AVFrame *decoded_frame = NULL;
2493 decoded_frame = m_dllAvCodec.avcodec_alloc_frame();
2495 if (m_dllAvCodec.avcodec_open2(dec_ctx, dec, NULL) >= 0)
2500 m_dllAvCodec.av_init_packet(&avpkt);
2502 while (m_dllAvFormat.av_read_frame(fmt_ctx, &avpkt) >= 0)
2505 len = m_dllAvCodec.avcodec_decode_audio4(dec_ctx, decoded_frame, &got_frame, &avpkt);
2508 m_dllAvCodec.avcodec_close(dec_ctx);
2509 m_dllAvUtil.av_free(dec_ctx);
2510 m_dllAvUtil.av_free(&decoded_frame);
2511 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2519 int samples = fileSize / m_dllAvUtil.av_get_bytes_per_sample(dec_ctx->sample_fmt) / config.channels;
2520 config.fmt = dec_ctx->sample_fmt;
2521 config.bits_per_sample = dec_ctx->bits_per_coded_sample;
2522 sound->InitSound(true, config, samples);
2525 sound->StoreSound(true, decoded_frame->extended_data,
2526 decoded_frame->nb_samples, decoded_frame->linesize[0]);
2529 m_dllAvCodec.avcodec_close(dec_ctx);
2532 m_dllAvUtil.av_free(dec_ctx);
2533 m_dllAvUtil.av_free(decoded_frame);
2534 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2539 m_dataPort.SendOutMessage(CActiveAEDataProtocol::NEWSOUND, &sound, sizeof(CActiveAESound*));
2544 void CActiveAE::FreeSound(IAESound *sound)
2546 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESOUND, &sound, sizeof(CActiveAESound*));
2549 void CActiveAE::PlaySound(CActiveAESound *sound)
2551 m_dataPort.SendOutMessage(CActiveAEDataProtocol::PLAYSOUND, &sound, sizeof(CActiveAESound*));
2554 void CActiveAE::StopSound(CActiveAESound *sound)
2556 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STOPSOUND, &sound, sizeof(CActiveAESound*));
2560 * resample sounds to destination format for mixing
2561 * destination format is either format of stream or
2562 * default sink format when no stream is playing
2564 void CActiveAE::ResampleSounds()
2566 if (m_settings.guisoundmode == AE_SOUND_OFF ||
2567 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
2570 std::vector<CActiveAESound*>::iterator it;
2571 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
2573 if (!(*it)->IsConverted())
2576 // only do one sound, then yield to main loop
2582 bool CActiveAE::ResampleSound(CActiveAESound *sound)
2584 SampleConfig orig_config, dst_config;
2585 uint8_t **dst_buffer;
2588 if (m_mode == MODE_RAW || m_internalFormat.m_dataFormat == AE_FMT_INVALID)
2591 if (!sound->GetSound(true))
2594 orig_config = sound->GetSound(true)->config;
2596 dst_config.channel_layout = CActiveAEResample::GetAVChannelLayout(m_internalFormat.m_channelLayout);
2597 dst_config.channels = m_internalFormat.m_channelLayout.Count();
2598 dst_config.sample_rate = m_internalFormat.m_sampleRate;
2599 dst_config.fmt = CActiveAEResample::GetAVSampleFormat(m_internalFormat.m_dataFormat);
2600 dst_config.bits_per_sample = CAEUtil::DataFormatToUsedBits(m_internalFormat.m_dataFormat);
2602 CActiveAEResample *resampler = new CActiveAEResample();
2603 resampler->Init(dst_config.channel_layout,
2604 dst_config.channels,
2605 dst_config.sample_rate,
2607 dst_config.bits_per_sample,
2608 orig_config.channel_layout,
2609 orig_config.channels,
2610 orig_config.sample_rate,
2612 orig_config.bits_per_sample,
2616 m_settings.resampleQuality);
2618 dst_samples = resampler->CalcDstSampleCount(sound->GetSound(true)->nb_samples,
2619 m_internalFormat.m_sampleRate,
2620 orig_config.sample_rate);
2622 dst_buffer = sound->InitSound(false, dst_config, dst_samples);
2628 int samples = resampler->Resample(dst_buffer, dst_samples,
2629 sound->GetSound(true)->data,
2630 sound->GetSound(true)->nb_samples,
2633 sound->GetSound(false)->nb_samples = samples;
2636 sound->SetConverted(true);
2640 //-----------------------------------------------------------------------------
2642 //-----------------------------------------------------------------------------
2644 IAEStream *CActiveAE::MakeStream(enum AEDataFormat dataFormat, unsigned int sampleRate, unsigned int encodedSampleRate, CAEChannelInfo channelLayout, unsigned int options)
2649 //TODO: pass number of samples in audio packet
2651 AEAudioFormat format;
2652 format.m_dataFormat = dataFormat;
2653 format.m_sampleRate = sampleRate;
2654 format.m_encodedRate = encodedSampleRate;
2655 format.m_channelLayout = channelLayout;
2656 format.m_frames = format.m_sampleRate / 10;
2657 format.m_frameSize = format.m_channelLayout.Count() *
2658 (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
2661 msg.format = format;
2662 msg.options = options;
2665 if (m_dataPort.SendOutMessageSync(CActiveAEDataProtocol::NEWSTREAM,
2667 &msg, sizeof(MsgStreamNew)))
2669 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2672 CActiveAEStream *stream = *(CActiveAEStream**)reply->data;
2679 CLog::Log(LOGERROR, "ActiveAE::%s - could not create stream", __FUNCTION__);
2683 IAEStream *CActiveAE::FreeStream(IAEStream *stream)
2685 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESTREAM, &stream, sizeof(IAEStream*));
2689 void CActiveAE::FlushStream(CActiveAEStream *stream)
2692 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::FLUSHSTREAM,
2694 &stream, sizeof(CActiveAEStream*)))
2696 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2700 CLog::Log(LOGERROR, "CActiveAE::FlushStream - failed");
2705 void CActiveAE::PauseStream(CActiveAEStream *stream, bool pause)
2707 // TODO pause sink, needs api change
2709 m_controlPort.SendOutMessage(CActiveAEControlProtocol::PAUSESTREAM,
2710 &stream, sizeof(CActiveAEStream*));
2712 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RESUMESTREAM,
2713 &stream, sizeof(CActiveAEStream*));
2716 void CActiveAE::SetStreamAmplification(CActiveAEStream *stream, float amplify)
2718 MsgStreamParameter msg;
2719 msg.stream = stream;
2720 msg.parameter.float_par = amplify;
2721 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMAMP,
2722 &msg, sizeof(MsgStreamParameter));
2725 void CActiveAE::SetStreamReplaygain(CActiveAEStream *stream, float rgain)
2727 MsgStreamParameter msg;
2728 msg.stream = stream;
2729 msg.parameter.float_par = rgain;
2730 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRGAIN,
2731 &msg, sizeof(MsgStreamParameter));
2734 void CActiveAE::SetStreamVolume(CActiveAEStream *stream, float volume)
2736 MsgStreamParameter msg;
2737 msg.stream = stream;
2738 msg.parameter.float_par = volume;
2739 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMVOLUME,
2740 &msg, sizeof(MsgStreamParameter));
2743 void CActiveAE::SetStreamResampleRatio(CActiveAEStream *stream, double ratio)
2745 MsgStreamParameter msg;
2746 msg.stream = stream;
2747 msg.parameter.double_par = ratio;
2748 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRESAMPLERATIO,
2749 &msg, sizeof(MsgStreamParameter));
2752 void CActiveAE::SetStreamFade(CActiveAEStream *stream, float from, float target, unsigned int millis)
2755 msg.stream = stream;
2757 msg.target = target;
2758 msg.millis = millis;
2759 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMFADE,
2760 &msg, sizeof(MsgStreamFade));
2763 void CActiveAE::RegisterAudioCallback(IAudioCallback* pCallback)
2765 CSingleLock lock(m_vizLock);
2766 m_audioCallback = pCallback;
2767 m_vizInitialized = false;
2770 void CActiveAE::UnregisterAudioCallback()
2772 CSingleLock lock(m_vizLock);
2773 m_audioCallback = NULL;