omxilvideocomps/omxilclock/src/clocksupervisor.cpp
changeset 0 5d29cba61097
equal deleted inserted replaced
-1:000000000000 0:5d29cba61097
       
     1 /*
       
     2 * Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of "Eclipse Public License v1.0"
       
     6 * which accompanies this distribution, and is available
       
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Nokia Corporation - initial contribution.
       
    11 *
       
    12 * Contributors:
       
    13 *
       
    14 * Description:
       
    15 *
       
    16 */
       
    17 
       
    18 
       
    19 // NOTE: Assumes OMX_SKIP64BIT is not set when building OMX CORE
       
    20 
       
    21 #include <hal.h>
       
    22 #include <openmax/il/khronos/v1_x/OMX_Other.h>	// OMX port
       
    23 #include <openmax/il/common/omxilspecversion.h>	// OMX version number
       
    24 #include "clocksupervisor.h"
       
    25 #include "comxilclockprocessingfunction.h"
       
    26 #include "clockpanics.h"
       
    27 #include "omxilclock.hrh"
       
    28 
       
    29 #include "log.h"
       
    30 
       
    31 //////////////
       
    32 // File scoped constants
       
    33 //
       
    34 
       
    35 /** The maximum number of simultaneous outstanding requests (across all ports) */
       
    36 static const TUint KMaxRequests = 20;
       
    37 static const TUint KThreadStackSize = 1024;
       
    38 
       
    39 /**
       
    40  * Assumption that timer will always take at least this long to complete.
       
    41  * How soon an outstanding delay must be before we complete immediately instead of setting a timer.
       
    42  */
       
    43 static const TInt KMinTimerOverhead = 1000;	// 1000usecs = 1ms
       
    44 
       
    45 // assumption that timers go off at some time rounded to this many microseconds
       
    46 static const TInt KTimerQuantization = 
       
    47 #ifdef __WINSCW__
       
    48 	15000;
       
    49 #else
       
    50 	1;
       
    51 #endif
       
    52 
       
    53 // aim to select a counter accurate to ~1ms
       
    54 #ifdef __WINSCW__
       
    55 #define USE_FASTCOUNTER // typically faster than 1ms on emulator, 1ms on hardware
       
    56 #else
       
    57 #define USE_NTICKCOUNT	// typically 5ms on emulator, 1ms on hardware
       
    58 #endif
       
    59 
       
    60 #if !defined(USE_FASTCOUNTER) && !defined(USE_NTICKCOUNT)
       
    61 #error Either USE_FASTCOUNTER or USE_NTICKCOUNT must be defined
       
    62 #endif
       
    63 
       
    64 /**
       
    65  * Structure to map OMX_INDEXTYPE to behaviour required by the Clock component.
       
    66  */
       
    67 
       
    68 // Indexes for time configs start after OMX_IndexTimeStartUnused = 0x09000000
       
    69 // Simply deduct this to index this table
       
    70 
       
    71 static const OMX_INDEXTYPE KMinJumpTableIndex = OMX_IndexConfigTimeScale;
       
    72 static const OMX_INDEXTYPE KMaxJumpTableIndex = OMX_IndexConfigTimeClientStartTime;
       
    73 
       
    74 const CClockSupervisor::FunctionPtr CClockSupervisor::iJumpTable[] = 
       
    75 	{
       
    76 	/*OMX_IndexConfigTimeScale*/					&CClockSupervisor::HandleGetSetTimeScale	     ,// requires buffers
       
    77 	/*OMX_IndexConfigTimeClockState*/				&CClockSupervisor::HandleGetSetClockState	     ,// requires buffers
       
    78 	/*OMX_IndexConfigTimeActiveRefClock*/			&CClockSupervisor::HandleGetSetActiveRefClock  ,
       
    79 	/*OMX_IndexConfigTimeCurrentMediaTime*/			&CClockSupervisor::HandleQueryCurrentMediaTime ,
       
    80 	/*OMX_IndexConfigTimeCurrentWallTime*/			&CClockSupervisor::HandleQueryCurrentWallTime	 ,
       
    81 	/*OMX_IndexConfigTimeCurrentAudioReference*/	&CClockSupervisor::HandleUpdateAudioReference	 ,
       
    82 	/*OMX_IndexConfigTimeCurrentVideoReference*/	&CClockSupervisor::HandleUpdateVideoReference	 ,
       
    83 	/*OMX_IndexConfigTimeMediaTimeRequest*/			&CClockSupervisor::HandleSubmitMediaTimeRequest,// requires buffers
       
    84 	/*OMX_IndexConfigTimeClientStartTime*/			&CClockSupervisor::HandleSetPortClientStartTime,
       
    85 	};
       
    86 
       
    87 #ifdef _DEBUG
       
    88 #define CHECK_DEBUG()	DbgCheck()
       
    89 #else
       
    90 #define CHECK_DEBUG()
       
    91 #endif
       
    92 
       
    93 
       
    94 //////////////
       
    95 
       
    96 
       
    97 /**
       
    98  * Euclid's algorithm.
       
    99  * Returns the largest common factor of aX and aY.
       
   100  */
       
   101 static TInt LargestCommonFactor(TInt aX, TInt aY)
       
   102 	{
       
   103 	// based on knowledge that lcf(x,0)=x, lcf(x,y)=lcf(y,x) and lcf(x,y)=lcf(y,x%y)
       
   104 	while(aX != 0)
       
   105 		{
       
   106 		aY %= aX;
       
   107 		if(aY == 0)
       
   108 			{
       
   109 			return aX;
       
   110 			}
       
   111 		aX %= aY;
       
   112 		}
       
   113 	return aY;
       
   114 	}
       
   115 
       
   116 
       
   117 /**
       
   118  *
       
   119  *
       
   120  */
       
   121 CClockSupervisor* CClockSupervisor::NewL(COmxILClockProcessingFunction& aProcessingFunction)
       
   122 	{
       
   123 	CClockSupervisor* self = new (ELeave) CClockSupervisor(aProcessingFunction);
       
   124 	CleanupStack::PushL(self);
       
   125 	self->ConstructL();
       
   126 	CleanupStack::Pop(self);
       
   127 	return self;
       
   128 	}
       
   129 
       
   130 
       
   131 /**
       
   132  *
       
   133  *
       
   134  */
       
   135 void CClockSupervisor::ConstructL()
       
   136 	{
       
   137 	// calculate tick frequency
       
   138 	//
       
   139 #ifdef USE_FASTCOUNTER
       
   140 	TInt frequency;	// tick frequency in Hz
       
   141 	User::LeaveIfError(HAL::Get(HAL::EFastCounterFrequency, frequency));
       
   142 	// conversion factor from ticks into microseconds
       
   143 	// using a fraction in integer arithmetic
       
   144 	iMicroConvNum = 1000000;
       
   145 	iMicroConvDen = frequency;
       
   146 	TInt countsUp;
       
   147 	User::LeaveIfError(HAL::Get(HAL::EFastCounterCountsUp, countsUp));
       
   148 	iSystemClockReversed = !countsUp;
       
   149 #elif defined(USE_NTICKCOUNT)
       
   150 	User::LeaveIfError(HAL::Get(HAL::ENanoTickPeriod, iMicroConvNum)); // tick period in microseconds
       
   151 	iMicroConvDen = 1;
       
   152 #else	
       
   153 #error
       
   154 #endif
       
   155 	
       
   156 	// divide out any common factor to reduce chance of overflow
       
   157 	TInt factor = LargestCommonFactor(iMicroConvNum, iMicroConvDen);
       
   158 	iMicroConvNum /= factor;
       
   159 	iMicroConvDen /= factor;
       
   160 
       
   161 	// wraparound time in microseconds is 2^32 * iMicroConv
       
   162 	// take the heartbeat interval as half of this (i.e shift left by 31 places) to ensure we wake up often enough to implement the carry properly
       
   163 	TUint64 interval = (static_cast<TUint64>(iMicroConvNum) << 31) / iMicroConvDen;
       
   164 	if (interval > KMaxTInt32)
       
   165 		{
       
   166 		iHeartbeatTimerInterval = KMaxTInt32;
       
   167 		}
       
   168 	else
       
   169 		{
       
   170 		iHeartbeatTimerInterval = interval;
       
   171 		}
       
   172 
       
   173 	// if denominator is a power of 2, use shift instead
       
   174 	// (shifting is faster than division)
       
   175 	if(iMicroConvDen & (iMicroConvDen - 1) == 0)
       
   176 		{
       
   177 		// PRECONDITION:  iMicroConvDen = 2^n, iMicroConvShift = 0
       
   178 		// POSTCONDITION: iMicroConvDen = 1,   iMicroConvShift = n
       
   179 		while(iMicroConvDen >= 2)
       
   180 			{
       
   181 			iMicroConvDen >>= 1;
       
   182 			iMicroConvShift++;
       
   183 			}
       
   184 		}
       
   185 
       
   186 	// Create the locks
       
   187 	User::LeaveIfError(iQueMutex.CreateLocal());
       
   188 	
       
   189 	// Create the memory block of empty Time requests that make up the free list.
       
   190 	iRequestBlock = new(ELeave) TMediaRequest [iMaxRequests];
       
   191 	
       
   192 	// zero the fields for peace of mind
       
   193 	Mem::FillZ(iRequestBlock, (sizeof(TMediaRequest)*iMaxRequests));
       
   194 	
       
   195    	// Initialise the free list
       
   196    	for(TInt requestIndex = 0; requestIndex < iMaxRequests; requestIndex++)
       
   197    		{
       
   198    		// Add all free items with delta 0
       
   199    		iFreeRequestQue.Add(iRequestBlock+requestIndex, static_cast<TInt64>(0));
       
   200    		}
       
   201    	
       
   202    	iStartTimes.ReserveL(KNumPorts);
       
   203    	for(TInt portIndex = 0; portIndex < KNumPorts; portIndex++)
       
   204    		{
       
   205    		iStartTimes.Append(0);
       
   206    		}
       
   207    	
       
   208 	__ASSERT_DEBUG(iMaxRequests == iFreeRequestQue.Count(), Panic(ERequestQueueCorrupt));
       
   209 
       
   210 	// Create the timer consumer thread
       
   211 	TBuf<19> threadName;
       
   212 	threadName.Format(_L("OmxILClock@%08X"), this);
       
   213 	
       
   214 	// Timer created on creation of the thread as it is thread relative
       
   215 	User::LeaveIfError(iThread.Create(threadName, ThreadEntryPoint, KThreadStackSize, NULL, this));
       
   216 
       
   217 	// High priority thread
       
   218 	iThread.SetPriority(EPriorityRealTime);
       
   219 	// start the thread and wait for it to create the timer
       
   220 	TRequestStatus status;
       
   221 	iThread.Rendezvous(status);
       
   222 	iThread.Resume();
       
   223 	iThreadStarted = ETrue;
       
   224 	User::WaitForRequest(status);
       
   225 	User::LeaveIfError(status.Int());
       
   226 	}
       
   227 
       
   228 
       
   229 /**
       
   230  *
       
   231  *
       
   232  */
       
   233 CClockSupervisor::CClockSupervisor(COmxILClockProcessingFunction& aProcessingFunction) 
       
   234 :	iActiveRefClock(OMX_TIME_RefClockAudio),
       
   235 	iMaxRequests(KMaxRequests),
       
   236 	iProcessingFunction(aProcessingFunction)
       
   237 	{
       
   238 	// compile time assertion that fields requiring atomic access are 
       
   239 	// 4-byte aligned
       
   240 	__ASSERT_COMPILE((_FOFF(CClockSupervisor, iWallTicks) & 3) == 0);
       
   241 
       
   242 	// run time assertion that class itself is allocated on a 4-byte boundary
       
   243 	__ASSERT_ALWAYS((reinterpret_cast<TInt>(this) & 3) == 0, Panic(EBadAlignment));
       
   244 
       
   245 	iMediaClockState.nSize = sizeof(iMediaClockState);
       
   246 	iMediaClockState.nVersion = TOmxILSpecVersion();
       
   247 	iMediaClockState.eState = OMX_TIME_ClockStateStopped;
       
   248 	
       
   249 	iCancelStatus = KRequestPending;
       
   250 	}
       
   251 
       
   252 /**
       
   253  *
       
   254  *
       
   255  */
       
   256 CClockSupervisor::~CClockSupervisor()
       
   257 	{
       
   258 	// signal the timing thread and wait for it to terminate
       
   259 	if(iThreadStarted)
       
   260 		{
       
   261 		iThreadRunning = EFalse;
       
   262 		TRequestStatus logonStatus;
       
   263 		iThread.Logon(logonStatus);
       
   264 		// Want the thread to terminate ASAP instead of waiting for a media
       
   265 		// time request completion or a wall time heartbeat. Can't cancel the
       
   266 		// timer without duplicating the handle, and that gives
       
   267 		// KErrPermissionDenied. So we use a second TRequestStatus to wake the
       
   268 		// timing thread before the timer completes.
       
   269 		TRequestStatus* cancelStatus = &iCancelStatus;
       
   270 		iThread.RequestComplete(cancelStatus, KErrCancel);
       
   271 		User::WaitForRequest(logonStatus);
       
   272 		}
       
   273 	
       
   274 	if (iRequestBlock)
       
   275 		{
       
   276 		delete[] iRequestBlock;
       
   277 		iRequestBlock = NULL;
       
   278 		}
       
   279 	
       
   280 	iStartTimes.Close();
       
   281 	iThread.Close();
       
   282 	iQueMutex.Close();
       
   283 	}
       
   284 
       
   285 
       
   286 /**
       
   287  * Timing thread entry point.
       
   288  */
       
   289 TInt CClockSupervisor::ThreadEntryPoint(TAny* aPtr)
       
   290 	{
       
   291 	CClockSupervisor& supervisor = *static_cast<CClockSupervisor*>(aPtr);
       
   292 	supervisor.iThreadRunning = ETrue;
       
   293 	CTrapCleanup* cleanup = CTrapCleanup::New();
       
   294 	if(cleanup == NULL)
       
   295 		{
       
   296 		return KErrNoMemory;
       
   297 		}
       
   298 
       
   299 	// Delegate to object's clock timing routine
       
   300 	TRAPD(err, supervisor.RunTimingThreadL());
       
   301 	delete cleanup;
       
   302 	return err;
       
   303 	}
       
   304 
       
   305 
       
   306 /**
       
   307  *
       
   308  *
       
   309  */
       
   310 void CClockSupervisor::RunTimingThreadL()
       
   311 	{
       
   312 	// Create the timer (thread relative)
       
   313 	User::LeaveIfError(iTimer.CreateLocal());
       
   314 	// rendezvous with the creating thread as it must be blocked until the timer is created
       
   315 	iThread.Rendezvous(KErrNone);
       
   316 	
       
   317 	// Start the timer loop to enable us to wake up on heart beat or requests
       
   318 	TimerLoop();
       
   319 	
       
   320 	iTimer.Close();
       
   321 	}
       
   322 
       
   323 /**
       
   324  * Services media time requests.
       
   325  */
       
   326 void CClockSupervisor::TimerLoop()
       
   327 	{
       
   328 	// Here we are only interested in setting the timer for a request timeout
       
   329 	// or the heart beat. States are taken care of in ConsumeRequests().
       
   330 	// On shutdown the flag iThreadRunning is set to EFalse and the timer
       
   331 	// completed with KErrCancel or something other than KRequestPending
       
   332 	// Therefore we no longer try to get another request.
       
   333 	
       
   334 	TInt measuredTimerOverhead = KTimerQuantization;
       
   335 	TRequestStatus timerStatus;
       
   336 	
       
   337 	while(iThreadRunning)
       
   338 		{
       
   339 		// Call our consumer function
       
   340 		TInt timeout = ConsumeRequests();
       
   341 		
       
   342 		// round down sleep based on overhead and quantization of timers
       
   343 		timeout -= timeout % KTimerQuantization;
       
   344 		timeout -= measuredTimerOverhead;
       
   345 		timeout -= KMinTimerOverhead;
       
   346 		
       
   347 		// limit sleep by the heartbeat interval
       
   348 		if(timeout > iHeartbeatTimerInterval)
       
   349 			{
       
   350 			timeout = iHeartbeatTimerInterval;
       
   351 			}
       
   352 		
       
   353 		// Perhaps timeout not positive from ConsumeRequests(), or due to
       
   354 		// rounding down it is no longer positive. In this case we may spin, so
       
   355 		// be careful when setting KTimerQuantization, KMinTimerOverhead and
       
   356 		// KRequestDeltaLimit
       
   357 		if(timeout <= 0)
       
   358 			{
       
   359 			continue;
       
   360 			}
       
   361 
       
   362 		iQueMutex.Wait();
       
   363 		TInt64 actualSleepTime = WallTime();
       
   364 		iQueMutex.Signal();
       
   365 		iTimer.HighRes(timerStatus, timeout);			
       
   366 		// can't cancel iTimer from another thread, instead we use a second
       
   367 		// TRequestStatus to wake up early, then we can cancel the timer in
       
   368 		// this thread.
       
   369 		User::WaitForRequest(timerStatus, iCancelStatus);
       
   370 		
       
   371 		if(iCancelStatus.Int() != KRequestPending)
       
   372 			{
       
   373 			iTimer.Cancel();
       
   374 			iCancelStatus = KRequestPending;
       
   375 			}
       
   376 		else
       
   377 			{
       
   378 			// update measuredTimerOverhead
       
   379 			iQueMutex.Wait();
       
   380 			actualSleepTime = WallTime() - actualSleepTime;
       
   381 			iQueMutex.Signal();
       
   382 			TInt sleepOverhead = (TInt) (actualSleepTime - timeout);
       
   383 			
       
   384 			/* Dampen adjustments to measuredTimerOverhead
       
   385 			 * 
       
   386 			 *   measuredTimerOverhead = max(sleepOverhead,
       
   387 			 *                           avg(measuredTimerOverhead, sleepOverhead))
       
   388 			 * 
       
   389 			 * i.e. immediate increase, gradual decrease
       
   390 			 */
       
   391 			measuredTimerOverhead = (measuredTimerOverhead + sleepOverhead) >> 1;
       
   392 			if(measuredTimerOverhead < sleepOverhead)
       
   393 				{
       
   394 				measuredTimerOverhead = sleepOverhead;
       
   395 				}
       
   396 			}
       
   397 		}
       
   398 	DEBUG_PRINTF(_L("Clock thread shutting down..."));
       
   399 	}
       
   400 
       
   401 
       
   402 /**
       
   403  * Update the wall clock with the system ticks
       
   404  *
       
   405  */
       
   406 void CClockSupervisor::UpdateWallTicks()
       
   407 	{
       
   408 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   409 	
       
   410 	TUint32 oldLowPart(I64LOW(iWallTicks));		// save lower 32-bits
       
   411 #ifdef USE_FASTCOUNTER
       
   412 	// Gets the fast iCounter.
       
   413 	// This is the current value of the machine's high resolution timer. 
       
   414 	// If a high resolution timer is not available, it uses the millisecond timer instead.
       
   415 	// The freqency of this iCounter can be determined by reading the HAL attribute EFastCounterFrequency.
       
   416 	TUint32 newLowPart(User::FastCounter());	// set lower 32-bits
       
   417 	if(iSystemClockReversed)
       
   418 		{
       
   419 		newLowPart = -newLowPart;
       
   420 		}
       
   421 #elif defined(USE_NTICKCOUNT)
       
   422 	TUint32 newLowPart(User::NTickCount());		// set lower 32-bits
       
   423 #else
       
   424 #error
       
   425 #endif
       
   426 	TUint32 newHighPart(I64HIGH(iWallTicks));	// save upper 32-bits
       
   427 	
       
   428 	// note: did not use LockedInc() here because:
       
   429 	// We need a critical section to capture the system time and update the wall clock
       
   430 	// at the same time.
       
   431 	// The wall clock is unsigned.
       
   432 	// LockedInc doesn't stop a preemption directly after the test, only during the inc	
       
   433 	if (newLowPart < oldLowPart) 
       
   434 		{
       
   435 		newHighPart++;
       
   436 		}
       
   437 	
       
   438 	iWallTicks = MAKE_TUINT64(newHighPart,newLowPart);
       
   439 	}
       
   440 
       
   441 
       
   442 /**
       
   443  * Returns the current wall time in microseconds.
       
   444  */
       
   445 TInt64 CClockSupervisor::WallTime()
       
   446 	 {
       
   447 	 __ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   448 	 
       
   449 	 UpdateWallTicks();
       
   450 	 
       
   451 	 // if power of two use shift (faster than division)
       
   452 	 if (iMicroConvDen == 1)
       
   453 		 {
       
   454 		 return iWallTicks * iMicroConvNum >> iMicroConvShift;
       
   455 		 }
       
   456 	 return iWallTicks * iMicroConvNum / iMicroConvDen;
       
   457 	 }
       
   458 
       
   459 /**
       
   460  *
       
   461  *
       
   462  */
       
   463 TBool CClockSupervisor::AllStartTimesReported ()
       
   464 	{
       
   465 	return !(static_cast<TBool>(iMediaClockState.nWaitMask));
       
   466 	}
       
   467 
       
   468 /**
       
   469  * Called when timer expires or is cancelled.
       
   470  *
       
   471  */
       
   472 TInt CClockSupervisor::ConsumeRequests()
       
   473 	{
       
   474 	// Events are consumed here only in the Running state.
       
   475 	// Waiting events, State change events, etc. are handled elsewhere.
       
   476 	// These are called broadcast events and have a higher priority 
       
   477 	// than the request events requested by the clients.
       
   478 	// This function is called by the TimerLoop only.
       
   479 	
       
   480 	// IMPORTANT: every code path through here must result in a call to UpdateWallTicks to ensure
       
   481 	// that 64-bit time is updated correctly (heartbeat interval makes sure ConsumeRequests is called
       
   482 	// often enough).
       
   483 	
       
   484 	// Our event loop - return if stopped but not for pause (keep heart beat going)
       
   485 	if(OMX_TIME_ClockStateStopped != iMediaClockState.eState)
       
   486 		{
       
   487 		// Acquire the mutex
       
   488 		iQueMutex.Wait();
       
   489 
       
   490 		// this can be entered from the timer on heartbeat or on a call to a state change. 
       
   491 		// Don't want this to happen on a state change!
       
   492 		if (OMX_TIME_ClockStateWaitingForStartTime == iMediaClockState.eState)
       
   493 			{
       
   494 			// We need to check if all clients have reported their start times
       
   495 			if (!AllStartTimesReported())
       
   496 				{
       
   497 				// Not all reported as yet...
       
   498 				UpdateWallTicks();
       
   499 				
       
   500 				// Release the mutex
       
   501 				iQueMutex.Signal();
       
   502 				
       
   503 				// wait until they have! keep heat beat going in case it takes looooong!
       
   504 				return iHeartbeatTimerInterval;
       
   505 				}
       
   506 			else
       
   507 				{
       
   508 				// depending on scale decide which start time to use
       
   509 				CalculateStartTime();
       
   510 
       
   511 				// no need to check error, we are in the waiting state
       
   512 				DoTransitionToRunningState();
       
   513 				
       
   514 				// Now just go and send the iNext request!
       
   515 				}
       
   516 			}
       
   517 		
       
   518 		///////////////////////////////
       
   519 		// There is a request pending !!!
       
   520 		// 
       
   521 				
       
   522 		// check the timeout period against the wall clock to determine if this is a heart beat
       
   523 		
       
   524 		if(iMtc.iScaleQ16 == 0)
       
   525 			{
       
   526 			// do not pop front of the queue because we are effectively paused
       
   527 			UpdateWallTicks();
       
   528 			
       
   529 			// Release the mutex
       
   530 			iQueMutex.Signal();
       
   531 			
       
   532 			return iHeartbeatTimerInterval;
       
   533 			}
       
   534 		
       
   535 		// try to pop the next pending request
       
   536 		TInt64 delta;
       
   537 		TBool present = iPendingRequestQue.FirstDelta(delta);
       
   538 		
       
   539 		// Is there nothing there?
       
   540 		if (!present)
       
   541 			{
       
   542 			// Nothing on the queue
       
   543 			// Here because of heart beat
       
   544 			UpdateWallTicks();
       
   545 			
       
   546 			// Release the mutex
       
   547 			iQueMutex.Signal();
       
   548 			
       
   549 			return iHeartbeatTimerInterval;
       
   550 			}
       
   551 		
       
   552 		// update the delta against clock 
       
   553 		delta -= WallTime();
       
   554 		
       
   555 		// Some time to go before head of queue should be serviced?
       
   556 		if (delta > KMinTimerOverhead)
       
   557 			{
       
   558 			// Release the mutex
       
   559 			iQueMutex.Signal();
       
   560 			
       
   561 			return delta;
       
   562 			}
       
   563 
       
   564 		// Request timed out, delta expired!
       
   565 		// Fulfill the request
       
   566 		TMediaRequest* request = iPendingRequestQue.RemoveFirst();
       
   567 		
       
   568 		// Acquire fulfillment buffer for a specific port
       
   569 		OMX_BUFFERHEADERTYPE* buffer = iProcessingFunction.AcquireBuffer(request->iPortIndex);
       
   570 		if(buffer == NULL)
       
   571 			{
       
   572 			// starved of buffers!
       
   573 			DEBUG_PRINTF(_L("ConsumeRequests starved of buffers, transitioning to OMX_StateInvalid"));
       
   574 			iThreadRunning = EFalse;
       
   575 			iQueMutex.Signal();
       
   576 			iProcessingFunction.InvalidateComponent();
       
   577 			return 0;
       
   578 			}
       
   579 		OMX_TIME_MEDIATIMETYPE* mT = reinterpret_cast<OMX_TIME_MEDIATIMETYPE*>(buffer->pBuffer);
       
   580 		buffer->nOffset = 0;
       
   581 		buffer->nFilledLen = sizeof(OMX_TIME_MEDIATIMETYPE);
       
   582 		
       
   583 		mT->nSize = sizeof(OMX_TIME_MEDIATIMETYPE);
       
   584 		mT->nVersion = TOmxILSpecVersion();
       
   585 		mT->eUpdateType = OMX_TIME_UpdateRequestFulfillment;
       
   586 		mT->nClientPrivate = reinterpret_cast<OMX_U32>(request->iClientPrivate);
       
   587 		mT->xScale = iMtc.iScaleQ16;
       
   588 		mT->eState = OMX_TIME_ClockStateRunning;
       
   589 		mT->nMediaTimestamp = request->iMediaTime;
       
   590 		mT->nWallTimeAtMediaTime = request->iTriggerWallTime + request->iOffset;
       
   591 		mT->nOffset = mT->nWallTimeAtMediaTime - WallTime(); // could be waiting on buffer b4 this!
       
   592 
       
   593 #ifdef _OMXIL_COMMON_DEBUG_TRACING_ON		
       
   594 		DEBUG_PRINTF(_L8("CLOCK::ConsumeRequest*******************************OMX_TIME_UpdateRequestFulfillment***VS2"));
       
   595 		TTime t;
       
   596 		t.HomeTime();
       
   597 		DEBUG_PRINTF2(_L8("CLOCK::ConsumeRequest : t.HomeTime() = %ld"), t.Int64());
       
   598 		DEBUG_PRINTF2(_L8("CLOCK::ConsumeRequest : Buffer = 0x%X"), mT->nClientPrivate);
       
   599 		DEBUG_PRINTF2(_L8("CLOCK::ConsumeRequest : mT->nMediaTimestamp = %ld"), mT->nMediaTimestamp);
       
   600 #endif 
       
   601 		
       
   602 		iProcessingFunction.SendBuffer(buffer);
       
   603 		
       
   604 		// clear the delta on this now free request
       
   605 		request->iTriggerWallTime = 0;
       
   606 		
       
   607 		// Add element back to the free pool
       
   608 		iFreeRequestQue.Add(request, 0);
       
   609 
       
   610 		// Release the mutex
       
   611 		iQueMutex.Signal();
       
   612 
       
   613 		// Update delta for next request.
       
   614 		// NOTE: we do not know if scale change or not so when we re-enter here
       
   615 		// we should recalculate the delta above and perform the appropriate action.
       
   616 		return 0;
       
   617 		}
       
   618 	else
       
   619 		{
       
   620 		// clock is stopped - sleep for the heartbeat interval
       
   621 		return iHeartbeatTimerInterval;
       
   622 		}
       
   623 	}
       
   624 
       
   625 /**
       
   626  *
       
   627  *
       
   628  */
       
   629 OMX_ERRORTYPE CClockSupervisor::ProduceRequest(OMX_INDEXTYPE aIndex, TEntryPoint aEntryPoint, TAny* aPassedStructPtr)
       
   630 	{
       
   631 	// Range checking on parameter/config index
       
   632 	if(aIndex < KMinJumpTableIndex || aIndex > KMaxJumpTableIndex)
       
   633 		{
       
   634 		return OMX_ErrorUnsupportedIndex;
       
   635 		}
       
   636 	// Note also that certain combinations on Get/Set within the supported range are unsupported.
       
   637 	// This is left to the function in the jump table.
       
   638 	
       
   639 	// Acquire the mutex
       
   640 	iQueMutex.Wait();
       
   641 	
       
   642 	// Index the routing table for the correct handler
       
   643 	FunctionPtr jumpTableFptr = iJumpTable[aIndex-KMinJumpTableIndex];
       
   644 	OMX_ERRORTYPE ret = (this->*jumpTableFptr)(aEntryPoint, aPassedStructPtr);
       
   645 	
       
   646 	// Release the mutex
       
   647 	iQueMutex.Signal();
       
   648 	
       
   649 	return ret;
       
   650 	}
       
   651 
       
   652 
       
   653 /**
       
   654  * According to scale, choose the earliest start time among the set of client
       
   655  * start times. For forward play this is the minimum, for reverse play this is
       
   656  * the maximum.
       
   657  */
       
   658 void CClockSupervisor::CalculateStartTime()
       
   659 	{
       
   660 	// The nWaitMask field of the Media clock state is a bit mask specifying the client 
       
   661 	// components that the clock component will wait on in the 
       
   662 	// OMX_TIME_ClockStateWaitingForStartTime state. Bit masks are defined 
       
   663 	// as OMX_CLOCKPORT0 through OMX_CLOCKPORT7.
       
   664 		
       
   665 	// Based on scale locate the minimum or maximum start times of all clients
       
   666 	TInt64 startTime;
       
   667 	
       
   668 	if (iMtc.iScaleQ16 >= 0)
       
   669 		{
       
   670 		startTime = KMaxTInt64;
       
   671 		
       
   672 		// choose minimum
       
   673 		for (TInt portIndex = 0; portIndex < iStartTimes.Count(); portIndex++)
       
   674 			{
       
   675 			if(iStartTimesSet & (1 << portIndex))
       
   676 				{
       
   677 				startTime = Min(startTime, iStartTimes[portIndex]);
       
   678 				}
       
   679 			}
       
   680 		}
       
   681 	else
       
   682 		{
       
   683 		startTime = KMinTInt64;
       
   684 		
       
   685 		// choose maximum
       
   686 		for (TInt portIndex = 0; portIndex < iStartTimes.Count(); portIndex++)
       
   687 			{
       
   688 			if(iStartTimesSet & (1 << portIndex))
       
   689 				{
       
   690 				startTime = Max(startTime, iStartTimes[portIndex]);
       
   691 				}
       
   692 			}
       
   693 		}
       
   694 	
       
   695 	// adjust the media time to the new start time
       
   696 	UpdateMediaTime(startTime);
       
   697 	}
       
   698 
       
   699 
       
   700 /**
       
   701  * Perform actions related to placing the clock into the Stopped state
       
   702  */
       
   703 void CClockSupervisor::DoTransitionToStoppedState()
       
   704 	{
       
   705 	// OMX_TIME_ClockStateStopped: Immediately stop the media clock, clear all
       
   706 	// pending media time requests, clear all client start times, and transition to the
       
   707 	// stopped state. This transition is valid from all other states.
       
   708 
       
   709 	// We should already have the mutex!
       
   710 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   711 		
       
   712 	// clear any current start time
       
   713 	iMediaClockState.nStartTime = 0;
       
   714 	iMediaClockState.nWaitMask = 0;
       
   715 	
       
   716 	// clear client start times
       
   717 	for(TInt index = 0, count = iStartTimes.Count(); index < count; index++)
       
   718 		{
       
   719 		iStartTimes[index] = 0;
       
   720 		}
       
   721 	iStartTimesSet = 0;
       
   722 	
       
   723 	// clear all pending requests, placing them back on the free queue
       
   724 	while (!iPendingRequestQue.IsEmpty())
       
   725 		{
       
   726 		TMediaRequest* request = iPendingRequestQue.RemoveFirst();
       
   727 
       
   728 		// clear the delta on this now free request
       
   729 		request->iTriggerWallTime = 0;
       
   730 
       
   731 		iFreeRequestQue.Add(request,0);
       
   732 		}
       
   733 
       
   734 	TInt64 wallTimeNow = WallTime();
       
   735 	
       
   736 	// if clock was previously running, stop the media time at the present value
       
   737 	if(iMediaClockState.eState == OMX_TIME_ClockStateRunning)
       
   738 		{
       
   739 		TInt64 mediaTimeNow = ((wallTimeNow - iMtc.iWallTimeBase) * iMtc.iScaleQ16 >> 16) + iMtc.iMediaTimeBase;
       
   740 		iMtc.iWallTimeBase = wallTimeNow;
       
   741 		iMtc.iMediaTimeBase = mediaTimeNow;
       
   742 		}
       
   743 	
       
   744 	// Indicate stopped state
       
   745 	iMediaClockState.eState = OMX_TIME_ClockStateStopped;
       
   746 
       
   747 	// Indicate to clients a state change
       
   748 	OMX_TIME_MEDIATIMETYPE update;
       
   749 	update.nSize = sizeof(OMX_TIME_MEDIATIMETYPE);
       
   750 	update.nVersion = TOmxILSpecVersion();
       
   751 	update.nClientPrivate = NULL;
       
   752 	update.eUpdateType = OMX_TIME_UpdateClockStateChanged;
       
   753 	update.xScale = iMtc.iScaleQ16;
       
   754 	update.eState = OMX_TIME_ClockStateStopped;
       
   755 	update.nMediaTimestamp = iMtc.iMediaTimeBase;
       
   756 	update.nWallTimeAtMediaTime = wallTimeNow;
       
   757 	update.nOffset = 0;
       
   758 
       
   759 	BroadcastUpdate(update);
       
   760 	}
       
   761 
       
   762 
       
   763 /**
       
   764  * Perform actions related to placing the clock into the Running state
       
   765  */
       
   766 void CClockSupervisor::DoTransitionToRunningState()
       
   767 	{
       
   768 	// OMX_TIME_ClockStateRunning: Immediately start the media clock using the given
       
   769 	// start time and offset, and transition to the running state. This transition is valid from
       
   770 	// all other states.
       
   771 	
       
   772 	// We should already have the mutex!
       
   773 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   774 	
       
   775 	// if we transistioned from stopped to running then start time will be cleared.
       
   776 	// we only set it on transition from waiting to running
       
   777 	// this is enforced not by a check but by logic flow!
       
   778 	// If this is not the case then start time should have been cleared and we can start now!
       
   779 
       
   780 	// Indicate running state
       
   781 	iMediaClockState.eState = OMX_TIME_ClockStateRunning;
       
   782 	
       
   783 	// Indicate to clients a state change
       
   784 	OMX_TIME_MEDIATIMETYPE update;
       
   785 	update.nSize = sizeof(OMX_TIME_MEDIATIMETYPE);
       
   786 	update.nVersion = TOmxILSpecVersion();
       
   787 	update.nClientPrivate = NULL;
       
   788 	update.eUpdateType = OMX_TIME_UpdateClockStateChanged;
       
   789 	update.xScale = iMtc.iScaleQ16;
       
   790 	update.eState = iMediaClockState.eState;
       
   791 	update.nMediaTimestamp = iMtc.iMediaTimeBase;
       
   792 	update.nWallTimeAtMediaTime = iMtc.iWallTimeBase;
       
   793 	update.nOffset = 0;
       
   794 	
       
   795 	BroadcastUpdate(update);
       
   796 	}
       
   797 
       
   798 /**
       
   799  * Perform actions related to placing the clock into the Waiting state
       
   800  */
       
   801 void CClockSupervisor::DoTransitionToWaitingState(OMX_U32 nWaitMask)
       
   802 	{
       
   803 	// OMX_TIME_WaitingForStartTime: Transition immediately to the waiting state, wait
       
   804 	// for all clients specified in nWaitMask to report their start time, start the media clock
       
   805 	// using the minimum of all client start times and transition to
       
   806 	// OMX_TIME_ClockStateRunning. This transition is only valid from the
       
   807 	// OMX_TIME_ClockStateStopped state.
       
   808 	// (*Added*) If in the backwards direction start the media clock using the maximum
       
   809 	// of all client start times.
       
   810 	
       
   811 	// validity of state transition has been checked in HandleGetSetClockState()
       
   812 	
       
   813 	// We should already have the mutex!
       
   814 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   815 	
       
   816 	iMediaClockState.eState = OMX_TIME_ClockStateWaitingForStartTime;
       
   817 	
       
   818 	// Start times set in calling function HandleClientStartTime()
       
   819 	
       
   820 	// Remember all clients that need to report their start times
       
   821 	iMediaClockState.nWaitMask = nWaitMask;
       
   822 
       
   823 	// Indicate to clients a state change
       
   824 	OMX_TIME_MEDIATIMETYPE update;
       
   825 	update.nSize = sizeof(OMX_TIME_MEDIATIMETYPE);
       
   826 	update.nVersion = TOmxILSpecVersion();
       
   827 	update.nClientPrivate = NULL;
       
   828 	update.eUpdateType = OMX_TIME_UpdateClockStateChanged;
       
   829 	update.xScale = iMtc.iScaleQ16;
       
   830 	update.eState = OMX_TIME_ClockStateWaitingForStartTime;
       
   831 	update.nMediaTimestamp = iMtc.iMediaTimeBase;
       
   832 	update.nWallTimeAtMediaTime = WallTime();
       
   833 	update.nOffset = 0;
       
   834 	
       
   835 	BroadcastUpdate(update);
       
   836 	}
       
   837 
       
   838 
       
   839  /**
       
   840   * Update the wall clock with the system ticks
       
   841   *
       
   842   */
       
   843  OMX_ERRORTYPE CClockSupervisor::HandleSubmitMediaTimeRequest(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
   844  	{
       
   845  	// We should already have the mutex!
       
   846  	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   847  	
       
   848 	// A client requests the transmission of a particular timestamp via OMX_SetConfig on its
       
   849  	// clock port using the OMX_IndexConfigTimeMediaTimeRequest configuration
       
   850  	// and structure OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE
       
   851 
       
   852  	// OMX_GetConfig doesn't make any sense for MediaTimeRequest
       
   853  	if(aEntry == EGetConfig)
       
   854  		{
       
   855  		return OMX_ErrorUnsupportedIndex;
       
   856  		}
       
   857  	
       
   858  	TMediaRequest *request = iFreeRequestQue.RemoveFirst();
       
   859 	if(request == NULL)
       
   860 		{
       
   861 		// too many pending requests!
       
   862 		return OMX_ErrorInsufficientResources;
       
   863 		}
       
   864 
       
   865 	OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE* rT = static_cast<OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE*>(aPassedStructPtr);
       
   866 	
       
   867 	request->iMediaTime = rT->nMediaTimestamp;
       
   868 	request->iOffset = rT->nOffset;
       
   869 	request->iTriggerWallTime = 
       
   870 		((rT->nMediaTimestamp - iMtc.iMediaTimeBase) * iMtc.iInverseScaleQ16 >> 16) 
       
   871 			+ iMtc.iWallTimeBase - rT->nOffset;
       
   872 	request->iPortIndex = rT->nPortIndex;
       
   873 	request->iClientPrivate = rT->pClientPrivate;
       
   874 	
       
   875 	TInt64 prevHeadTime(0);
       
   876 	TBool nonEmpty = iPendingRequestQue.FirstDelta(prevHeadTime);
       
   877 	iPendingRequestQue.Add(request, request->iTriggerWallTime);
       
   878 	// Wake the thread immediately if head of queue now will complete sooner
       
   879 	// than it would have previously, or if the queue was empty previously.
       
   880 	// This causes the timing thread to recalculate the sleep time.
       
   881 	if(!nonEmpty || prevHeadTime > request->iTriggerWallTime)
       
   882 		{
       
   883 		TRequestStatus* status = &iCancelStatus;
       
   884 		iThread.RequestComplete(status, KErrCancel);
       
   885 		}
       
   886 	return OMX_ErrorNone;
       
   887  	}
       
   888  	
       
   889 
       
   890  /**
       
   891   *
       
   892   *
       
   893   */
       
   894  OMX_ERRORTYPE CClockSupervisor::HandleQueryCurrentWallTime(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
   895 	 {
       
   896 	 // An IL client may query the current wall time via OMX_GetConfig on OMX_IndexConfigTimeCurrentWallTime.	 
       
   897 	 // A client may obtain the current wall time, which is obtained via OMX_GetConfig on
       
   898 	 // OMX_IndexConfigTimeCurrentWallTime.
       
   899 	 
       
   900 	 // OMX_SetConfig doesn't make sense for wall time
       
   901 	 if(aEntry == ESetConfig)
       
   902 		 {
       
   903 		 return OMX_ErrorUnsupportedIndex;
       
   904 		 }
       
   905 	 
       
   906 	// We should already have the mutex!
       
   907 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   908 	
       
   909 	OMX_TIME_CONFIG_TIMESTAMPTYPE& wallTs = *static_cast<OMX_TIME_CONFIG_TIMESTAMPTYPE*>(aPassedStructPtr);
       
   910 	wallTs.nTimestamp = WallTime();
       
   911 	return OMX_ErrorNone;
       
   912 	}
       
   913 
       
   914 
       
   915 /**
       
   916  * Calculates and returns the current media time.
       
   917  */
       
   918 OMX_ERRORTYPE CClockSupervisor::HandleQueryCurrentMediaTime(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
   919 	{
       
   920 	// The clock component can be queried for the current media clock time using
       
   921 	// OMX_GetConfig with the read-only index OMX_IndexConfigTimeCurrentMediaTime and structure
       
   922 	// OMX_TIME_CONFIG_TIMESTAMPTYPE.	
       
   923 
       
   924 	// OMX_SetConfig cannot be used for Media Time (audio or video reference updates are used instead)
       
   925 	if(aEntry == ESetConfig)
       
   926 		{
       
   927 		return OMX_ErrorUnsupportedIndex;
       
   928 		}
       
   929 	
       
   930 	// We should already have the mutex!
       
   931 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   932 	
       
   933 	OMX_TIME_CONFIG_TIMESTAMPTYPE* ts = static_cast<OMX_TIME_CONFIG_TIMESTAMPTYPE*>(aPassedStructPtr);
       
   934 	if(iMediaClockState.eState == OMX_TIME_ClockStateRunning)
       
   935 		{
       
   936 		ts->nTimestamp = ((WallTime() - iMtc.iWallTimeBase) * iMtc.iScaleQ16 >> 16) + iMtc.iMediaTimeBase;
       
   937 		}
       
   938 	else
       
   939 		{
       
   940 		ts->nTimestamp = iMtc.iMediaTimeBase;
       
   941 		}
       
   942 	return OMX_ErrorNone;
       
   943 	}
       
   944 
       
   945 /**
       
   946  * An external component is providing an Audio reference time update.
       
   947  */
       
   948 OMX_ERRORTYPE CClockSupervisor::HandleUpdateAudioReference(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
   949 	{
       
   950 	// The clock component can accept an audio reference clock. 
       
   951 	// The reference clock tracks the media time at its associated component 
       
   952 	// (i.e., the timestamp of the data currently being processed at that component) 
       
   953 	// and provides periodic references to the clock component via OMX_SetConfig 
       
   954 	// using OMX_IndexConfigTimeCurrentAudioReference, and structure OMX_TIME_CONFIG_TIMESTAMPTYPE
       
   955 	//
       
   956 	// When the clock component receives a reference, it updates its internally maintained
       
   957 	// media time with the reference. This action synchronizes the clock component with the
       
   958 	// component that is providing the reference clock.
       
   959 	
       
   960 	// OMX_GetConfig not supported on reference time as it will generally be
       
   961 	// some arbitary time in the past
       
   962 	if(aEntry == EGetConfig)
       
   963 		{
       
   964 		return OMX_ErrorUnsupportedIndex;
       
   965 		}
       
   966 	
       
   967 	// We should already have the mutex!
       
   968 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
   969 
       
   970 	if(iActiveRefClock == OMX_TIME_RefClockAudio)
       
   971 		{
       
   972 		OMX_TIME_CONFIG_TIMESTAMPTYPE* ts = static_cast<OMX_TIME_CONFIG_TIMESTAMPTYPE*>(aPassedStructPtr);
       
   973 		UpdateMediaTime(ts->nTimestamp);
       
   974 		}
       
   975 	
       
   976 	return OMX_ErrorNone;
       
   977 	}
       
   978 
       
   979 /**
       
   980  * An external component is providing a Video reference time update.
       
   981  */
       
   982 OMX_ERRORTYPE CClockSupervisor::HandleUpdateVideoReference(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
   983 	{
       
   984 	// The clock component can accept a video reference clock. 
       
   985 	// The reference clock tracks the media time at its associated component 
       
   986 	// (i.e., the timestamp of the data currently being processed at that component) 
       
   987 	// and provides periodic references to the clock component via OMX_SetConfig 
       
   988 	// using OMX_IndexConfigTimeCurrentVideoReference, and structure OMX_TIME_CONFIG_TIMESTAMPTYPE
       
   989 	//
       
   990 	// When the clock component receives a reference, it updates its internally maintained
       
   991 	// media time with the reference. This action synchronizes the clock component with the
       
   992 	// component that is providing the reference clock.
       
   993 
       
   994 	// OMX_GetConfig not supported on reference time as it will generally be
       
   995 	// some arbitary time in the past
       
   996 	if(aEntry == EGetConfig)
       
   997 		{
       
   998 		return OMX_ErrorUnsupportedIndex;
       
   999 		}
       
  1000 	
       
  1001 	// We should already have the mutex!
       
  1002 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
  1003 	
       
  1004 	if(iActiveRefClock == OMX_TIME_RefClockVideo)
       
  1005 		{
       
  1006 		OMX_TIME_CONFIG_TIMESTAMPTYPE* ts = static_cast<OMX_TIME_CONFIG_TIMESTAMPTYPE*>(aPassedStructPtr);
       
  1007 		UpdateMediaTime(ts->nTimestamp);
       
  1008 		}
       
  1009 	
       
  1010 	return OMX_ErrorNone;
       
  1011 	}
       
  1012 
       
  1013  /**
       
  1014   *
       
  1015   *
       
  1016   */
       
  1017  OMX_ERRORTYPE CClockSupervisor::HandleSetPortClientStartTime(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
  1018 	{
       
  1019 	// We should already have the mutex!
       
  1020 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
  1021 	
       
  1022 	// When a clock component client receives a buffer with flag OMX_BUFFERFLAG_STARTTIME set, 
       
  1023 	// it performs an OMX_SetConfig call with OMX_IndexConfigTimeClientStartTime 
       
  1024 	// on the clock component that is sending the buffer’s timestamp. 
       
  1025 	// The transmission of the start time informs the clock component that the client’s stream 
       
  1026 	// is ready for presentation and the timestamp of the first data to be presented.
       
  1027 	// 
       
  1028 	// If the IL client requests a transition to OMX_TIME_ClockStateWaitingForStartTime, it
       
  1029 	// designates which clock component clients to wait for. The clock component then waits
       
  1030 	// for these clients to send their start times via the
       
  1031 	// OMX_IndexConfigTimeClientStartTime configuration. Once all required
       
  1032 	// clients have responded, the clock component starts the media clock using the earliest
       
  1033 	// client start time.
       
  1034 	// 
       
  1035 	// When a client is sent a start time (i.e., the timestamp of a buffer marked with the
       
  1036 	// OMX_BUFFERFLAG_STARTTIME flag ), it sends the start time to the clock component
       
  1037 	// via OMX_SetConfig on OMX_IndexConfigTimeClientStartTime. This
       
  1038 	// action communicates to the clock component the following information about the client’s
       
  1039 	// data stream:
       
  1040 	// - The stream is ready.
       
  1041 	// - The starting timestamp of the stream
       
  1042 	
       
  1043 	// TODO Perhaps OMX_GetConfig can be done for client start time, after all
       
  1044 	// the start times on each port have been stored. But for now this is not
       
  1045 	// supported.
       
  1046 	if(aEntry == EGetConfig)
       
  1047 		{
       
  1048 		return OMX_ErrorUnsupportedIndex;
       
  1049 		}
       
  1050 	
       
  1051 	if(iMediaClockState.eState != OMX_TIME_ClockStateWaitingForStartTime)
       
  1052 		{
       
  1053 		return OMX_ErrorIncorrectStateOperation;
       
  1054 		}
       
  1055 	
       
  1056 	OMX_TIME_CONFIG_TIMESTAMPTYPE* state = static_cast<OMX_TIME_CONFIG_TIMESTAMPTYPE*>(aPassedStructPtr);
       
  1057 	iMediaClockState.nWaitMask &= ~(1 << state->nPortIndex); // switch off bit
       
  1058 	iStartTimesSet |= 1 << state->nPortIndex;	// switch on bit
       
  1059 	iStartTimes[state->nPortIndex] = state->nTimestamp;
       
  1060 	
       
  1061 	if(iMediaClockState.nWaitMask == 0)
       
  1062 		{
       
  1063 		// cancel timer so transition occurs immediately instead of waiting for a heartbeat
       
  1064 		TRequestStatus* cancelStatus = &iCancelStatus;
       
  1065 		iThread.RequestComplete(cancelStatus, KErrCancel);
       
  1066 		}
       
  1067 	
       
  1068 	return OMX_ErrorNone;
       
  1069 	}
       
  1070 
       
  1071 /**
       
  1072  * Sets the current media time to the specified value.
       
  1073  */
       
  1074 void CClockSupervisor::UpdateMediaTime(TInt64 aMediaTime)
       
  1075 	{
       
  1076 #ifdef _OMXIL_COMMON_DEBUG_TRACING_ON
       
  1077 	OMX_TIME_CONFIG_TIMESTAMPTYPE ts;
       
  1078 	HandleQueryCurrentMediaTime(EGetConfig, &ts);
       
  1079 	DEBUG_PRINTF4(_L8("Clock::UpdateMediaTime=[%ld]currentmediaTime=<%d> MediaTime <%ld>"), ts.nTimestamp-aMediaTime,ts.nTimestamp, aMediaTime);
       
  1080 #endif // _OMXIL_COMMON_DEBUG_TRACING_ON
       
  1081 	iMtc.iWallTimeBase = WallTime();
       
  1082 	iMtc.iMediaTimeBase = aMediaTime;
       
  1083 	iPendingRequestQue.RecalculateAndReorder(iMtc);
       
  1084 	
       
  1085 	TRequestStatus* status = &iCancelStatus;
       
  1086     iThread.RequestComplete(status, KErrCancel);
       
  1087 	}
       
  1088 
       
  1089  /**
       
  1090   *
       
  1091   *
       
  1092   */
       
  1093  OMX_ERRORTYPE CClockSupervisor::HandleGetSetTimeScale(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
  1094 	{
       
  1095 	// The IL client queries and sets the media clock’s scale via the
       
  1096 	// OMX_IndexConfigTimeScale configuration, passing  structure
       
  1097 	// OMX_TIME_CONFIG_SCALETYPE 
       
  1098 
       
  1099 	// We should already have the mutex!
       
  1100 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
  1101 	
       
  1102 	OMX_TIME_CONFIG_SCALETYPE* sT = static_cast<OMX_TIME_CONFIG_SCALETYPE*>(aPassedStructPtr);
       
  1103 
       
  1104 	if (EGetConfig == aEntry)
       
  1105 		{
       
  1106 		sT->xScale = iMtc.iScaleQ16;
       
  1107 		}
       
  1108 	else 
       
  1109 		{ // ESetConfig
       
  1110 		
       
  1111 		if(sT->xScale == iMtc.iScaleQ16)
       
  1112 			{
       
  1113 			// do not broadcast update if the scale changed to the same value
       
  1114 			// IL client causes the scale change but only IL components receive the notification
       
  1115 			return OMX_ErrorNone;
       
  1116 			}
       
  1117 		iMtc.SetScaleQ16(sT->xScale, WallTime());
       
  1118 		
       
  1119 		// Reorder before sending notifications
       
  1120 		iPendingRequestQue.RecalculateAndReorder(iMtc);
       
  1121 		
       
  1122 		// Indicate to clients a scale change
       
  1123 		// The buffer payload is written here then copied to all clients' buffers
       
  1124 		// It should be noted that as this is happening across all ports, time can pass
       
  1125 		// making nMediaTimestamp and nWallTimeAtMediaTime inaccurate. Since at present we do
       
  1126 		// not recover buffer exhaustion scenarios, it is assumed that the messaging time is short
       
  1127 		// thus we do not recalculate the time.
       
  1128 		
       
  1129 		OMX_TIME_MEDIATIMETYPE update;
       
  1130 		update.nSize = sizeof(OMX_TIME_MEDIATIMETYPE);
       
  1131 		update.nVersion = TOmxILSpecVersion();
       
  1132 		update.nClientPrivate = NULL;
       
  1133 		update.eUpdateType = OMX_TIME_UpdateScaleChanged;
       
  1134 		update.xScale = iMtc.iScaleQ16;
       
  1135 		update.eState = iMediaClockState.eState;
       
  1136 		update.nMediaTimestamp = iMtc.iMediaTimeBase;
       
  1137 		update.nWallTimeAtMediaTime = iMtc.iWallTimeBase;
       
  1138 		update.nOffset = 0;
       
  1139 		
       
  1140 		BroadcastUpdate(update);
       
  1141 		
       
  1142 		// Signal the Timer thread as it may need to fulfill all requests on a direction change,
       
  1143 		// of fulfill some requests as we have moved forward in time
       
  1144 		TRequestStatus* cancelStatus = &iCancelStatus;
       
  1145 		iThread.RequestComplete(cancelStatus, KErrCancel);
       
  1146 		//******************************************
       
  1147 		}
       
  1148 	return OMX_ErrorNone;
       
  1149 	}
       
  1150  
       
  1151  
       
  1152  /**
       
  1153   *
       
  1154   *
       
  1155   */
       
  1156  OMX_ERRORTYPE CClockSupervisor::HandleGetSetClockState(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
  1157 	{
       
  1158 	// An OMX_GetConfig execution using index OMX_IndexConfigTimeClockState
       
  1159 	// and structure OMX_TIME_CONFIG_CLOCKSTATETYPE queries the current clock state.
       
  1160 	// An OMX_SetConfig execution using index OMX_IndexConfigTimeClockState
       
  1161 	// and structure OMX_TIME_CONFIG_CLOCKSTATETYPE commands the clock
       
  1162 	// component to transition to the given state, effectively providing the IL client a
       
  1163 	// mechanism for starting and stopping the media clock.
       
  1164 	// 
       
  1165 	// Upon receiving OMX_SetConfig from the IL client that requests a transition to the
       
  1166 	// given state, the clock component will do the following:
       
  1167 	//
       
  1168 	// - OMX_TIME_ClockStateStopped: Immediately stop the media clock, clear all
       
  1169 	// pending media time requests, clear and all client start times, and transition to the
       
  1170 	// stopped state. This transition is valid from all other states.
       
  1171 	//
       
  1172 	// - OMX_TIME_ClockStateRunning: Immediately start the media clock using the given
       
  1173 	// start time and offset, and transition to the running state. This transition is valid from
       
  1174 	// all other states.
       
  1175 	//
       
  1176 	// - OMX_TIME_WaitingForStartTime: Transition immediately to the waiting state, wait
       
  1177 	// for all clients specified in nWaitMask to report their start time, start the media clock
       
  1178 	// using the minimum of all client start times and transition to
       
  1179 	// OMX_TIME_ClockStateRunning. This transition is only valid from the
       
  1180 	// OMX_TIME_ClockStateStopped state.
       
  1181 
       
  1182 	// We should already have the mutex!
       
  1183 	__ASSERT_DEBUG(iQueMutex.IsHeld(), Panic(EMutexUnheld));
       
  1184 
       
  1185 	OMX_ERRORTYPE ret = OMX_ErrorNone;
       
  1186 	
       
  1187 	OMX_TIME_CONFIG_CLOCKSTATETYPE* const &clkState 
       
  1188 		= static_cast<OMX_TIME_CONFIG_CLOCKSTATETYPE*>(aPassedStructPtr);
       
  1189 	
       
  1190 	if (ESetConfig == aEntry)
       
  1191 		{		
       
  1192 		if (iMediaClockState.eState == clkState->eState)
       
  1193 			{
       
  1194 			// Already in this state!
       
  1195 			return OMX_ErrorSameState;
       
  1196 			}
       
  1197 		if (clkState->eState != OMX_TIME_ClockStateStopped &&
       
  1198 			clkState->eState != OMX_TIME_ClockStateWaitingForStartTime &&
       
  1199 			clkState->eState != OMX_TIME_ClockStateRunning)
       
  1200 			{
       
  1201 			return OMX_ErrorUnsupportedSetting;
       
  1202 			}
       
  1203 		
       
  1204 		// need buffers to notify clock state changes, so require to be in Executing
       
  1205 		if(!iProcessingFunction.IsExecuting())
       
  1206 			{
       
  1207 			return OMX_ErrorIncorrectStateOperation;
       
  1208 			}
       
  1209 		
       
  1210 		switch (clkState->eState)
       
  1211 			{
       
  1212 			case OMX_TIME_ClockStateStopped:
       
  1213 				{
       
  1214 				DoTransitionToStoppedState();
       
  1215 				break;
       
  1216 				}
       
  1217 			case OMX_TIME_ClockStateWaitingForStartTime:
       
  1218 				{
       
  1219 				// Can't go into this state from Running state
       
  1220 				if (OMX_TIME_ClockStateRunning == iMediaClockState.eState)
       
  1221 					{
       
  1222 					ret = OMX_ErrorIncorrectStateTransition;
       
  1223 					break;
       
  1224 					}
       
  1225 				// Waiting for no ports makes no sense. Also don't allow wait on ports we don't have.
       
  1226 				if (clkState->nWaitMask == 0 || clkState->nWaitMask >= 1 << KNumPorts)
       
  1227 					{
       
  1228 					ret = OMX_ErrorUnsupportedSetting;
       
  1229 					break;
       
  1230 					}
       
  1231 				DoTransitionToWaitingState(clkState->nWaitMask);
       
  1232 				break;
       
  1233 				}			
       
  1234 			case OMX_TIME_ClockStateRunning:
       
  1235 				{
       
  1236 				// set media time to that passed by the IL client
       
  1237 				iMtc.iWallTimeBase = WallTime();
       
  1238 				iMtc.iMediaTimeBase = clkState->nStartTime;
       
  1239 				// changed time base so pending trigger wall times may be different
       
  1240 				iPendingRequestQue.RecalculateAndReorder(iMtc);
       
  1241 				DoTransitionToRunningState();
       
  1242  				// wake the timer thread to reset timer or service pending updates
       
  1243 				TRequestStatus* statusPtr = &iCancelStatus;
       
  1244 				iThread.RequestComplete(statusPtr, KErrCancel);
       
  1245 
       
  1246 				break;
       
  1247 				}
       
  1248 			// default condition already checked before Executing test
       
  1249 			}
       
  1250 		}
       
  1251 	else
       
  1252 		{
       
  1253 		clkState->eState = iMediaClockState.eState;
       
  1254 		}
       
  1255 	
       
  1256 	return ret;
       
  1257 	}
       
  1258  
       
  1259  /**
       
  1260   *
       
  1261   *
       
  1262   */
       
  1263  OMX_ERRORTYPE CClockSupervisor::HandleGetSetActiveRefClock(TEntryPoint aEntry, OMX_PTR aPassedStructPtr)
       
  1264 	{
       
  1265 	// The IL client controls which reference clock the clock component uses (if any) via the
       
  1266 	// OMX_IndexConfigTimeActiveRefClock configuration and structure OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE
       
  1267 	
       
  1268 	// don't need the mutex here as just getting/setting one machine word
       
  1269 	
       
  1270 	OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE& ref = *static_cast<OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE*>(aPassedStructPtr);
       
  1271 
       
  1272 	if (ESetConfig == aEntry)
       
  1273 		{
       
  1274 		if (ref.eClock != OMX_TIME_RefClockAudio &&
       
  1275 			ref.eClock != OMX_TIME_RefClockVideo &&
       
  1276 			ref.eClock != OMX_TIME_RefClockNone)
       
  1277 			{
       
  1278 			return OMX_ErrorUnsupportedSetting;
       
  1279 			}
       
  1280 		iActiveRefClock = ref.eClock;
       
  1281 		}
       
  1282 	else // EGetConfig
       
  1283 		{
       
  1284 		ref.eClock = iActiveRefClock;
       
  1285 		}
       
  1286 	return OMX_ErrorNone;
       
  1287 	}
       
  1288 
       
  1289 void CClockSupervisor::BroadcastUpdate(const OMX_TIME_MEDIATIMETYPE& aUpdate)
       
  1290 	{
       
  1291 	// notify state change on all enabled ports
       
  1292  	for(TInt portIndex = 0; portIndex < KNumPorts; portIndex++)
       
  1293  		{
       
  1294  		if(iProcessingFunction.PortEnabled(portIndex))
       
  1295  			{
       
  1296  			OMX_BUFFERHEADERTYPE* buffer = iProcessingFunction.AcquireBuffer(portIndex);
       
  1297  			if(buffer == NULL)
       
  1298  				{
       
  1299  				// starved of buffers!
       
  1300  				iThreadRunning = EFalse;
       
  1301  				iProcessingFunction.InvalidateComponent();
       
  1302  				return;
       
  1303  				}
       
  1304  			OMX_TIME_MEDIATIMETYPE& mT = *reinterpret_cast<OMX_TIME_MEDIATIMETYPE*>(buffer->pBuffer);
       
  1305  			mT = aUpdate;
       
  1306  			buffer->nOffset = 0;
       
  1307  			buffer->nFilledLen = sizeof(OMX_TIME_MEDIATIMETYPE);
       
  1308  			iProcessingFunction.SendBuffer(buffer);
       
  1309  			}
       
  1310  		}
       
  1311 	}
       
  1312 
       
  1313 void CClockSupervisor::ReportClockThreadPanic()
       
  1314     {
       
  1315         iThreadRunning = EFalse;
       
  1316         iProcessingFunction.InvalidateComponent();
       
  1317     }
       
  1318 /**
       
  1319  * Adjusts the media time scale.
       
  1320  * The wall/media time bases are updated so there is no instantaneous change to media time.
       
  1321  * iInverseScaleQ16 is also recalculated.
       
  1322  */
       
  1323 void TMediaTimeContext::SetScaleQ16(TInt32 aScaleQ16, TInt64 aWallTimeNow)
       
  1324 	{
       
  1325 	TInt64 mediaTimeNow = ((aWallTimeNow - iWallTimeBase) * iScaleQ16 >> 16) + iMediaTimeBase;
       
  1326 	iWallTimeBase = aWallTimeNow;
       
  1327 	iMediaTimeBase = mediaTimeNow;
       
  1328 	iScaleQ16 = aScaleQ16;
       
  1329 	
       
  1330 	// calculate inverse scale
       
  1331 	// 1.0/scale in Q16 format becomes 2^32/scaleQ16
       
  1332 	// values of -1 and +1 will cause overflow and are clipped
       
  1333 	// division by zero also yields KMaxTInt (2^31 - 1)
       
  1334 	if(iScaleQ16 == 0 || iScaleQ16 == 1)
       
  1335 		{
       
  1336 		iInverseScaleQ16 = 0x7FFFFFFF;
       
  1337 		}
       
  1338 	else if(iScaleQ16 == -1)
       
  1339 		{
       
  1340 		iInverseScaleQ16 = 0x80000000;
       
  1341 		}
       
  1342 	else
       
  1343 		{
       
  1344 		iInverseScaleQ16 = static_cast<TInt32>(0x100000000LL / iScaleQ16);
       
  1345 		}
       
  1346 	}
       
  1347 
       
  1348 
       
  1349 TRequestDeltaQue::TRequestDeltaQue()
       
  1350  :	iHead(0),
       
  1351  	iCount(0)
       
  1352 	 {
       
  1353 	 // do nothing
       
  1354 	 }
       
  1355 
       
  1356  void TRequestDeltaQue::Add(TMediaRequest* aElement, TInt64 aDelta)
       
  1357 	{
       
  1358 	CHECK_DEBUG();
       
  1359 	
       
  1360 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1361 					Panic(ERequestQueueCorrupt));
       
  1362 	
       
  1363 	if (!iHead)
       
  1364 		{
       
  1365 		iHead = aElement;
       
  1366 		aElement->iPrev = aElement;
       
  1367 		aElement->iNext = aElement;
       
  1368 		}
       
  1369 	else // set the new element links
       
  1370 		{
       
  1371 		TBool front(EFalse);
       
  1372 		TMediaRequest* item(NULL);
       
  1373 		front = InsertBeforeFoundPosition (aDelta, item);
       
  1374 		
       
  1375 		if (front)
       
  1376 			{
       
  1377 			// insert infront BEFORE as we have the lesser delta
       
  1378 			// set up the element
       
  1379 			aElement->iPrev = item->iPrev;
       
  1380 			aElement->iNext = item;
       
  1381 			
       
  1382 			// set up the item before in the list
       
  1383 			item->iPrev->iNext = aElement;
       
  1384 			
       
  1385 			// set up the item after in the list
       
  1386 			item->iPrev = aElement;
       
  1387 			
       
  1388 			// setup the new head
       
  1389 			iHead = aElement;
       
  1390 			}
       
  1391 		else
       
  1392 			{
       
  1393 			// insert this element AFTER the item in the list
       
  1394 			// set up the element
       
  1395 			aElement->iPrev = item;
       
  1396 			aElement->iNext = item->iNext;
       
  1397 			
       
  1398 			// set up the item before in the list
       
  1399 			item->iNext = aElement;
       
  1400 			
       
  1401 			// set up the item after in the list
       
  1402 			aElement->iNext->iPrev = aElement;
       
  1403 			}
       
  1404 		}
       
  1405 	iCount++;
       
  1406 	
       
  1407 #ifdef _OMXIL_COMMON_DEBUG_TRACING_ON
       
  1408 	// print the trigger times in debug mode
       
  1409 	DbgPrint();
       
  1410 #endif
       
  1411 	
       
  1412 	CHECK_DEBUG();
       
  1413 	}
       
  1414 
       
  1415  TBool TRequestDeltaQue::InsertBeforeFoundPosition(TInt64 aDelta, TMediaRequest*& aItem) const
       
  1416 	{
       
  1417 	CHECK_DEBUG();
       
  1418 	
       
  1419 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1420 						Panic(ERequestQueueCorrupt));
       
  1421 	
       
  1422 	// search for the position where to insert
       
  1423 	// and insert after this
       
  1424 	
       
  1425 	aItem = iHead->iPrev; // tail
       
  1426 	
       
  1427 	// start from the end and linearly work backwards
       
  1428 	while (aItem->iTriggerWallTime > aDelta && aItem != iHead)
       
  1429 		{
       
  1430 		aItem = aItem->iPrev;
       
  1431 		}
       
  1432 	
       
  1433 	// indicates that we insert before the item and not after it
       
  1434 	if (aItem == iHead && aItem->iTriggerWallTime > aDelta)
       
  1435 		{
       
  1436 		return ETrue;
       
  1437 		}
       
  1438 
       
  1439 	// no CHECK_DEBUG required as this method is const
       
  1440 	
       
  1441 	return EFalse;
       
  1442 	}
       
  1443  
       
  1444 /**
       
  1445  * If scale changes, the iTriggerWallTimes must be recalculated.
       
  1446  *
       
  1447  * In addition, because offset is not affected by scale, it is possible for
       
  1448  * the order of the elements to change. This event is assumed to be rare, and
       
  1449  * when it does occur we expect the list to remain 'roughly sorted' requiring
       
  1450  * few exchanges.
       
  1451  * 
       
  1452  * So we choose ** bubble sort **.
       
  1453  *
       
  1454  * Time recalculation is merged with the first pass of bubble sort. Times are
       
  1455  * recalculated in the first iteration only. Swaps can occur as necessary in
       
  1456  * all iterations. We expect that in most cases there will only be one pass
       
  1457  * with no swaps.
       
  1458  *
       
  1459  * Note that bubble sort would be worst-case complexity if reversing the list
       
  1460  * due to a time direction change. In such cases future requests complete
       
  1461  * immediately (because they are now in the past). So we do not sort at at all
       
  1462  * in this case.
       
  1463  */
       
  1464  void TRequestDeltaQue::RecalculateAndReorder(TMediaTimeContext& aMtc)
       
  1465 	{
       
  1466 	CHECK_DEBUG();
       
  1467 	
       
  1468 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1469 						Panic(ERequestQueueCorrupt));
       
  1470 	
       
  1471 	if(iCount == 0)
       
  1472 		{
       
  1473 		// nothing to do
       
  1474 		return;
       
  1475 		}
       
  1476 	// note if there is 1 item there is no reorder but we do need to recalculate
       
  1477 	
       
  1478 	TBool swapped(EFalse);
       
  1479 	TBool deltaCalculated(EFalse);
       
  1480 
       
  1481 	do
       
  1482 		{
       
  1483 		// start from end of queue
       
  1484 		swapped = EFalse;
       
  1485 		TMediaRequest* item(iHead->iPrev); // tail
       
  1486 		
       
  1487 		if (!deltaCalculated)
       
  1488 			{
       
  1489 			// calculate the tails new delta
       
  1490 			item->iTriggerWallTime = 
       
  1491 				((item->iMediaTime - aMtc.iMediaTimeBase) * aMtc.iInverseScaleQ16 >> 16) 
       
  1492 					+ aMtc.iWallTimeBase - item->iOffset;
       
  1493 			}
       
  1494 
       
  1495 		while (item != iHead)
       
  1496 			{
       
  1497 			TMediaRequest* swap = item->iPrev;
       
  1498 			if (!deltaCalculated)
       
  1499 				{
       
  1500 				// recalculate the Prev item delta
       
  1501 				swap->iTriggerWallTime = 
       
  1502 					((swap->iMediaTime - aMtc.iMediaTimeBase) * aMtc.iInverseScaleQ16 >> 16) 
       
  1503 						+ aMtc.iWallTimeBase - swap->iOffset;
       
  1504 				}
       
  1505 
       
  1506 			if (swap->iTriggerWallTime > item->iTriggerWallTime)
       
  1507 				{
       
  1508 				// switch (swap, item) for (item, swap)
       
  1509 				item->Deque();
       
  1510 				item->AddBefore(swap);
       
  1511 				if(swap == iHead)
       
  1512 					{
       
  1513 					iHead = item;
       
  1514 					}
       
  1515 
       
  1516 				swapped = ETrue;
       
  1517 				}
       
  1518 			else
       
  1519 				{
       
  1520 				// move along list
       
  1521 				item = item->iPrev;
       
  1522 				}
       
  1523 			
       
  1524 			} // while
       
  1525 
       
  1526 		// after the first pass of the queue, all deltas calculated
       
  1527 		deltaCalculated = ETrue;
       
  1528 		
       
  1529 		} while (swapped);
       
  1530 	
       
  1531 #ifdef _OMXIL_COMMON_DEBUG_TRACING_ON
       
  1532 	DbgPrint();
       
  1533 #endif
       
  1534 
       
  1535 	CHECK_DEBUG();
       
  1536 	}
       
  1537  
       
  1538  
       
  1539  TMediaRequest* TRequestDeltaQue::RemoveFirst()
       
  1540 	{
       
  1541 	CHECK_DEBUG();
       
  1542 	
       
  1543 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1544 						Panic(ERequestQueueCorrupt));
       
  1545 	
       
  1546 	TMediaRequest* item = NULL;
       
  1547 	
       
  1548 	// empty?
       
  1549 	if (!iHead)
       
  1550 		{
       
  1551 		return NULL;
       
  1552 		}
       
  1553 	else
       
  1554 	// only one element?
       
  1555 	if (1 == iCount)
       
  1556 		{
       
  1557 		item = iHead;
       
  1558 		iHead = NULL;
       
  1559 		}
       
  1560 	else
       
  1561 		{
       
  1562 		item = iHead;
       
  1563 		item->iPrev->iNext = item->iNext;
       
  1564 		item->iNext->iPrev = item->iPrev;
       
  1565 		
       
  1566 		// setup the new head
       
  1567 		iHead = item->iNext;
       
  1568 		}
       
  1569 	
       
  1570 	iCount--;
       
  1571 	
       
  1572 	CHECK_DEBUG();
       
  1573 	
       
  1574 	return item;
       
  1575 	}
       
  1576 
       
  1577  TBool TRequestDeltaQue::FirstDelta(TInt64& aDelta) const
       
  1578 	{
       
  1579 	CHECK_DEBUG();
       
  1580 	
       
  1581 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1582 						Panic(ERequestQueueCorrupt));
       
  1583 		
       
  1584 	if (!iHead)
       
  1585 		{
       
  1586 		return EFalse;
       
  1587 		}
       
  1588 	
       
  1589 	aDelta = iHead->iTriggerWallTime;
       
  1590 	return ETrue;
       
  1591 	}
       
  1592 
       
  1593  TBool TRequestDeltaQue::IsEmpty() const
       
  1594 	{
       
  1595 	__ASSERT_DEBUG(((iHead == NULL && iCount == 0) || (iHead != NULL && iCount > 0)), 
       
  1596 						Panic(ERequestQueueCorrupt));
       
  1597 		
       
  1598 	return (!iHead);
       
  1599 	}
       
  1600 
       
  1601  TUint TRequestDeltaQue::Count() const
       
  1602 	{
       
  1603 	return iCount;
       
  1604 	}
       
  1605 
       
  1606 void TMediaRequest::Deque()
       
  1607 	{
       
  1608 	iPrev->iNext = iNext;
       
  1609 	iNext->iPrev = iPrev;
       
  1610 	}
       
  1611 
       
  1612 void TMediaRequest::AddBefore(TMediaRequest* x)
       
  1613 	{
       
  1614 	x->iPrev->iNext = this;
       
  1615 	iPrev = x->iPrev;
       
  1616 	iNext = x;
       
  1617 	x->iPrev = this;
       
  1618 	}
       
  1619 
       
  1620 #ifdef _DEBUG
       
  1621  
       
  1622  /**
       
  1623   * Checks the linked list for consistency.
       
  1624   */
       
  1625  void TRequestDeltaQue::DbgCheck() const
       
  1626 	 {
       
  1627 	 if(iCount == 0)
       
  1628 		 {
       
  1629 		 __ASSERT_DEBUG(iHead == NULL, Panic(ERequestQueueCorrupt));
       
  1630 		 }
       
  1631 	 else
       
  1632 		 {
       
  1633 		 TMediaRequest* last = iHead;
       
  1634 		 TInt index = iCount - 1;
       
  1635 		 while(index-- > 0)
       
  1636 			 {
       
  1637 			 TMediaRequest* current = last->iNext;
       
  1638 			 __ASSERT_DEBUG(current->iPrev == last, Panic(ERequestQueueCorrupt));
       
  1639 			 __ASSERT_DEBUG(current->iTriggerWallTime >= last->iTriggerWallTime, Panic(ERequestQueueUnordered));
       
  1640 			 last = current;
       
  1641 			 }
       
  1642 		 __ASSERT_DEBUG(last->iNext == iHead, Panic(ERequestQueueCorrupt));
       
  1643 		 __ASSERT_DEBUG(iHead->iPrev == last, Panic(ERequestQueueCorrupt));
       
  1644 		 }
       
  1645 	 }
       
  1646  
       
  1647 #endif
       
  1648  
       
  1649 #ifdef _OMXIL_COMMON_DEBUG_TRACING_ON
       
  1650 
       
  1651 void TRequestDeltaQue::DbgPrint() const
       
  1652  	{
       
  1653 	TMediaRequest* x = iHead;
       
  1654 	TBuf8<256> msg;
       
  1655  	msg.Append(_L8("pending times: "));
       
  1656  	for(TInt index = 0; index < iCount; index++)
       
  1657  		{
       
  1658  		if(index > 0)
       
  1659  			{
       
  1660  			msg.Append(_L8(", "));
       
  1661  			}
       
  1662  		msg.AppendFormat(_L8("%ld"), x->iTriggerWallTime);
       
  1663  		x = x->iNext;
       
  1664  		}
       
  1665  	DEBUG_PRINTF(msg);
       
  1666  	}
       
  1667  
       
  1668 #endif