2 * Copyright (C) 2010-2013 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
23 using namespace ActiveAE;
24 #include "ActiveAESound.h"
25 #include "ActiveAEStream.h"
26 #include "cores/AudioEngine/Utils/AEUtil.h"
27 #include "cores/AudioEngine/Encoders/AEEncoderFFmpeg.h"
29 #include "settings/Settings.h"
30 #include "settings/AdvancedSettings.h"
31 #include "windowing/WindowingFactory.h"
33 #define MAX_CACHE_LEVEL 0.5 // total cache time of stream in seconds
34 #define MAX_WATER_LEVEL 0.25 // buffered time after stream stages in seconds
36 void CEngineStats::Reset(unsigned int sampleRate)
38 CSingleLock lock(m_lock);
39 m_sinkUpdate = XbmcThreads::SystemClockMillis();
41 m_sinkSampleRate = sampleRate;
42 m_bufferedSamples = 0;
46 void CEngineStats::UpdateSinkDelay(double delay, int samples)
48 CSingleLock lock(m_lock);
49 m_sinkUpdate = XbmcThreads::SystemClockMillis();
51 if (samples > m_bufferedSamples)
53 CLog::Log(LOGERROR, "CEngineStats::UpdateSinkDelay - inconsistency in buffer time");
56 m_bufferedSamples -= samples;
59 void CEngineStats::AddSamples(int samples, std::list<CActiveAEStream*> &streams)
61 CSingleLock lock(m_lock);
62 m_bufferedSamples += samples;
64 //update buffered time of streams
65 std::list<CActiveAEStream*>::iterator it;
66 for(it=streams.begin(); it!=streams.end(); ++it)
69 std::deque<CSampleBuffer*>::iterator itBuf;
70 for(itBuf=(*it)->m_processingSamples.begin(); itBuf!=(*it)->m_processingSamples.end(); ++itBuf)
72 delay += (float)(*itBuf)->pkt->nb_samples / (*itBuf)->pkt->config.sample_rate;
74 delay += (*it)->m_resampleBuffers->GetDelay();
75 (*it)->m_bufferedTime = delay;
79 float CEngineStats::GetDelay()
81 CSingleLock lock(m_lock);
82 unsigned int now = XbmcThreads::SystemClockMillis();
83 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
84 delay += (float)m_bufferedSamples / m_sinkSampleRate;
92 // this is used to sync a/v so we need to add sink latency here
93 float CEngineStats::GetDelay(CActiveAEStream *stream)
95 CSingleLock lock(m_lock);
96 unsigned int now = XbmcThreads::SystemClockMillis();
97 float delay = m_sinkDelay - (double)(now-m_sinkUpdate) / 1000;
98 delay += m_sinkLatency;
99 delay += (float)m_bufferedSamples / m_sinkSampleRate;
104 delay += stream->m_bufferedTime;
108 float CEngineStats::GetCacheTime(CActiveAEStream *stream)
110 CSingleLock lock(m_lock);
111 float delay = (float)m_bufferedSamples / m_sinkSampleRate;
113 delay += stream->m_bufferedTime;
117 float CEngineStats::GetCacheTotal(CActiveAEStream *stream)
119 return MAX_CACHE_LEVEL + m_sinkCacheTotal;
122 float CEngineStats::GetWaterLevel()
124 return (float)m_bufferedSamples / m_sinkSampleRate;
127 void CEngineStats::SetSuspended(bool state)
129 CSingleLock lock(m_lock);
133 bool CEngineStats::IsSuspended()
135 CSingleLock lock(m_lock);
139 CActiveAE::CActiveAE() :
141 m_controlPort("OutputControlPort", &m_inMsgEvent, &m_outMsgEvent),
142 m_dataPort("OutputDataPort", &m_inMsgEvent, &m_outMsgEvent),
143 m_sink(&m_outMsgEvent)
145 m_sinkBuffers = NULL;
146 m_silenceBuffers = NULL;
147 m_encoderBuffers = NULL;
149 m_vizBuffersInput = NULL;
156 m_audioCallback = NULL;
157 m_vizInitialized = false;
158 m_sinkHasVolume = false;
161 CActiveAE::~CActiveAE()
166 void CActiveAE::Dispose()
168 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
169 g_Windowing.Unregister(this);
175 m_controlPort.Purge();
179 m_dllAvFormat.Unload();
180 m_dllAvCodec.Unload();
181 m_dllAvUtil.Unload();
184 //-----------------------------------------------------------------------------
186 //-----------------------------------------------------------------------------
192 AE_TOP_UNCONFIGURED, // 2
193 AE_TOP_RECONFIGURING, // 3
194 AE_TOP_CONFIGURED, // 4
195 AE_TOP_CONFIGURED_SUSPEND, // 5
196 AE_TOP_CONFIGURED_IDLE, // 6
197 AE_TOP_CONFIGURED_PLAY, // 7
200 int AE_parentStates[] = {
203 0, //TOP_UNCONFIGURED
205 0, //TOP_RECONFIGURING
206 4, //TOP_CONFIGURED_SUSPEND
207 4, //TOP_CONFIGURED_IDLE
208 4, //TOP_CONFIGURED_PLAY
211 void CActiveAE::StateMachine(int signal, Protocol *port, Message *msg)
213 for (int state = m_state; ; state = AE_parentStates[state])
218 if (port == &m_controlPort)
222 case CActiveAEControlProtocol::GETSTATE:
223 msg->Reply(CActiveAEControlProtocol::ACC, &m_state, sizeof(m_state));
225 case CActiveAEControlProtocol::VOLUME:
226 m_volume = *(float*)msg->data;
228 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
230 case CActiveAEControlProtocol::MUTE:
231 m_muted = *(bool*)msg->data;
233 case CActiveAEControlProtocol::KEEPCONFIG:
234 m_extKeepConfig = *(unsigned int*)msg->data;
236 case CActiveAEControlProtocol::DISPLAYRESET:
242 else if (port == &m_dataPort)
246 case CActiveAEDataProtocol::NEWSOUND:
247 CActiveAESound *sound;
248 sound = *(CActiveAESound**)msg->data;
251 m_sounds.push_back(sound);
255 case CActiveAEDataProtocol::FREESTREAM:
256 CActiveAEStream *stream;
257 stream = *(CActiveAEStream**)msg->data;
258 DiscardStream(stream);
260 case CActiveAEDataProtocol::FREESOUND:
261 sound = *(CActiveAESound**)msg->data;
264 case CActiveAEDataProtocol::DRAINSTREAM:
265 stream = *(CActiveAEStream**)msg->data;
266 stream->m_drain = true;
267 stream->m_resampleBuffers->m_drain = true;
268 msg->Reply(CActiveAEDataProtocol::ACC);
269 stream->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
275 else if (port == &m_sink.m_dataPort)
279 case CSinkDataProtocol::RETURNSAMPLE:
280 CSampleBuffer **buffer;
281 buffer = (CSampleBuffer**)msg->data;
292 std::string portName = port == NULL ? "timer" : port->portName;
293 CLog::Log(LOGWARNING, "CActiveAE::%s - signal: %d from port: %s not handled for state: %d", __FUNCTION__, signal, portName.c_str(), m_state);
298 if (port == NULL) // timeout
302 case CActiveAEControlProtocol::TIMEOUT:
308 m_state = AE_TOP_CONFIGURED_IDLE;
313 m_state = AE_TOP_ERROR;
323 case AE_TOP_UNCONFIGURED:
324 if (port == &m_controlPort)
328 case CActiveAEControlProtocol::INIT:
330 m_sink.EnumerateSinkList(false);
333 msg->Reply(CActiveAEControlProtocol::ACC);
336 m_state = AE_TOP_CONFIGURED_IDLE;
341 m_state = AE_TOP_ERROR;
352 case AE_TOP_RECONFIGURING:
353 if (port == NULL) // timeout
357 case CActiveAEControlProtocol::TIMEOUT:
364 if (!m_sinkBuffers->m_inputSamples.empty() || !m_sinkBuffers->m_outputSamples.empty())
369 if (NeedReconfigureSink())
376 m_state = AE_TOP_CONFIGURED_PLAY;
381 m_state = AE_TOP_ERROR;
384 m_extDeferData = false;
392 case AE_TOP_CONFIGURED:
393 if (port == &m_controlPort)
397 case CActiveAEControlProtocol::RECONFIGURE:
398 if (m_streams.empty())
400 bool silence = false;
401 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
405 if (!NeedReconfigureBuffers() && !NeedReconfigureSink())
407 m_state = AE_TOP_RECONFIGURING;
409 // don't accept any data until we are reconfigured
410 m_extDeferData = true;
412 case CActiveAEControlProtocol::SUSPEND:
414 m_stats.SetSuspended(true);
415 m_state = AE_TOP_CONFIGURED_SUSPEND;
416 m_extDeferData = true;
418 case CActiveAEControlProtocol::DISPLAYLOST:
419 if (m_sink.GetDeviceType(m_mode == MODE_PCM ? m_settings.device : m_settings.passthoughdevice) == AE_DEVTYPE_HDMI)
422 m_stats.SetSuspended(true);
423 m_state = AE_TOP_CONFIGURED_SUSPEND;
424 m_extDeferData = true;
426 msg->Reply(CActiveAEControlProtocol::ACC);
428 case CActiveAEControlProtocol::DEVICECHANGE:
431 while (!m_extLastDeviceChange.empty() && (now - m_extLastDeviceChange.front() > 0))
433 m_extLastDeviceChange.pop();
435 if (m_extLastDeviceChange.size() > 2)
437 CLog::Log(LOGWARNING,"CActiveAE - received %ld device change events within one second", m_extLastDeviceChange.size());
440 m_extLastDeviceChange.push(now);
442 m_sink.EnumerateSinkList(true);
448 m_state = AE_TOP_CONFIGURED_PLAY;
453 m_state = AE_TOP_ERROR;
456 m_controlPort.PurgeOut(CActiveAEControlProtocol::DEVICECHANGE);
458 case CActiveAEControlProtocol::PAUSESTREAM:
459 CActiveAEStream *stream;
460 stream = *(CActiveAEStream**)msg->data;
461 if (stream->m_paused != true && m_streams.size() == 1)
463 stream->m_paused = true;
465 case CActiveAEControlProtocol::RESUMESTREAM:
466 stream = *(CActiveAEStream**)msg->data;
467 stream->m_paused = false;
470 case CActiveAEControlProtocol::FLUSHSTREAM:
471 stream = *(CActiveAEStream**)msg->data;
472 SFlushStream(stream);
473 msg->Reply(CActiveAEControlProtocol::ACC);
476 case CActiveAEControlProtocol::STREAMAMP:
477 MsgStreamParameter *par;
478 par = (MsgStreamParameter*)msg->data;
479 par->stream->m_limiter.SetAmplification(par->parameter.float_par);
480 par->stream->m_amplify = par->parameter.float_par;
482 case CActiveAEControlProtocol::STREAMVOLUME:
483 par = (MsgStreamParameter*)msg->data;
484 par->stream->m_volume = par->parameter.float_par;
486 case CActiveAEControlProtocol::STREAMRGAIN:
487 par = (MsgStreamParameter*)msg->data;
488 par->stream->m_rgain = par->parameter.float_par;
490 case CActiveAEControlProtocol::STREAMRESAMPLERATIO:
491 par = (MsgStreamParameter*)msg->data;
492 if (par->stream->m_resampleBuffers)
494 par->stream->m_resampleBuffers->m_resampleRatio = par->parameter.double_par;
497 case CActiveAEControlProtocol::STREAMFADE:
499 fade = (MsgStreamFade*)msg->data;
500 fade->stream->m_fadingBase = fade->from;
501 fade->stream->m_fadingTarget = fade->target;
502 fade->stream->m_fadingTime = fade->millis;
503 fade->stream->m_fadingSamples = -1;
505 case CActiveAEControlProtocol::STOPSOUND:
506 CActiveAESound *sound;
507 sound = *(CActiveAESound**)msg->data;
514 else if (port == &m_dataPort)
518 case CActiveAEDataProtocol::PLAYSOUND:
519 CActiveAESound *sound;
520 sound = *(CActiveAESound**)msg->data;
521 if (m_settings.guisoundmode == AE_SOUND_OFF ||
522 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
526 SoundState st = {sound, 0};
527 m_sounds_playing.push_back(st);
529 m_state = AE_TOP_CONFIGURED_PLAY;
532 case CActiveAEDataProtocol::NEWSTREAM:
533 MsgStreamNew *streamMsg;
534 CActiveAEStream *stream;
535 streamMsg = (MsgStreamNew*)msg->data;
536 stream = CreateStream(streamMsg);
539 msg->Reply(CActiveAEDataProtocol::ACC, &stream, sizeof(CActiveAEStream*));
544 m_state = AE_TOP_CONFIGURED_PLAY;
549 m_state = AE_TOP_ERROR;
554 msg->Reply(CActiveAEDataProtocol::ERR);
556 case CActiveAEDataProtocol::STREAMSAMPLE:
557 MsgStreamSample *msgData;
558 CSampleBuffer *samples;
559 msgData = (MsgStreamSample*)msg->data;
560 samples = msgData->stream->m_processingSamples.front();
561 msgData->stream->m_processingSamples.pop_front();
562 if (samples != msgData->buffer)
563 CLog::Log(LOGERROR, "CActiveAE - inconsistency in stream sample message");
564 if (msgData->buffer->pkt->nb_samples == 0)
565 msgData->buffer->Return();
567 msgData->stream->m_resampleBuffers->m_inputSamples.push_back(msgData->buffer);
569 m_state = AE_TOP_CONFIGURED_PLAY;
571 case CActiveAEDataProtocol::FREESTREAM:
572 stream = *(CActiveAEStream**)msg->data;
573 DiscardStream(stream);
574 if (m_streams.empty())
577 m_extDrainTimer.Set(m_extKeepConfig);
579 m_extDrainTimer.Set(m_stats.GetDelay() * 1000);
583 m_state = AE_TOP_CONFIGURED_PLAY;
585 case CActiveAEDataProtocol::DRAINSTREAM:
586 stream = *(CActiveAEStream**)msg->data;
587 stream->m_drain = true;
588 stream->m_resampleBuffers->m_drain = true;
590 m_state = AE_TOP_CONFIGURED_PLAY;
591 msg->Reply(CActiveAEDataProtocol::ACC);
597 else if (port == &m_sink.m_dataPort)
601 case CSinkDataProtocol::RETURNSAMPLE:
602 CSampleBuffer **buffer;
603 buffer = (CSampleBuffer**)msg->data;
609 m_state = AE_TOP_CONFIGURED_PLAY;
617 case AE_TOP_CONFIGURED_SUSPEND:
618 if (port == &m_controlPort)
620 bool displayReset = false;
623 case CActiveAEControlProtocol::DISPLAYRESET:
625 case CActiveAEControlProtocol::INIT:
629 m_sink.EnumerateSinkList(true);
634 msg->Reply(CActiveAEControlProtocol::ACC);
637 m_state = AE_TOP_CONFIGURED_PLAY;
642 m_state = AE_TOP_ERROR;
645 m_stats.SetSuspended(false);
646 m_extDeferData = false;
652 else if (port == &m_sink.m_dataPort)
656 case CSinkDataProtocol::RETURNSAMPLE:
657 CSampleBuffer **buffer;
658 buffer = (CSampleBuffer**)msg->data;
668 else if (port == NULL) // timeout
672 case CActiveAEControlProtocol::TIMEOUT:
681 case AE_TOP_CONFIGURED_IDLE:
682 if (port == &m_controlPort)
686 case CActiveAEControlProtocol::RESUMESTREAM:
687 CActiveAEStream *stream;
688 stream = *(CActiveAEStream**)msg->data;
689 stream->m_paused = false;
690 m_state = AE_TOP_CONFIGURED_PLAY;
693 case CActiveAEControlProtocol::FLUSHSTREAM:
694 stream = *(CActiveAEStream**)msg->data;
695 SFlushStream(stream);
696 msg->Reply(CActiveAEControlProtocol::ACC);
697 m_state = AE_TOP_CONFIGURED_PLAY;
704 else if (port == NULL) // timeout
708 case CActiveAEControlProtocol::TIMEOUT:
710 ClearDiscardedBuffers();
713 if (m_extDrainTimer.IsTimePast())
718 m_state = AE_TOP_CONFIGURED_PLAY;
723 m_state = AE_TOP_ERROR;
728 m_extTimeout = m_extDrainTimer.MillisLeft();
739 case AE_TOP_CONFIGURED_PLAY:
740 if (port == NULL) // timeout
744 case CActiveAEControlProtocol::TIMEOUT:
747 m_state = AE_TOP_ERROR;
756 if (!m_extDrain && HasWork())
758 ClearDiscardedBuffers();
763 m_state = AE_TOP_CONFIGURED_IDLE;
771 default: // we are in no state, should not happen
772 CLog::Log(LOGERROR, "CActiveAE::%s - no valid state: %d", __FUNCTION__, m_state);
778 void CActiveAE::Process()
781 Protocol *port = NULL;
783 XbmcThreads::EndTime timer;
785 m_state = AE_TOP_UNCONFIGURED;
787 m_bStateMachineSelfTrigger = false;
789 m_extDeferData = false;
798 timer.Set(m_extTimeout);
800 if (m_bStateMachineSelfTrigger)
802 m_bStateMachineSelfTrigger = false;
803 // self trigger state machine
804 StateMachine(msg->signal, port, msg);
805 if (!m_bStateMachineSelfTrigger)
812 // check control port
813 else if (m_controlPort.ReceiveOutMessage(&msg))
816 port = &m_controlPort;
818 // check sink data port
819 else if (m_sink.m_dataPort.ReceiveInMessage(&msg))
822 port = &m_sink.m_dataPort;
824 else if (!m_extDeferData)
827 if (m_dataPort.ReceiveOutMessage(&msg))
835 std::list<CActiveAEStream*>::iterator it;
836 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
838 if((*it)->m_streamPort->ReceiveOutMessage(&msg))
850 StateMachine(msg->signal, port, msg);
851 if (!m_bStateMachineSelfTrigger)
860 else if (m_outMsgEvent.WaitMSec(m_extTimeout))
862 m_extTimeout = timer.MillisLeft();
868 msg = m_controlPort.GetMessage();
869 msg->signal = CActiveAEControlProtocol::TIMEOUT;
871 // signal timeout to state machine
872 StateMachine(msg->signal, port, msg);
873 if (!m_bStateMachineSelfTrigger)
882 AEAudioFormat CActiveAE::GetInputFormat(AEAudioFormat *desiredFmt)
884 AEAudioFormat inputFormat;
886 if (m_streams.empty())
888 inputFormat.m_dataFormat = AE_FMT_FLOAT;
889 inputFormat.m_sampleRate = 44100;
890 inputFormat.m_encodedRate = 0;
891 inputFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
892 inputFormat.m_frames = 0;
893 inputFormat.m_frameSamples = 0;
894 inputFormat.m_frameSize = 0;
896 // force input format after unpausing slave
897 else if (desiredFmt != NULL)
899 inputFormat = *desiredFmt;
901 // keep format when having multiple streams
902 else if (m_streams.size() > 1 && m_silenceBuffers == NULL)
904 inputFormat = m_inputFormat;
908 inputFormat = m_streams.front()->m_format;
909 m_inputFormat = inputFormat;
915 void CActiveAE::Configure(AEAudioFormat *desiredFmt)
917 bool initSink = false;
919 AEAudioFormat sinkInputFormat, inputFormat;
920 AEAudioFormat oldInternalFormat = m_internalFormat;
921 AEAudioFormat oldSinkRequestFormat = m_sinkRequestFormat;
923 inputFormat = GetInputFormat(desiredFmt);
925 m_sinkRequestFormat = inputFormat;
926 ApplySettingsToFormat(m_sinkRequestFormat, m_settings, (int*)&m_mode);
929 std::string device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
931 CAESinkFactory::ParseDevice(device, driver);
932 if ((!CompareFormat(m_sinkRequestFormat, m_sinkFormat) && !CompareFormat(m_sinkRequestFormat, oldSinkRequestFormat)) ||
933 m_currDevice.compare(device) != 0 ||
934 m_settings.driver.compare(driver) != 0)
938 m_settings.driver = driver;
939 m_currDevice = device;
941 m_stats.Reset(m_sinkFormat.m_sampleRate);
942 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::VOLUME, &m_volume, sizeof(float));
944 // limit buffer size in case of sink returns large buffer
945 unsigned int buffertime = (m_sinkFormat.m_frames*1000) / m_sinkFormat.m_sampleRate;
948 CLog::Log(LOGWARNING, "ActiveAE::%s - sink returned large buffer of %d ms, reducing to 80 ms", __FUNCTION__, buffertime);
949 m_sinkFormat.m_frames = 80 * m_sinkFormat.m_sampleRate / 1000;
953 if (m_silenceBuffers)
955 m_discardBufferPools.push_back(m_silenceBuffers);
956 m_silenceBuffers = NULL;
959 // buffers for driving gui sounds if no streams are active
960 if (m_streams.empty())
962 inputFormat = m_sinkFormat;
963 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
965 inputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
966 inputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
968 inputFormat.m_dataFormat = AE_FMT_FLOAT;
969 inputFormat.m_frameSize = inputFormat.m_channelLayout.Count() *
970 (CAEUtil::DataFormatToBits(inputFormat.m_dataFormat) >> 3);
971 m_silenceBuffers = new CActiveAEBufferPool(inputFormat);
972 m_silenceBuffers->Create(MAX_WATER_LEVEL*1000);
973 sinkInputFormat = inputFormat;
974 m_internalFormat = inputFormat;
976 bool silence = false;
977 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
982 if (m_encoderBuffers)
984 m_discardBufferPools.push_back(m_encoderBuffers);
985 m_encoderBuffers = NULL;
989 m_discardBufferPools.push_back(m_vizBuffers);
992 if (m_vizBuffersInput)
994 m_discardBufferPools.push_back(m_vizBuffersInput);
995 m_vizBuffersInput = NULL;
998 // resample buffers for streams
1001 bool silence = true;
1002 m_sink.m_controlPort.SendOutMessage(CSinkControlProtocol::SILENCEMODE, &silence, sizeof(bool));
1004 AEAudioFormat outputFormat;
1005 if (m_mode == MODE_RAW)
1007 inputFormat.m_frames = m_sinkFormat.m_frames;
1008 outputFormat = inputFormat;
1009 sinkInputFormat = m_sinkFormat;
1011 // transcode everything with more than 2 channels
1012 else if (m_mode == MODE_TRANSCODE)
1014 outputFormat = inputFormat;
1015 outputFormat.m_dataFormat = AE_FMT_FLOATP;
1016 outputFormat.m_sampleRate = 48000;
1021 m_encoder = new CAEEncoderFFmpeg();
1022 m_encoder->Initialize(outputFormat, true);
1023 m_encoderFormat = outputFormat;
1026 outputFormat = m_encoderFormat;
1028 outputFormat.m_channelLayout = m_encoderFormat.m_channelLayout;
1029 outputFormat.m_frames = m_encoderFormat.m_frames;
1032 if (m_encoder->GetCodecID() == AV_CODEC_ID_AC3)
1034 AEAudioFormat format;
1035 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1036 format.m_dataFormat = AE_FMT_S16NE;
1037 format.m_frameSize = 2* (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
1038 format.m_frames = AC3_FRAME_SIZE;
1039 format.m_sampleRate = 48000;
1040 format.m_encodedRate = m_encoderFormat.m_sampleRate;
1041 if (m_encoderBuffers && initSink)
1043 m_discardBufferPools.push_back(m_encoderBuffers);
1044 m_encoderBuffers = NULL;
1046 if (!m_encoderBuffers)
1048 m_encoderBuffers = new CActiveAEBufferPool(format);
1049 m_encoderBuffers->Create(MAX_WATER_LEVEL*1000);
1053 sinkInputFormat = m_sinkFormat;
1057 outputFormat = m_sinkFormat;
1058 outputFormat.m_dataFormat = AE_FMT_FLOAT;
1059 outputFormat.m_frameSize = outputFormat.m_channelLayout.Count() *
1060 (CAEUtil::DataFormatToBits(outputFormat.m_dataFormat) >> 3);
1062 // due to channel ordering of the driver, a sink may return more channels than
1063 // requested, i.e. 2.1 request returns FL,FR,BL,BR,FC,LFE for ALSA
1064 // in this case we need to downmix to requested format
1065 if (m_sinkFormat.m_channelLayout.Count() > m_sinkRequestFormat.m_channelLayout.Count())
1067 outputFormat.m_channelLayout = m_sinkRequestFormat.m_channelLayout;
1068 outputFormat.m_channelLayout.ResolveChannels(m_sinkFormat.m_channelLayout);
1071 // TODO: adjust to decoder
1072 sinkInputFormat = outputFormat;
1074 m_internalFormat = outputFormat;
1076 std::list<CActiveAEStream*>::iterator it;
1077 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1079 // check if we support input format of stream
1080 if (!AE_IS_RAW((*it)->m_format.m_dataFormat) &&
1081 CActiveAEResample::GetAVSampleFormat((*it)->m_format.m_dataFormat) == AV_SAMPLE_FMT_FLT &&
1082 (*it)->m_format.m_dataFormat != AE_FMT_FLOAT)
1084 (*it)->m_convertFn = CAEConvert::ToFloat((*it)->m_format.m_dataFormat);
1085 (*it)->m_format.m_dataFormat = AE_FMT_FLOAT;
1088 if (!(*it)->m_inputBuffers)
1090 // align input buffers with period of sink or encoder
1091 (*it)->m_format.m_frames = m_internalFormat.m_frames * ((float)(*it)->m_format.m_sampleRate / m_internalFormat.m_sampleRate);
1093 // create buffer pool
1094 (*it)->m_inputBuffers = new CActiveAEBufferPool((*it)->m_format);
1095 (*it)->m_inputBuffers->Create(MAX_CACHE_LEVEL*1000);
1096 (*it)->m_streamSpace = (*it)->m_format.m_frameSize * (*it)->m_format.m_frames;
1098 // if input format does not follow ffmpeg channel mask, we may need to remap channels
1099 (*it)->InitRemapper();
1101 if (initSink && (*it)->m_resampleBuffers)
1103 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1104 (*it)->m_resampleBuffers = NULL;
1106 if (!(*it)->m_resampleBuffers)
1108 (*it)->m_resampleBuffers = new CActiveAEBufferPoolResample((*it)->m_inputBuffers->m_format, outputFormat, m_settings.resampleQuality);
1109 (*it)->m_resampleBuffers->m_changeResampler = (*it)->m_forceResampler;
1110 (*it)->m_resampleBuffers->Create(MAX_CACHE_LEVEL*1000, false, m_settings.stereoupmix, m_settings.normalizelevels);
1112 if (m_mode == MODE_TRANSCODE || m_streams.size() > 1)
1113 (*it)->m_resampleBuffers->m_fillPackets = true;
1116 (*it)->m_limiter.SetSamplerate(outputFormat.m_sampleRate);
1119 // update buffered time of streams
1120 m_stats.AddSamples(0, m_streams);
1123 if (!AE_IS_RAW(inputFormat.m_dataFormat))
1125 if (initSink && m_vizBuffers)
1127 m_discardBufferPools.push_back(m_vizBuffers);
1128 m_vizBuffers = NULL;
1129 m_discardBufferPools.push_back(m_vizBuffersInput);
1130 m_vizBuffersInput = NULL;
1134 AEAudioFormat vizFormat = m_internalFormat;
1135 vizFormat.m_channelLayout = AE_CH_LAYOUT_2_0;
1136 vizFormat.m_dataFormat = AE_FMT_FLOAT;
1139 m_vizBuffersInput = new CActiveAEBufferPool(m_internalFormat);
1140 m_vizBuffersInput->Create(2000);
1143 m_vizBuffers = new CActiveAEBufferPoolResample(m_internalFormat, vizFormat, m_settings.resampleQuality);
1144 // TODO use cache of sync + water level
1145 m_vizBuffers->Create(2000, false, false);
1146 m_vizInitialized = false;
1151 // resample buffers for sink
1152 if (m_sinkBuffers &&
1153 (!CompareFormat(m_sinkBuffers->m_format,m_sinkFormat) || !CompareFormat(m_sinkBuffers->m_inputFormat, sinkInputFormat)))
1155 m_discardBufferPools.push_back(m_sinkBuffers);
1156 m_sinkBuffers = NULL;
1160 m_sinkBuffers = new CActiveAEBufferPoolResample(sinkInputFormat, m_sinkFormat, m_settings.resampleQuality);
1161 m_sinkBuffers->Create(MAX_WATER_LEVEL*1000, true, false);
1165 if (!CompareFormat(oldInternalFormat, m_internalFormat))
1167 if (m_settings.guisoundmode == AE_SOUND_ALWAYS ||
1168 (m_settings.guisoundmode == AE_SOUND_IDLE && m_streams.empty()))
1170 std::vector<CActiveAESound*>::iterator it;
1171 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
1173 (*it)->SetConverted(false);
1176 m_sounds_playing.clear();
1179 ClearDiscardedBuffers();
1183 CActiveAEStream* CActiveAE::CreateStream(MsgStreamNew *streamMsg)
1185 // we only can handle a single pass through stream
1186 bool hasRawStream = false;
1187 bool hasStream = false;
1188 std::list<CActiveAEStream*>::iterator it;
1189 for(it = m_streams.begin(); it != m_streams.end(); ++it)
1191 if((*it)->IsDrained())
1193 if(AE_IS_RAW((*it)->m_format.m_dataFormat))
1194 hasRawStream = true;
1197 if (hasRawStream || (hasStream && AE_IS_RAW(streamMsg->format.m_dataFormat)))
1202 // create the stream
1203 CActiveAEStream *stream;
1204 stream = new CActiveAEStream(&streamMsg->format);
1205 stream->m_streamPort = new CActiveAEDataProtocol("stream",
1206 &stream->m_inMsgEvent, &m_outMsgEvent);
1208 // create buffer pool
1209 stream->m_inputBuffers = NULL; // create in Configure when we know the sink format
1210 stream->m_resampleBuffers = NULL; // create in Configure when we know the sink format
1211 stream->m_statsLock = m_stats.GetLock();
1212 stream->m_fadingSamples = 0;
1213 stream->m_started = false;
1215 if (streamMsg->options & AESTREAM_PAUSED)
1216 stream->m_paused = true;
1218 if (streamMsg->options & AESTREAM_FORCE_RESAMPLE)
1219 stream->m_forceResampler = true;
1221 m_streams.push_back(stream);
1226 void CActiveAE::DiscardStream(CActiveAEStream *stream)
1228 std::list<CActiveAEStream*>::iterator it;
1229 for (it=m_streams.begin(); it!=m_streams.end(); )
1231 if (stream == (*it))
1233 while (!(*it)->m_processingSamples.empty())
1235 (*it)->m_processingSamples.front()->Return();
1236 (*it)->m_processingSamples.pop_front();
1238 m_discardBufferPools.push_back((*it)->m_inputBuffers);
1239 m_discardBufferPools.push_back((*it)->m_resampleBuffers);
1240 CLog::Log(LOGDEBUG, "CActiveAE::DiscardStream - audio stream deleted");
1241 delete (*it)->m_streamPort;
1243 it = m_streams.erase(it);
1249 ClearDiscardedBuffers();
1252 void CActiveAE::SFlushStream(CActiveAEStream *stream)
1254 while (!stream->m_processingSamples.empty())
1256 stream->m_processingSamples.front()->Return();
1257 stream->m_processingSamples.pop_front();
1259 stream->m_resampleBuffers->Flush();
1260 stream->m_streamPort->Purge();
1261 stream->m_bufferedTime = 0.0;
1262 stream->m_paused = false;
1264 // flush the engine if we only have a single stream
1265 if (m_streams.size() == 1)
1271 void CActiveAE::FlushEngine()
1274 m_sinkBuffers->Flush();
1276 m_vizBuffers->Flush();
1278 // send message to sink
1280 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::FLUSH,
1283 bool success = reply->signal == CSinkControlProtocol::ACC;
1286 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on flush", __FUNCTION__);
1293 CLog::Log(LOGERROR, "ActiveAE::%s - failed to flush", __FUNCTION__);
1296 m_stats.Reset(m_sinkFormat.m_sampleRate);
1299 void CActiveAE::ClearDiscardedBuffers()
1301 std::list<CActiveAEBufferPool*>::iterator it;
1302 for (it=m_discardBufferPools.begin(); it!=m_discardBufferPools.end(); ++it)
1304 CActiveAEBufferPoolResample *rbuf = dynamic_cast<CActiveAEBufferPoolResample*>(*it);
1309 // if all buffers have returned, we can delete the buffer pool
1310 if ((*it)->m_allSamples.size() == (*it)->m_freeSamples.size())
1313 CLog::Log(LOGDEBUG, "CActiveAE::ClearDiscardedBuffers - buffer pool deleted");
1314 m_discardBufferPools.erase(it);
1320 void CActiveAE::SStopSound(CActiveAESound *sound)
1322 std::list<SoundState>::iterator it;
1323 for (it=m_sounds_playing.begin(); it!=m_sounds_playing.end(); ++it)
1325 if (it->sound == sound)
1327 m_sounds_playing.erase(it);
1333 void CActiveAE::DiscardSound(CActiveAESound *sound)
1337 std::vector<CActiveAESound*>::iterator it;
1338 for (it=m_sounds.begin(); it!=m_sounds.end(); ++it)
1348 void CActiveAE::ChangeResamplers()
1350 std::list<CActiveAEStream*>::iterator it;
1351 for(it=m_streams.begin(); it!=m_streams.end(); ++it)
1353 bool normalize = true;
1354 if (((*it)->m_resampleBuffers->m_format.m_channelLayout.Count() <
1355 (*it)->m_resampleBuffers->m_inputFormat.m_channelLayout.Count()) &&
1356 !m_settings.normalizelevels)
1359 if ((*it)->m_resampleBuffers && (*it)->m_resampleBuffers->m_resampler &&
1360 (((*it)->m_resampleBuffers->m_resampleQuality != m_settings.resampleQuality) ||
1361 (((*it)->m_resampleBuffers->m_stereoUpmix != m_settings.stereoupmix)) ||
1362 ((*it)->m_resampleBuffers->m_normalize != normalize)))
1364 (*it)->m_resampleBuffers->m_changeResampler = true;
1366 (*it)->m_resampleBuffers->m_resampleQuality = m_settings.resampleQuality;
1367 (*it)->m_resampleBuffers->m_stereoUpmix = m_settings.stereoupmix;
1368 (*it)->m_resampleBuffers->m_normalize = normalize;
1372 void CActiveAE::ApplySettingsToFormat(AEAudioFormat &format, AudioSettings &settings, int *mode)
1374 int oldMode = m_mode;
1379 if (AE_IS_RAW(format.m_dataFormat))
1381 if ((format.m_dataFormat == AE_FMT_AC3 && !settings.ac3passthrough) ||
1382 (format.m_dataFormat == AE_FMT_EAC3 && !settings.eac3passthrough) ||
1383 (format.m_dataFormat == AE_FMT_TRUEHD && !settings.truehdpassthrough) ||
1384 (format.m_dataFormat == AE_FMT_DTS && !settings.dtspassthrough) ||
1385 (format.m_dataFormat == AE_FMT_DTSHD && !settings.dtshdpassthrough))
1387 CLog::Log(LOGERROR, "CActiveAE::ApplySettingsToFormat - input audio format is wrong");
1393 else if (settings.channels <= AE_CH_LAYOUT_2_0 && // no multichannel pcm
1394 settings.passthrough &&
1395 settings.ac3passthrough &&
1396 settings.ac3transcode &&
1397 !m_streams.empty() &&
1398 (format.m_channelLayout.Count() > 2 || settings.stereoupmix))
1400 format.m_dataFormat = AE_FMT_AC3;
1401 format.m_sampleRate = 48000;
1402 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1404 *mode = MODE_TRANSCODE;
1408 format.m_dataFormat = AE_FMT_FLOAT;
1409 // consider user channel layout for those cases
1410 // 1. input stream is multichannel
1411 // 2. stereo upmix is selected
1413 if ((format.m_channelLayout.Count() > 2) ||
1414 settings.stereoupmix ||
1415 (settings.config == AE_CONFIG_FIXED))
1417 CAEChannelInfo stdLayout;
1418 switch (settings.channels)
1421 case 0: stdLayout = AE_CH_LAYOUT_2_0; break;
1422 case 1: stdLayout = AE_CH_LAYOUT_2_0; break;
1423 case 2: stdLayout = AE_CH_LAYOUT_2_1; break;
1424 case 3: stdLayout = AE_CH_LAYOUT_3_0; break;
1425 case 4: stdLayout = AE_CH_LAYOUT_3_1; break;
1426 case 5: stdLayout = AE_CH_LAYOUT_4_0; break;
1427 case 6: stdLayout = AE_CH_LAYOUT_4_1; break;
1428 case 7: stdLayout = AE_CH_LAYOUT_5_0; break;
1429 case 8: stdLayout = AE_CH_LAYOUT_5_1; break;
1430 case 9: stdLayout = AE_CH_LAYOUT_7_0; break;
1431 case 10: stdLayout = AE_CH_LAYOUT_7_1; break;
1434 if (m_settings.config == AE_CONFIG_FIXED || (settings.stereoupmix && format.m_channelLayout.Count() <= 2))
1435 format.m_channelLayout = stdLayout;
1436 else if (m_extKeepConfig && (settings.config == AE_CONFIG_AUTO) && (oldMode != MODE_RAW))
1437 format.m_channelLayout = m_internalFormat.m_channelLayout;
1439 format.m_channelLayout.ResolveChannels(stdLayout);
1441 // don't change from multi to stereo in AUTO mode
1442 else if ((settings.config == AE_CONFIG_AUTO) &&
1443 m_stats.GetWaterLevel() > 0 && m_internalFormat.m_channelLayout.Count() > 2)
1445 format.m_channelLayout = m_internalFormat.m_channelLayout;
1448 if (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958)
1450 if (format.m_sampleRate > m_settings.samplerate)
1452 format.m_sampleRate = m_settings.samplerate;
1453 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - limit samplerate for SPDIF to %d", format.m_sampleRate);
1455 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1458 if (m_settings.config == AE_CONFIG_FIXED)
1460 format.m_sampleRate = m_settings.samplerate;
1461 CLog::Log(LOGINFO, "CActiveAE::ApplySettings - Forcing samplerate to %d", format.m_sampleRate);
1464 // sinks may not support mono
1465 if (format.m_channelLayout.Count() == 1)
1467 format.m_channelLayout = AE_CH_LAYOUT_2_0;
1472 bool CActiveAE::NeedReconfigureBuffers()
1474 AEAudioFormat newFormat = GetInputFormat();
1475 ApplySettingsToFormat(newFormat, m_settings);
1477 if (newFormat.m_dataFormat != m_sinkRequestFormat.m_dataFormat ||
1478 newFormat.m_channelLayout != m_sinkRequestFormat.m_channelLayout ||
1479 newFormat.m_sampleRate != m_sinkRequestFormat.m_sampleRate)
1485 bool CActiveAE::NeedReconfigureSink()
1487 AEAudioFormat newFormat = GetInputFormat();
1488 ApplySettingsToFormat(newFormat, m_settings);
1490 std::string device = AE_IS_RAW(newFormat.m_dataFormat) ? m_settings.passthoughdevice : m_settings.device;
1492 CAESinkFactory::ParseDevice(device, driver);
1494 if (!CompareFormat(newFormat, m_sinkFormat) ||
1495 m_currDevice.compare(device) != 0 ||
1496 m_settings.driver.compare(driver) != 0)
1502 bool CActiveAE::InitSink()
1505 config.format = m_sinkRequestFormat;
1506 config.stats = &m_stats;
1507 config.device = AE_IS_RAW(m_sinkRequestFormat.m_dataFormat) ? &m_settings.passthoughdevice :
1510 // send message to sink
1512 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::CONFIGURE,
1515 &config, sizeof(config)))
1517 bool success = reply->signal == CSinkControlProtocol::ACC;
1521 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1526 data = (SinkReply*)reply->data;
1529 m_sinkFormat = data->format;
1530 m_sinkHasVolume = data->hasVolume;
1531 m_stats.SetSinkCacheTotal(data->cacheTotal);
1532 m_stats.SetSinkLatency(data->latency);
1538 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
1539 m_stats.SetSinkCacheTotal(0);
1540 m_stats.SetSinkLatency(0);
1545 m_inMsgEvent.Reset();
1549 void CActiveAE::DrainSink()
1551 // send message to sink
1553 if (m_sink.m_dataPort.SendOutMessageSync(CSinkDataProtocol::DRAIN,
1557 bool success = reply->signal == CSinkDataProtocol::ACC;
1561 CLog::Log(LOGERROR, "ActiveAE::%s - returned error on drain", __FUNCTION__);
1569 CLog::Log(LOGERROR, "ActiveAE::%s - failed to drain", __FUNCTION__);
1575 void CActiveAE::UnconfigureSink()
1577 // send message to sink
1579 if (m_sink.m_controlPort.SendOutMessageSync(CSinkControlProtocol::UNCONFIGURE,
1583 bool success = reply->signal == CSinkControlProtocol::ACC;
1586 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
1593 CLog::Log(LOGERROR, "ActiveAE::%s - failed to unconfigure", __FUNCTION__);
1597 // make sure we open sink on next configure
1600 m_inMsgEvent.Reset();
1604 bool CActiveAE::RunStages()
1608 // serve input streams
1609 std::list<CActiveAEStream*>::iterator it;
1610 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1612 if ((*it)->m_resampleBuffers && !(*it)->m_paused)
1613 busy = (*it)->m_resampleBuffers->ResampleBuffers();
1614 else if ((*it)->m_resampleBuffers &&
1615 ((*it)->m_resampleBuffers->m_inputSamples.size() > (*it)->m_resampleBuffers->m_allSamples.size() * 0.5))
1617 CSingleLock lock((*it)->m_streamLock);
1618 (*it)->m_streamIsBuffering = false;
1621 // provide buffers to stream
1622 float time = m_stats.GetCacheTime((*it));
1623 CSampleBuffer *buffer;
1624 if (!(*it)->m_drain)
1626 while (time < MAX_CACHE_LEVEL && !(*it)->m_inputBuffers->m_freeSamples.empty())
1628 buffer = (*it)->m_inputBuffers->GetFreeBuffer();
1629 (*it)->m_processingSamples.push_back(buffer);
1630 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMBUFFER, &buffer, sizeof(CSampleBuffer*));
1631 (*it)->IncFreeBuffers();
1632 time += (float)buffer->pkt->max_nb_samples / buffer->pkt->config.sample_rate;
1637 if ((*it)->m_resampleBuffers->m_inputSamples.empty() &&
1638 (*it)->m_resampleBuffers->m_outputSamples.empty() &&
1639 (*it)->m_processingSamples.empty())
1641 (*it)->m_streamPort->SendInMessage(CActiveAEDataProtocol::STREAMDRAINED);
1642 (*it)->m_drain = false;
1643 (*it)->m_resampleBuffers->m_drain = false;
1644 (*it)->m_started = false;
1646 // set variables being polled via stream interface
1647 CSingleLock lock((*it)->m_streamLock);
1648 if ((*it)->m_streamSlave)
1650 CActiveAEStream *slave = (CActiveAEStream*)((*it)->m_streamSlave);
1651 slave->m_paused = false;
1653 // TODO: find better solution for this
1654 // gapless bites audiophile
1655 if (m_settings.config == AE_CONFIG_MATCH)
1656 Configure(&slave->m_format);
1658 (*it)->m_streamSlave = NULL;
1660 (*it)->m_streamDrained = true;
1661 (*it)->m_streamDraining = false;
1662 (*it)->m_streamFading = false;
1667 if (m_stats.GetWaterLevel() < MAX_WATER_LEVEL &&
1668 (m_mode != MODE_TRANSCODE || (m_encoderBuffers && !m_encoderBuffers->m_freeSamples.empty())))
1670 // mix streams and sounds sounds
1671 if (m_mode != MODE_RAW)
1673 CSampleBuffer *out = NULL;
1674 if (!m_sounds_playing.empty() && m_streams.empty())
1676 if (m_silenceBuffers && !m_silenceBuffers->m_freeSamples.empty())
1678 out = m_silenceBuffers->GetFreeBuffer();
1679 for (int i=0; i<out->pkt->planes; i++)
1681 memset(out->pkt->data[i], 0, out->pkt->linesize);
1683 out->pkt->nb_samples = out->pkt->max_nb_samples;
1688 std::list<CActiveAEStream*>::iterator it;
1690 // if we deal with more than a single stream, all streams
1691 // must provide samples for mixing
1692 bool allStreamsReady = true;
1693 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1695 if ((*it)->m_paused || !(*it)->m_started || !(*it)->m_resampleBuffers)
1698 if ((*it)->m_resampleBuffers->m_outputSamples.empty())
1699 allStreamsReady = false;
1702 bool needClamp = false;
1703 for (it = m_streams.begin(); it != m_streams.end() && allStreamsReady; ++it)
1705 if ((*it)->m_paused || !(*it)->m_resampleBuffers)
1708 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1710 (*it)->m_started = true;
1714 out = (*it)->m_resampleBuffers->m_outputSamples.front();
1715 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1717 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1719 float fadingStep = 0.0f;
1722 if ((*it)->m_fadingSamples == -1)
1724 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1725 (*it)->m_volume = (*it)->m_fadingBase;
1727 if ((*it)->m_fadingSamples > 0)
1729 nb_floats = out->pkt->config.channels / out->pkt->planes;
1730 nb_loops = out->pkt->nb_samples;
1731 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1732 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1733 fadingStep = delta / samples;
1736 // for stream amplification,
1737 // turned off downmix normalization,
1738 // or if sink format is float (in order to prevent from clipping)
1739 // we need to run on a per sample basis
1740 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize || (m_sinkFormat.m_dataFormat == AE_FMT_FLOAT))
1742 nb_floats = out->pkt->config.channels / out->pkt->planes;
1743 nb_loops = out->pkt->nb_samples;
1746 for(int i=0; i<nb_loops; i++)
1748 if ((*it)->m_fadingSamples > 0)
1750 (*it)->m_volume += fadingStep;
1751 (*it)->m_fadingSamples--;
1753 if ((*it)->m_fadingSamples == 0)
1755 // set variables being polled via stream interface
1756 CSingleLock lock((*it)->m_streamLock);
1757 (*it)->m_streamFading = false;
1761 // volume for stream
1762 float volume = (*it)->m_volume * (*it)->m_rgain;
1764 volume *= (*it)->m_limiter.Run((float**)out->pkt->data, out->pkt->config.channels, i*nb_floats, out->pkt->planes > 1);
1766 for(int j=0; j<out->pkt->planes; j++)
1769 CAEUtil::SSEMulArray((float*)out->pkt->data[j]+i*nb_floats, volume, nb_floats);
1771 float* fbuffer = (float*) out->pkt->data[j]+i*nb_floats;
1772 for (int k = 0; k < nb_floats; ++k)
1774 fbuffer[k] *= volume;
1782 CSampleBuffer *mix = NULL;
1783 mix = (*it)->m_resampleBuffers->m_outputSamples.front();
1784 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1786 int nb_floats = mix->pkt->nb_samples * mix->pkt->config.channels / mix->pkt->planes;
1788 float fadingStep = 0.0f;
1791 if ((*it)->m_fadingSamples == -1)
1793 (*it)->m_fadingSamples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1794 (*it)->m_volume = (*it)->m_fadingBase;
1796 if ((*it)->m_fadingSamples > 0)
1798 nb_floats = mix->pkt->config.channels / mix->pkt->planes;
1799 nb_loops = mix->pkt->nb_samples;
1800 float delta = (*it)->m_fadingTarget - (*it)->m_fadingBase;
1801 int samples = m_internalFormat.m_sampleRate * (float)(*it)->m_fadingTime / 1000.0f;
1802 fadingStep = delta / samples;
1805 // for streams amplification of turned off downmix normalization
1806 // we need to run on a per sample basis
1807 if ((*it)->m_amplify != 1.0 || !(*it)->m_resampleBuffers->m_normalize)
1809 nb_floats = out->pkt->config.channels / out->pkt->planes;
1810 nb_loops = out->pkt->nb_samples;
1813 for(int i=0; i<nb_loops; i++)
1815 if ((*it)->m_fadingSamples > 0)
1817 (*it)->m_volume += fadingStep;
1818 (*it)->m_fadingSamples--;
1820 if ((*it)->m_fadingSamples == 0)
1822 // set variables being polled via stream interface
1823 CSingleLock lock((*it)->m_streamLock);
1824 (*it)->m_streamFading = false;
1828 // volume for stream
1829 float volume = (*it)->m_volume * (*it)->m_rgain;
1831 volume *= (*it)->m_limiter.Run((float**)mix->pkt->data, mix->pkt->config.channels, i*nb_floats, mix->pkt->planes > 1);
1833 for(int j=0; j<out->pkt->planes && j<mix->pkt->planes; j++)
1835 float *dst = (float*)out->pkt->data[j]+i*nb_floats;
1836 float *src = (float*)mix->pkt->data[j]+i*nb_floats;
1838 CAEUtil::SSEMulAddArray(dst, src, volume, nb_floats);
1839 for (int k = 0; k < nb_floats; ++k)
1841 if (fabs(dst[k]) > 1.0f)
1848 for (int k = 0; k < nb_floats; ++k)
1850 dst[k] += src[k] * volume;
1851 if (fabs(dst[k]) > 1.0f)
1863 // finally clamp samples
1864 if(out && needClamp)
1866 int nb_floats = out->pkt->nb_samples * out->pkt->config.channels / out->pkt->planes;
1867 for(int i=0; i<out->pkt->planes; i++)
1869 CAEUtil::ClampArray((float*)out->pkt->data[i], nb_floats);
1873 // process output buffer, gui sounds, encode, viz
1878 CSingleLock lock(m_vizLock);
1879 if (m_audioCallback && m_vizBuffers && !m_streams.empty())
1881 if (!m_vizInitialized)
1883 m_audioCallback->OnInitialize(2, m_vizBuffers->m_format.m_sampleRate, 32);
1884 m_vizInitialized = true;
1887 if (!m_vizBuffersInput->m_freeSamples.empty())
1889 // copy the samples into the viz input buffer
1890 CSampleBuffer *viz = m_vizBuffersInput->GetFreeBuffer();
1891 int samples = std::min(512, out->pkt->nb_samples);
1892 int bytes = samples * out->pkt->config.channels / out->pkt->planes * out->pkt->bytes_per_sample;
1893 for(int i= 0; i < out->pkt->planes; i++)
1895 memcpy(viz->pkt->data[i], out->pkt->data[i], bytes);
1897 viz->pkt->nb_samples = samples;
1898 m_vizBuffers->m_inputSamples.push_back(viz);
1901 CLog::Log(LOGWARNING,"ActiveAE::%s - viz ran out of free buffers", __FUNCTION__);
1902 unsigned int now = XbmcThreads::SystemClockMillis();
1903 unsigned int timestamp = now + m_stats.GetDelay() * 1000;
1904 busy |= m_vizBuffers->ResampleBuffers(timestamp);
1905 while(!m_vizBuffers->m_outputSamples.empty())
1907 CSampleBuffer *buf = m_vizBuffers->m_outputSamples.front();
1908 if ((now - buf->timestamp) & 0x80000000)
1913 samples = std::min(512, buf->pkt->nb_samples);
1914 m_audioCallback->OnAudioData((float*)(buf->pkt->data[0]), samples);
1916 m_vizBuffers->m_outputSamples.pop_front();
1920 else if (m_vizBuffers)
1921 m_vizBuffers->Flush();
1925 MixSounds(*(out->pkt));
1926 if (!m_sinkHasVolume || m_muted)
1927 Deamplify(*(out->pkt));
1929 if (m_mode == MODE_TRANSCODE && m_encoder)
1931 CSampleBuffer *buf = m_encoderBuffers->GetFreeBuffer();
1932 m_encoder->Encode(out->pkt->data[0], out->pkt->planes*out->pkt->linesize,
1933 buf->pkt->data[0], buf->pkt->planes*buf->pkt->linesize);
1934 buf->pkt->nb_samples = buf->pkt->max_nb_samples;
1944 m_stats.AddSamples(out->pkt->nb_samples, m_streams);
1945 m_sinkBuffers->m_inputSamples.push_back(out);
1951 std::list<CActiveAEStream*>::iterator it;
1952 CSampleBuffer *buffer;
1953 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1955 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1957 buffer = (*it)->m_resampleBuffers->m_outputSamples.front();
1958 (*it)->m_resampleBuffers->m_outputSamples.pop_front();
1959 m_stats.AddSamples(buffer->pkt->nb_samples, m_streams);
1960 m_sinkBuffers->m_inputSamples.push_back(buffer);
1965 // serve sink buffers
1966 busy = m_sinkBuffers->ResampleBuffers();
1967 while(!m_sinkBuffers->m_outputSamples.empty())
1969 CSampleBuffer *out = NULL;
1970 out = m_sinkBuffers->m_outputSamples.front();
1971 m_sinkBuffers->m_outputSamples.pop_front();
1972 m_sink.m_dataPort.SendOutMessage(CSinkDataProtocol::SAMPLE,
1973 &out, sizeof(CSampleBuffer*));
1981 bool CActiveAE::HasWork()
1983 if (!m_sounds_playing.empty())
1985 if (!m_sinkBuffers->m_inputSamples.empty())
1987 if (!m_sinkBuffers->m_outputSamples.empty())
1990 std::list<CActiveAEStream*>::iterator it;
1991 for (it = m_streams.begin(); it != m_streams.end(); ++it)
1993 if (!(*it)->m_resampleBuffers->m_inputSamples.empty())
1995 if (!(*it)->m_resampleBuffers->m_outputSamples.empty())
1997 if (!(*it)->m_processingSamples.empty())
2004 void CActiveAE::MixSounds(CSoundPacket &dstSample)
2006 if (m_sounds_playing.empty())
2011 float *sample_buffer;
2012 int max_samples = dstSample.nb_samples;
2014 std::list<SoundState>::iterator it;
2015 for (it = m_sounds_playing.begin(); it != m_sounds_playing.end(); )
2017 if (!it->sound->IsConverted())
2018 ResampleSound(it->sound);
2019 int available_samples = it->sound->GetSound(false)->nb_samples - it->samples_played;
2020 int mix_samples = std::min(max_samples, available_samples);
2021 int start = it->samples_played *
2022 m_dllAvUtil.av_get_bytes_per_sample(it->sound->GetSound(false)->config.fmt) *
2023 it->sound->GetSound(false)->config.channels /
2024 it->sound->GetSound(false)->planes;
2026 for(int j=0; j<dstSample.planes; j++)
2028 volume = it->sound->GetVolume();
2029 out = (float*)dstSample.data[j];
2030 sample_buffer = (float*)(it->sound->GetSound(false)->data[j]+start);
2031 int nb_floats = mix_samples * dstSample.config.channels / dstSample.planes;
2033 CAEUtil::SSEMulAddArray(out, sample_buffer, volume, nb_floats);
2035 for (int k = 0; k < nb_floats; ++k)
2036 *out++ += *sample_buffer++ * volume;
2040 it->samples_played += mix_samples;
2042 // no more frames, so remove it from the list
2043 if (it->samples_played >= it->sound->GetSound(false)->nb_samples)
2045 it = m_sounds_playing.erase(it);
2052 void CActiveAE::Deamplify(CSoundPacket &dstSample)
2054 if (m_volume < 1.0 || m_muted)
2057 int nb_floats = dstSample.nb_samples * dstSample.config.channels / dstSample.planes;
2059 for(int j=0; j<dstSample.planes; j++)
2061 buffer = (float*)dstSample.data[j];
2063 CAEUtil::SSEMulArray(buffer, m_muted ? 0.0 : m_volume, nb_floats);
2065 float *fbuffer = buffer;
2066 for (int i = 0; i < nb_floats; i++)
2067 *fbuffer++ *= m_volume;
2073 //-----------------------------------------------------------------------------
2075 //-----------------------------------------------------------------------------
2077 void CActiveAE::LoadSettings()
2079 m_settings.device = CSettings::Get().GetString("audiooutput.audiodevice");
2080 m_settings.passthoughdevice = CSettings::Get().GetString("audiooutput.passthroughdevice");
2082 m_settings.config = CSettings::Get().GetInt("audiooutput.config");
2083 m_settings.channels = (m_sink.GetDeviceType(m_settings.device) == AE_DEVTYPE_IEC958) ? AE_CH_LAYOUT_2_0 : CSettings::Get().GetInt("audiooutput.channels");
2084 m_settings.samplerate = CSettings::Get().GetInt("audiooutput.samplerate");
2086 m_settings.stereoupmix = IsSettingVisible("audiooutput.stereoupmix") ? CSettings::Get().GetBool("audiooutput.stereoupmix") : false;
2087 m_settings.normalizelevels = CSettings::Get().GetBool("audiooutput.normalizelevels");
2088 m_settings.guisoundmode = CSettings::Get().GetInt("audiooutput.guisoundmode");
2090 m_settings.passthrough = m_settings.config == AE_CONFIG_FIXED ? false : CSettings::Get().GetBool("audiooutput.passthrough");
2091 if (!m_sink.HasPassthroughDevice())
2092 m_settings.passthrough = false;
2093 m_settings.ac3passthrough = CSettings::Get().GetBool("audiooutput.ac3passthrough");
2094 m_settings.ac3transcode = CSettings::Get().GetBool("audiooutput.ac3transcode");
2095 m_settings.eac3passthrough = CSettings::Get().GetBool("audiooutput.eac3passthrough");
2096 m_settings.truehdpassthrough = CSettings::Get().GetBool("audiooutput.truehdpassthrough");
2097 m_settings.dtspassthrough = CSettings::Get().GetBool("audiooutput.dtspassthrough");
2098 m_settings.dtshdpassthrough = CSettings::Get().GetBool("audiooutput.dtshdpassthrough");
2100 m_settings.resampleQuality = static_cast<AEQuality>(CSettings::Get().GetInt("audiooutput.processquality"));
2103 bool CActiveAE::Initialize()
2105 if (!m_dllAvUtil.Load() || !m_dllAvCodec.Load() || !m_dllAvFormat.Load())
2107 CLog::Log(LOGERROR,"CActiveAE::Initialize - failed to load ffmpeg libraries");
2110 m_dllAvFormat.av_register_all();
2114 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2118 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2122 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2129 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2134 // hook into windowing for receiving display reset events
2135 #if defined(HAS_GLX) || defined(TARGET_DARWIN_OSX)
2136 g_Windowing.Register(this);
2139 m_inMsgEvent.Reset();
2143 void CActiveAE::EnumerateOutputDevices(AEDeviceList &devices, bool passthrough)
2145 m_sink.EnumerateOutputDevices(devices, passthrough);
2148 std::string CActiveAE::GetDefaultDevice(bool passthrough)
2150 return m_sink.GetDefaultDevice(passthrough);
2153 void CActiveAE::OnSettingsChange(const std::string& setting)
2155 if (setting == "audiooutput.passthroughdevice" ||
2156 setting == "audiooutput.audiodevice" ||
2157 setting == "audiooutput.config" ||
2158 setting == "audiooutput.ac3passthrough" ||
2159 setting == "audiooutput.ac3transcode" ||
2160 setting == "audiooutput.eac3passthrough" ||
2161 setting == "audiooutput.dtspassthrough" ||
2162 setting == "audiooutput.truehdpassthrough" ||
2163 setting == "audiooutput.dtshdpassthrough" ||
2164 setting == "audiooutput.channels" ||
2165 setting == "audiooutput.stereoupmix" ||
2166 setting == "audiooutput.streamsilence" ||
2167 setting == "audiooutput.processquality" ||
2168 setting == "audiooutput.passthrough" ||
2169 setting == "audiooutput.samplerate" ||
2170 setting == "audiooutput.normalizelevels" ||
2171 setting == "audiooutput.guisoundmode")
2173 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RECONFIGURE);
2177 bool CActiveAE::SupportsRaw(AEDataFormat format)
2179 if (!m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), format))
2185 bool CActiveAE::SupportsSilenceTimeout()
2190 bool CActiveAE::SupportsQualityLevel(enum AEQuality level)
2192 if (level == AE_QUALITY_LOW || level == AE_QUALITY_MID || level == AE_QUALITY_HIGH)
2198 bool CActiveAE::IsSettingVisible(const std::string &settingId)
2200 if (settingId == "audiooutput.samplerate")
2202 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958)
2204 if (CSettings::Get().GetInt("audiooutput.config") == AE_CONFIG_FIXED)
2207 else if (settingId == "audiooutput.channels")
2209 if (m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) != AE_DEVTYPE_IEC958)
2212 else if (settingId == "audiooutput.passthrough")
2214 if (m_sink.HasPassthroughDevice() && CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2217 else if (settingId == "audiooutput.truehdpassthrough")
2219 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_TRUEHD) &&
2220 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2223 else if (settingId == "audiooutput.dtshdpassthrough")
2225 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_DTSHD) &&
2226 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2229 else if (settingId == "audiooutput.eac3passthrough")
2231 if (m_sink.SupportsFormat(CSettings::Get().GetString("audiooutput.passthroughdevice"), AE_FMT_EAC3) &&
2232 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED)
2235 else if (settingId == "audiooutput.stereoupmix")
2237 if (m_sink.HasPassthroughDevice() ||
2238 CSettings::Get().GetInt("audiooutput.channels") > AE_CH_LAYOUT_2_0)
2241 else if (settingId == "audiooutput.ac3transcode")
2243 if (m_sink.HasPassthroughDevice() &&
2244 CSettings::Get().GetBool("audiooutput.ac3passthrough") &&
2245 CSettings::Get().GetInt("audiooutput.config") != AE_CONFIG_FIXED &&
2246 (CSettings::Get().GetInt("audiooutput.channels") <= AE_CH_LAYOUT_2_0 || m_sink.GetDeviceType(CSettings::Get().GetString("audiooutput.audiodevice")) == AE_DEVTYPE_IEC958))
2252 void CActiveAE::Shutdown()
2257 bool CActiveAE::Suspend()
2259 return m_controlPort.SendOutMessage(CActiveAEControlProtocol::SUSPEND);
2262 bool CActiveAE::Resume()
2265 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::INIT,
2269 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2273 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2279 CLog::Log(LOGERROR, "ActiveAE::%s - failed to init", __FUNCTION__);
2283 m_inMsgEvent.Reset();
2287 bool CActiveAE::IsSuspended()
2289 return m_stats.IsSuspended();
2292 float CActiveAE::GetVolume()
2297 void CActiveAE::SetVolume(const float volume)
2299 m_aeVolume = std::max( 0.0f, std::min(1.0f, volume));
2300 m_controlPort.SendOutMessage(CActiveAEControlProtocol::VOLUME, &m_aeVolume, sizeof(float));
2303 void CActiveAE::SetMute(const bool enabled)
2305 m_aeMuted = enabled;
2306 m_controlPort.SendOutMessage(CActiveAEControlProtocol::MUTE, &m_aeMuted, sizeof(bool));
2309 bool CActiveAE::IsMuted()
2314 void CActiveAE::SetSoundMode(const int mode)
2319 void CActiveAE::KeepConfiguration(unsigned int millis)
2321 unsigned int timeMs = millis;
2322 m_controlPort.SendOutMessage(CActiveAEControlProtocol::KEEPCONFIG, &timeMs, sizeof(unsigned int));
2325 void CActiveAE::DeviceChange()
2327 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DEVICECHANGE);
2330 void CActiveAE::OnLostDevice()
2333 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::DISPLAYLOST,
2337 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2341 CLog::Log(LOGERROR, "ActiveAE::%s - returned error", __FUNCTION__);
2346 CLog::Log(LOGERROR, "ActiveAE::%s - timed out", __FUNCTION__);
2350 void CActiveAE::OnResetDevice()
2352 m_controlPort.SendOutMessage(CActiveAEControlProtocol::DISPLAYRESET);
2355 //-----------------------------------------------------------------------------
2357 //-----------------------------------------------------------------------------
2359 uint8_t **CActiveAE::AllocSoundSample(SampleConfig &config, int &samples, int &bytes_per_sample, int &planes, int &linesize)
2362 planes = m_dllAvUtil.av_sample_fmt_is_planar(config.fmt) ? config.channels : 1;
2363 buffer = new uint8_t*[planes];
2365 // align buffer to 16 in order to be compatible with sse in CAEConvert
2366 m_dllAvUtil.av_samples_alloc(buffer, &linesize, config.channels,
2367 samples, config.fmt, 16);
2368 bytes_per_sample = m_dllAvUtil.av_get_bytes_per_sample(config.fmt);
2372 void CActiveAE::FreeSoundSample(uint8_t **data)
2374 m_dllAvUtil.av_freep(data);
2378 bool CActiveAE::CompareFormat(AEAudioFormat &lhs, AEAudioFormat &rhs)
2380 if (lhs.m_channelLayout != rhs.m_channelLayout ||
2381 lhs.m_dataFormat != rhs.m_dataFormat ||
2382 lhs.m_sampleRate != rhs.m_sampleRate)
2388 //-----------------------------------------------------------------------------
2390 //-----------------------------------------------------------------------------
2393 * load sound from an audio file and store original format
2394 * register the sound in ActiveAE
2395 * later when the engine is idle it will convert the sound to sink format
2398 #define SOUNDBUFFER_SIZE 20480
2400 IAESound *CActiveAE::MakeSound(const std::string& file)
2402 AVFormatContext *fmt_ctx = NULL;
2403 AVCodecContext *dec_ctx = NULL;
2404 AVIOContext *io_ctx;
2405 AVInputFormat *io_fmt;
2406 AVCodec *dec = NULL;
2407 CActiveAESound *sound = NULL;
2408 SampleConfig config;
2410 sound = new CActiveAESound(file);
2411 if (!sound->Prepare())
2416 int fileSize = sound->GetFileSize();
2418 fmt_ctx = m_dllAvFormat.avformat_alloc_context();
2419 unsigned char* buffer = (unsigned char*)m_dllAvUtil.av_malloc(SOUNDBUFFER_SIZE+FF_INPUT_BUFFER_PADDING_SIZE);
2420 io_ctx = m_dllAvFormat.avio_alloc_context(buffer, SOUNDBUFFER_SIZE, 0,
2421 sound, CActiveAESound::Read, NULL, CActiveAESound::Seek);
2422 io_ctx->max_packet_size = sound->GetChunkSize();
2423 if(io_ctx->max_packet_size)
2424 io_ctx->max_packet_size *= SOUNDBUFFER_SIZE / io_ctx->max_packet_size;
2426 if(!sound->IsSeekPosible())
2427 io_ctx->seekable = 0;
2429 fmt_ctx->pb = io_ctx;
2431 m_dllAvFormat.av_probe_input_buffer(io_ctx, &io_fmt, file.c_str(), NULL, 0, 0);
2434 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2440 if (m_dllAvFormat.avformat_open_input(&fmt_ctx, file.c_str(), NULL, NULL) == 0)
2442 fmt_ctx->flags |= AVFMT_FLAG_NOPARSE;
2443 if (m_dllAvFormat.avformat_find_stream_info(fmt_ctx, NULL) >= 0)
2445 dec_ctx = fmt_ctx->streams[0]->codec;
2446 dec = m_dllAvCodec.avcodec_find_decoder(dec_ctx->codec_id);
2447 config.sample_rate = dec_ctx->sample_rate;
2448 config.channels = dec_ctx->channels;
2449 config.channel_layout = dec_ctx->channel_layout;
2454 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2459 dec_ctx = m_dllAvCodec.avcodec_alloc_context3(dec);
2460 dec_ctx->sample_rate = config.sample_rate;
2461 dec_ctx->channels = config.channels;
2462 if (!config.channel_layout)
2463 config.channel_layout = m_dllAvUtil.av_get_default_channel_layout(config.channels);
2464 dec_ctx->channel_layout = config.channel_layout;
2467 AVFrame *decoded_frame = NULL;
2468 decoded_frame = m_dllAvCodec.avcodec_alloc_frame();
2470 if (m_dllAvCodec.avcodec_open2(dec_ctx, dec, NULL) >= 0)
2475 m_dllAvCodec.av_init_packet(&avpkt);
2477 while (m_dllAvFormat.av_read_frame(fmt_ctx, &avpkt) >= 0)
2480 len = m_dllAvCodec.avcodec_decode_audio4(dec_ctx, decoded_frame, &got_frame, &avpkt);
2483 m_dllAvCodec.avcodec_close(dec_ctx);
2484 m_dllAvUtil.av_free(dec_ctx);
2485 m_dllAvUtil.av_free(&decoded_frame);
2486 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2494 int samples = fileSize / m_dllAvUtil.av_get_bytes_per_sample(dec_ctx->sample_fmt) / config.channels;
2495 config.fmt = dec_ctx->sample_fmt;
2496 config.bits_per_sample = dec_ctx->bits_per_coded_sample;
2497 sound->InitSound(true, config, samples);
2500 sound->StoreSound(true, decoded_frame->extended_data,
2501 decoded_frame->nb_samples, decoded_frame->linesize[0]);
2504 m_dllAvCodec.avcodec_close(dec_ctx);
2507 m_dllAvUtil.av_free(dec_ctx);
2508 m_dllAvUtil.av_free(decoded_frame);
2509 m_dllAvFormat.avformat_close_input(&fmt_ctx);
2514 m_dataPort.SendOutMessage(CActiveAEDataProtocol::NEWSOUND, &sound, sizeof(CActiveAESound*));
2519 void CActiveAE::FreeSound(IAESound *sound)
2521 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESOUND, &sound, sizeof(CActiveAESound*));
2524 void CActiveAE::PlaySound(CActiveAESound *sound)
2526 m_dataPort.SendOutMessage(CActiveAEDataProtocol::PLAYSOUND, &sound, sizeof(CActiveAESound*));
2529 void CActiveAE::StopSound(CActiveAESound *sound)
2531 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STOPSOUND, &sound, sizeof(CActiveAESound*));
2535 * resample sounds to destination format for mixing
2536 * destination format is either format of stream or
2537 * default sink format when no stream is playing
2539 void CActiveAE::ResampleSounds()
2541 if (m_settings.guisoundmode == AE_SOUND_OFF ||
2542 (m_settings.guisoundmode == AE_SOUND_IDLE && !m_streams.empty()))
2545 std::vector<CActiveAESound*>::iterator it;
2546 for (it = m_sounds.begin(); it != m_sounds.end(); ++it)
2548 if (!(*it)->IsConverted())
2551 // only do one sound, then yield to main loop
2557 bool CActiveAE::ResampleSound(CActiveAESound *sound)
2559 SampleConfig orig_config, dst_config;
2560 uint8_t **dst_buffer;
2563 if (m_mode == MODE_RAW || m_internalFormat.m_dataFormat == AE_FMT_INVALID)
2566 if (!sound->GetSound(true))
2569 orig_config = sound->GetSound(true)->config;
2571 dst_config.channel_layout = CActiveAEResample::GetAVChannelLayout(m_internalFormat.m_channelLayout);
2572 dst_config.channels = m_internalFormat.m_channelLayout.Count();
2573 dst_config.sample_rate = m_internalFormat.m_sampleRate;
2574 dst_config.fmt = CActiveAEResample::GetAVSampleFormat(m_internalFormat.m_dataFormat);
2575 dst_config.bits_per_sample = CAEUtil::DataFormatToUsedBits(m_internalFormat.m_dataFormat);
2577 CActiveAEResample *resampler = new CActiveAEResample();
2578 resampler->Init(dst_config.channel_layout,
2579 dst_config.channels,
2580 dst_config.sample_rate,
2582 dst_config.bits_per_sample,
2583 orig_config.channel_layout,
2584 orig_config.channels,
2585 orig_config.sample_rate,
2587 orig_config.bits_per_sample,
2591 m_settings.resampleQuality);
2593 dst_samples = resampler->CalcDstSampleCount(sound->GetSound(true)->nb_samples,
2594 m_internalFormat.m_sampleRate,
2595 orig_config.sample_rate);
2597 dst_buffer = sound->InitSound(false, dst_config, dst_samples);
2603 int samples = resampler->Resample(dst_buffer, dst_samples,
2604 sound->GetSound(true)->data,
2605 sound->GetSound(true)->nb_samples,
2608 sound->GetSound(false)->nb_samples = samples;
2611 sound->SetConverted(true);
2615 //-----------------------------------------------------------------------------
2617 //-----------------------------------------------------------------------------
2619 IAEStream *CActiveAE::MakeStream(enum AEDataFormat dataFormat, unsigned int sampleRate, unsigned int encodedSampleRate, CAEChannelInfo channelLayout, unsigned int options)
2621 //TODO: pass number of samples in audio packet
2623 AEAudioFormat format;
2624 format.m_dataFormat = dataFormat;
2625 format.m_sampleRate = sampleRate;
2626 format.m_encodedRate = encodedSampleRate;
2627 format.m_channelLayout = channelLayout;
2628 format.m_frames = format.m_sampleRate / 10;
2629 format.m_frameSize = format.m_channelLayout.Count() *
2630 (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
2633 msg.format = format;
2634 msg.options = options;
2637 if (m_dataPort.SendOutMessageSync(CActiveAEDataProtocol::NEWSTREAM,
2639 &msg, sizeof(MsgStreamNew)))
2641 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2644 CActiveAEStream *stream = *(CActiveAEStream**)reply->data;
2651 CLog::Log(LOGERROR, "ActiveAE::%s - could not create stream", __FUNCTION__);
2655 IAEStream *CActiveAE::FreeStream(IAEStream *stream)
2657 m_dataPort.SendOutMessage(CActiveAEDataProtocol::FREESTREAM, &stream, sizeof(IAEStream*));
2661 void CActiveAE::FlushStream(CActiveAEStream *stream)
2664 if (m_controlPort.SendOutMessageSync(CActiveAEControlProtocol::FLUSHSTREAM,
2666 &stream, sizeof(CActiveAEStream*)))
2668 bool success = reply->signal == CActiveAEControlProtocol::ACC;
2672 CLog::Log(LOGERROR, "CActiveAE::FlushStream - failed");
2677 void CActiveAE::PauseStream(CActiveAEStream *stream, bool pause)
2679 // TODO pause sink, needs api change
2681 m_controlPort.SendOutMessage(CActiveAEControlProtocol::PAUSESTREAM,
2682 &stream, sizeof(CActiveAEStream*));
2684 m_controlPort.SendOutMessage(CActiveAEControlProtocol::RESUMESTREAM,
2685 &stream, sizeof(CActiveAEStream*));
2688 void CActiveAE::SetStreamAmplification(CActiveAEStream *stream, float amplify)
2690 MsgStreamParameter msg;
2691 msg.stream = stream;
2692 msg.parameter.float_par = amplify;
2693 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMAMP,
2694 &msg, sizeof(MsgStreamParameter));
2697 void CActiveAE::SetStreamReplaygain(CActiveAEStream *stream, float rgain)
2699 MsgStreamParameter msg;
2700 msg.stream = stream;
2701 msg.parameter.float_par = rgain;
2702 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRGAIN,
2703 &msg, sizeof(MsgStreamParameter));
2706 void CActiveAE::SetStreamVolume(CActiveAEStream *stream, float volume)
2708 MsgStreamParameter msg;
2709 msg.stream = stream;
2710 msg.parameter.float_par = volume;
2711 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMVOLUME,
2712 &msg, sizeof(MsgStreamParameter));
2715 void CActiveAE::SetStreamResampleRatio(CActiveAEStream *stream, double ratio)
2717 MsgStreamParameter msg;
2718 msg.stream = stream;
2719 msg.parameter.double_par = ratio;
2720 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMRESAMPLERATIO,
2721 &msg, sizeof(MsgStreamParameter));
2724 void CActiveAE::SetStreamFade(CActiveAEStream *stream, float from, float target, unsigned int millis)
2727 msg.stream = stream;
2729 msg.target = target;
2730 msg.millis = millis;
2731 m_controlPort.SendOutMessage(CActiveAEControlProtocol::STREAMFADE,
2732 &msg, sizeof(MsgStreamFade));
2735 void CActiveAE::RegisterAudioCallback(IAudioCallback* pCallback)
2737 CSingleLock lock(m_vizLock);
2738 m_audioCallback = pCallback;
2739 m_vizInitialized = false;
2742 void CActiveAE::UnregisterAudioCallback()
2744 CSingleLock lock(m_vizLock);
2745 m_audioCallback = NULL;