os/kernelhwsrv/kernel/eka/drivers/soundsc/soundldd.cpp
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/kernelhwsrv/kernel/eka/drivers/soundsc/soundldd.cpp	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,3000 @@
     1.4 +// Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
     1.5 +// All rights reserved.
     1.6 +// This component and the accompanying materials are made available
     1.7 +// under the terms of the License "Eclipse Public License v1.0"
     1.8 +// which accompanies this distribution, and is available
     1.9 +// at the URL "http://www.eclipse.org/legal/epl-v10.html".
    1.10 +//
    1.11 +// Initial Contributors:
    1.12 +// Nokia Corporation - initial contribution.
    1.13 +//
    1.14 +// Contributors:
    1.15 +//
    1.16 +// Description:
    1.17 +// e32\drivers\soundsc\soundldd.cpp
    1.18 +// LDD for the shared chunk sound driver.
    1.19 +// 
    1.20 +//
    1.21 +
    1.22 +/**
    1.23 + @file
    1.24 + @internalTechnology
    1.25 + @prototype
    1.26 +*/
    1.27 +
    1.28 +#include <drivers/soundsc.h>
    1.29 +#include <kernel/kern_priv.h>
    1.30 +#include <kernel/cache.h>
    1.31 +
    1.32 +//#define USE_PLAY_EOF_TIMER
    1.33 +
    1.34 +// Define TEST_WITH_PAGING_CACHE_FLUSHES to flush the paging cache when testing read/writes to user thread in a data-paging system
    1.35 +//#define TEST_WITH_PAGING_CACHE_FLUSHES
    1.36 +
    1.37 +static const char KSoundLddPanic[]="Sound LDD";
    1.38 +
    1.39 +LOCAL_C TInt HighestCapabilitySupported(TUint32 aCapsBitField)
    1.40 +	{
    1.41 +	TInt n;
    1.42 +	for (n=31 ; n>=0 ; n--)
    1.43 +		{
    1.44 +		if (aCapsBitField&(1<<n))
    1.45 +			break;
    1.46 +		}
    1.47 +	return(n);
    1.48 +	}
    1.49 +
    1.50 +/**
    1.51 +Standard export function for LDDs. This creates a DLogicalDevice derived object,
    1.52 +in this case, DSoundScLddFactory.
    1.53 +*/
    1.54 +DECLARE_STANDARD_LDD()
    1.55 +	{
    1.56 +	return new DSoundScLddFactory;
    1.57 +	}
    1.58 +
    1.59 +/**
    1.60 +Constructor for the sound driver factory class.
    1.61 +*/
    1.62 +DSoundScLddFactory::DSoundScLddFactory()
    1.63 +	{
    1.64 +//	iUnitsOpenMask=0;
    1.65 +
    1.66 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLddFactory::DSoundScLddFactory"));
    1.67 +
    1.68 +	// Set version number for this device.
    1.69 +	iVersion=RSoundSc::VersionRequired();
    1.70 +	
    1.71 +	// Indicate that units / PDD are supported.
    1.72 +	iParseMask=KDeviceAllowUnit|KDeviceAllowPhysicalDevice;
    1.73 +	
    1.74 +	// Leave the units decision to the PDD
    1.75 +	iUnitsMask=0xffffffff;
    1.76 +	}
    1.77 +	
    1.78 +/**
    1.79 +Second stage constructor for the sound driver factory class.
    1.80 +This must at least set a name for the driver object.
    1.81 +@return KErrNone if successful, otherwise one of the other system wide error codes.
    1.82 +*/
    1.83 +TInt DSoundScLddFactory::Install()
    1.84 +	{
    1.85 +	return(SetName(&KDevSoundScName));
    1.86 +	}
    1.87 +
    1.88 +/**
    1.89 +Return the 'capabilities' of the sound driver in general.
    1.90 +Called in the response to an RDevice::GetCaps() request.
    1.91 +@param aDes A user-side descriptor to write the capabilities information into.
    1.92 +*/
    1.93 +void DSoundScLddFactory::GetCaps(TDes8& aDes) const
    1.94 +	{
    1.95 +	// Create a capabilities object
    1.96 +	TCapsSoundScV01 caps;
    1.97 +	caps.iVersion=iVersion;
    1.98 +	
    1.99 +	// Write it back to user memory
   1.100 +	Kern::InfoCopy(aDes,(TUint8*)&caps,sizeof(caps));
   1.101 +	}
   1.102 +
   1.103 +/**
   1.104 +Called by the kernel's device driver framework to create a logical channel.
   1.105 +This is called in the context of the client thread which requested the creation of a logical channel.
   1.106 +The thread is in a critical section.
   1.107 +@param aChannel Set by this function to point to the created logical channel.
   1.108 +@return KErrNone if successful, otherwise one of the other system wide error codes.
   1.109 +*/
   1.110 +TInt DSoundScLddFactory::Create(DLogicalChannelBase*& aChannel)
   1.111 +	{
   1.112 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLddFactory::Create"));
   1.113 +	aChannel=new DSoundScLdd;
   1.114 +	if (!aChannel)
   1.115 +		return(KErrNoMemory);
   1.116 +
   1.117 +	return(KErrNone);
   1.118 +	}
   1.119 +	
   1.120 +/**
   1.121 +Check whether a channel has is currently open on the specified unit.
   1.122 +@param aUnit The number of the unit to be checked.
   1.123 +@return ETrue if a channel is open on the specified channel, EFalse otherwise.
   1.124 +@pre The unit info. mutex must be held.
   1.125 +*/
   1.126 +TBool DSoundScLddFactory::IsUnitOpen(TInt aUnit)
   1.127 +	{
   1.128 +	return(iUnitsOpenMask&(1<<aUnit));
   1.129 +	}
   1.130 +
   1.131 +/**
   1.132 +Attempt to change the state of the channel open status for a particular channel.
   1.133 +@param aUnit The number of the unit to be updated.
   1.134 +@param aIsOpenSetting The required new state for the channel open status: either ETrue to set the status to open or 
   1.135 +	EFalse to set the status to closed.
   1.136 +@return KErrNone if the status was updated successfully, KErrInUse if an attempt has been made to set the channnel status
   1.137 +	to open while it is already open.
   1.138 +*/		
   1.139 +TInt DSoundScLddFactory::SetUnitOpen(TInt aUnit,TBool aIsOpenSetting)
   1.140 +	{
   1.141 +	NKern::FMWait(&iUnitInfoMutex); // Acquire the unit info. mutex.
   1.142 +	
   1.143 +	// Fail a request to open an channel that is already open
   1.144 +	if (aIsOpenSetting && IsUnitOpen(aUnit))
   1.145 +		{
   1.146 +		NKern::FMSignal(&iUnitInfoMutex); // Release the unit info. mutex.
   1.147 +		return(KErrInUse);
   1.148 +		}
   1.149 +	
   1.150 +	// Update the open status as requested
   1.151 +	if (aIsOpenSetting)
   1.152 +		iUnitsOpenMask|=(1<<aUnit);
   1.153 +	else
   1.154 +		iUnitsOpenMask&=~(1<<aUnit);
   1.155 +	
   1.156 +	NKern::FMSignal(&iUnitInfoMutex); // Release the unit info. mutex.	
   1.157 +	return(KErrNone);
   1.158 +	}	
   1.159 +
   1.160 +/**
   1.161 +Constructor for the sound driver logical channel.
   1.162 +*/
   1.163 +DSoundScLdd::DSoundScLdd()
   1.164 +	: iPowerDownDfc(DSoundScLdd::PowerDownDfc,this,3),
   1.165 +	  iPowerUpDfc(DSoundScLdd::PowerUpDfc,this,3),
   1.166 +	  iEofTimer(DSoundScLdd::PlayEofTimerExpired,this),
   1.167 +	  iPlayEofDfc(DSoundScLdd::PlayEofTimerDfc,this,3)
   1.168 +	{
   1.169 +//	iDirection=ESoundDirRecord;
   1.170 +//	iState=EOpen;
   1.171 +// 	iBufConfig=NULL;
   1.172 +//	iPowerHandler=NULL;
   1.173 +//	iSoundConfigFlags=0;
   1.174 +//	iBytesTransferred=0;
   1.175 +//	iBufManager=NULL;
   1.176 +//	iTestSettings=0;
   1.177 +//	iPlayEofTimerActive=EFalse;
   1.178 +//	iThreadOpenCount=0;
   1.179 +
   1.180 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DSoundScLdd"));
   1.181 +
   1.182 +	iUnit=-1;	// Invalid unit number
   1.183 +	
   1.184 +	// Many drivers would open the client thread's DThread object here. However, since this driver allows a channel to be shared by multiple client 
   1.185 +	// threads - we have to open and close the relevent DThread object for each request. 
   1.186 +	}
   1.187 +
   1.188 +/**
   1.189 +Destructor for the sound driver logical channel.
   1.190 +*/
   1.191 +DSoundScLdd::~DSoundScLdd()
   1.192 +	{
   1.193 +
   1.194 +	if (iNotifyChangeOfHwClientRequest)
   1.195 +		Kern::DestroyClientRequest(iNotifyChangeOfHwClientRequest);
   1.196 +
   1.197 +	// Free the TClientRequest structures associated with requests
   1.198 +	if (iClientRequests)
   1.199 +		{
   1.200 +		for (TInt index=0; index<RSoundSc::ERequestRecordData+1; ++index)
   1.201 +			if (iClientRequests[index])
   1.202 +				Kern::DestroyClientRequest(iClientRequests[index]);
   1.203 +
   1.204 +		delete[] iClientRequests;
   1.205 +		}
   1.206 +
   1.207 +	// Check if we need to delete the shared chunk / audio buffers.
   1.208 +	if (iBufManager)
   1.209 +		delete iBufManager;
   1.210 +	
   1.211 +	// Delete any memory allocated to hold the current buffer configuration.
   1.212 +	if (iBufConfig)
   1.213 +		delete iBufConfig;
   1.214 +	
   1.215 +	// Remove and delete the power handler.
   1.216 +	if (iPowerHandler)
   1.217 +		{
   1.218 +		iPowerHandler->Remove(); 
   1.219 +		delete iPowerHandler;
   1.220 +		}
   1.221 +		
   1.222 +	// Delete the request queue
   1.223 +	if (iReqQueue)
   1.224 +		delete iReqQueue;		
   1.225 +	
   1.226 +	__ASSERT_DEBUG(iThreadOpenCount==0,Kern::Fault(KSoundLddPanic,__LINE__));	
   1.227 +	
   1.228 +	// Clear the 'units open mask' in the LDD factory.
   1.229 +	if (iUnit>=0)
   1.230 +		((DSoundScLddFactory*)iDevice)->SetUnitOpen(iUnit,EFalse);
   1.231 +	}
   1.232 +	
   1.233 +/**
   1.234 +Second stage constructor for the sound driver - called by the kernel's device driver framework.
   1.235 +This is called in the context of the client thread which requested the creation of a logical channel.
   1.236 +The thread is in a critical section.
   1.237 +@param aUnit The unit argument supplied by the client.
   1.238 +@param aInfo The info argument supplied by the client. Always NULL in this case.
   1.239 +@param aVer The version argument supplied by the client.
   1.240 +@return KErrNone if successful, otherwise one of the other system wide error codes.
   1.241 +*/
   1.242 +TInt DSoundScLdd::DoCreate(TInt aUnit, const TDesC8* /*aInfo*/, const TVersion& aVer)
   1.243 +	{
   1.244 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DoCreate"));
   1.245 +	
   1.246 +	// Check the client has ECapabilityMultimediaDD capability.
   1.247 +	if (!Kern::CurrentThreadHasCapability(ECapabilityMultimediaDD,__PLATSEC_DIAGNOSTIC_STRING("Checked by ESOUNDSC.LDD (Sound driver)")))
   1.248 +		return(KErrPermissionDenied);
   1.249 +
   1.250 +	// Check that the sound driver version specified by the client is compatible.
   1.251 +	if (!Kern::QueryVersionSupported(RSoundSc::VersionRequired(),aVer))
   1.252 +		return(KErrNotSupported);
   1.253 +	
   1.254 +	// Check that a channel hasn't already been opened on this unit.
   1.255 +	TInt r=((DSoundScLddFactory*)iDevice)->SetUnitOpen(aUnit,ETrue); // Try to update 'units open mask' in the LDD factory.
   1.256 +	if (r!=KErrNone)
   1.257 +		return(r);
   1.258 +	iUnit=aUnit;
   1.259 +
   1.260 +	// Create a TClientRequest for each request that can be completed by the DFC thread.  These TClientRequest
   1.261 +	// instances are separate to those embedded in the TSoundScRequest structures and are used for requests that
   1.262 +	// have no associated TSoundScRequest structure or which are completing prematurely before they can be
   1.263 +	// associated with a TSoundScRequest structure
   1.264 +	if ((iClientRequests=new TClientRequest*[RSoundSc::ERequestRecordData+1])==NULL)
   1.265 +		return KErrNoMemory;
   1.266 +
   1.267 +	for (TInt index=0; index<RSoundSc::ERequestRecordData+1; ++index)
   1.268 +		if ((r=Kern::CreateClientRequest(iClientRequests[index]))!=KErrNone)
   1.269 +			return r;
   1.270 +
   1.271 +	if ((r=Kern::CreateClientDataRequest(iNotifyChangeOfHwClientRequest))!=KErrNone)
   1.272 +		return r;
   1.273 +
   1.274 +	// Initialise the PDD
   1.275 +	Pdd()->iLdd=this;
   1.276 +	
   1.277 +	// Read back the capabilities of this device from the PDD and determine the data transfer direction for this unit.
   1.278 +	TPckg<TSoundFormatsSupportedV02> capsBuf(iCaps);
   1.279 +	Pdd()->Caps(capsBuf);
   1.280 +	iDirection=iCaps.iDirection;
   1.281 +
   1.282 +	// Check the client has UserEnvironment capability if recording.
   1.283 +	if(iDirection==ESoundDirRecord)
   1.284 +		{
   1.285 +		if (!Kern::CurrentThreadHasCapability(ECapabilityUserEnvironment,__PLATSEC_DIAGNOSTIC_STRING("Checked by ESOUNDSC.LDD (Sound driver)")))
   1.286 +			return(KErrPermissionDenied);
   1.287 +		}
   1.288 +	
   1.289 +	// Create the appropriate request queue
   1.290 +	if (iDirection==ESoundDirPlayback)
   1.291 +		iReqQueue=new TSoundScPlayRequestQueue(this);
   1.292 +	else
   1.293 +		iReqQueue=new TSoundScRequestQueue(this);
   1.294 +	if (!iReqQueue)
   1.295 +		return(KErrNoMemory);
   1.296 +	r=iReqQueue->Create();
   1.297 +	if (r!=KErrNone)
   1.298 +		return(r);
   1.299 +	
   1.300 +	// Setup the default audio configuration acording to these capabilities.
   1.301 +	iSoundConfig.iChannels=HighestCapabilitySupported(iCaps.iChannels)+1;
   1.302 +	__ASSERT_ALWAYS(iSoundConfig.iChannels>0,Kern::Fault(KSoundLddPanic,__LINE__));
   1.303 +	iSoundConfig.iRate=(TSoundRate)HighestCapabilitySupported(iCaps.iRates);
   1.304 +	__ASSERT_ALWAYS(iSoundConfig.iRate>=0,Kern::Fault(KSoundLddPanic,__LINE__));
   1.305 +	iSoundConfig.iEncoding=(TSoundEncoding)HighestCapabilitySupported(iCaps.iEncodings);
   1.306 +	__ASSERT_ALWAYS(iSoundConfig.iEncoding>=0,Kern::Fault(KSoundLddPanic,__LINE__));
   1.307 +	iSoundConfig.iDataFormat=(TSoundDataFormat)HighestCapabilitySupported(iCaps.iDataFormats);
   1.308 +	__ASSERT_ALWAYS(iSoundConfig.iDataFormat>=0,Kern::Fault(KSoundLddPanic,__LINE__));
   1.309 +	__ASSERT_ALWAYS(ValidateConfig(iSoundConfig)==KErrNone,Kern::Fault(KSoundLddPanic,__LINE__));
   1.310 +	iSoundConfigFlags=0;
   1.311 +	
   1.312 +	// Setup the default setting for the record level / play volume.
   1.313 +	iVolume=KSoundMaxVolume;
   1.314 +		
   1.315 +	// Set up the correct DFC queue
   1.316 +	TDfcQue* dfcq=((DSoundScPdd*)iPdd)->DfcQ(aUnit);
   1.317 +	SetDfcQ(dfcq);
   1.318 +	iPowerDownDfc.SetDfcQ(dfcq);
   1.319 +	iPowerUpDfc.SetDfcQ(dfcq);
   1.320 +	iMsgQ.Receive();
   1.321 +	
   1.322 +	// Create the power handler
   1.323 +	iPowerHandler=new DSoundScPowerHandler(this);
   1.324 +	if (!iPowerHandler)
   1.325 +		return(KErrNoMemory);
   1.326 +	iPowerHandler->Add();
   1.327 +	
   1.328 +	// Power up the hardware.
   1.329 +	r=Pdd()->PowerUp();
   1.330 +	
   1.331 +	return(r);
   1.332 +	}
   1.333 +	
   1.334 +/**
   1.335 +Shutdown the audio device.
   1.336 +Terminate all device activity and power down the hardware.
   1.337 +*/
   1.338 +void DSoundScLdd::Shutdown()
   1.339 +	{
   1.340 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::Shutdown"));
   1.341 +
   1.342 +	Pdd()->StopTransfer();
   1.343 +	
   1.344 +	// Power down the hardware
   1.345 +	Pdd()->PowerDown();
   1.346 +
   1.347 +	// Cancel any requests that we may be handling	
   1.348 +	DoCancel(RSoundSc::EAllRequests);
   1.349 +	
   1.350 +	iState=EOpen;
   1.351 +
   1.352 +	// Make sure DFCs and timers are not queued.
   1.353 +	iPowerDownDfc.Cancel();
   1.354 +	iPowerUpDfc.Cancel();
   1.355 +	CancelPlayEofTimer();
   1.356 +	}
   1.357 +	
   1.358 +/**
   1.359 +Process a request on this logical channel
   1.360 +Called in the context of the client thread.
   1.361 +@param aReqNo The request number:
   1.362 +  	          ==KMaxTInt: a 'DoCancel' message;
   1.363 +	          >=0: a 'DoControl' message with function number equal to value.
   1.364 +	          <0: a 'DoRequest' message with function number equal to ~value.
   1.365 +@param a1 The first request argument. For DoRequest(), this is a pointer to the TRequestStatus.
   1.366 +@param a2 The second request argument. For DoRequest(), this is a pointer to the 2 actual TAny* arguments.
   1.367 +@return The result of the request. This is ignored by device driver framework for DoRequest().
   1.368 +*/ 
   1.369 +TInt DSoundScLdd::Request(TInt aReqNo, TAny* a1, TAny* a2)
   1.370 +	{
   1.371 +//	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::Request(%d)",aReqNo));
   1.372 +	TInt r;
   1.373 +	
   1.374 +	// Check for DoControl or DoRequest functions which are configured to execute in kernel thread context. This
   1.375 +	// also applies to DoCancel functions and ERequestRecordData requests where recording mode is not yet enabled.
   1.376 +	if ((aReqNo<RSoundSc::EMsgControlMax && aReqNo>(~RSoundSc::EMsgRequestMax)) ||
   1.377 +	    aReqNo==KMaxTInt ||
   1.378 +	    ((~aReqNo)==RSoundSc::ERequestRecordData && (iState==EOpen || iState==EConfigured)) 
   1.379 +	   )
   1.380 +		{
   1.381 +		// Implement in the context of the kernel thread - prepare and issue a kernel message.
   1.382 +		r=DLogicalChannel::Request(aReqNo,a1,a2);		
   1.383 +		}	
   1.384 +	else
   1.385 +		{
   1.386 +		// Implement in the context of the client thread.	
   1.387 +		// Decode the message type and dispatch it to the relevent handler function.
   1.388 +		if ((TUint)aReqNo<(TUint)KMaxTInt)
   1.389 +			r=DoControl(aReqNo,a1,a2,&Kern::CurrentThread());	// DoControl - process the request.
   1.390 +		
   1.391 +		else
   1.392 +			{
   1.393 +			// DoRequest - read the arguments from the client thread and process the request.
   1.394 +			TAny* a[2];
   1.395 +			kumemget32(a,a2,sizeof(a)); 
   1.396 +			TRequestStatus* status=(TRequestStatus*)a1;
   1.397 +			NKern::ThreadEnterCS(); 				// Need to be in critical section while manipulating the request/buffer list (for record).
   1.398 +			r=DoRequest(~aReqNo,status,a[0],a[1],&Kern::CurrentThread());
   1.399 +		
   1.400 +			// Complete request if there was an error
   1.401 +			if (r!=KErrNone)
   1.402 +				CompleteRequest(&Kern::CurrentThread(),status,r);
   1.403 +			r=KErrNone;
   1.404 +			NKern::ThreadLeaveCS();
   1.405 +			}
   1.406 +		}
   1.407 +//	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::Request - %d",r));
   1.408 +	return(r);
   1.409 +	}
   1.410 +
   1.411 +/**
   1.412 +Send a message to the DFC thread for processing by HandleMsg().
   1.413 +
   1.414 +This function is called in the context of the client thread.
   1.415 +
   1.416 +Overridden to ensure client data is copied kernel-side to avoid page-faults.
   1.417 +
   1.418 +@param aMsg  The message to process.
   1.419 +
   1.420 +@return KErrNone if the message was send successfully, otherwise one of the other system-wide error
   1.421 +        codes.
   1.422 +*/
   1.423 +TInt DSoundScLdd::SendMsg(TMessageBase* aMsg)
   1.424 +	{
   1.425 +	// Executes in context of client thread
   1.426 +
   1.427 +	TThreadMessage& m=*(TThreadMessage*)aMsg;
   1.428 +    TInt id = m.iValue;
   1.429 +
   1.430 +	TInt r(KErrNone);
   1.431 +	if (id == ~RSoundSc::EMsgRequestPlayData)
   1.432 +		{
   1.433 +		r = PrePlay(aMsg);
   1.434 +		if (r!=KErrNone)
   1.435 +			{
   1.436 +			// This is an asynchronous request so need to return error through the TRequestStatus
   1.437 +			TRequestStatus* status = (TRequestStatus*)(m.Ptr0());
   1.438 +			Kern::RequestComplete(status,r);
   1.439 +			return(r);
   1.440 +			}
   1.441 +		r = DLogicalChannel::SendMsg(aMsg);
   1.442 +		if (r!=KErrNone)
   1.443 +			{
   1.444 +			iReqQueue->Free((TSoundScPlayRequest*)m.iArg[1]);	// Return the unused request object	
   1.445 +			}
   1.446 +		return(r);
   1.447 +		}
   1.448 +	else if (id == RSoundSc::EMsgControlSetBufChunkCreate || id == RSoundSc::EMsgControlSetBufChunkOpen)
   1.449 +		{
   1.450 +		r = PreSetBufferChunkCreateOrOpen(aMsg);
   1.451 +		if (r!=KErrNone)
   1.452 +			{
   1.453 +			return(r);
   1.454 +			}
   1.455 +		}
   1.456 +	else if (id == RSoundSc::EMsgControlSetAudioFormat)
   1.457 +		{
   1.458 +		r = PreSetSoundConfig(aMsg);
   1.459 +		if (r!=KErrNone)
   1.460 +			{
   1.461 +			return(r);
   1.462 +			}
   1.463 +		}
   1.464 +
   1.465 +	r = DLogicalChannel::SendMsg(aMsg);
   1.466 +		
   1.467 +
   1.468 +	return(r);
   1.469 +	}
   1.470 +
   1.471 +/**
   1.472 +PreProcess a play request on this logical channel
   1.473 +Called in the context of the client thread.
   1.474 +
   1.475 +@param aMsg  The message to process.
   1.476 +
   1.477 +@return KErrNone if the parameters are validated and request structure populated. Otherwise a system-wide error.
   1.478 +*/ 
   1.479 +TInt DSoundScLdd::PrePlay(TMessageBase* aMsg)
   1.480 +	{
   1.481 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::PrePlay"));
   1.482 +
   1.483 +	// Executes in context of client thread
   1.484 +
   1.485 +	TThreadMessage* m=(TThreadMessage*)aMsg;
   1.486 +
   1.487 +	// Copy play information to kernel side before checking
   1.488 +	SRequestPlayDataInfo info;
   1.489 +	kumemget(&info,m->iArg[1],sizeof(info));
   1.490 +
   1.491 +	__KTRACE_OPT(KSOUND1, Kern::Printf("DSoundScLdd::PrePlay - off %x len %x flg %x ",info.iBufferOffset,info.iLength,info.iFlags));
   1.492 +
   1.493 +	// validate parameters in the play structure
   1.494 +
   1.495 +	// Check that the offset argument is aligned correctly for the PDD.
   1.496 +	TUint32 alignmask=(1<<iCaps.iRequestAlignment)-1; // iRequestAlignment holds log to base 2 of alignment required
   1.497 +	if ((info.iBufferOffset & alignmask) != 0)
   1.498 +		return(KErrArgument);
   1.499 +	
   1.500 +	// Check that the length argument is compatible with the minimum request size required for the PDD.
   1.501 +	if (iCaps.iRequestMinSize && info.iLength%iCaps.iRequestMinSize)
   1.502 +		return(KErrArgument);
   1.503 +	
   1.504 +	// Check that the specified offset and length are valid in the chunk. If so, get a pointer to the corresponding 
   1.505 +	// audio buffer object.
   1.506 +	TAudioBuffer* buf;
   1.507 +	if (iBufManager)
   1.508 +		{
   1.509 +		TInt r=iBufManager->ValidateRegion(info.iBufferOffset,info.iLength,buf);
   1.510 +		if (r!=KErrNone)
   1.511 +			return(r);
   1.512 +		}
   1.513 +	else
   1.514 +		{
   1.515 +		return(KErrNotReady);
   1.516 +		}	
   1.517 +
   1.518 +	// Acquire a free request object and add it to the queue of pending requests.
   1.519 +	TSoundScPlayRequest* req=(TSoundScPlayRequest*)iReqQueue->NextFree();
   1.520 +	if (!req)
   1.521 +		return(KErrGeneral);										// Must have exceeded KMaxSndScRequestsPending.
   1.522 +	req->iTf.Init((TUint)buf,info.iBufferOffset,info.iLength,buf); 	// Use pointer to audio buffer as unique ID
   1.523 +	req->iFlags=info.iFlags;
   1.524 +
   1.525 +	// replace the argument with a pointer to the kernel-side structure
   1.526 +	m->iArg[1]=req;
   1.527 +	
   1.528 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::PrePlay"));
   1.529 +
   1.530 +	return(KErrNone);
   1.531 +	}
   1.532 +
   1.533 +/**
   1.534 +PreProcess a SetBufferChunkCreate and SetBufferChunkOpen on this logical channel
   1.535 +Called in the context of the client thread.
   1.536 +This is synchronous so only need one copy of the data on the kernel-side.
   1.537 +
   1.538 +@param aMsg  The message to process.
   1.539 +
   1.540 +@return KErrNone if the parameters are validated and request structure populated. Otherwise a system-wide error.
   1.541 +*/ 
   1.542 +TInt DSoundScLdd::PreSetBufferChunkCreateOrOpen(TMessageBase* aMsg)
   1.543 +	{
   1.544 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::PreSetBufferChunkCreateOrOpen"));
   1.545 +	TInt r(KErrNone);
   1.546 +
   1.547 +	TThreadMessage* m=(TThreadMessage*)aMsg;
   1.548 +
   1.549 +	TInt length, maxLength;
   1.550 +	const TDesC8* userDesc = (const TDesC8*)m->Ptr0();
   1.551 +	const TUint8* configData = Kern::KUDesInfo(*userDesc,length,maxLength);
   1.552 +
   1.553 +	//__KTRACE_OPT(KSOUND1, Kern::Printf("DSoundScLdd::PreSetBufferChunkCreateOrOpen - len %x maxlen %x",length,maxLength));
   1.554 +
   1.555 +	// check the descriptor length is >= the base class size
   1.556 +	TInt minDesLen=sizeof(TSharedChunkBufConfigBase);
   1.557 +	if (length<minDesLen)
   1.558 +		return(KErrArgument);
   1.559 +
   1.560 +	// Temporary copy of client-side buffer config structure  
   1.561 +	TSharedChunkBufConfigBase chunkBufConfig;
   1.562 +
   1.563 +	kumemget(&chunkBufConfig, configData, minDesLen);
   1.564 +
   1.565 +	//__KTRACE_OPT(KSOUND1, Kern::Printf("DSoundScLdd::PreSetBufferChunkCreateOrOpen - num %x size %x flg %x ",chunkBufConfig.iNumBuffers,chunkBufConfig.iBufferSizeInBytes,chunkBufConfig.iFlags));
   1.566 +
   1.567 +	// check the buffer argument
   1.568 +	if (chunkBufConfig.iNumBuffers<=0)
   1.569 +		return(KErrArgument);
   1.570 +
   1.571 +	// Validate the rest of the configuration supplied.
   1.572 +	if (chunkBufConfig.iBufferSizeInBytes<=0)
   1.573 +		return(KErrArgument);
   1.574 +
   1.575 +	if (iDirection==ESoundDirRecord)
   1.576 +		{
   1.577 +		// If this is a record channel then the size of each buffer must comply with the PDD contraints.
   1.578 +		if (iCaps.iRequestMinSize && chunkBufConfig.iBufferSizeInBytes%iCaps.iRequestMinSize)
   1.579 +			return(KErrArgument);
   1.580 +		}	
   1.581 +
   1.582 +	//Allocate space for the buffer list 
   1.583 +	NKern::ThreadEnterCS();
   1.584 +	r=ReAllocBufferConfigInfo(chunkBufConfig.iNumBuffers);
   1.585 +	NKern::ThreadLeaveCS();
   1.586 +	if (r!=KErrNone)
   1.587 +		return(r);
   1.588 +
   1.589 +	//__KTRACE_OPT(KSOUND1, Kern::Printf("DSoundScLdd::PreSetBufferChunkCreateOrOpen - cfg %x size %x",iBufConfig,iBufConfigSize));
   1.590 +
   1.591 +	// copy all data into the buffer list 
   1.592 +	kumemget(iBufConfig, configData, iBufConfigSize);
   1.593 +
   1.594 +	return(r);
   1.595 +	}
   1.596 +
   1.597 +/**
   1.598 +PreProcess a SetSoundConfig on this logical channel
   1.599 +Called in the context of the client thread.
   1.600 +This is synchronous so only need one copy of the data on the kernel-side.
   1.601 +
   1.602 +@param aMsg  The message to process.
   1.603 +
   1.604 +@return KErrNone if the parameters are validated and request structure populated. Otherwise a system-wide error.
   1.605 +*/ 
   1.606 +TInt DSoundScLdd::PreSetSoundConfig(TMessageBase* aMsg)
   1.607 +	{
   1.608 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::PreSetSoundConfig"));
   1.609 +
   1.610 +	TThreadMessage* m=(TThreadMessage*)aMsg;
   1.611 +
   1.612 +	TPtr8 localPtr((TUint8*)&iTempSoundConfig, sizeof(TCurrentSoundFormatV02));
   1.613 +
   1.614 +	Kern::KUDesGet(localPtr,*(const TDesC8*)m->Ptr0());
   1.615 +
   1.616 +	//__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::PreSetSoundConfig chan %x rate %x enc %x form %x",
   1.617 +	//	iTempSoundConfig.iChannels,iTempSoundConfig.iRate,iTempSoundConfig.iEncoding,iTempSoundConfig.iDataFormat));
   1.618 +
   1.619 +	// Check that it is compatible with this sound device.
   1.620 +	TInt r=ValidateConfig(iTempSoundConfig);
   1.621 +	
   1.622 +	return(r);
   1.623 +	}
   1.624 +
   1.625 +/**
   1.626 +Processes a message for this logical channel.
   1.627 +This function is called in the context of a DFC thread.
   1.628 +@param aMsg The message to process.
   1.629 +	        The iValue member of this distinguishes the message type:
   1.630 +	          iValue==ECloseMsg: channel close message.
   1.631 +	          iValue==KMaxTInt: a 'DoCancel' message
   1.632 +	          iValue>=0: a 'DoControl' message with function number equal to iValue
   1.633 +	          iValue<0: a 'DoRequest' message with function number equal to ~iValue
   1.634 +*/
   1.635 +void DSoundScLdd::HandleMsg(TMessageBase* aMsg)
   1.636 +	{
   1.637 +#ifdef _DEBUG
   1.638 +#ifdef TEST_WITH_PAGING_CACHE_FLUSHES
   1.639 +	Kern::SetRealtimeState(ERealtimeStateOn);  
   1.640 +	Kern::HalFunction(EHalGroupVM,EVMHalFlushCache,0,0);
   1.641 +#endif
   1.642 +#endif
   1.643 +
   1.644 +	TThreadMessage& m=*(TThreadMessage*)aMsg;
   1.645 +    TInt id=m.iValue;
   1.646 +//	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::HandleMsg(%d)",id));
   1.647 +    
   1.648 +	if (id==(TInt)ECloseMsg)
   1.649 +		{
   1.650 +		// Channel close.
   1.651 +		Shutdown();
   1.652 +		m.Complete(KErrNone,EFalse);
   1.653 +		return;
   1.654 +		}
   1.655 +    else if (id==KMaxTInt)
   1.656 +		{
   1.657 +		// DoCancel
   1.658 +		DoCancel(m.Int0());
   1.659 +		m.Complete(KErrNone,ETrue);
   1.660 +		return;
   1.661 +		}
   1.662 +    else if (id<0)
   1.663 +		{
   1.664 +		// DoRequest
   1.665 +		TRequestStatus* pS=(TRequestStatus*)m.Ptr0();
   1.666 +		TInt r=DoRequest(~id,pS,m.Ptr1(),m.Ptr2(),m.Client());
   1.667 +		if (r!=KErrNone)
   1.668 +			{
   1.669 +			iClientRequests[~id]->SetStatus(pS);
   1.670 +			CompleteRequest(m.Client(),NULL,r,iClientRequests[~id]);
   1.671 +			}
   1.672 +		m.Complete(KErrNone,ETrue);
   1.673 +		}
   1.674 +    else
   1.675 +		{
   1.676 +		// DoControl
   1.677 +		TInt r=DoControl(id,m.Ptr0(),m.Ptr1(),m.Client());
   1.678 +		m.Complete(r,ETrue);
   1.679 +		}
   1.680 +	}
   1.681 +
   1.682 +/**
   1.683 +Process a synchronous 'DoControl' request.
   1.684 +@param aFunction The request number.
   1.685 +@param a1 The first request argument.
   1.686 +@param a2 The second request argument.
   1.687 +@param aThread The client thread which issued the request.
   1.688 +@return The result of the request.
   1.689 +*/
   1.690 +TInt DSoundScLdd::DoControl(TInt aFunction,TAny* a1,TAny* a2,DThread* aThread)
   1.691 +	{
   1.692 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DoControl(%d)",aFunction));
   1.693 +	
   1.694 +	TInt r=KErrNotSupported;
   1.695 +	switch (aFunction)
   1.696 +		{
   1.697 +		case RSoundSc::EControlGetCaps:
   1.698 +			{
   1.699 +			// Return the capabilities for this device. Read this from the PDD and 
   1.700 +			// then write it to the client. 
   1.701 +			TSoundFormatsSupportedV02Buf caps;
   1.702 +			Pdd()->Caps(caps);
   1.703 +			Kern::InfoCopy(*((TDes8*)a1),caps);
   1.704 +			r=KErrNone;
   1.705 +			break;	
   1.706 +			}
   1.707 +		case RSoundSc::EControlGetAudioFormat:
   1.708 +			{
   1.709 +			// Write the current audio configuration back to the client.
   1.710 +			TPtrC8 ptr((const TUint8*)&iSoundConfig,sizeof(iSoundConfig));
   1.711 +			Kern::InfoCopy(*((TDes8*)a1),ptr);
   1.712 +			r=KErrNone;
   1.713 +			break;	
   1.714 +			}
   1.715 +		case RSoundSc::EMsgControlSetAudioFormat:
   1.716 +			{
   1.717 +			if (iState==EOpen || iState==EConfigured || iPlayEofTimerActive)
   1.718 +				{
   1.719 +				// If the play EOF timer is active then it is OK to change the audio configuration - but we
   1.720 +				// need to bring the PDD out of transfer mode first.
   1.721 +				if (iPlayEofTimerActive)
   1.722 +					{
   1.723 +					CancelPlayEofTimer();
   1.724 +					Pdd()->StopTransfer();
   1.725 +					}
   1.726 +				
   1.727 +				r=SetSoundConfig(); 
   1.728 +				if (r==KErrNone && (iSoundConfigFlags&KSndScVolumeIsSetup) && iBufConfig)
   1.729 +					iState=EConfigured;
   1.730 +				}		
   1.731 +			else
   1.732 +				r=KErrInUse;
   1.733 +			break;
   1.734 +			}
   1.735 +		case RSoundSc::EControlGetBufConfig:
   1.736 +			if (iBufConfig)
   1.737 +				{
   1.738 +				// Write the buffer config to the client.
   1.739 +				TPtrC8 ptr((const TUint8*)iBufConfig,iBufConfigSize);
   1.740 +				Kern::InfoCopy(*((TDes8*)a1),ptr);
   1.741 +				r=KErrNone;	
   1.742 +				}	
   1.743 +			break;
   1.744 +		case RSoundSc::EMsgControlSetBufChunkCreate:
   1.745 +			{
   1.746 +			if (iState==EOpen || iState==EConfigured || iPlayEofTimerActive)
   1.747 +				{
   1.748 +				// Need to be in critical section while deleting an exisiting config and creating a new one
   1.749 +				NKern::ThreadEnterCS();
   1.750 +				r=SetBufferConfig(aThread);
   1.751 +				NKern::ThreadLeaveCS();
   1.752 +				if (r==KErrNone && (iSoundConfigFlags&KSndScSoundConfigIsSetup) && (iSoundConfigFlags&KSndScVolumeIsSetup))
   1.753 +					iState=EConfigured; 		
   1.754 +				}
   1.755 +			else
   1.756 +				r=KErrInUse;
   1.757 +			break;
   1.758 +			}
   1.759 +		case RSoundSc::EMsgControlSetBufChunkOpen:
   1.760 +			{
   1.761 +			if (iState==EOpen || iState==EConfigured || iPlayEofTimerActive)
   1.762 +				{
   1.763 +				// Need to be in critical section while deleting an exisiting config and creating a new one
   1.764 +				NKern::ThreadEnterCS();
   1.765 +				r=SetBufferConfig((TInt)a2,aThread);
   1.766 +				NKern::ThreadLeaveCS();
   1.767 +				if (r==KErrNone && (iSoundConfigFlags&KSndScSoundConfigIsSetup) && (iSoundConfigFlags&KSndScVolumeIsSetup))
   1.768 +					iState=EConfigured; 		
   1.769 +				}
   1.770 +			else
   1.771 +				r=KErrInUse;
   1.772 +			break;
   1.773 +			}
   1.774 +		case RSoundSc::EControlGetVolume:
   1.775 +			r=iVolume;
   1.776 +			break;
   1.777 +		case RSoundSc::EMsgControlSetVolume:
   1.778 +			{
   1.779 +			r=SetVolume((TInt)a1);
   1.780 +			if (r==KErrNone && iState==EOpen && (iSoundConfigFlags&KSndScSoundConfigIsSetup) && iBufConfig)
   1.781 +				iState=EConfigured;
   1.782 +			break;	
   1.783 +			}
   1.784 +		case RSoundSc::EMsgControlCancelSpecific:
   1.785 +			{
   1.786 +			if (iDirection==ESoundDirPlayback)
   1.787 +				{
   1.788 +				// Don't try to cancel a play transfer that has already started - let it complete in its own time.
   1.789 +				TSoundScPlayRequest* req=(TSoundScPlayRequest*)iReqQueue->Find((TRequestStatus*)a1);
   1.790 +				if (req && req->iTf.iTfState==TSndScTransfer::ETfNotStarted)
   1.791 +					{
   1.792 +					iReqQueue->Remove(req);
   1.793 +					CompleteRequest(req->iOwningThread,NULL,KErrCancel,req->iClientRequest);
   1.794 +					iReqQueue->Free(req);
   1.795 +					}
   1.796 +				}
   1.797 +			else
   1.798 +				{
   1.799 +				// Need to aquire the buffer/request list mutex when removing record requests - RecordData() runs in
   1.800 +				// client thread context and this may access the queue. Record requests a treated differently to play
   1.801 +				// requests and you don't have to worry about record requests already being in progress.
   1.802 +				NKern::FMWait(&iMutex);
   1.803 +				TSoundScRequest* req=iReqQueue->Find((TRequestStatus*)a1);
   1.804 +				if (req)
   1.805 +					{
   1.806 +					iReqQueue->Remove(req);
   1.807 +					DThread* thread=req->iOwningThread;				// Take a copy before we free it.
   1.808 +					TClientRequest* clreq=req->iClientRequest;		// Take a copy before we free it.
   1.809 +					NKern::FMSignal(&iMutex);
   1.810 +					iReqQueue->Free(req);
   1.811 +					CompleteRequest(thread,NULL,KErrCancel,clreq);
   1.812 +					}
   1.813 +				else
   1.814 +					NKern::FMSignal(&iMutex);	
   1.815 +				}
   1.816 +			r=KErrNone;	
   1.817 +			break;	
   1.818 +			}
   1.819 +		case RSoundSc::EControlBytesTransferred:
   1.820 +			r=iBytesTransferred;
   1.821 +			break;
   1.822 +		case RSoundSc::EControlResetBytesTransferred:
   1.823 +			iBytesTransferred=0;
   1.824 +			r=KErrNone;	
   1.825 +			break;
   1.826 +		case RSoundSc::EMsgControlPause:
   1.827 +			if (iState==EActive)
   1.828 +				{
   1.829 +				// Have to update the status early here because a record PDD may call us back with RecordCallback() in
   1.830 +				// handling PauseTransfer() - to complete a partially filled buffer.  
   1.831 +				iState=EPaused;
   1.832 +				iCompletesWhilePausedCount=0;		
   1.833 +				r=Pdd()->PauseTransfer();
   1.834 +				if (r!=KErrNone)
   1.835 +					iState=EActive;
   1.836 +				else if (iDirection==ESoundDirRecord)
   1.837 +					{
   1.838 +					// For record, complete any pending record requests that are still outstanding following PauseTransfer().
   1.839 +					iReqQueue->CompleteAll(KErrCancel);	
   1.840 +					}
   1.841 +				}
   1.842 +			else
   1.843 +				r=KErrNotReady;	
   1.844 +			break;
   1.845 +		case RSoundSc::EMsgControlResume:
   1.846 +			if (iState==EPaused)
   1.847 +				{
   1.848 +				r=Pdd()->ResumeTransfer();
   1.849 +				if (r==KErrNone && iDirection==ESoundDirRecord)
   1.850 +					r=StartNextRecordTransfers();
   1.851 +				if (r==KErrNone)
   1.852 +					iState=EActive;	// Successfully resumed transfer - update the status.
   1.853 +				}
   1.854 +			else
   1.855 +				r=KErrNotReady;	
   1.856 +			break;
   1.857 +		case RSoundSc::EControlReleaseBuffer:
   1.858 +			if (iDirection==ESoundDirRecord)
   1.859 +				r=ReleaseBuffer((TInt)a1);
   1.860 +			break; 
   1.861 +		case RSoundSc::EMsgControlCustomConfig:
   1.862 +			r=CustomConfig((TInt)a1,a2);
   1.863 +			break;
   1.864 +		case RSoundSc::EControlTimePlayed:
   1.865 +			if (iDirection==ESoundDirPlayback)
   1.866 +				{
   1.867 +				TInt64 time=0;
   1.868 +				r=Pdd()->TimeTransferred(time,iState);
   1.869 +				TPtrC8 timePtr((TUint8*)&time,sizeof(TInt64));
   1.870 +				Kern::ThreadDesWrite(aThread,a1,timePtr,0,KTruncateToMaxLength,NULL);
   1.871 +				}
   1.872 +			else
   1.873 +				r=KErrNotSupported;
   1.874 +			break;
   1.875 +		case RSoundSc::EControlTimeRecorded:
   1.876 +			if (iDirection==ESoundDirRecord)
   1.877 +				{
   1.878 +				TInt64 time=0;
   1.879 +				r=Pdd()->TimeTransferred(time,iState);
   1.880 +				TPtrC8 timePtr((TUint8*)&time,sizeof(TInt64));
   1.881 +				Kern::ThreadDesWrite(aThread,a1,timePtr,0,KTruncateToMaxLength,NULL);
   1.882 +				}
   1.883 +			else
   1.884 +				r=KErrNotSupported;
   1.885 +			break;
   1.886 +		}
   1.887 +		
   1.888 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::DoControl - %d",r));
   1.889 +	return(r);
   1.890 +	}
   1.891 +
   1.892 +/**
   1.893 +Process an asynchronous 'DoRequest' request.
   1.894 +@param aFunction The request number.
   1.895 +@param aStatus A pointer to the TRequestStatus.
   1.896 +@param a1 The first request argument.
   1.897 +@param a2 The second request argument.
   1.898 +@param aThread The client thread which issued the request.
   1.899 +@return The result of the request.
   1.900 +*/
   1.901 +TInt DSoundScLdd::DoRequest(TInt aFunction, TRequestStatus* aStatus, TAny* a1, TAny* /*a2*/,DThread* aThread)
   1.902 +	{
   1.903 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DoRequest(%d)",aFunction));
   1.904 +	
   1.905 +	// Open a reference on the client thread while the request is pending so it's control block can't disappear until this driver has finished with it.
   1.906 +	TInt r=aThread->Open();
   1.907 +	__ASSERT_ALWAYS(r==KErrNone,Kern::Fault(KSoundLddPanic,__LINE__));
   1.908 +#ifdef _DEBUG
   1.909 +	__e32_atomic_add_ord32(&iThreadOpenCount, 1);
   1.910 +#endif		
   1.911 +
   1.912 +	r=KErrNotSupported;
   1.913 +	switch (aFunction)
   1.914 +		{
   1.915 +		case RSoundSc::EMsgRequestPlayData:
   1.916 +			{
   1.917 +			if (iDirection==ESoundDirPlayback)
   1.918 +				{
   1.919 +				if (iState==EOpen)
   1.920 +					{
   1.921 +					// Not yet fully configured - maybe we can use the default settings.
   1.922 +					r=KErrNone;
   1.923 +					if (!iBufConfig)
   1.924 +						r=KErrNotReady;	// Can't guess a default buffer configuration.
   1.925 +					else
   1.926 +						{
   1.927 +						if (!(iSoundConfigFlags&KSndScSoundConfigIsSetup))
   1.928 +							r=DoSetSoundConfig(iSoundConfig);	// Apply default sound configuration.
   1.929 +						if (r==KErrNone && !(iSoundConfigFlags&KSndScVolumeIsSetup))
   1.930 +							r=SetVolume(iVolume);				// Apply default volume level
   1.931 +						}
   1.932 +					if (r!=KErrNone)
   1.933 +						break;
   1.934 +					else
   1.935 +						iState=EConfigured;		
   1.936 +					}
   1.937 +					
   1.938 +				if (iState==EConfigured || iState==EActive || iState==EPaused)
   1.939 +					{
   1.940 +					r=PlayData(aStatus, (TSoundScPlayRequest*)a1,aThread);
   1.941 +					}
   1.942 +				else
   1.943 +					r=KErrNotReady;
   1.944 +				}
   1.945 +			break;
   1.946 +			}
   1.947 +		case RSoundSc::ERequestRecordData:
   1.948 +			if (iDirection==ESoundDirRecord)
   1.949 +				{
   1.950 +				// Check if the device has been configured yet
   1.951 +				if (iState==EOpen)
   1.952 +					{
   1.953 +					// Not yet fully configured - maybe we can use the default settings.
   1.954 +					r=KErrNone;
   1.955 +					if (!iBufConfig)
   1.956 +						r=KErrNotReady;	// Can't guess a default buffer configuration.
   1.957 +					else
   1.958 +						{
   1.959 +						if (!(iSoundConfigFlags&KSndScSoundConfigIsSetup))
   1.960 +							r=DoSetSoundConfig(iSoundConfig);	// Apply default sound configuration.
   1.961 +						if (r==KErrNone && !(iSoundConfigFlags&KSndScVolumeIsSetup))
   1.962 +							r=SetVolume(iVolume);				// Apply default volume level
   1.963 +						}
   1.964 +					if (r!=KErrNone)
   1.965 +						break;
   1.966 +					else
   1.967 +						iState=EConfigured;		
   1.968 +					}
   1.969 +				// Check if we need to start recording
   1.970 +				if (iState==EConfigured)
   1.971 +					{
   1.972 +					r=StartRecord();
   1.973 +					if (r!=KErrNone)
   1.974 +						break;
   1.975 +					else
   1.976 +						iState=EActive;
   1.977 +					}	
   1.978 +				
   1.979 +				// State must be either active or paused so process the record request as appropriate for these states.
   1.980 +				r=RecordData(aStatus,(TInt*)a1,aThread);
   1.981 +				}
   1.982 +			break;
   1.983 +		case RSoundSc::ERequestNotifyChangeOfHwConfig:
   1.984 +			{
   1.985 +			// Check if this device can detect changes in its hardware configuration.
   1.986 +			if (iCaps.iHwConfigNotificationSupport)
   1.987 +				{
   1.988 +				r=KErrNone;
   1.989 +				if (!iNotifyChangeOfHwClientRequest->IsReady())
   1.990 +					{
   1.991 +					iChangeOfHwConfigThread=aThread;
   1.992 +					iNotifyChangeOfHwClientRequest->SetDestPtr((TBool*)a1);
   1.993 +					r = iNotifyChangeOfHwClientRequest->SetStatus(aStatus);
   1.994 +					}
   1.995 +				else
   1.996 +					r=KErrInUse;
   1.997 +				}
   1.998 +			else
   1.999 +				r=KErrNotSupported;	
  1.1000 +			break;
  1.1001 +			}
  1.1002 +		}
  1.1003 +		
  1.1004 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::DoRequest - %d",r));
  1.1005 +	return(r);
  1.1006 +	}
  1.1007 +
  1.1008 +/**
  1.1009 +Process the cancelling of asynchronous requests.
  1.1010 +@param aMask A mask indicating which requests need to be cancelled.
  1.1011 +@return The result of the cancel.
  1.1012 +*/
  1.1013 +TInt DSoundScLdd::DoCancel(TUint aMask)
  1.1014 +	{
  1.1015 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DoCancel(%08x)",aMask));
  1.1016 +
  1.1017 +	if (aMask&(1<<RSoundSc::EMsgRequestPlayData))
  1.1018 +		{
  1.1019 +		Pdd()->StopTransfer();
  1.1020 +		iReqQueue->CompleteAll(KErrCancel);					// Cancel any outstanding play requests
  1.1021 +		if ((iState==EActive)||(iState==EPaused))
  1.1022 +			iState=EConfigured;
  1.1023 +		}
  1.1024 +	if (aMask&(1<<RSoundSc::ERequestRecordData))
  1.1025 +		{
  1.1026 +		Pdd()->StopTransfer();
  1.1027 +		iReqQueue->CompleteAll(KErrCancel,&iMutex);		// Cancel any outstanding record requests
  1.1028 +		if ((iState==EActive)||(iState==EPaused))
  1.1029 +			iState=EConfigured;
  1.1030 +		}
  1.1031 +	if (aMask&(1<<RSoundSc::ERequestNotifyChangeOfHwConfig))
  1.1032 +		{
  1.1033 +		// Complete any pending hardware change notifier with KErrCancel.
  1.1034 +		if (iNotifyChangeOfHwClientRequest->IsReady())
  1.1035 +			CompleteRequest(iChangeOfHwConfigThread,NULL,KErrCancel,iNotifyChangeOfHwClientRequest); 
  1.1036 +		}		
  1.1037 +	return(KErrNone);
  1.1038 +	}
  1.1039 +
  1.1040 +/**
  1.1041 +Set the current buffer configuration - creating a shared chunk.
  1.1042 +@param aBufferConfigBuf A packaged TSharedChunkBufConfigBase derived object holding the buffer configuration settings of
  1.1043 +	the shared chunk required.
  1.1044 +@param aThread The client thread which has requested to own the chunk.
  1.1045 +@return A handle to the shared chunk for the owning thread (a value >0), if successful;
  1.1046 +        otherwise one of the other system wide error codes, (a value <0).
  1.1047 +@pre The thread must be in a critical section. 
  1.1048 +*/	
  1.1049 +TInt DSoundScLdd::SetBufferConfig(DThread* aThread)
  1.1050 +	{
  1.1051 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:SetBufferConfig"));
  1.1052 +	
  1.1053 +	TInt r(KErrNone);
  1.1054 +
  1.1055 +	// Delete any existing buffers and the shared chunk.
  1.1056 +	if (iBufManager)
  1.1057 +		{
  1.1058 +		delete iBufManager;
  1.1059 +		iBufManager=NULL;
  1.1060 +		} 
  1.1061 +						
  1.1062 +	// If a handle to the shared chunk was created, close it, using the handle of the thread on which
  1.1063 +	// it was created, in case a different thread is now calling us
  1.1064 +	if (iChunkHandle>0)
  1.1065 +		{
  1.1066 +		Kern::CloseHandle(iChunkHandleThread,iChunkHandle);
  1.1067 +		iChunkHandle=0;
  1.1068 +		}
  1.1069 +
  1.1070 +	// Create the shared chunk, then create buffer objects for the committed buffers within it. This is
  1.1071 +	// done by creating a buffer manager - create the apppropraiate version according to the audio direction.
  1.1072 +	if (iDirection==ESoundDirPlayback)
  1.1073 +		iBufManager=new DBufferManager(this);
  1.1074 +	else
  1.1075 +		iBufManager=new DRecordBufferManager(this);
  1.1076 +	if (!iBufManager)
  1.1077 +		return(KErrNoMemory);
  1.1078 +	r=iBufManager->Create(iBufConfig);
  1.1079 +	if (r!=KErrNone)
  1.1080 +		{
  1.1081 +		delete iBufManager;
  1.1082 +		iBufManager=NULL;
  1.1083 +		return(r);
  1.1084 +		} 
  1.1085 +	
  1.1086 +	// Create handle to the shared chunk for the owning thread.
  1.1087 +	r=Kern::MakeHandleAndOpen(aThread,iBufManager->iChunk);
  1.1088 +
  1.1089 +	// And save the the chunk and thread handles for later.  Normally the chunk handle will be closed when the chunk
  1.1090 +	// is closed, but if the chunk is re-allocated then it will need to be closed before re-allocation.
  1.1091 +	iChunkHandle=r;
  1.1092 +	iChunkHandleThread=aThread;
  1.1093 +
  1.1094 +	return(r);
  1.1095 +	}	
  1.1096 +
  1.1097 +/**
  1.1098 +Set the current buffer configuration - using an existing shared chunk.
  1.1099 +@param aBufferConfigBuf A packaged TSharedChunkBufConfigBase derived object holding the buffer configuration settings of
  1.1100 +	the shared chunk supplied.
  1.1101 +@param aChunkHandle A handle for the shared chunk supplied by the client.
  1.1102 +@param aThread The thread in which the given handle is valid.
  1.1103 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.1104 +@pre The thread must be in a critical section. 
  1.1105 +*/	
  1.1106 +TInt DSoundScLdd::SetBufferConfig(TInt aChunkHandle,DThread* aThread)
  1.1107 +	{
  1.1108 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:SetBufferConfig(Handle-%d)",aChunkHandle));
  1.1109 +
  1.1110 +	TInt r(KErrNone);
  1.1111 +
  1.1112 +	// Delete any existing buffers and the shared chunk.
  1.1113 +	if (iBufManager)
  1.1114 +		{
  1.1115 +		delete iBufManager;
  1.1116 +		iBufManager=NULL;
  1.1117 +		} 
  1.1118 +	
  1.1119 +	// Open the shared chunk supplied and create buffer objects for the committed buffers within it. This is
  1.1120 +	// done by creating a buffer manager - create the apppropraiate version according to the audio direction.
  1.1121 +	if (iDirection==ESoundDirPlayback)
  1.1122 +		iBufManager=new DBufferManager(this);
  1.1123 +	else
  1.1124 +		iBufManager=new DRecordBufferManager(this);
  1.1125 +	if (!iBufManager)
  1.1126 +		return(KErrNoMemory);
  1.1127 +	r=iBufManager->Create(*iBufConfig,aChunkHandle,aThread);
  1.1128 +	if (r!=KErrNone)
  1.1129 +		{
  1.1130 +		delete iBufManager;
  1.1131 +		iBufManager=NULL;
  1.1132 +		} 
  1.1133 +	return(r);
  1.1134 +	}	
  1.1135 +
  1.1136 +/**
  1.1137 +Set the current audio format configuration.
  1.1138 +@param aSoundConfigBuf A packaged sound configuration object holding the new audio configuration settings to be used.
  1.1139 +@param aThread The client thread which contains the sound configuration object.
  1.1140 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.1141 +*/
  1.1142 +TInt DSoundScLdd::SetSoundConfig()
  1.1143 +	{
  1.1144 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:SetSoundConfig"));
  1.1145 +	
  1.1146 +	TInt r=DoSetSoundConfig(iTempSoundConfig);
  1.1147 +
  1.1148 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::SetSoundConfig - %d",KErrNone));
  1.1149 +	return(r);
  1.1150 +	}
  1.1151 +
  1.1152 +/**
  1.1153 +Apply a new audio format configuration.
  1.1154 +@param aSoundConfig A reference to a sound configuration object holding the new audio configuration settings to be applied.
  1.1155 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.1156 +*/	
  1.1157 +TInt DSoundScLdd::DoSetSoundConfig(const TCurrentSoundFormatV02& aSoundConfig)
  1.1158 +	{
  1.1159 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:DoSetSoundConfig"));
  1.1160 +		
  1.1161 +	// We're about to replace any previous configuration - so set the
  1.1162 +	// status back to un-configured in case we don't succeed with the new one.
  1.1163 +	iSoundConfigFlags&=~KSndScSoundConfigIsSetup;
  1.1164 +	
  1.1165 +	// Call the PDD to change the hardware configuration according to the new specification.
  1.1166 +	// Pass it as a descriptor - to support future changes to the config structure.
  1.1167 +	TPtrC8 ptr((TUint8*)&aSoundConfig,sizeof(aSoundConfig));
  1.1168 +	TInt r=Pdd()->SetConfig(ptr);
  1.1169 +	if (r!=KErrNone)
  1.1170 +		return(r);
  1.1171 +	
  1.1172 +	// Setting up the new play configuration has succeeded so save the new configuration.
  1.1173 +	iSoundConfig=aSoundConfig;
  1.1174 +	iSoundConfigFlags|=KSndScSoundConfigIsSetup;
  1.1175 +	
  1.1176 +	// For some devices, the maximum transfer length supported will vary according to the configuration.
  1.1177 +	if (iBufManager)
  1.1178 +		iBufManager->iMaxTransferLen=Pdd()->MaxTransferLen();
  1.1179 +	
  1.1180 +	return(r);
  1.1181 +	}	
  1.1182 +	
  1.1183 +/**
  1.1184 +Set the current play volume or record level.
  1.1185 +@param aVolume The play volume / record level to be set - a value in the range 0 to 255. The value 255 equates to
  1.1186 +	the maximum volume and each value below this equates to a 0.5dB step below it.
  1.1187 +@return KErrNone if successful, otherwise one of the other system wide error codes.	
  1.1188 +*/
  1.1189 +TInt DSoundScLdd::SetVolume(TInt aVolume)
  1.1190 +	{
  1.1191 +	TInt r;
  1.1192 +	// Check if the volume specified is in range.
  1.1193 +	if (aVolume>=0 && aVolume<=255)
  1.1194 +		{
  1.1195 +		// Check if we need to change it.
  1.1196 +		if (!(iSoundConfigFlags&KSndScVolumeIsSetup) || aVolume!=iVolume)
  1.1197 +			{
  1.1198 +			// We're about to replace any previous volume setting - so set the
  1.1199 +			// status back to un-set in case we don't succeed with the new setting.
  1.1200 +			iSoundConfigFlags&=~KSndScVolumeIsSetup;
  1.1201 +			
  1.1202 +			r=Pdd()->SetVolume(aVolume);
  1.1203 +			if (r==KErrNone)
  1.1204 +				{
  1.1205 +				iVolume=aVolume;
  1.1206 +				iSoundConfigFlags|=KSndScVolumeIsSetup;
  1.1207 +				}
  1.1208 +			}
  1.1209 +		else
  1.1210 +			r=KErrNone;	
  1.1211 +		}
  1.1212 +	else
  1.1213 +		r=KErrArgument;	
  1.1214 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::SetVolume(%d) - %d",aVolume,r));
  1.1215 +	return(r);
  1.1216 +	}
  1.1217 +	
  1.1218 +/**
  1.1219 +Handle a play request from the client.
  1.1220 +@param aStatus The request status to be signalled when the play request is complete.
  1.1221 +@param aChunkOffset Offset from the beginning of the play chunk for the start of data to be played.
  1.1222 +@param aLength The number of bytes of data to be played.
  1.1223 +@param aFlags The play request flags which were supplied by the client for this request.
  1.1224 +@param aThread The client thread which issued the request and which supplied the request status.
  1.1225 +@return KErrNone if successful;
  1.1226 +        KErrArgument if the offset or length arguments are not fully contained within a buffer or don't meet the
  1.1227 +        	alignment contraints of the PDD;
  1.1228 +        KErrNoMemory if a memory error was ecountered in the handling of this request.
  1.1229 +        otherwise one of the other system-wide error codes.
  1.1230 +*/
  1.1231 +TInt DSoundScLdd::PlayData(TRequestStatus* aStatus,TSoundScPlayRequest* aRequest,DThread* aThread)
  1.1232 +	{
  1.1233 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:PlayData(off:%x len:%d)",aRequest->iTf.GetStartOffset(),aRequest->iTf.GetNotStartedLen()));
  1.1234 +	
  1.1235 +	// Purge the region of the play chunk concerned.
  1.1236 +	iBufManager->FlushData(aRequest->iTf.GetStartOffset(),aRequest->iTf.GetNotStartedLen(),DBufferManager::EFlushBeforeDmaWrite);
  1.1237 +	
  1.1238 +	
  1.1239 +	TInt r(KErrNone);
  1.1240 +
  1.1241 +	// finalise the request data here
  1.1242 +	r = aRequest->iClientRequest->SetStatus(aStatus);
  1.1243 +	if (r!=KErrNone)
  1.1244 +		return(r);
  1.1245 +
  1.1246 +	aRequest->iOwningThread = aThread;
  1.1247 +
  1.1248 +
  1.1249 +	// Check whether we have started the codec yet.
  1.1250 +	CancelPlayEofTimer();
  1.1251 +	if (iState==EConfigured)
  1.1252 +		{
  1.1253 +		r=Pdd()->StartTransfer();
  1.1254 +	
  1.1255 +		// Test settings - only possible in debug mode. Test handling of an error returned from the PDD for StartTransfer().
  1.1256 +#ifdef _DEBUG	
  1.1257 +		if (iTestSettings & KSoundScTest_StartTransferError)
  1.1258 +			{
  1.1259 +			iTestSettings&=(~KSoundScTest_StartTransferError);
  1.1260 +			r=KErrTimedOut;
  1.1261 +			// Any time that StartTransfer() is called on the PDD it must have a matching StopTransfer() before
  1.1262 +			// it is called again
  1.1263 +			Pdd()->StopTransfer();
  1.1264 +			}
  1.1265 +#endif
  1.1266 +		}
  1.1267 +	
  1.1268 +	if (r==KErrNone)
  1.1269 +		{
  1.1270 +		// No further error is possible at this stage so add the request to the queue.
  1.1271 +		iReqQueue->Add(aRequest);
  1.1272 +		
  1.1273 +		if (iState!=EPaused)
  1.1274 +			{
  1.1275 +			iState=EActive;	
  1.1276 +			StartNextPlayTransfers(); // Queue as many transfer requests on the PDD as it can accept.
  1.1277 +			}
  1.1278 +		}
  1.1279 +	else
  1.1280 +		iReqQueue->Free(aRequest);	// Return the unused request object	
  1.1281 +	
  1.1282 +	return(r);
  1.1283 +	}
  1.1284 +	
  1.1285 +/**
  1.1286 +@publishedPartner
  1.1287 +@prototype
  1.1288 +
  1.1289 +Called from the PDD each time it has completed a data transfer from a play buffer.  This function must be called
  1.1290 +in the context of the DFC thread used for processing requests.
  1.1291 +The function performed here is to check whether the entire transfer for the current request is now complete. Also to
  1.1292 +queue further requests on the PDD which should now have the capability to accept more transfers. If the current
  1.1293 +request is complete then we signal completion to the client.
  1.1294 +@param aTransferID A value provided by the LDD when it initiated the transfer allowing the transfer fragment to be 
  1.1295 +	uniquely identified.
  1.1296 +@param aTransferResult The result of the transfer being completed: KErrNone if successful, otherwise one of the other
  1.1297 +	system wide error codes.
  1.1298 +@param aBytesPlayed The number of bytes played from the play buffer.	
  1.1299 +*/
  1.1300 +void DSoundScLdd::PlayCallback(TUint aTransferID,TInt aTransferResult,TInt aBytesPlayed)
  1.1301 +	{
  1.1302 +#ifdef _DEBUG
  1.1303 +#ifdef TEST_WITH_PAGING_CACHE_FLUSHES
  1.1304 +	Kern::HalFunction(EHalGroupVM,EVMHalFlushCache,0,0);
  1.1305 +#endif
  1.1306 +#endif
  1.1307 +	// Test settings - only possible in debug mode.
  1.1308 +#ifdef _DEBUG	
  1.1309 +	if (iTestSettings & KSoundScTest_TransferDataError)
  1.1310 +		{
  1.1311 +		iTestSettings&=(~KSoundScTest_TransferDataError);
  1.1312 +		aTransferResult=KErrTimedOut;
  1.1313 +		}
  1.1314 +#endif
  1.1315 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::PlayCallback(ID:%xH,Len:%d) - %d",aTransferID,aBytesPlayed,aTransferResult));		
  1.1316 +	
  1.1317 +	// The PDD has completed transfering a fragment. Find the associated request from its ID
  1.1318 +	TBool isNextToComplete;
  1.1319 +	TSoundScPlayRequest* req=((TSoundScPlayRequestQueue*)iReqQueue)->Find(aTransferID,isNextToComplete);
  1.1320 +	
  1.1321 +	// Check if this is a fragment from an earlier request which failed - which we should ignore. This is the case if the request cannot be found 
  1.1322 +	// (because it was already completed back to client) or if the request status is already set as 'done'. 
  1.1323 +	if (req && req->iTf.iTfState!=TSndScTransfer::ETfDone)
  1.1324 +		{
  1.1325 +		__ASSERT_DEBUG(req->iTf.iTfState!=TSndScTransfer::ETfNotStarted,Kern::Fault(KSoundLddPanic,__LINE__));
  1.1326 +		
  1.1327 +		// Update the count of bytes played.
  1.1328 +		iBytesTransferred+=aBytesPlayed;
  1.1329 +		
  1.1330 +		if (aTransferResult!=KErrNone)
  1.1331 +			{
  1.1332 +			// Transfer failed - immediately mark the request as being complete.
  1.1333 +			req->SetFail(aTransferResult);
  1.1334 +			}
  1.1335 +		else
  1.1336 +			req->UpdateProgress(aBytesPlayed);	// Transfer successful so update the progress of the request.
  1.1337 +									
  1.1338 +		// If we have just played an entire request and the PDD has not signalled it ahead of any earlier unfinished ones then complete it back to client.
  1.1339 +		if (req->iTf.iTfState==TSndScTransfer::ETfDone && isNextToComplete)
  1.1340 +			CompleteAllDonePlayRequests(req);
  1.1341 +		}
  1.1342 +	
  1.1343 +	// PDD should now have the capacity to accept another transfer so queue as many transfers
  1.1344 +	// on it as it can accept.
  1.1345 +	StartNextPlayTransfers();
  1.1346 +		
  1.1347 +	
  1.1348 +	return;
  1.1349 +	}
  1.1350 +	
  1.1351 +/**
  1.1352 +This function checks whether there are any outstanding play requests. While there are, it breaks these down into
  1.1353 +transfers sizes which are compatible with the PDD and then repeatedly attempts to queue these data transfers on the
  1.1354 +PDD until it indicates that it can accept no more for the moment.
  1.1355 +@post Data transfer may be stopped in the PDD and the operating state of the channel moved back to EConfigured.
  1.1356 +*/
  1.1357 +void DSoundScLdd::StartNextPlayTransfers()
  1.1358 +	{
  1.1359 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::StartNextPlayTransfers"));
  1.1360 +	
  1.1361 +	// Queue as many transfers on the PDD as it can accept.
  1.1362 +	TSoundScPlayRequest* req;
  1.1363 +	TInt r=KErrNone;
  1.1364 +	while (r==KErrNone && (req=((TSoundScPlayRequestQueue*)iReqQueue)->NextRequestForTransfer())!=NULL)
  1.1365 +		{
  1.1366 +		TInt pos=req->iTf.GetStartOffset();
  1.1367 +		TPhysAddr physAddr;
  1.1368 +		TInt len=req->iTf.iAudioBuffer->GetFragmentLength(pos,req->iTf.GetNotStartedLen(),physAddr);
  1.1369 +		if (len>0)
  1.1370 +			{
  1.1371 +			r=Pdd()->TransferData(req->iTf.iId,(iBufManager->iChunkBase+pos),physAddr,len);
  1.1372 +			__KTRACE_OPT(KSOUND1, Kern::Printf("<PDD:TransferData(off:%x len:%d) - %d",pos,len,r));
  1.1373 +			if (r==KErrNone)
  1.1374 +				req->iTf.SetStarted(len);	// Successfully queued a transfer - update the request status.
  1.1375 +			else if (r!=KErrNotReady)
  1.1376 +				{
  1.1377 +				// Transfer error from PDD, fail the request straight away. (Might not be the one at the head of queue).	
  1.1378 +				CompletePlayRequest(req,r);
  1.1379 +				}	
  1.1380 +			}
  1.1381 +		else
  1.1382 +			{
  1.1383 +			// This can only be a zero length play request - just complete it straight away
  1.1384 +			CompletePlayRequest(req,KErrNone);	
  1.1385 +			}
  1.1386 +		} 
  1.1387 +	return;	
  1.1388 +	}
  1.1389 +
  1.1390 +/**
  1.1391 +Complete a client play request back to the client and remove it from the request queue.
  1.1392 +@param aReq A pointer to the play request object to be completed.
  1.1393 +@post Data transfer may be stopped in the PDD and the operating state of the channel moved back to EConfigured.
  1.1394 +*/	
  1.1395 +void DSoundScLdd::DoCompletePlayRequest(TSoundScPlayRequest* aReq)
  1.1396 +	{
  1.1397 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::DoCompletePlayRequest(%x) - %d",aReq,aReq->iCompletionReason));
  1.1398 +	
  1.1399 +	iReqQueue->Remove(aReq);
  1.1400 +	
  1.1401 +	// If the request queue is now empty then turn off the codec
  1.1402 +	if (iReqQueue->IsEmpty())
  1.1403 +		{
  1.1404 +#ifdef USE_PLAY_EOF_TIMER
  1.1405 +		StartPlayEofTimer();
  1.1406 +#else
  1.1407 +		Pdd()->StopTransfer();
  1.1408 +		iState=EConfigured;
  1.1409 +#endif						
  1.1410 +		// This is an underflow situation.
  1.1411 +		if (aReq->iCompletionReason==KErrNone && aReq->iFlags!=KSndFlagLastSample)
  1.1412 +			aReq->iCompletionReason=KErrUnderflow;
  1.1413 +		}
  1.1414 +		
  1.1415 +	CompleteRequest(aReq->iOwningThread,NULL,aReq->iCompletionReason,aReq->iClientRequest);
  1.1416 +	iReqQueue->Free(aReq);
  1.1417 +	return;	
  1.1418 +	}
  1.1419 +
  1.1420 +/**
  1.1421 +Complete one or more play requests. This function completes the play request specified. It also completes any other play 
  1.1422 +requests which immediately follow the one specified in the play request queue and for which transfer has been completed by the PDD.
  1.1423 +@param aReq A pointer to the play request object to be completed.
  1.1424 +@post Data transfer may be stopped in the PDD and the operating state of the channel moved back to EConfigured.
  1.1425 +*/		
  1.1426 +void DSoundScLdd::CompleteAllDonePlayRequests(TSoundScPlayRequest* aReq)
  1.1427 +	{
  1.1428 +	TSoundScPlayRequest* nextReq=aReq;
  1.1429 +	TSoundScPlayRequest* req;
  1.1430 +	do 
  1.1431 +		{
  1.1432 +		req=nextReq;
  1.1433 +		nextReq=(TSoundScPlayRequest*)req->iNext;
  1.1434 +		DoCompletePlayRequest(req);
  1.1435 +		}
  1.1436 +	while (!iReqQueue->IsAnchor(nextReq) && nextReq->iTf.iTfState==TSndScTransfer::ETfDone);
  1.1437 +	return;	
  1.1438 +	}	
  1.1439 +		
  1.1440 +/**
  1.1441 +Start the audio device recording data.
  1.1442 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.1443 +*/
  1.1444 +TInt DSoundScLdd::StartRecord()
  1.1445 +	{
  1.1446 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::StartRecord"));
  1.1447 +		
  1.1448 +	// Reset all the audio buffer lists 
  1.1449 +	NKern::FMWait(&iMutex); 		// Acquire the buffer/request list mutex.
  1.1450 +	((DRecordBufferManager*)iBufManager)->Reset();
  1.1451 +	NKern::FMSignal(&iMutex); 		// Release the buffer/request list mutex.
  1.1452 +	
  1.1453 +	// Reset the transfer status for the current and pending record buffers.
  1.1454 +	TAudioBuffer* buf=((DRecordBufferManager*)iBufManager)->GetCurrentRecordBuffer();
  1.1455 +	iCurrentRecBufTf.Init((TUint)buf,buf->iChunkOffset,buf->iSize,buf);		// Use pointer to record buffer as unique ID
  1.1456 +	buf=((DRecordBufferManager*)iBufManager)->GetNextRecordBuffer();
  1.1457 +	iNextRecBufTf.Init((TUint)buf,buf->iChunkOffset,buf->iSize,buf);		// Use pointer to record buffer as unique ID
  1.1458 +	
  1.1459 +	// Call the PDD to prepare the hardware for recording.
  1.1460 +	TInt r=Pdd()->StartTransfer();
  1.1461 +	
  1.1462 +	// Test settings - only possible in debug mode. Test handling of an error returned from the PDD for StartTransfer().
  1.1463 +#ifdef _DEBUG	
  1.1464 +	if (iTestSettings & KSoundScTest_StartTransferError)
  1.1465 +		{
  1.1466 +		iTestSettings&=(~KSoundScTest_StartTransferError);
  1.1467 +		r=KErrTimedOut;
  1.1468 +		}
  1.1469 +#endif		
  1.1470 +	
  1.1471 +	// Initiate data transfer into the first record buffer(s).	
  1.1472 +	if (r==KErrNone)
  1.1473 +		r=StartNextRecordTransfers();
  1.1474 +	return(r);	
  1.1475 +	}
  1.1476 +	
  1.1477 +/**
  1.1478 +Handle a record request from the client once data transfer has been intiated.
  1.1479 +@param aStatus The request status to be signalled when the record request is complete. If the request is successful
  1.1480 +   then this is set to the offset within the shared chunk where the record data resides. Alternatively, if an error 
  1.1481 +   occurs, it will be set to one of the system wide error values.
  1.1482 +@param aLengthPtr A pointer to a TInt object in client memory. On completion, the number of bytes successfully
  1.1483 +   recorded are written to this object.
  1.1484 +@param aThread The client thread which issued the request and which supplied the request status.    	
  1.1485 +@return KErrNone if successful;
  1.1486 +		KErrInUse: if the client needs to free up record buffers before further record requests can be accepted;
  1.1487 +		KErrCancel: if the driver is in paused mode and there are no complete or partially full buffers to return.
  1.1488 +        otherwise one of the other system-wide error codes.
  1.1489 +*/
  1.1490 +TInt DSoundScLdd::RecordData(TRequestStatus* aStatus,TInt* aLengthPtr,DThread* aThread)
  1.1491 +	{
  1.1492 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd:RecordData"));
  1.1493 +	
  1.1494 +	TInt r=KErrNone;
  1.1495 +
  1.1496 +	NKern::FMWait(&iMutex); 		// Acquire the buffer/request list mutex.
  1.1497 +	 
  1.1498 +	// Check if we have had an overflow since the last record request was completed.
  1.1499 +	if (((DRecordBufferManager*)iBufManager)->iBufOverflow)
  1.1500 +		{
  1.1501 +		((DRecordBufferManager*)iBufManager)->iBufOverflow=EFalse;
  1.1502 +		NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.	
  1.1503 +		return(KErrOverflow);	
  1.1504 +		}
  1.1505 +	
  1.1506 +	// See if there is a buffer already available.
  1.1507 +	TAudioBuffer* buf=((DRecordBufferManager*)iBufManager)->GetBufferForClient();
  1.1508 +	if (buf)
  1.1509 +		{
  1.1510 +		// There is an buffer available already - complete the request returning the offset of the buffer to the client.
  1.1511 +		NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.
  1.1512 +		
  1.1513 +		r=buf->iResult;
  1.1514 +
  1.1515 +		if (r==KErrNone)
  1.1516 +			{
  1.1517 +			kumemput(aLengthPtr,&buf->iBytesAdded,sizeof(TInt));
  1.1518 +			// Only complete if successful here. Errors will be completed on returning from this method.
  1.1519 +			CompleteRequest(aThread,aStatus,(buf->iChunkOffset));
  1.1520 +			}
  1.1521 +		return(r);	
  1.1522 +		}
  1.1523 +	
  1.1524 +	// If we are paused and there was no un-read data to return to the client then return KErrCancel to prompt them to resume.
  1.1525 +	if (iState==EPaused)
  1.1526 +		{
  1.1527 +		NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.
  1.1528 +		return(KErrCancel);
  1.1529 +		}			
  1.1530 +		
  1.1531 +	// The buffer 'completed' list is empty. If the buffer 'free' list is empty too then the client needs
  1.1532 +	// to free some buffers up - return an error.
  1.1533 +	if (((DRecordBufferManager*)iBufManager)->iFreeBufferQ.IsEmpty())
  1.1534 +		{
  1.1535 +		NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.	
  1.1536 +		return(KErrInUse);	
  1.1537 +		}	
  1.1538 +	
  1.1539 +	// Acquire a new request object and add it to the queue of pending requests. The request will be completed
  1.1540 +	// from the PDD and the DFC thread when a buffer is available.
  1.1541 +	NKern::FMSignal(&iMutex);
  1.1542 +	TSoundScRequest* req=iReqQueue->NextFree();
  1.1543 +	NKern::FMWait(&iMutex);
  1.1544 +	if (req)
  1.1545 +		{
  1.1546 +		r=req->iClientRequest->SetStatus(aStatus);
  1.1547 +		req->iOwningThread=aThread;
  1.1548 +		((TClientDataRequest<TInt>*)req->iClientRequest)->SetDestPtr((TInt*)aLengthPtr);
  1.1549 +		// Add the request to the queue
  1.1550 +		iReqQueue->Add(req);		
  1.1551 +		}
  1.1552 +	else
  1.1553 +		r=KErrGeneral;				// Must have exceeded KMaxSndScRequestsPending.
  1.1554 +	NKern::FMSignal(&iMutex); 		// Release the buffer/request list mutex.
  1.1555 +	
  1.1556 +	return(r);
  1.1557 +	}
  1.1558 +
  1.1559 +/**
  1.1560 +Release a buffer which was being used by client.
  1.1561 +@param aChunkOffset The chunk offset corresponding to the buffer to be freed.
  1.1562 +@return KErrNone if successful;
  1.1563 +		KErrNotFound if no 'in use' buffer had the specified chunk offset.
  1.1564 +		KErrNotReady if the channel is not configured (either for audio or its buffer config).
  1.1565 +*/
  1.1566 +TInt DSoundScLdd::ReleaseBuffer(TInt aChunkOffset)	
  1.1567 +	{
  1.1568 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::ReleaseBuffer(%x)",aChunkOffset));
  1.1569 +
  1.1570 +	TInt r=KErrNotReady;
  1.1571 +	if (iState!=EOpen && iBufManager)
  1.1572 +		{
  1.1573 +		TAudioBuffer* buf=NULL;
  1.1574 +		NKern::FMWait(&iMutex); 		// Acquire the buffer/request list mutex.
  1.1575 +		buf=((DRecordBufferManager*)iBufManager)->ReleaseBuffer(aChunkOffset);
  1.1576 +		NKern::FMSignal(&iMutex); 		// Release the buffer/request list mutex.	
  1.1577 +		if (buf)
  1.1578 +			{
  1.1579 +			buf->Flush(DBufferManager::EFlushBeforeDmaRead);
  1.1580 +			r=KErrNone;
  1.1581 +			}
  1.1582 +		else
  1.1583 +			r=KErrNotFound;
  1.1584 +		}
  1.1585 +	return(r);
  1.1586 +	}
  1.1587 +	
  1.1588 +/**
  1.1589 +Handle a custom configuration request.
  1.1590 +@param aFunction A number identifying the request.
  1.1591 +@param aParam A 32-bit value passed to the driver. Its meaning depends on the request.
  1.1592 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.1593 +*/	
  1.1594 +TInt DSoundScLdd::CustomConfig(TInt aFunction,TAny* aParam)
  1.1595 +	{
  1.1596 +	
  1.1597 +	TInt r;
  1.1598 +	if (aFunction>KSndCustomConfigMaxReserved)
  1.1599 +		r=Pdd()->CustomConfig(aFunction,aParam);
  1.1600 +	else
  1.1601 +		{
  1.1602 +		r=KErrNotSupported;
  1.1603 +#ifdef _DEBUG		
  1.1604 +		switch (aFunction)
  1.1605 +			{
  1.1606 +			case KSndCustom_ForceHwConfigNotifSupported:
  1.1607 +				iCaps.iHwConfigNotificationSupport=ETrue;
  1.1608 +				r=KErrNone;
  1.1609 +				break;
  1.1610 +			case KSndCustom_CompleteChangeOfHwConfig:
  1.1611 +				NotifyChangeOfHwConfigCallback((TBool)aParam);
  1.1612 +				r=KErrNone;
  1.1613 +				break;
  1.1614 +			case KSndCustom_ForceStartTransferError:
  1.1615 +				iTestSettings|=KSoundScTest_StartTransferError;
  1.1616 +				r=KErrNone;
  1.1617 +				break;
  1.1618 +			case KSndCustom_ForceTransferDataError:
  1.1619 +				iTestSettings|=KSoundScTest_TransferDataError;
  1.1620 +				r=KErrNone;
  1.1621 +				break;
  1.1622 +			case KSndCustom_ForceTransferTimeout:
  1.1623 +				iTestSettings|=KSoundScTest_TransferTimeout;
  1.1624 +				r=KErrNone;
  1.1625 +				break;
  1.1626 +			}
  1.1627 +#endif	
  1.1628 +		}
  1.1629 +	return(r);	
  1.1630 +	}
  1.1631 +	
  1.1632 +/**
  1.1633 +@publishedPartner
  1.1634 +@prototype
  1.1635 + 
  1.1636 +Called from the PDD each time it has completed a data transfer into the current record buffer. 
  1.1637 +The function performed here is to check whether the transfer into the current buffer is now complete. Also to queue
  1.1638 +further requests on the PDD which should now have the capability to accept more transfers. If transfer into the
  1.1639 +current buffer is now complete then we need to update the buffer lists and possibly complete a request back the client.
  1.1640 +While recording hasn't been paused and no error has occured then this completed buffer ought to be full. However, when
  1.1641 +recording has just been paused, the PDD can also call this function to complete a partially filled record buffer. In fact
  1.1642 +in some circumstances, pausing may result in the PDD calling this function where it turns out that no data has been
  1.1643 +recorded into this buffer. In this case we don't want to signal a null transfer back to the client.
  1.1644 +@param aTransferID A value provided by the LDD when it initiated the transfer allowing the transfer fragment to be 
  1.1645 +	uniquely identified.
  1.1646 +@param aTransferResult The result of the transfer being completed: KErrNone if successful, otherwise one of the other
  1.1647 +	system wide error codes.
  1.1648 +@param aBytesRecorded The number of bytes recorded into the record buffer.	
  1.1649 +*/
  1.1650 +void DSoundScLdd::RecordCallback(TUint aTransferID,TInt aTransferResult,TInt aBytesRecorded)
  1.1651 +	{
  1.1652 +#ifdef _DEBUG
  1.1653 +#ifdef TEST_WITH_PAGING_CACHE_FLUSHES
  1.1654 +	Kern::HalFunction(EHalGroupVM,EVMHalFlushCache,0,0);
  1.1655 +#endif
  1.1656 +#endif
  1.1657 +
  1.1658 +#ifdef _DEBUG	
  1.1659 +	// Test settings - only possible in debug mode.
  1.1660 +	if (iTestSettings & KSoundScTest_TransferDataError)
  1.1661 +		{
  1.1662 +		iTestSettings&=(~KSoundScTest_TransferDataError);
  1.1663 +		aTransferResult=KErrTimedOut;
  1.1664 +		}
  1.1665 +#endif
  1.1666 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::RecordCallback(ID:%xH,Len:%d) - %d (iCurrentRecBufTf.iTfState %d)",aTransferID,aBytesRecorded,aTransferResult, iCurrentRecBufTf.iTfState));
  1.1667 +	
  1.1668 +	// If the transfer fragment is not for the current record buffer and were not paused then ignore it. Either the PDD
  1.1669 +	// has got very confused or more likely its a trailing fragment from an earlier buffer we have already failed. If 
  1.1670 +	// we're paused, the PDD doesn't need to bother with a transfer ID, we assume its for the current buffer.
  1.1671 +	if (iCurrentRecBufTf.iTfState != TSndScTransfer::ETfDone &&
  1.1672 +		(aTransferID==iCurrentRecBufTf.iId || (aTransferID == 0 && iState==EPaused)))
  1.1673 +		{
  1.1674 +		// Update the count of bytes recorded.
  1.1675 +		iBytesTransferred+=aBytesRecorded;
  1.1676 +		
  1.1677 +		// Update the transfer status of the current buffer.
  1.1678 +		if (aTransferResult!=KErrNone)
  1.1679 +			{
  1.1680 +			// Transfer failed. Mark the buffer as being complete.
  1.1681 +			iCurrentRecBufTf.iTfState=TSndScTransfer::ETfDone;	
  1.1682 +			}
  1.1683 +		else	
  1.1684 +			iCurrentRecBufTf.SetCompleted(aBytesRecorded); // Transfer successful so update the progress.
  1.1685 +		
  1.1686 +		// Check if this is the PDD completing a fragment due to record being paused. In this situation we only allow the
  1.1687 +		// PDD to complete one fragment.	
  1.1688 +		TAudioBuffer* buf;
  1.1689 +		if (iState==EPaused && ++iCompletesWhilePausedCount<2)
  1.1690 +			{
  1.1691 +			// Complete (i.e. abort) the transfer to the current buffer.
  1.1692 +			iCurrentRecBufTf.iTfState=TSndScTransfer::ETfDone; 
  1.1693 +			
  1.1694 +			// Reset the transfer status for the pending record buffer. This will be switched to the current buffer later
  1.1695 +			// in this function - ready for when record is resumed.
  1.1696 +			buf=((DRecordBufferManager*)iBufManager)->GetNextRecordBuffer();
  1.1697 +			iNextRecBufTf.Init((TUint)buf,buf->iChunkOffset,buf->iSize,buf);		// Use pointer to record buffer as unique ID
  1.1698 +			}	
  1.1699 +		
  1.1700 +		// Check if we have just completed the transfer into the current buffer.	
  1.1701 +		if (iCurrentRecBufTf.iTfState==TSndScTransfer::ETfDone)
  1.1702 +			HandleCurrentRecordBufferDone(aTransferResult);
  1.1703 +		}
  1.1704 +			
  1.1705 +	// If we're not paused then the PDD should now have the capacity to accept another transfer so queue as many
  1.1706 +	// transfers on it as it can accept.
  1.1707 +	if (iState==EActive)
  1.1708 +		{
  1.1709 +#ifdef _DEBUG	
  1.1710 +		// Test settings - only possible in debug mode. Test LDD being slow servicing transfer completes from PDD. Disabled.
  1.1711 +/*		if (iTestSettings & KSoundScTest_TransferTimeout)
  1.1712 +			{
  1.1713 +			iTestSettings&=(~KSoundScTest_TransferTimeout);
  1.1714 +			Kern::NanoWait(500000000); // Pause for 0.5 second
  1.1715 +			} */
  1.1716 +#endif
  1.1717 +		TInt r=StartNextRecordTransfers();
  1.1718 +		if (r!=KErrNone)
  1.1719 +			{
  1.1720 +			// Problem starting the next transfer. That's fairly serious so complete all pending record requests and 
  1.1721 +			// stop recording.
  1.1722 +			Pdd()->StopTransfer();
  1.1723 +			iReqQueue->CompleteAll(r,&iMutex);
  1.1724 +			iState=EConfigured;
  1.1725 +			}
  1.1726 +		}
  1.1727 +	return;
  1.1728 +	}
  1.1729 +	
  1.1730 +/** Perform the necessary processing required when transfer into the current buffer is complete. This involves updating
  1.1731 +the buffer lists and possibly complete a request back the client.
  1.1732 +@param aTransferResult The result of the transfer being completed: KErrNone if successful, otherwise one of the other
  1.1733 +	system wide error codes.
  1.1734 +*/
  1.1735 +void DSoundScLdd::HandleCurrentRecordBufferDone(TInt aTransferResult)
  1.1736 +	{
  1.1737 +	TAudioBuffer* buf;
  1.1738 +	
  1.1739 +	// Flush the buffer before acquiring the mutex.
  1.1740 +	buf=((DRecordBufferManager*)iBufManager)->GetCurrentRecordBuffer();
  1.1741 +	buf->Flush(DBufferManager::EFlushAfterDmaRead);
  1.1742 +	
  1.1743 +	NKern::FMWait(&iMutex); 		// Acquire the buffer/request list mutex.
  1.1744 +	
  1.1745 +	// Update the buffer list (by either adding the current buffer to the completed list or the free list).
  1.1746 +	TInt bytesRecorded=iCurrentRecBufTf.GetLengthTransferred();
  1.1747 +	((DRecordBufferManager*)iBufManager)->SetBufferFilled(bytesRecorded,aTransferResult);
  1.1748 +    
  1.1749 +    // The pending buffer now becomes the current one and we need to get a new pending one.
  1.1750 +    iCurrentRecBufTf=iNextRecBufTf;
  1.1751 +    buf=((DRecordBufferManager*)iBufManager)->GetNextRecordBuffer();
  1.1752 +    iNextRecBufTf.Init((TUint)buf,buf->iChunkOffset,buf->iSize,buf);	// Use pointer to record buffer as unique ID
  1.1753 +    
  1.1754 +    // Check if there is a client record request pending.
  1.1755 +    if (!iReqQueue->IsEmpty())
  1.1756 +    	{
  1.1757 +    	// A record request is pending. Check if we have had an overflow since the last record request was completed.
  1.1758 +    	if (((DRecordBufferManager*)iBufManager)->iBufOverflow)
  1.1759 +    		{
  1.1760 +    		TSoundScRequest* req=iReqQueue->Remove();
  1.1761 +    		DThread* thread=req->iOwningThread;					// Take a copy before we free it.
  1.1762 +			TClientRequest* clreq = req->iClientRequest;		// Take a copy before we free it.
  1.1763 +    		((DRecordBufferManager*)iBufManager)->iBufOverflow=EFalse;
  1.1764 +			NKern::FMSignal(&iMutex); 							// Release the buffer/request list mutex.
  1.1765 +			iReqQueue->Free(req);
  1.1766 +    		CompleteRequest(thread,NULL,KErrOverflow,clreq);			// Complete the request.
  1.1767 +    		}
  1.1768 +    	else
  1.1769 +    		{
  1.1770 +	    	// Check there really is a buffer available. (There's no guarentee the one just completed hasn't
  1.1771 +	    	// immediately been queued again: if the client has too many 'in-use' or the one completed was a NULL
  1.1772 +	    	// transfer due to pausing).
  1.1773 +			TAudioBuffer* buf=((DRecordBufferManager*)iBufManager)->GetBufferForClient();
  1.1774 +			if (buf)
  1.1775 +				{
  1.1776 +				// There still a buffer available so complete the request.
  1.1777 +				TSoundScRequest* req=iReqQueue->Remove();
  1.1778 +				DThread* thread=req->iOwningThread;							// Take a copy before we free it.
  1.1779 +				TClientRequest* clreq = req->iClientRequest;				// Take a copy before we free it.
  1.1780 +				NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.
  1.1781 +				iReqQueue->Free(req);
  1.1782 +				if (buf->iResult==KErrNone)
  1.1783 +					{
  1.1784 +					((TClientDataRequest<TInt>*)clreq)->Data() = buf->iBytesAdded;
  1.1785 +					CompleteRequest(thread,NULL,buf->iChunkOffset,clreq);					// Complete the request.	
  1.1786 +					}
  1.1787 +				else	
  1.1788 +					CompleteRequest(thread,NULL,buf->iResult,clreq);				// Complete the request.
  1.1789 +				}
  1.1790 +			else
  1.1791 +				NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.	
  1.1792 +    		}
  1.1793 +    	}
  1.1794 +    else
  1.1795 +    	NKern::FMSignal(&iMutex); 	// Release the buffer/request list mutex.	
  1.1796 +	}
  1.1797 +	
  1.1798 +/**
  1.1799 +This function starts the next record data transfer. It starts with the current record buffer - checking whether all of
  1.1800 +this has now been transferred or queued for transfer. If not it breaks this down into transfers sizes which are
  1.1801 +compatible with the PDD and then repeatedly attempts to queue these on the PDD until the PDF indicates that it can
  1.1802 +accept no more transfers for the moment. If the record buffer is fully started in this way and the PDD still has the
  1.1803 +capacity to accept more transfers then it moves on to start the pending record buffer.
  1.1804 +@return Normally KErrNone unless the PDD incurs an error while attempting to start a new transfer.
  1.1805 +*/
  1.1806 +TInt DSoundScLdd::StartNextRecordTransfers()
  1.1807 +	{
  1.1808 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::StartNextRecordTransfers"));
  1.1809 +	
  1.1810 +	// First start with the current record buffer - keep queuing transfers either until this buffer is
  1.1811 +	// fully started or until the PDD can accept no more transfers.
  1.1812 +	TInt r=KErrNone;
  1.1813 +	while (r==KErrNone && iCurrentRecBufTf.iTfState<TSndScTransfer::ETfFullyStarted)
  1.1814 +		{
  1.1815 +		TInt pos=iCurrentRecBufTf.GetStartOffset();
  1.1816 +		TPhysAddr physAddr;
  1.1817 +		TInt len=iCurrentRecBufTf.iAudioBuffer->GetFragmentLength(pos,iCurrentRecBufTf.GetNotStartedLen(),physAddr);
  1.1818 +		
  1.1819 +		r=Pdd()->TransferData(iCurrentRecBufTf.iId,(iBufManager->iChunkBase+pos),physAddr,len);
  1.1820 +		__KTRACE_OPT(KSOUND1, Kern::Printf("<PDD:TransferData(off:%x len:%d) A - %d",pos,len,r));
  1.1821 +		if (r==KErrNone)
  1.1822 +			iCurrentRecBufTf.SetStarted(len);	// Successfully queued a transfer - update the status.
  1.1823 +		}
  1.1824 +	
  1.1825 +	// Either the current record transfer is now fully started, or the PDD can accept no more transfers
  1.1826 +	// If the PDD can still accept more transfers then move on to the next record buffer - again, keep queuing
  1.1827 +	// transfers either until this buffer is fully started or until the PDD can accept no more.
  1.1828 +	while (r==KErrNone && iNextRecBufTf.iTfState<TSndScTransfer::ETfFullyStarted)
  1.1829 +		{
  1.1830 +		TInt pos=iNextRecBufTf.GetStartOffset();
  1.1831 +		TPhysAddr physAddr;
  1.1832 +		TInt len=iNextRecBufTf.iAudioBuffer->GetFragmentLength(pos,iNextRecBufTf.GetNotStartedLen(),physAddr);
  1.1833 +		
  1.1834 +		r=Pdd()->TransferData(iNextRecBufTf.iId,(iBufManager->iChunkBase+pos),physAddr,len);
  1.1835 +		__KTRACE_OPT(KSOUND1, Kern::Printf("<PDD:TransferData(off:%x len:%d) B - %d",pos,len,r));
  1.1836 +		if (r==KErrNone)
  1.1837 +			iNextRecBufTf.SetStarted(len);	// Successfully queued a transfer - update the status.
  1.1838 +		}
  1.1839 +	if (r==KErrNotReady)
  1.1840 +		r=KErrNone;		// KErrNotReady means the PDD the cannot accept any more requests - this isn't an error.	
  1.1841 +	return(r);	
  1.1842 +	}	
  1.1843 +	
  1.1844 +/**
  1.1845 +@publishedPartner
  1.1846 +@prototype
  1.1847 +
  1.1848 +Called from the PDD each time it detects a change in the hardware configuration of the device.
  1.1849 +@param aHeadsetPresent This is set by the PDD to ETrue if a microphone or headset socket is now present or EFalse if 
  1.1850 +such a device is not present.
  1.1851 +*/
  1.1852 +void DSoundScLdd::NotifyChangeOfHwConfigCallback(TBool aHeadsetPresent)
  1.1853 +	{
  1.1854 +#ifdef _DEBUG
  1.1855 +#ifdef TEST_WITH_PAGING_CACHE_FLUSHES 
  1.1856 +	Kern::HalFunction(EHalGroupVM,EVMHalFlushCache,0,0);
  1.1857 +#endif
  1.1858 +#endif
  1.1859 +
  1.1860 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::NotifyChangeOfHwConfigCallback(Pres:%d)",aHeadsetPresent));
  1.1861 +	
  1.1862 +	__ASSERT_DEBUG(iCaps.iHwConfigNotificationSupport,Kern::Fault(KSoundLddPanic,__LINE__));		
  1.1863 +	
  1.1864 +	if (iNotifyChangeOfHwClientRequest->IsReady())
  1.1865 +		{
  1.1866 +		iNotifyChangeOfHwClientRequest->Data() = aHeadsetPresent;
  1.1867 +		CompleteRequest(iChangeOfHwConfigThread,NULL,KErrNone,iNotifyChangeOfHwClientRequest);	// Complete the request.
  1.1868 +		}
  1.1869 +	}
  1.1870 +	
  1.1871 +/**
  1.1872 +This function validates that a new sound format configuration is both sensible and supported by this device.
  1.1873 +@param aConfig A reference to the new sound format configuration object.
  1.1874 +*/	
  1.1875 +TInt DSoundScLdd::ValidateConfig(const TCurrentSoundFormatV02& aConfig)
  1.1876 +	{
  1.1877 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScLdd::ValidateConfig"));
  1.1878 +	
  1.1879 +	// Check that the audio channel configuration requested is sensible and supported by this device.
  1.1880 +	if (aConfig.iChannels<0) 
  1.1881 +		return(KErrNotSupported);
  1.1882 +	TInt chans=(aConfig.iChannels-1);
  1.1883 +	if (!(iCaps.iChannels & (1<<chans)))
  1.1884 +		return(KErrNotSupported);
  1.1885 +	
  1.1886 +	// Check that the sample rate requested is sensible and supported by this device.
  1.1887 +	if (aConfig.iRate<0 || !(iCaps.iRates & (1<<aConfig.iRate)))
  1.1888 +		return(KErrNotSupported);
  1.1889 +	
  1.1890 +	// Check that the encoding format requested is sensible and supported by this device.
  1.1891 +	if (aConfig.iEncoding<0 || !(iCaps.iEncodings & (1<<aConfig.iEncoding)))
  1.1892 +		return(KErrNotSupported);
  1.1893 +	
  1.1894 +	// Check that the data format requested is sensible and supported by this device.
  1.1895 +	if (aConfig.iDataFormat<0 || !(iCaps.iDataFormats & (1<<aConfig.iDataFormat)))
  1.1896 +		return(KErrNotSupported);
  1.1897 +		
  1.1898 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DSoundScLdd::ValidateConfig - %d",KErrNone));
  1.1899 +	return(KErrNone);
  1.1900 +	}
  1.1901 +	
  1.1902 +/**
  1.1903 +Increase or decrease the memory area allocated to hold the current buffer configuration in the play/record chunk.
  1.1904 +@param aNumBuffers The number of buffers within the new buffer configuration. This determines the size of the memory
  1.1905 +	area required.
  1.1906 +@pre The thread must be in a critical section. 
  1.1907 +*/
  1.1908 +TInt DSoundScLdd::ReAllocBufferConfigInfo(TInt aNumBuffers)
  1.1909 +	{
  1.1910 +	if (iBufConfig)
  1.1911 +		{
  1.1912 +		delete iBufConfig;
  1.1913 +		iBufConfig=NULL;
  1.1914 +		}	 
  1.1915 +	
  1.1916 +	iBufConfigSize=aNumBuffers*sizeof(TInt);	
  1.1917 +	iBufConfigSize+=sizeof(TSharedChunkBufConfigBase);
  1.1918 +	iBufConfig=(TSoundSharedChunkBufConfig*)Kern::AllocZ(iBufConfigSize);
  1.1919 +	if (!iBufConfig)
  1.1920 +		return(KErrNoMemory);	
  1.1921 +	
  1.1922 +	return(KErrNone);
  1.1923 +	}
  1.1924 +
  1.1925 +/**
  1.1926 +Start the EOF play timer. A 2 second timer is queued each time the transfer of playback data ceases by the LLD and if it
  1.1927 +is allowed to expire, then the PDD is called to release any resources in use for playback transfer. 
  1.1928 +*/
  1.1929 +void DSoundScLdd::StartPlayEofTimer()
  1.1930 +	{
  1.1931 +	iEofTimer.Cancel();
  1.1932 +	iPlayEofDfc.Cancel();
  1.1933 +	iEofTimer.OneShot(NKern::TimerTicks(2000)); // Queue the 2 second EOF timer to stop transfer on the PDD.
  1.1934 +	iPlayEofTimerActive=ETrue;
  1.1935 +	}
  1.1936 +
  1.1937 +/**
  1.1938 +Cancel the EOF play timer. 
  1.1939 +*/	
  1.1940 +void DSoundScLdd::CancelPlayEofTimer()
  1.1941 +	{
  1.1942 +	iEofTimer.Cancel();
  1.1943 +	iPlayEofDfc.Cancel();
  1.1944 +	iPlayEofTimerActive=EFalse;
  1.1945 +	}
  1.1946 +	
  1.1947 +/**
  1.1948 +@publishedPartner
  1.1949 +@prototype
  1.1950 +
  1.1951 +Returns the buffer configuration of the play/record chunk.
  1.1952 +@return A pointer to the current buffer configuration of the play/record chunk.
  1.1953 +*/	
  1.1954 +TSoundSharedChunkBufConfig* DSoundScLdd::BufConfig()
  1.1955 +	{
  1.1956 +	return(iBufConfig);
  1.1957 +	}
  1.1958 +
  1.1959 +/**
  1.1960 +@publishedPartner
  1.1961 +@prototype
  1.1962 +
  1.1963 +Returns the address of the start of the play/record chunk.
  1.1964 +@return The linear address of the start of the play/record chunk.
  1.1965 +*/	
  1.1966 +TLinAddr DSoundScLdd::ChunkBase()
  1.1967 +	{
  1.1968 +	return(iBufManager->iChunkBase);
  1.1969 +	}			
  1.1970 +		
  1.1971 +/**
  1.1972 +The ISR to handle the EOF play timer.
  1.1973 +@param aChannel A pointer to the sound driver logical channel object.
  1.1974 +*/	
  1.1975 +void DSoundScLdd::PlayEofTimerExpired(TAny* aChannel)
  1.1976 +	{
  1.1977 +	DSoundScLdd& drv=*(DSoundScLdd*)aChannel;
  1.1978 +	
  1.1979 +	drv.iPlayEofDfc.Add();
  1.1980 +	}
  1.1981 +	
  1.1982 +/**
  1.1983 +The DFC used to handle the EOF play timer. 
  1.1984 +@param aChannel A pointer to the sound driver logical channel object.
  1.1985 +*/	
  1.1986 +void DSoundScLdd::PlayEofTimerDfc(TAny* aChannel)
  1.1987 +	{	
  1.1988 +	DSoundScLdd& drv=*(DSoundScLdd*)aChannel;
  1.1989 +	
  1.1990 +	drv.Pdd()->StopTransfer();
  1.1991 +	drv.iState=EConfigured;
  1.1992 +	drv.iPlayEofTimerActive=EFalse;
  1.1993 +	}				
  1.1994 +	
  1.1995 +/**
  1.1996 +The DFC used to handle power down requests from the power manager before a transition into system
  1.1997 +shutdown/standby.
  1.1998 +@param aChannel A pointer to the sound driver logical channel object.
  1.1999 +*/
  1.2000 +void DSoundScLdd::PowerDownDfc(TAny* aChannel)
  1.2001 +	{
  1.2002 +	DSoundScLdd& drv=*(DSoundScLdd*)aChannel;
  1.2003 +	drv.Shutdown();
  1.2004 +	drv.iPowerHandler->PowerDownDone();
  1.2005 +	}
  1.2006 +	
  1.2007 +/**
  1.2008 +The DFC used to handle power up requests from the power manager following a transition out of system standby.
  1.2009 +@param aChannel A pointer to the sound driver logical channel object.
  1.2010 +*/	
  1.2011 +void DSoundScLdd::PowerUpDfc(TAny* aChannel)
  1.2012 +	{
  1.2013 +	DSoundScLdd& drv=*(DSoundScLdd*)aChannel;
  1.2014 +	
  1.2015 +	// Restore the channel to a default state.
  1.2016 +	drv.DoCancel(RSoundSc::EAllRequests);
  1.2017 +	drv.Pdd()->PowerUp();
  1.2018 +	drv.DoSetSoundConfig(drv.iSoundConfig);
  1.2019 +	drv.SetVolume(drv.iVolume);			
  1.2020 +	drv.iState=(!drv.iBufConfig)?EOpen:EConfigured;
  1.2021 +	
  1.2022 +	drv.iPowerHandler->PowerUpDone();
  1.2023 +	}	
  1.2024 +
  1.2025 +/** 
  1.2026 +Complete an asynchronous request back to the client.
  1.2027 +@param aThread The client thread which issued the request.
  1.2028 +@param aStatus The TRequestStatus instance that will receive the request status code or NULL if aClientRequest used. 
  1.2029 +@param aReason The request status code.  
  1.2030 +@param aClientRequest The TClientRequest instance that will receive the request status code or NULL if aStatus used. 
  1.2031 +@pre The thread must be in a critical section. 
  1.2032 +*/
  1.2033 +
  1.2034 +void DSoundScLdd::CompleteRequest(DThread* aThread, TRequestStatus* aStatus, TInt aReason, TClientRequest* aClientRequest)
  1.2035 +	{
  1.2036 +	if (aClientRequest)
  1.2037 +		{
  1.2038 +		if (aClientRequest->IsReady())
  1.2039 +			{
  1.2040 +			Kern::QueueRequestComplete(aThread,aClientRequest,aReason);
  1.2041 +			}
  1.2042 +		else
  1.2043 +			{
  1.2044 +			// should always be ready
  1.2045 +			__ASSERT_DEBUG(EFalse,Kern::Fault(KSoundLddPanic,__LINE__));
  1.2046 +			}
  1.2047 +		}
  1.2048 +	else if (aStatus)
  1.2049 +		{
  1.2050 +		Kern::RequestComplete(aStatus,aReason);		// Complete the request back to the client.
  1.2051 +		}
  1.2052 +	else
  1.2053 +		{
  1.2054 +		// never get here - either aStatus or aClientRequest must be valid
  1.2055 +		__ASSERT_DEBUG(EFalse,Kern::Fault(KSoundLddPanic,__LINE__));
  1.2056 +		}
  1.2057 +	
  1.2058 +	aThread->AsyncClose();	// Asynchronously close our reference on the client thread - don't want to be blocked if this is final reference. 
  1.2059 +	
  1.2060 +#ifdef _DEBUG	
  1.2061 +	__e32_atomic_add_ord32(&iThreadOpenCount, TUint32(-1));
  1.2062 +#endif		
  1.2063 +	}
  1.2064 +
  1.2065 +/**
  1.2066 +Constructor for the play request object.
  1.2067 +*/
  1.2068 +TSoundScPlayRequest::TSoundScPlayRequest()
  1.2069 +	: TSoundScRequest()
  1.2070 +	{
  1.2071 +	iFlags=0; 
  1.2072 +	iCompletionReason=KErrGeneral;
  1.2073 +	}
  1.2074 +
  1.2075 +/*
  1.2076 +Second phase construction of the requests
  1.2077 +*/
  1.2078 +TInt TSoundScPlayRequest::Construct()
  1.2079 +	{
  1.2080 +	return Kern::CreateClientRequest(iClientRequest);
  1.2081 +	}
  1.2082 +
  1.2083 +/*
  1.2084 +Second phase construction of the requests
  1.2085 +*/
  1.2086 +TInt TSoundScRequest::Construct()
  1.2087 +	{
  1.2088 +	TClientDataRequest<TInt>* tempClientDataRequest=0;
  1.2089 +	TInt r = Kern::CreateClientDataRequest(tempClientDataRequest);
  1.2090 +	iClientRequest = tempClientDataRequest;
  1.2091 +	return r;
  1.2092 +	}
  1.2093 +
  1.2094 +/**
  1.2095 +Destructor of play requests
  1.2096 +*/
  1.2097 +TSoundScRequest::~TSoundScRequest()
  1.2098 +	{
  1.2099 +	Kern::DestroyClientRequest(iClientRequest);
  1.2100 +	}
  1.2101 +
  1.2102 +/**
  1.2103 +Constructor for the request object queue.
  1.2104 +*/
  1.2105 +TSoundScRequestQueue::TSoundScRequestQueue(DSoundScLdd* aLdd)
  1.2106 +	{
  1.2107 +	iLdd=aLdd;
  1.2108 +	memclr(&iRequest[0],sizeof(TSoundScRequest*)*KMaxSndScRequestsPending);
  1.2109 +	}
  1.2110 +	
  1.2111 +/**
  1.2112 +Destructor for the request object queue.
  1.2113 +*/
  1.2114 +TSoundScRequestQueue::~TSoundScRequestQueue()
  1.2115 +	{
  1.2116 +	for (TInt i=0 ; i<KMaxSndScRequestsPending ; i++)
  1.2117 +		{
  1.2118 +		delete iRequest[i];
  1.2119 +		}
  1.2120 +	}
  1.2121 +	
  1.2122 +/**
  1.2123 +Second stage constructor for the basic request object queue.
  1.2124 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2125 +@pre The thread must be in a critical section.
  1.2126 +*/
  1.2127 +TInt TSoundScRequestQueue::Create()	
  1.2128 +	{
  1.2129 +	// Create the set of available request objects and add them to the unused request queue. 	
  1.2130 +	for (TInt i=0 ; i<KMaxSndScRequestsPending ; i++)
  1.2131 +		{
  1.2132 +		iRequest[i]=new TSoundScRequest;		// Normal request object
  1.2133 +		if (!iRequest[i])
  1.2134 +			return(KErrNoMemory);
  1.2135 +		TInt retConstruct = iRequest[i]->Construct();
  1.2136 +		if ( retConstruct != KErrNone)
  1.2137 +			{
  1.2138 +			return(retConstruct);
  1.2139 +			}
  1.2140 +		iUnusedRequestQ.Add(iRequest[i]);
  1.2141 +		}
  1.2142 +		
  1.2143 +	return(KErrNone);
  1.2144 +	}
  1.2145 +		
  1.2146 +/**
  1.2147 +Second stage constructor for the play request object queue.
  1.2148 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2149 +@pre The thread must be in a critical section.
  1.2150 +*/
  1.2151 +TInt TSoundScPlayRequestQueue::Create()	
  1.2152 +	{
  1.2153 +	// Create the set of available play request objects and add them to the unused request queue. 	
  1.2154 +	for (TInt i=0 ; i<KMaxSndScRequestsPending ; i++)
  1.2155 +		{
  1.2156 +		iRequest[i]=new TSoundScPlayRequest();
  1.2157 +		if (!iRequest[i])
  1.2158 +			return(KErrNoMemory);
  1.2159 +		TInt retConstruct = iRequest[i]->Construct();
  1.2160 +		if ( retConstruct != KErrNone)
  1.2161 +			{
  1.2162 +			return(retConstruct);
  1.2163 +			}
  1.2164 +		iUnusedRequestQ.Add(iRequest[i]);
  1.2165 +		}
  1.2166 +		
  1.2167 +	return(KErrNone);
  1.2168 +	}	
  1.2169 +
  1.2170 +/**
  1.2171 +Get an unused request object.
  1.2172 +@return A pointer to a free request object or NULL if there are none available.
  1.2173 +*/ 	
  1.2174 +TSoundScRequest* TSoundScRequestQueue::NextFree()
  1.2175 +	{
  1.2176 +	NKern::FMWait(&iUnusedRequestQLock);
  1.2177 +	TSoundScRequest* req = (TSoundScRequest*)iUnusedRequestQ.GetFirst();
  1.2178 +	NKern::FMSignal(&iUnusedRequestQLock);
  1.2179 +	return req;
  1.2180 +	}
  1.2181 +		
  1.2182 +/**
  1.2183 +Add a request object to the tail of the pending request queue. 
  1.2184 +@param aReq A pointer to the request object to be added to the queue.
  1.2185 +*/ 
  1.2186 +void TSoundScRequestQueue::Add(TSoundScRequest* aReq)	
  1.2187 +	{
  1.2188 +	iPendRequestQ.Add(aReq);
  1.2189 +	} 	
  1.2190 +
  1.2191 +/**
  1.2192 +If the pending request queue is not empty, remove the request object from the head of this queue.
  1.2193 +@return A pointer to request object removed or NULL if the list was empty.
  1.2194 +*/ 
  1.2195 +TSoundScRequest* TSoundScRequestQueue::Remove()
  1.2196 +	{
  1.2197 +	return((TSoundScRequest*)iPendRequestQ.GetFirst());
  1.2198 +	}
  1.2199 +						
  1.2200 +/**
  1.2201 +Remove a request object from anywhere in the pending request queue. 
  1.2202 +@param aReq A pointer to the request object to be removed from the queue.
  1.2203 +@return A pointer to request object removed or NULL if it wasn't found.
  1.2204 +*/	
  1.2205 +TSoundScRequest* TSoundScRequestQueue::Remove(TSoundScRequest* aReq)	
  1.2206 +	{
  1.2207 +	TSoundScRequest* retReq;
  1.2208 +	
  1.2209 +	// Scan through the pending queue looking for a request object which matches.
  1.2210 +	retReq=(TSoundScRequest*)iPendRequestQ.First();
  1.2211 +	while (!IsAnchor(retReq) && retReq!=aReq)
  1.2212 +		retReq=(TSoundScRequest*)retReq->iNext;
  1.2213 +	
  1.2214 +	// If we got a match then remove the request object from the queue and return it.
  1.2215 +	if (!IsAnchor(retReq))
  1.2216 +		retReq->Deque();
  1.2217 +	else
  1.2218 +		retReq=NULL;
  1.2219 +	return(retReq);
  1.2220 +	}
  1.2221 +
  1.2222 +/**
  1.2223 +Free up a request object - making it available for further requests. 
  1.2224 +@param aReq A pointer to the request object being freed up.
  1.2225 +*/ 
  1.2226 +void TSoundScRequestQueue::Free(TSoundScRequest* aReq)	
  1.2227 +	{
  1.2228 +	NKern::FMWait(&iUnusedRequestQLock);
  1.2229 +	iUnusedRequestQ.Add(aReq);
  1.2230 +	NKern::FMSignal(&iUnusedRequestQLock);
  1.2231 +	}
  1.2232 +	 
  1.2233 +/**
  1.2234 +Find a request object (specified by its associated request status pointer) within in the pending request queue. 
  1.2235 +@param aStatus The request status pointer of the request object to be found in the queue.
  1.2236 +@return A pointer to the request object if it was found or NULL if it wasn't found.
  1.2237 +*/	
  1.2238 +TSoundScRequest* TSoundScRequestQueue::Find(TRequestStatus* aStatus)	
  1.2239 +	{
  1.2240 +	TSoundScRequest* retReq;
  1.2241 +	
  1.2242 +	// Scan through the queue looking for a request object containing a TRequestStatus* which matches.
  1.2243 +	retReq=(TSoundScRequest*)iPendRequestQ.First();
  1.2244 +	while (!IsAnchor(retReq) && retReq->iClientRequest->StatusPtr()!=aStatus)
  1.2245 +		retReq=(TSoundScRequest*)retReq->iNext;
  1.2246 +		
  1.2247 +	return((IsAnchor(retReq))?NULL:retReq);
  1.2248 +	}				
  1.2249 +	
  1.2250 +/**
  1.2251 +Remove each request object from the pending request queue, completing each request removed with a specified completion
  1.2252 +reason.
  1.2253 +@param aCompletionReason The error value to be returned when completing any requests in the queue.
  1.2254 +@param aMutex A pointer to a mutex to be aquired when removing requests from the queue. May be NULL.
  1.2255 +*/		
  1.2256 +void TSoundScRequestQueue::CompleteAll(TInt aCompletionReason,NFastMutex* aMutex)	
  1.2257 +	{
  1.2258 +	if (aMutex)
  1.2259 +		NKern::FMWait(aMutex); 							// Acquire the mutex.
  1.2260 +	
  1.2261 +	TSoundScRequest* req;
  1.2262 +	while ((req=Remove())!=NULL)
  1.2263 +		{
  1.2264 +		if (aMutex)
  1.2265 +			NKern::FMSignal(aMutex); 					// Release the mutex while we complete the request.
  1.2266 +		iLdd->CompleteRequest(req->iOwningThread,NULL,aCompletionReason,req->iClientRequest);	
  1.2267 +		Free(req);	
  1.2268 +		if (aMutex)
  1.2269 +			NKern::FMWait(aMutex); 						// Re-acquire the mutex.
  1.2270 +
  1.2271 +		}
  1.2272 +		
  1.2273 +	if (aMutex)	
  1.2274 +		NKern::FMSignal(aMutex); 						// Release mutex.	
  1.2275 +	}
  1.2276 +
  1.2277 +/**
  1.2278 +Constructor for the play request object queue.
  1.2279 +*/					
  1.2280 +TSoundScPlayRequestQueue::TSoundScPlayRequestQueue(DSoundScLdd* aLdd)
  1.2281 +	: TSoundScRequestQueue(aLdd)
  1.2282 +{
  1.2283 +}
  1.2284 +
  1.2285 +/**
  1.2286 +Return the play request object from the request queue which is next to be transferrred. If this
  1.2287 +play request is being handled using multiple data transfers then the transfer of earlier parts of
  1.2288 +this request may already be in progress. 
  1.2289 +@return Either a pointer to the next play request object for transfer, or NULL if no more are pending. 	
  1.2290 +*/
  1.2291 +TSoundScPlayRequest* TSoundScPlayRequestQueue::NextRequestForTransfer()
  1.2292 +	{
  1.2293 +	TSoundScPlayRequest* retReq;
  1.2294 +	
  1.2295 +	retReq=(TSoundScPlayRequest*)iPendRequestQ.First();
  1.2296 +	while (!IsAnchor(retReq) && retReq->iTf.iTfState>TSndScTransfer::ETfPartlyStarted)
  1.2297 +		retReq=(TSoundScPlayRequest*)retReq->iNext;
  1.2298 +		
  1.2299 +	return((IsAnchor(retReq))?NULL:retReq);	
  1.2300 +	}	
  1.2301 +
  1.2302 +/**
  1.2303 +Search the play request queue for a particular play request object specified by its transfer ID.
  1.2304 +@param aTransferID The transfer ID of the particular play request object to be found.
  1.2305 +@param aIsNextToComplete If the search is successful then this indicates whether the request 
  1.2306 +object found is the next in the queue to be completed to the client. ETrue if next to be 
  1.2307 +completed, EFalse otherwise.
  1.2308 +@return Either a pointer to the specified request object, or NULL if it was not found.
  1.2309 +*/	
  1.2310 +TSoundScPlayRequest* TSoundScPlayRequestQueue::Find(TUint aTransferID,TBool& aIsNextToComplete)
  1.2311 +	{
  1.2312 +	TSoundScPlayRequest* retReq;
  1.2313 +	TSoundScPlayRequest* nextToCompleteReq=NULL;
  1.2314 +	
  1.2315 +	retReq=(TSoundScPlayRequest*)iPendRequestQ.First();
  1.2316 +	
  1.2317 +	// Walk all the way through the list either until we find the specified object or until we get to the end
  1.2318 +	for ( ; !IsAnchor(retReq) ; retReq=(TSoundScPlayRequest*)retReq->iNext )
  1.2319 +		{
  1.2320 +		// The first request we find which isn't complete must be the next to complete
  1.2321 +		if (!nextToCompleteReq && retReq->iTf.iTfState!=TSndScTransfer::ETfDone)
  1.2322 +			nextToCompleteReq=retReq;
  1.2323 +		if (retReq->iTf.iId==aTransferID)
  1.2324 +			break;
  1.2325 +		}
  1.2326 +	
  1.2327 +	if (IsAnchor(retReq))
  1.2328 +		return(NULL);		// Object not found
  1.2329 +	else
  1.2330 +		{
  1.2331 +		aIsNextToComplete=(retReq==nextToCompleteReq);
  1.2332 +		return(retReq);		// Object found
  1.2333 +		}
  1.2334 +	}					
  1.2335 +/**
  1.2336 +Constructor for the audio data transfer class. 
  1.2337 +*/	
  1.2338 +TSndScTransfer::TSndScTransfer()
  1.2339 +	{
  1.2340 +	iId=0;
  1.2341 +	iTfState=ETfNotStarted;
  1.2342 +	iAudioBuffer=NULL;
  1.2343 +	iLengthTransferred=0;
  1.2344 +	iTransfersInProgress=0;
  1.2345 +	}
  1.2346 +	
  1.2347 +/**
  1.2348 +Initialisation function for the audio data transfer class.
  1.2349 +@param aId A value to uniquely identify this particular transfer.
  1.2350 +@param aChunkOffset The start postition of the transfer - an offset within the shared chunk.
  1.2351 +@param aLength The total length of the transfer in bytes.
  1.2352 +@param anAudioBuffer The audio buffer associated with the transfer.
  1.2353 +*/		
  1.2354 +void TSndScTransfer::Init(TUint aId,TInt aChunkOffset,TInt aLength,TAudioBuffer* anAudioBuffer)
  1.2355 +	{
  1.2356 +	iId=aId;
  1.2357 +	iTfState=ETfNotStarted;
  1.2358 +	iAudioBuffer=anAudioBuffer;
  1.2359 +	iStartedOffset=aChunkOffset;
  1.2360 +	iEndOffset=aChunkOffset+aLength;
  1.2361 +	iLengthTransferred=0;
  1.2362 +	iTransfersInProgress=0;
  1.2363 +	}
  1.2364 +	
  1.2365 +/**
  1.2366 +Update the progress of the audio data transfer with the amount of data now queued for transfer on the audio device.
  1.2367 +@param aLength The amount of data (in bytes) that has just been queued on the audio device.
  1.2368 +*/
  1.2369 +void TSndScTransfer::SetStarted(TInt aLength)
  1.2370 +	{	
  1.2371 +	iTransfersInProgress++;
  1.2372 +	iStartedOffset+=aLength;
  1.2373 +	TInt notqueued=(iEndOffset - iStartedOffset);
  1.2374 +	__ASSERT_ALWAYS(notqueued>=0,Kern::Fault(KSoundLddPanic,__LINE__));
  1.2375 +	iTfState=(notqueued) ? ETfPartlyStarted : ETfFullyStarted;
  1.2376 +	}
  1.2377 +	
  1.2378 +/**
  1.2379 +Update the progress of the audio data transfer with the amount of data now successfully transfered by the audio device.
  1.2380 +@param aLength The amount of data (in bytes) that has just been transferred by the audio device.
  1.2381 +@return ETrue if the transfer is now fully complete, otherwise EFalse.
  1.2382 +*/
  1.2383 +TBool TSndScTransfer::SetCompleted(TInt aLength)
  1.2384 +	{		
  1.2385 +	iLengthTransferred+=aLength;
  1.2386 +	iTransfersInProgress--;
  1.2387 +	__ASSERT_ALWAYS(iTransfersInProgress>=0,Kern::Fault(KSoundLddPanic,__LINE__));
  1.2388 +	
  1.2389 +	if (GetNotStartedLen()==0 && iTransfersInProgress==0)
  1.2390 +		{
  1.2391 +		iTfState=ETfDone;	// Transfer is now fully completed
  1.2392 +		return(ETrue);
  1.2393 +		}
  1.2394 +	else
  1.2395 +		return(EFalse);	
  1.2396 +	}
  1.2397 +		
  1.2398 +/**
  1.2399 +Constructor for the sound driver power handler class.
  1.2400 +@param aChannel A pointer to the sound driver logical channel which owns this power handler.
  1.2401 +*/
  1.2402 +DSoundScPowerHandler::DSoundScPowerHandler(DSoundScLdd* aChannel)
  1.2403 +:	DPowerHandler(KDevSoundScName),
  1.2404 +	iChannel(aChannel)
  1.2405 +	{	
  1.2406 +	}
  1.2407 +
  1.2408 +/**
  1.2409 +A request from the power manager for the power down of the audio device.
  1.2410 +This is called during a transition of the phone into standby or power off.
  1.2411 +@param aState The target power state; can be EPwStandby or EPwOff only.
  1.2412 +*/
  1.2413 +void DSoundScPowerHandler::PowerDown(TPowerState aPowerState)
  1.2414 +	{
  1.2415 +	(void)aPowerState;
  1.2416 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScPowerHandler::PowerDown(State-%d)",aPowerState));
  1.2417 +	
  1.2418 +	// Power-down involves hardware access so queue a DFC to perform this from the driver thread.
  1.2419 +	iChannel->iPowerDownDfc.Enque();
  1.2420 +	}
  1.2421 +
  1.2422 +/**
  1.2423 +A request from the power manager for the power up of the audio device.
  1.2424 +This is called during a transition of the phone out of standby.
  1.2425 +*/
  1.2426 +void DSoundScPowerHandler::PowerUp()
  1.2427 +	{
  1.2428 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DSoundScPowerHandler::PowerUp"));
  1.2429 +	
  1.2430 +	// Power-up involves hardware access so queue a DFC to perform this from the driver thread.
  1.2431 +	iChannel->iPowerUpDfc.Enque();
  1.2432 +	}	
  1.2433 +
  1.2434 +/**
  1.2435 +Constructor for the buffer manager.
  1.2436 +*/
  1.2437 +DBufferManager::DBufferManager(DSoundScLdd* aLdd)
  1.2438 +	: iLdd(aLdd)
  1.2439 +	{
  1.2440 +//	iChunk=NULL;
  1.2441 +//	iNumBuffers=0;
  1.2442 +//	iAudioBuffers=NULL;	
  1.2443 +//	iMaxTransferLen=0;	
  1.2444 +	}
  1.2445 +
  1.2446 +/**
  1.2447 +Destructor for the buffer manager.
  1.2448 +@pre The thread must be in a critical section.
  1.2449 +*/
  1.2450 +DBufferManager::~DBufferManager()
  1.2451 +	{
  1.2452 +	if (iChunk)
  1.2453 +		Kern::ChunkClose(iChunk);
  1.2454 +	delete[] iAudioBuffers;
  1.2455 +	}
  1.2456 +		
  1.2457 +/**
  1.2458 +Second stage constructor for the buffer manager. This version creates a shared chunk and a buffer object for each
  1.2459 +buffer specified within this. Then it commits memory within the chunk for each of these buffers. This also involves the
  1.2460 +creation of a set of buffer lists to manage the buffers.
  1.2461 +@param aBufConfig The shared chunk buffer configuration object specifying the geometry of the buffer configuration
  1.2462 +required.
  1.2463 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2464 +@pre The thread must be in a critical section.
  1.2465 +*/
  1.2466 +TInt DBufferManager::Create(TSoundSharedChunkBufConfig* aBufConfig)
  1.2467 +	{
  1.2468 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::Create(Bufs-%d,Sz-%d)",aBufConfig->iNumBuffers,aBufConfig->iBufferSizeInBytes));
  1.2469 +
  1.2470 +	// Create the required number of buffer objects, and the buffer lists to manage these.
  1.2471 +	TInt r=CreateBufferLists(aBufConfig->iNumBuffers);
  1.2472 +	if (r!=KErrNone)
  1.2473 +		return(r);
  1.2474 +		
  1.2475 +	TInt chunkSz;
  1.2476 +	TInt bufferSz=aBufConfig->iBufferSizeInBytes;
  1.2477 +	TInt* bufferOffsetList=&aBufConfig->iBufferOffsetListStart;	
  1.2478 +	
  1.2479 +	// Calculate the required size for the chunk and the buffer offsets. 
  1.2480 +	if (aBufConfig->iFlags & KScFlagUseGuardPages)
  1.2481 +		{
  1.2482 +		// Commit each buffer separately with an uncommitted guard pages around each buffer.
  1.2483 +		TInt guardPageSize=Kern::RoundToPageSize(1);
  1.2484 +		bufferSz=Kern::RoundToPageSize(aBufConfig->iBufferSizeInBytes); // Commit size to be a multiple of the MMU page size.
  1.2485 +		chunkSz=guardPageSize;											// Leave an un-committed guard page at the start.
  1.2486 +		for (TInt i=0 ; i<aBufConfig->iNumBuffers ; i++)
  1.2487 +			{
  1.2488 +			bufferOffsetList[i]=chunkSz;
  1.2489 +			chunkSz += (bufferSz + guardPageSize);						// Leave an un-committed guard page after each buffer.
  1.2490 +			}
  1.2491 +		}
  1.2492 +	else
  1.2493 +		{
  1.2494 +		// Commit all the buffers contiguously into a single region (ie with no guard pages between each buffer).
  1.2495 +		chunkSz=0;
  1.2496 +		for (TInt i=0 ; i<aBufConfig->iNumBuffers ; i++)
  1.2497 +			{
  1.2498 +			bufferOffsetList[i]=chunkSz;
  1.2499 +			chunkSz += bufferSz;
  1.2500 +			}
  1.2501 +		chunkSz=Kern::RoundToPageSize(chunkSz);							// Commit size to be a multiple of the MMU page size.
  1.2502 +		}	
  1.2503 +	aBufConfig->iFlags|=KScFlagBufOffsetListInUse;
  1.2504 +	__KTRACE_OPT(KSOUND1, Kern::Printf("Chunk size is %d bytes",chunkSz));	
  1.2505 +    
  1.2506 +    // Create the shared chunk. The PDD supplies most of the chunk create info - but not the maximum size.
  1.2507 +	TChunkCreateInfo info;
  1.2508 +	info.iMaxSize=chunkSz;
  1.2509 +	iLdd->Pdd()->GetChunkCreateInfo(info);		// Call down to the PDD for the rest.
  1.2510 +	
  1.2511 +	r = Kern::ChunkCreate(info,iChunk,iChunkBase,iChunkMapAttr);
  1.2512 +	__KTRACE_OPT(KSOUND1, Kern::Printf("Create chunk - %d",r));	
  1.2513 +	if (r!=KErrNone)
  1.2514 +     	return(r);
  1.2515 +	
  1.2516 +	if (aBufConfig->iFlags & KScFlagUseGuardPages)
  1.2517 +		{
  1.2518 +		// Map each of the buffers into the chunk separately - try to allocate physically contiguous RAM pages. Create a buffer object for each buffer.
  1.2519 + 		TBool isContiguous;
  1.2520 + 		for (TInt i=0 ; i<aBufConfig->iNumBuffers ; i++)
  1.2521 +			{
  1.2522 +			r=CommitMemoryForBuffer(bufferOffsetList[i],bufferSz,isContiguous);
  1.2523 +			if (r!=KErrNone)
  1.2524 +				return(r);
  1.2525 +			r=iAudioBuffers[i].Create(iChunk,bufferOffsetList[i],(aBufConfig->iBufferSizeInBytes),isContiguous,this);
  1.2526 +			if (r!=KErrNone)
  1.2527 +				return(r);	
  1.2528 +			}		
  1.2529 +		}
  1.2530 +	else
  1.2531 +		{
  1.2532 +		// Map memory for the all buffers into the chunk - try to allocate physically contiguous RAM pages. 
  1.2533 + 		TBool isContiguous;
  1.2534 +		r=CommitMemoryForBuffer(0,chunkSz,isContiguous);
  1.2535 +		if (r!=KErrNone)
  1.2536 +			return(r);
  1.2537 +		
  1.2538 +		// Create a buffer object for each buffer.
  1.2539 + 		for (TInt i=0 ; i<aBufConfig->iNumBuffers ; i++)
  1.2540 +			{
  1.2541 +			r=iAudioBuffers[i].Create(iChunk,bufferOffsetList[i],(aBufConfig->iBufferSizeInBytes),isContiguous,this);
  1.2542 +			if (r!=KErrNone)
  1.2543 +				return(r);	
  1.2544 +			}	
  1.2545 +		}
  1.2546 +
  1.2547 +	// Read back and store the maximum transfer length supported by this device from the PDD.
  1.2548 +	iMaxTransferLen=iLdd->Pdd()->MaxTransferLen();
  1.2549 +	
  1.2550 +    __KTRACE_OPT(KSOUND1, Kern::Printf("<DBufferManager::Create - %d",r));
  1.2551 +	return(r);
  1.2552 +	}
  1.2553 +	
  1.2554 +/**
  1.2555 +Second stage constructor for the buffer manager. This version opens an existing shared chunk using a client supplied
  1.2556 +handle. It then creates a buffer object for each buffer that exists within the chunk as well as creating a set of buffer
  1.2557 +lists to manage the buffers.
  1.2558 +@param aBufConfig The shared chunk buffer configuration object - specifying the geometry of the buffer configuration
  1.2559 +within the shared chunk supplied.
  1.2560 +@param aChunkHandle A handle for the shared chunk supplied by the client.
  1.2561 +@param anOwningThread The thread in which the given handle is valid.
  1.2562 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2563 +@pre The thread must be in a critical section.
  1.2564 +*/
  1.2565 +TInt DBufferManager::Create(TSoundSharedChunkBufConfig& aBufConfig,TInt aChunkHandle,DThread* anOwningThread)
  1.2566 +	{	
  1.2567 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::Create(Handle-%d)",aChunkHandle));
  1.2568 +
  1.2569 +	// Validate the buffer configuration information.
  1.2570 +	if (!aBufConfig.iFlags&KScFlagBufOffsetListInUse)
  1.2571 +		return(KErrArgument);
  1.2572 +	TInt numBuffers=aBufConfig.iNumBuffers;
  1.2573 +	TInt bufferSizeInBytes=aBufConfig.iBufferSizeInBytes;
  1.2574 +	TInt* bufferOffsetList=&aBufConfig.iBufferOffsetListStart;
  1.2575 +	TInt r=ValidateBufferOffsets(bufferOffsetList,numBuffers,bufferSizeInBytes);
  1.2576 +	if (r<0)
  1.2577 +		return(r);
  1.2578 +	
  1.2579 +	// Create the required number of buffer objects, and the buffer lists to manage these.
  1.2580 +	r=CreateBufferLists(numBuffers);
  1.2581 +	if (r!=KErrNone)
  1.2582 +		return(r);
  1.2583 +	
  1.2584 +	// Open the shared chunk.
  1.2585 +	DChunk* chunk;
  1.2586 +	chunk=Kern::OpenSharedChunk(anOwningThread,aChunkHandle,ETrue);
  1.2587 +	if (!chunk)
  1.2588 +		return(KErrBadHandle);
  1.2589 +	iChunk=chunk;
  1.2590 +	
  1.2591 +	// Read the physical address for the 1st buffer in order to determine the kernel address and the map attributes.
  1.2592 +	TInt offset=bufferOffsetList[0];
  1.2593 +	TPhysAddr physAddr;
  1.2594 +	TLinAddr kernelAddress;
  1.2595 +	r=Kern::ChunkPhysicalAddress(iChunk,offset,bufferSizeInBytes,kernelAddress,iChunkMapAttr,physAddr,NULL);
  1.2596 +	if (r!=KErrNone)
  1.2597 +		return(r);
  1.2598 +	iChunkBase=(kernelAddress-offset);
  1.2599 +	
  1.2600 +	// For each buffer, validate that the buffer specified contains committed memory and store the buffer info. into each buffer object.
  1.2601 +	while (numBuffers)
  1.2602 +		{
  1.2603 +		numBuffers--;
  1.2604 +		offset=bufferOffsetList[numBuffers];
  1.2605 +		// Assume it isn't contiguous here - Create() will detect and do the right thing if it is contiguous.
  1.2606 +		r=iAudioBuffers[numBuffers].Create(iChunk,offset,bufferSizeInBytes,EFalse,this);	
  1.2607 +		if (r!=KErrNone)
  1.2608 +			return(r);
  1.2609 +		}
  1.2610 +		
  1.2611 +	// Read back and store the maximum transfer length supported by this device from the PDD.
  1.2612 +	iMaxTransferLen=iLdd->Pdd()->MaxTransferLen();	
  1.2613 +		
  1.2614 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DBufferManager::Create - %d",KErrNone));
  1.2615 +	return(KErrNone);
  1.2616 +	}
  1.2617 +
  1.2618 +/**
  1.2619 +Allocate an array of buffer objects, - one for each buffer contained within the shared chunk.
  1.2620 +@param aNumBuffers The number of buffer objects required.
  1.2621 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2622 +@pre The thread must be in a critical section.
  1.2623 +*/
  1.2624 +TInt DBufferManager::CreateBufferLists(TInt aNumBuffers)
  1.2625 +	{
  1.2626 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::CreateBufferLists(Bufs-%d)",aNumBuffers));
  1.2627 +
  1.2628 +	// Construct the array of buffers.
  1.2629 +	iNumBuffers=aNumBuffers;
  1.2630 +	iAudioBuffers=new TAudioBuffer[aNumBuffers];
  1.2631 +	if (!iAudioBuffers)
  1.2632 +		return(KErrNoMemory);
  1.2633 +	
  1.2634 +	return(KErrNone);
  1.2635 +	}
  1.2636 +	
  1.2637 +/**
  1.2638 +Validate a shared chunk buffer offset list.
  1.2639 +@param aBufferOffsetList The buffer offset list to be validated.
  1.2640 +@param aNumBuffers The number of offsets that the list contains.
  1.2641 +@param aBufferSizeInBytes The size in bytes of each buffer.
  1.2642 +@return If the buffer list is found to be valid, the calculated minimum size of the corresponding chunk is returned
  1.2643 +	(i.e. a value>=0). Otherwise, KErrArgument is returned.
  1.2644 +*/
  1.2645 +TInt DBufferManager::ValidateBufferOffsets(TInt* aBufferOffsetList,TInt aNumBuffers,TInt aBufferSizeInBytes)	
  1.2646 +	{
  1.2647 +	TUint32 alignmask=(1<<iLdd->iCaps.iRequestAlignment)-1; // iRequestAlignment holds log to base 2 of alignment required
  1.2648 +			
  1.2649 +	// Verify each of the buffer offsets supplied
  1.2650 +	TInt offset=0;
  1.2651 +	for (TInt i=0 ; i<aNumBuffers ; i++)
  1.2652 +		{
  1.2653 +		// If this is a record channel then the offset must comply with the PDD alignment constraints.
  1.2654 +		if (iLdd->iDirection==ESoundDirRecord && ((TUint32)aBufferOffsetList[i] & alignmask) != 0)	
  1.2655 +			return(KErrArgument);
  1.2656 +			
  1.2657 +		// Check the offset doesn't overlap the previous buffer - offset holds the offset to next byte after
  1.2658 +		// the previous buffer.
  1.2659 +		if (aBufferOffsetList[i]<offset)
  1.2660 +			return(KErrArgument);
  1.2661 +		
  1.2662 +		offset=(aBufferOffsetList[i]+aBufferSizeInBytes);
  1.2663 +		}
  1.2664 +	return(offset);	
  1.2665 +	}
  1.2666 +	
  1.2667 +/**
  1.2668 +Verify that a specified region of the shared chunk (specified by its offset and length) is valid within the 
  1.2669 +chunk and corresponds to a region of committed memory.
  1.2670 +@param aChunkOffset Offset of the region from the beginning of the chunk.
  1.2671 +@param aLength The length in bytes of the region.
  1.2672 +@param anAudioBuffer A reference to a pointer to an audio buffer object. On return this will either contain a pointer
  1.2673 +to the audio buffer object which corresonds to the specified region, or NULL if the region is invalid.
  1.2674 +@return KErrNone if the region is valid, otherwise KErrArgument.
  1.2675 +*/	
  1.2676 +TInt DBufferManager::ValidateRegion(TUint aChunkOffset,TUint aLength,TAudioBuffer*& anAudioBuffer)
  1.2677 +	{
  1.2678 +	
  1.2679 +	TUint bufStart;
  1.2680 +	TUint bufEnd;
  1.2681 +	TUint regEnd=(aChunkOffset+aLength);
  1.2682 +	for (TInt i=0 ; i<iNumBuffers ; i++)
  1.2683 +		{
  1.2684 +		bufStart=iAudioBuffers[i].iChunkOffset;
  1.2685 +		bufEnd=iAudioBuffers[i].iChunkOffset+iAudioBuffers[i].iSize;
  1.2686 +		if (aChunkOffset<bufStart || aChunkOffset>=bufEnd)
  1.2687 +			continue;
  1.2688 +		if (regEnd<=bufEnd)
  1.2689 +			{
  1.2690 +			anAudioBuffer=&iAudioBuffers[i];
  1.2691 +			return(KErrNone);
  1.2692 +			}
  1.2693 +		}
  1.2694 +	return(KErrArgument);
  1.2695 +	}
  1.2696 +			
  1.2697 +/**
  1.2698 +Commit memory for a single buffer within the shared chunk.
  1.2699 +@param aChunkOffset The offset (in bytes) from start of chunk, which indicates the start of the memory region to be
  1.2700 +	committed. Must be a multiple of the MMU page size. 
  1.2701 +@param aSize The number of bytes to commit. Must be a multiple of the MMU page size.
  1.2702 +@param aIsContiguous On return, this is set to ETrue if the function succeeded in committing physically contiguous memory;
  1.2703 +	EFalse if the committed memory is not contiguous.	
  1.2704 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2705 +*/	
  1.2706 +TInt DBufferManager::CommitMemoryForBuffer(TInt aChunkOffset,TInt aSize,TBool& aIsContiguous)
  1.2707 +	{
  1.2708 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::CommitMemoryForBuffer(Offset-%x,Sz-%d)",aChunkOffset,aSize));
  1.2709 +	
  1.2710 +	// Try for physically contiguous memory first.
  1.2711 +	TInt r;	
  1.2712 +	TPhysAddr physicalAddress;
  1.2713 +	r=Kern::ChunkCommitContiguous(iChunk,aChunkOffset,aSize,physicalAddress);
  1.2714 +	if (r==KErrNone)
  1.2715 +		{
  1.2716 +		aIsContiguous=ETrue;
  1.2717 +		return(r);
  1.2718 +		}
  1.2719 +			
  1.2720 +	// Try to commit memory that isn't contiguous instead.
  1.2721 +	aIsContiguous=EFalse;
  1.2722 +	r=Kern::ChunkCommit(iChunk,aChunkOffset,aSize);
  1.2723 +	return(r);
  1.2724 +	}
  1.2725 +	
  1.2726 +/**
  1.2727 +Purge a region of the audio chunk. That is, if this region contains cacheable memory, flush it.
  1.2728 +@param aChunkOffset The offset within the chunk for the start of the data to be flushed.
  1.2729 +@param aLength The length in bytes of the region to be flushed.
  1.2730 +@param aFlushOp The type of flush operation required - @see TFlushOp.
  1.2731 +*/
  1.2732 +void DBufferManager::FlushData(TInt aChunkOffset,TInt aLength,TFlushOp aFlushOp)
  1.2733 +	{
  1.2734 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::FlushData(%d)",aFlushOp));
  1.2735 +	TLinAddr dataAddr=(iChunkBase+aChunkOffset);
  1.2736 +	switch (aFlushOp)
  1.2737 +		{
  1.2738 +		case EFlushBeforeDmaWrite:
  1.2739 +			Cache::SyncMemoryBeforeDmaWrite(dataAddr,aLength,iChunkMapAttr);
  1.2740 +			break;
  1.2741 +		case EFlushBeforeDmaRead:
  1.2742 +			Cache::SyncMemoryBeforeDmaRead(dataAddr,aLength,iChunkMapAttr);
  1.2743 +			break;
  1.2744 +		case EFlushAfterDmaRead:
  1.2745 +			Cache::SyncMemoryAfterDmaRead(dataAddr,aLength);
  1.2746 +			break;
  1.2747 +		default:
  1.2748 +			break;
  1.2749 +		}
  1.2750 +	}
  1.2751 +		
  1.2752 +/**
  1.2753 +Constructor for the record buffer manager.
  1.2754 +*/
  1.2755 +DRecordBufferManager::DRecordBufferManager(DSoundScLdd* aLdd)
  1.2756 +	: DBufferManager(aLdd)
  1.2757 +	{
  1.2758 +	}
  1.2759 +			
  1.2760 +/**
  1.2761 +Reset all the audio buffer lists to reflect the state at the start of the record capture process.
  1.2762 +@pre The buffer/request queue mutex must be held.
  1.2763 +*/
  1.2764 +void DRecordBufferManager::Reset()
  1.2765 +	{
  1.2766 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::Reset"));
  1.2767 +	TAudioBuffer* pBuf;
  1.2768 +	
  1.2769 +	// Before reseting buffer lists, purge the cache for all cached buffers currently in use by client.
  1.2770 +	pBuf=(TAudioBuffer*)iInUseBufferQ.First();
  1.2771 +	SDblQueLink* anchor=&iInUseBufferQ.iA;
  1.2772 +	while (pBuf!=anchor)
  1.2773 +		{
  1.2774 +		pBuf->Flush(DBufferManager::EFlushBeforeDmaRead);
  1.2775 +		pBuf=(TAudioBuffer*)pBuf->iNext;
  1.2776 +		}
  1.2777 +		
  1.2778 +	// Start by reseting all the lists.
  1.2779 +	iFreeBufferQ.iA.iNext=iFreeBufferQ.iA.iPrev=&iFreeBufferQ.iA;	
  1.2780 +	iCompletedBufferQ.iA.iNext=iCompletedBufferQ.iA.iPrev=&iCompletedBufferQ.iA;
  1.2781 +	iInUseBufferQ.iA.iNext=iInUseBufferQ.iA.iPrev=&iInUseBufferQ.iA;	
  1.2782 +		
  1.2783 +	// Set the pointers to the current and the next record buffers.
  1.2784 +	pBuf=iAudioBuffers; 		// This is the first buffer
  1.2785 +	iCurrentBuffer=pBuf++;
  1.2786 +	iNextBuffer = pBuf++;
  1.2787 +	
  1.2788 +	// Add all other buffers to the free list.
  1.2789 +	TAudioBuffer* bufferLimit=iAudioBuffers+iNumBuffers; 
  1.2790 +	while(pBuf<bufferLimit)
  1.2791 +		iFreeBufferQ.Add(pBuf++);
  1.2792 +	
  1.2793 +	iBufOverflow=EFalse;	
  1.2794 +	}
  1.2795 +	
  1.2796 +/**
  1.2797 +Update buffer lists after a record buffer has been filled.
  1.2798 +@param aBytesAdded The number of bytes added to the buffer to get it into the 'filled' state. Of course, this is
  1.2799 +	normally equal to the size of the buffer. The exception is when recording has been paused: in which
  1.2800 +	case the number of bytes added to 'fill' the buffer may be less than the buffer size.
  1.2801 +@param aTransferResult The result of the transfer.	
  1.2802 +@return A pointer to the next buffer for recording.
  1.2803 +@pre The buffer/request queue mutex must be held.
  1.2804 +*/
  1.2805 +TAudioBuffer* DRecordBufferManager::SetBufferFilled(TInt aBytesAdded,TInt aTransferResult)
  1.2806 +	{
  1.2807 +	// If record has been paused then its possible (depending on the PDD implementation) that although the current
  1.2808 +	// buffer is marked as being filled, no data has been added. If this is the case then there is no point in informing 
  1.2809 +	// the client about it. Instead we need to return it to the free list. Otherwise the more normal course of action is
  1.2810 +	// to add the current buffer to the completed list ready for the client. If there is any amount of data in the record
  1.2811 +	// buffer, this needs to be passed to the client (and if we're not paused then each buffer should actually be full).
  1.2812 +	// If an error occured then we always add the buffer to the completed list.
  1.2813 +	TAudioBuffer* buffer=iCurrentBuffer;
  1.2814 +	if (aBytesAdded || aTransferResult)
  1.2815 +		{
  1.2816 +		buffer->iBytesAdded=aBytesAdded;
  1.2817 +		buffer->iResult=aTransferResult;
  1.2818 +		iCompletedBufferQ.Add(buffer);
  1.2819 +		}
  1.2820 +	else
  1.2821 +		iFreeBufferQ.Add(buffer);
  1.2822 +
  1.2823 +	// Make the pending buffer the current one.
  1.2824 +	iCurrentBuffer=iNextBuffer;
  1.2825 +
  1.2826 +	// Obtain the next pending buffer. If there are none left on the free list then we have to take one back
  1.2827 +	// from the completed list.
  1.2828 +	iNextBuffer=(TAudioBuffer*)iFreeBufferQ.GetFirst();
  1.2829 +	if (!iNextBuffer)
  1.2830 +		{
  1.2831 +		iNextBuffer=(TAudioBuffer*)iCompletedBufferQ.GetFirst();
  1.2832 +		iBufOverflow=ETrue;	// This is the buffer overflow situation.
  1.2833 +		}
  1.2834 +	__ASSERT_DEBUG(iNextBuffer,Kern::Fault(KSoundLddPanic,__LINE__));	
  1.2835 +	iNextBuffer->iBytesAdded=0;
  1.2836 +	
  1.2837 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DBufferManager::SetBufferFilled(buf=%08x len=%d)",buffer->iChunkOffset,buffer->iBytesAdded));
  1.2838 +	return(iNextBuffer);
  1.2839 +	}
  1.2840 +
  1.2841 +/**
  1.2842 +Get the next record buffer from the completed buffer list. If there is no error associated with the buffer, 
  1.2843 +make it 'in use' by the client. Otherwise, return the buffer to the free list.
  1.2844 +@return A pointer to the next completed buffer or NULL if there isn't one available.
  1.2845 +@pre The buffer/request queue mutex must be held.
  1.2846 +*/
  1.2847 +TAudioBuffer* DRecordBufferManager::GetBufferForClient()
  1.2848 +	{	
  1.2849 +	TAudioBuffer* buffer=(TAudioBuffer*)iCompletedBufferQ.GetFirst();
  1.2850 +	if (buffer)
  1.2851 +		{
  1.2852 +		if (buffer->iResult==KErrNone)
  1.2853 +			iInUseBufferQ.Add(buffer);
  1.2854 +		else
  1.2855 +			iFreeBufferQ.Add(buffer);
  1.2856 +		}
  1.2857 +	
  1.2858 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<DBufferManager::BufferForClient(buf=%08x)",(buffer ? buffer->iChunkOffset : -1)));
  1.2859 +	return(buffer);
  1.2860 +	}
  1.2861 +
  1.2862 +/**
  1.2863 +Release (move to free list) the 'in use' record buffer specified by the given chunk offset.
  1.2864 +@param aChunkOffset The chunk offset corresponding to the buffer to be freed.
  1.2865 +@return The freed buffer, or NULL if no 'in use' buffer had the specified chunk offset.
  1.2866 +@pre The buffer/request queue mutex must be held.
  1.2867 +*/
  1.2868 +TAudioBuffer* DRecordBufferManager::ReleaseBuffer(TInt aChunkOffset)
  1.2869 +	{
  1.2870 +	// Scan 'in use' list for the audio buffer
  1.2871 +	TAudioBuffer* pBuf;
  1.2872 +	pBuf=(TAudioBuffer*)iInUseBufferQ.First();
  1.2873 +	SDblQueLink* anchor=&iInUseBufferQ.iA;
  1.2874 +	while (pBuf!=anchor && pBuf->iChunkOffset!=aChunkOffset)
  1.2875 +		pBuf=(TAudioBuffer*)pBuf->iNext;
  1.2876 +	
  1.2877 +	// Move buffer to the free list (if found)
  1.2878 +	if (pBuf!=anchor)
  1.2879 +		iFreeBufferQ.Add(pBuf->Deque());
  1.2880 +	else
  1.2881 +		pBuf=NULL;
  1.2882 +	
  1.2883 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">DBufferManager::BufferRelease(buf=%08x)",(pBuf ? pBuf->iChunkOffset : -1)));
  1.2884 +	return(pBuf);
  1.2885 +	}
  1.2886 +
  1.2887 +/**
  1.2888 +Constructor for the audio buffer class.
  1.2889 +Clears all member data
  1.2890 +*/
  1.2891 +TAudioBuffer::TAudioBuffer()
  1.2892 +	{
  1.2893 +	memclr(this,sizeof(*this));
  1.2894 +	}
  1.2895 +
  1.2896 +/**
  1.2897 +Destructor for the audio buffer class.
  1.2898 +*/
  1.2899 +TAudioBuffer::~TAudioBuffer()
  1.2900 +	{
  1.2901 +	delete[] iPhysicalPages;
  1.2902 +	}
  1.2903 +	
  1.2904 +/**
  1.2905 +Second stage constructor for the audio buffer class - validate and acquire information on the memory
  1.2906 +allocated to this buffer.
  1.2907 +@param aChunk  The chunk in which this buffer belongs.
  1.2908 +@param aChunkOffset The offset within aChunk to the start of the audio buffer.
  1.2909 +@param aSize The size (in bytes) of the buffer.
  1.2910 +@param aIsContiguous A boolean indicating whether the buffer contains physically contiguous memory. Set to ETrue if it
  1.2911 +	does physically contiguous memory, EFalse otherwise.		
  1.2912 +@param aBufManager A pointer to the buffer manager which owns this object.
  1.2913 +@return KErrNone if successful, otherwise one of the other system wide error codes.
  1.2914 +@pre The thread must be in a critical section.
  1.2915 +*/
  1.2916 +TInt TAudioBuffer::Create(DChunk* aChunk,TInt aChunkOffset,TInt aSize,TBool aIsContiguous,DBufferManager* aBufManager)
  1.2917 +	{
  1.2918 +	__KTRACE_OPT(KSOUND1, Kern::Printf(">TAudioBuffer::Create(Off-%x,Sz-%d,Contig-%d)",aChunkOffset,aSize,aIsContiguous));
  1.2919 +
  1.2920 +	// Save info. on the offset and size of the buffer. Also the buffer manager.
  1.2921 +	iChunkOffset=aChunkOffset;
  1.2922 +	iSize=aSize;
  1.2923 +	iBufManager=aBufManager;
  1.2924 +
  1.2925 +	TInt r=KErrNone;
  1.2926 +	iPhysicalPages=NULL;
  1.2927 +	if (!aIsContiguous)
  1.2928 +		{
  1.2929 +		// Allocate an array for a list of the physical pages.
  1.2930 +		iPhysicalPages = new TPhysAddr[aSize/Kern::RoundToPageSize(1)+2];
  1.2931 +		if (!iPhysicalPages)
  1.2932 +			r=KErrNoMemory;	
  1.2933 +		}
  1.2934 +		
  1.2935 +	if (r==KErrNone)
  1.2936 +		{
  1.2937 +		// Check that the region of the chunk specified for the buffer contains committed memory. If so, get the physical addresses of the
  1.2938 +		// pages in this buffer.
  1.2939 +		TUint32 kernAddr;
  1.2940 +		TUint32 mapAttr;
  1.2941 +		r=Kern::ChunkPhysicalAddress(aChunk,aChunkOffset,aSize,kernAddr,mapAttr,iPhysicalAddress,iPhysicalPages);
  1.2942 +		// r = 0 or 1 on success. (1 meaning the physical pages are not contiguous).
  1.2943 +		if (r==1)
  1.2944 +			{
  1.2945 +			// The physical pages are not contiguous.
  1.2946 +			iPhysicalAddress=KPhysAddrInvalid;	// Mark the physical address as invalid.
  1.2947 +			r=(aIsContiguous) ? KErrGeneral : KErrNone;
  1.2948 +			}
  1.2949 +		if (r==0)
  1.2950 +			{
  1.2951 +			delete[] iPhysicalPages;	// We shouldn't retain this info. if the physical pages are contiguous.
  1.2952 +			iPhysicalPages=NULL;
  1.2953 +			}
  1.2954 +			
  1.2955 +		}
  1.2956 +	__KTRACE_OPT(KSOUND1, Kern::Printf("<TAudioBuffer::Create - %d",r));
  1.2957 +	return(r);
  1.2958 +	}
  1.2959 +
  1.2960 +/**
  1.2961 +Calculate the length for the next part of a data transfer request so that that the length returned specifies a physically
  1.2962 +contiguous region and is also valid for the PDD. If necessary, return a truncated length that meets these criteria. Also,
  1.2963 +return the physical address of the start of the region specified.
  1.2964 +@param aChunkOffset The offset within the chunk for the start of the data transfer being fragmented.
  1.2965 +@param aLengthRemaining The remaining length of the data transfer request.
  1.2966 +@param aPhysAddr On return, this contains the physical address corresonding to aChunkOffset.
  1.2967 +@return The length calculated.
  1.2968 +*/	
  1.2969 +TInt TAudioBuffer::GetFragmentLength(TInt aChunkOffset,TInt aLengthRemaining,TPhysAddr& aPhysAddr)		
  1.2970 +	{
  1.2971 +	TInt len;
  1.2972 +	TInt bufOffset=(aChunkOffset - iChunkOffset); 	// Convert from chunk offset to buffer offset.
  1.2973 +	
  1.2974 +	if (iPhysicalAddress==KPhysAddrInvalid)
  1.2975 +		{
  1.2976 +		// Buffer is not physically contiguous. Truncate length to the next page boundary. Then calculate physical addr.
  1.2977 +		// (This function doesn't look for pages which are contiguous within the physical page list - but it could).
  1.2978 +		TInt pageSize=Kern::RoundToPageSize(1);
  1.2979 +		TInt pageOffset=bufOffset%pageSize;
  1.2980 +		len=pageSize - pageOffset;
  1.2981 +		aPhysAddr=iPhysicalPages[bufOffset/pageSize] + pageOffset;
  1.2982 +		}
  1.2983 +	else
  1.2984 +		{
  1.2985 +		// Buffer is physically contiguous so no need to truncate the length. Then calculate physical address.  
  1.2986 +		len=aLengthRemaining;
  1.2987 +		aPhysAddr=iPhysicalAddress + bufOffset;
  1.2988 +		}
  1.2989 +		
  1.2990 +	// Ensure length does not exceed the max. supported by the PDD.
  1.2991 +	len=Min(iBufManager->iMaxTransferLen,len);		
  1.2992 +	return(len);
  1.2993 +	}
  1.2994 +	
  1.2995 +/**
  1.2996 +Purge the entire audio buffer. That is, if it contains cacheable memory, flush it.
  1.2997 +@param aFlushOp The type of flush operation required - @see DBufferManager::TFlushOp.
  1.2998 +*/
  1.2999 +void TAudioBuffer::Flush(DBufferManager::TFlushOp aFlushOp)
  1.3000 +	{
  1.3001 +	iBufManager->FlushData(iChunkOffset,iSize,aFlushOp);
  1.3002 +	}
  1.3003 +