// ----------------------------------------------------------------------------
// An array must be supplied to receive UIDs, so a temporary one is created
// here before being copied into the buffer
// ----------------------------------------------------------------------------
//
TInt CMPXPlaybackSession::CreatePlayerUidsBufferL(const RMessage2& aMessage)
    {
    RArray<TUid> players;
    CleanupClosePushL(players);
    iPlayer->PluginHandler()->GetPlayerListL(players,
                        static_cast<TMPXPlaybackPlayerType>(aMessage.Int0()));
    ::CreateBufferL<TUid>(players.Array(), iSyncBuffer);
    TInt r = iSyncBuffer->Size();
    CleanupStack::PopAndDestroy(&players);
    return r;
    }
// ---------------------------------------------------------------------------
// 2nd Phased Constructor
// ---------------------------------------------------------------------------
//
void CMPXCollectionHelperImp::ConstructL()
    {
    iHvsUtility = CMPXHarvesterFactory::NewL();
    iCollectionUtil = MMPXCollectionUtility::NewL();
    iMediator = CMPXCollectionMediator::NewL( iCollectionUtil->Collection(),
                                              this );
    
    RArray<TUid> ary;
    CleanupClosePushL( ary );
    ary.AppendL( TUid::Uid(EMPXCollectionPluginMusic) );
    iMusicCollectionId = iCollectionUtil->CollectionIDL( ary.Array() );
    CleanupStack::PopAndDestroy( &ary );
    }
// -----------------------------------------------------------------------------
// SortItemsBySortingStyleL
// sort aItemArray with aSortingStyle
// add undefined items to aUndefinedItemArray
// -----------------------------------------------------------------------------
//
void SortItemsBySortingStyleL( RPointerArray<MCLFItem>& aItemArray,
                               MCLFSortingStyle& aSortingStyle,
                               RPointerArray<MCLFItem>& aUndefinedItemArray )
{
    RArray<TCLFFieldId> sortingFields;
    CleanupClosePushL( sortingFields );
    aSortingStyle.GetFieldsL( sortingFields );
    const TInt sortingFieldsCount( sortingFields.Count() );
    if( sortingFieldsCount )  // sort only if there are sorting fields
    {
        TCLFItemDataType sortingDataType( aSortingStyle.SortingDataType() );

        RArray<TCLFSortingItem> sortingArray;
        CleanupClosePushL( sortingArray );
        MakeSortingItemsL( sortingArray,
                           aUndefinedItemArray,
                           aItemArray.Array(),
                           sortingFields.Array(),
                           sortingDataType );

        SortSortingItemsL( sortingArray, sortingDataType );

        aItemArray.Reset();
        if( aSortingStyle.Ordering() == ECLFOrderingAscending )
        {
            AppendSortingItemsToArrayL( sortingArray.Array(),
                                        aItemArray );
        }
        else
        {
            AppendSortingItemsToArrayReverseL( sortingArray.Array(),
                                               aItemArray );
        }

        CleanupStack::PopAndDestroy( &sortingArray ); // sortingArray.Close
    }
    CleanupStack::PopAndDestroy( &sortingFields ); // sortingFields.Close
}
// ---------------------------------------------------------------------------
// Requests Media.
// ---------------------------------------------------------------------------
//
void CAiPlayerPluginEngine::RequestMediaL()
    {
    MMPXSource* s = iPlaybackUtility->Source();
    if ( s )
        {
        RArray<TMPXAttribute> attrs;
        CleanupClosePushL(attrs);
        attrs.Append( KMPXMediaGeneralUri );
        attrs.Append( KMPXMediaGeneralTitle );
        attrs.Append( KMPXMediaMusicArtist );
        attrs.Append( KMPXMediaMusicAlbumArtFileName );
        iPlaybackUtility->PropertyL( *this, EPbPropertyDuration );
        s->MediaL( attrs.Array(), *this );
        CleanupStack::PopAndDestroy( &attrs );
        }
    }
// ============================ LOCAL FUNCTIONS ==============================
// ----------------------------------------------------------------------------
// Add an item to the media array
// ----------------------------------------------------------------------------
//
LOCAL_C void AppendL(const TGlxMediaId& aId, const TDesC& aTitle,
        CMPXMediaArray& aArray, TMPXGeneralType aType,TMPXGeneralCategory aCat)
    {
    RArray<TInt> supportedIds;
    CleanupClosePushL(supportedIds);
    supportedIds.AppendL(KMPXMediaIdGeneral);
    CMPXMedia* entry=CMPXMedia::NewL(supportedIds.Array());
    CleanupStack::PushL(entry);
    entry->SetTObjectValueL(KMPXMediaGeneralId, aId);
    entry->SetTextValueL(KMPXMediaGeneralTitle, aTitle);
    entry->SetTObjectValueL(KMPXMediaGeneralType, aType);
    entry->SetTObjectValueL(KMPXMediaGeneralCategory, aCat);
    aArray.AppendL(entry);
    CleanupStack::Pop(entry);
    CleanupStack::PopAndDestroy(&supportedIds);
    }
// ----------------------------------------------------------------------------
// Navigates to the given path
// ----------------------------------------------------------------------------
//
void CGlxMediaListsTestCollectionPlugin::OpenL(const CMPXCollectionPath& aPath,
                   const TArray<TMPXAttribute>& /*aAttrs*/,
                   CMPXFilter* /*aFilter*/)
    {
    RArray<TInt> supportedIds;
    CleanupClosePushL(supportedIds);
    supportedIds.AppendL(KMPXMediaIdContainer);
    supportedIds.AppendL(KMPXMediaIdGeneral);
    iOpenEntries = CMPXMedia::NewL(supportedIds.Array());

    CMPXMediaArray* array = CMPXMediaArray::NewL();
    CleanupStack::PushL(array);

 	if ( aPath.Levels() == 1 ) 
 		{
 		TInt count = _iItemDBHackAlbums.Count();
 		for ( TInt i = 0; i < count; i++ )
 			{
 			AppendL(_iItemDBHackAlbums[i]->iId, *_iItemDBHackAlbums[i]->iTitle, *array, EMPXGroup, EMPXAlbum);
 			}
 		}
 	else if ( aPath.Levels() == 2 ) 
 		{
 		TInt count = _iItemDBHackContent.Count();
 		for ( TInt i = 0; i < count; i++ )
 			{
 			AppendL(_iItemDBHackContent[i]->iId, *_iItemDBHackContent[i]->iTitle, *array, EMPXItem, EMPXImage);
 			}

		StartEvents();
 		}
 	else 
 		{
 		__DEBUG_ONLY(Panic(EGlxPanicDebugUnexpectedError));
 		}
    
    iOpenEntries->SetCObjectValueL(KMPXMediaArrayContents, array);
    iOpenEntries->SetTObjectValueL(KMPXMediaArrayCount, array->Count());

    CleanupStack::PopAndDestroy(array);    

	//iObs->HandleOpen(*iOpenEntries, KErrNone);
	
    AsyncNotifyL(iOpenEntries, KErrNone, CGlxAsyncNotifier::EOpen);
        
    CleanupStack::PopAndDestroy(&supportedIds);        
    }
EXPORT_C void CGlxDataSourceTask::ListToMediaL(const RArray<TGlxMediaId>& aList)
	{
    TRACER("void CGlxDataSourceTask::ListToMediaL(const RArray<TGlxMediaId>& aList)");    
	RArray<TMPXItemId> mpxIds;
	CleanupClosePushL(mpxIds);
 
	for (TInt i = 0; i < aList.Count(); i++)
		{
		mpxIds.AppendL(aList[i].Value());
		}
    if (dynamic_cast<CGlxIdListRequest*>(iRequest))
        {
        CGlxIdListRequest* request = static_cast<CGlxIdListRequest*>(iRequest);
        request->CollectionPath().AppendL(mpxIds.Array());
        }

    CleanupStack::PopAndDestroy(&mpxIds);
	}
// ---------------------------------------------------------------------------
// Requests Media.
// ---------------------------------------------------------------------------
//
void CAiPlayerPluginEngine::RequestMediaL()
    {
  //  MPX_DEBUG1( "CAiPlayerPluginEngine::RequestMediaL" );
    MMPXSource* s = iPlaybackUtility->Source();
    if ( s )
        {
        RArray<TMPXAttribute> attrs;
        CleanupClosePushL(attrs);
        attrs.Append( KMPXMediaGeneralUri );
        attrs.Append( KMPXMediaGeneralTitle );
        attrs.Append( KMPXMediaMusicArtist );
        attrs.Append( KMPXMediaMusicAlbumArtFileName );
        s->MediaL( attrs.Array(), *this );
        CleanupStack::PopAndDestroy( &attrs );
        }
    else 
        {
        iObserver->PlaylisIsEmpty();
        }
    }
// ----------------------------------------------------------------------------
// Append an item into the media array
// ----------------------------------------------------------------------------
//
void MPXDbUtil::AppendMediaL(
    CMPXMediaArray& aArray,
    const TDesC& aTitle,
    TMPXGeneralType aType,
    TMPXGeneralCategory aCat,
    TMPXPodcastType aPodcastType,
    TMPXPodcastCategory aPodcastCat,
    TMPXItemId aId,
    TInt aNonPermissibleActions)
    {
    MPX_FUNC("MPXDbUtil::AppendMediaL");

    RArray<TInt> supportedIds;
    CleanupClosePushL (supportedIds);
    supportedIds.AppendL (KMPXMediaIdGeneral);
    supportedIds.AppendL (KMPXMediaIdPodcast);
    CMPXMedia* entry = CMPXMedia::NewL(supportedIds.Array());
    CleanupStack::PushL (entry);
    entry->SetTextValueL (KMPXMediaGeneralTitle, aTitle);
    entry->SetTObjectValueL(KMPXMediaPodcastType, aPodcastType);
    entry->SetTObjectValueL(KMPXMediaPodcastCategoryGroup, aPodcastCat);
    entry->SetTObjectValueL(KMPXMediaGeneralId, aId);
    entry->SetTObjectValueL(KMPXMediaGeneralType, aType);
    entry->SetTObjectValueL(KMPXMediaGeneralCategory, aCat);

    // temp fix: Beryl BEGIN
    if ( aNonPermissibleActions != 0 )
        {
        // set non-permissible actions
        entry->SetTObjectValueL(KMPXMediaGeneralNonPermissibleActions,
            static_cast<TMPXGeneralNonPermissibleActions>(aNonPermissibleActions));
        }
    // temp fix: Beryl END
    aArray.AppendL (entry);
    CleanupStack::Pop (entry);
    CleanupStack::PopAndDestroy (&supportedIds);
    }
// ----------------------------------------------------------------------------
// Message dispatcher
// ----------------------------------------------------------------------------
//
void CMPXPlaybackSession::DispatchMessageL( const RMessage2& aMessage, TInt& aMsgHandleResult )
    {
    aMsgHandleResult = KErrNone;
    //
    // All methods apart from the player creation methods, require a player
    //
    TInt op=aMessage.Function();
    if (op != EPbsSetMode)
        {
        CheckPlayerL();
        }
    MPX_DEBUG3("-->CMPXPlaybackSession::DispatchMessageL %d, this 0x%08x",
            op, this);
    switch(op)
        {
        case EPbsSetMode:
            {
            SetModeL(aMessage);
            break;
            }
        case EPbsGetClients:
            {
            RArray<TProcessId> procArray;
            ::CopyArrayL<TProcessId>(
                iPlayer->ClientList()->ClientProcessList(),
                procArray );
            TProcessId lastPid = static_cast<CMPXPlaybackServer*>(
                         const_cast<CServer2*>(Server()))->LastActiveProcessId();

            TInt index( procArray.Find( lastPid ));
            if ( KErrNotFound != index && index )
                {
                procArray.Remove( index );
                procArray.Insert( lastPid, 0 );
                }
            ::CreateBufferL<TProcessId>(
                            procArray.Array(),
                            iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            procArray.Close();
            break;
            }
        case EPbsGetSyncBuffer:
            {
            aMessage.WriteL(0,iSyncBuffer->Ptr(0));
            delete iSyncBuffer;
            iSyncBuffer = NULL;
            break;
            }
        case EPbsGetAsyncBuffer:
            {
            //In case of other application leaving, causing us to leave
            //we could have a task that does not get removed from the top of the queue
            //but the data for that task has been deleted.
            //When the task runs again, there will be no data causing a panic - leave if this occurs
            User::LeaveIfNull(iAsyncBuffer);                         
            aMessage.WriteL(0,iAsyncBuffer->Ptr(0));
            delete iAsyncBuffer;
            iAsyncBuffer = NULL;       
            break;                            
            }
        case EPbsInitFromCollection:
            {
            MPXUser::CreateBufferL(aMessage, 0, iSyncBuffer);
            CMPXCollectionPlaylist* p = NULL;
            ::NewFromBufferL(*iSyncBuffer, p);
            delete iSyncBuffer;
            iSyncBuffer = NULL;
            CleanupStack::PushL(p);
            iPlayer->InitL(*p,aMessage.Int1());
            CleanupStack::PopAndDestroy(p);
            }
            break;
        case EPbsInitFromUri:
            {
            CBufBase* buf0(NULL);
            MPXUser::CreateBufferL(aMessage,0,buf0);
            CleanupStack::PushL(buf0);

            // Type parameter is optional
            if ( aMessage.GetDesLength( 1 ) > 0 )
                {
                CBufBase* buf1(NULL);
                MPXUser::CreateBufferL(aMessage,1,buf1);
                CleanupStack::PushL(buf1);
                iPlayer->InitL(MPXUser::Ptr(buf0->Ptr(0)), buf1->Ptr(0));
                CleanupStack::PopAndDestroy(buf1);
                }
            else
                {
                MPX_DEBUG2("CMPXPlaybackSession::DispatchMessageL %d: Type is empty", op);
                iPlayer->InitL( MPXUser::Ptr( buf0->Ptr(0) ), KNullDesC8 );
                }
            CleanupStack::PopAndDestroy(buf0);
            }
            break;
        case EPbsInitFromFile:
            {
            InitFromFileL(aMessage);
            break;
            }
        case EPbsInitStreamingFromUri:
            {            
            CBufBase* buf0(NULL);
            MPXUser::CreateBufferL(aMessage,0,buf0);
            CleanupStack::PushL(buf0);

            // Type parameter is optional
            if ( aMessage.GetDesLength( 1 ) > 0 )
                {
                CBufBase* buf1(NULL);
                MPXUser::CreateBufferL(aMessage,1,buf1);
                CleanupStack::PushL(buf1);
                iPlayer->InitStreamingL(MPXUser::Ptr(buf0->Ptr(0)), buf1->Ptr(0), aMessage.Int2());
                CleanupStack::PopAndDestroy(buf1);
                }
            else
                {
                MPX_DEBUG2("CMPXPlaybackSession::DispatchMessageL %d: Type is empty", op);
                iPlayer->InitStreamingL( MPXUser::Ptr( buf0->Ptr(0) ), KNullDesC8, aMessage.Int2() );
                }
            CleanupStack::PopAndDestroy(buf0);
            break;                          
            }
         case EPbsInitStreamingFromFile:
            {
            RFile file;
            User::LeaveIfError(file.AdoptFromClient(aMessage,0,1));
            iPlayer->InitStreamingL(file, aMessage.Int2());
            file.Close();
            break;
            }            
        case EPbsCancelRequest:
            {
            CancelRequests();
            break;
            }
        case EPbsGetState:
            {
            aMsgHandleResult = iPlayer->State();
            break;
            }
        case EPbsSetProperty:
            {
            iPlayer->SetL(static_cast<TMPXPlaybackProperty>(aMessage.Int0()),
                          aMessage.Int1());
            break;
            }
        case EPbsGetProperty:
            {
            SetAsync(aMessage);
            iPlayer->PropertyL(
                    static_cast<TMPXPlaybackProperty>(aMessage.Int0()),*this);
            break;
            }
        case EPbsGetPlayerTypes:
            {
            RArray<TMPXPlaybackPlayerType> pluginTypes;
            CleanupClosePushL(pluginTypes);
            RArray<TInt> types;
            CleanupClosePushL(types);
            iPlayer->PluginHandler()->GetPluginTypes(types);
            for (TInt i=0; i< types.Count(); ++i)
                {
                pluginTypes.AppendL(
                        static_cast<TMPXPlaybackPlayerType>(types[i]));
                }
            CleanupStack::PopAndDestroy(&types);
            ::CreateBufferL<TMPXPlaybackPlayerType>(
                                    pluginTypes.Array(),
                                    iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            CleanupStack::PopAndDestroy(&pluginTypes);
            break;
            }
        case EPbsGetPlayerTypeDisplayName:
            {
            const TDesC& playerName = iPlayer->PluginHandler()->PlayerName(
                        static_cast<TMPXPlaybackPlayerType>(aMessage.Int0()));
            aMsgHandleResult = 0;
            if (playerName.Length()>0)
                {
                MPXUser::CreateBufferL(playerName, iSyncBuffer);
                aMsgHandleResult = iSyncBuffer->Size();
                }
            break;
            }
        case EPbsGetAllPlayersUids:
            {
            RArray<TUid> uids;
            CleanupClosePushL(uids);
            iPlayer->PluginHandler()->GetPluginUids(uids);

            ::CreateBufferL<TUid>(
                    uids.Array(),
                    iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            CleanupStack::PopAndDestroy(&uids);
            break;
            }
        case EPbsGetPlayersUidsForType:
            {
            aMsgHandleResult = CreatePlayerUidsBufferL(aMessage);
            break;
            }
        case EPbsGetSubPlayerNamesByUid:
            {
            SetAsync(aMessage);
            iPlayer->SubPlayerNamesL(TUid::Uid(aMessage.Int0()),*this);
            break;
            }
        case EPbsSelectPlayerByType:
            {
            iPlayer->PluginHandler()->SelectPlayersL(
                         static_cast<TMPXPlaybackPlayerType>(aMessage.Int0()));
            break;
            }
        case EPbsSelectPlayerByUid:
            {
            iPlayer->PluginHandler()->SelectPlayerL(TUid::Uid(aMessage.Int0()));
            break;
            }
        case EPbsSelectSubPlayer:
            {
            iPlayer->PluginHandler()->SelectSubPlayerL(
                                  TUid::Uid(aMessage.Int0()),aMessage.Int1());
            break;
            }
        case EPbsClearPlayerSelection:
            {
            iPlayer->PluginHandler()->ClearSelectPlayersL();
            break;
            }
        case EPbsGetSelection:
            {
            GetSelectionL(aMessage);
            break;
            }
        case EPbsPlayerFound:
            {
            aMsgHandleResult = iPlayer->PluginHandler()->PlayerFound();
            break;
            }
        case EPbsGetPlayerType:
            {
            aMsgHandleResult = iPlayer->PluginHandler()->PluginType();
            break;
            }
        case EPbsGetTypeName:
            {
            MPXUser::CreateBufferL(iPlayer->PluginHandler()->PlayerName(),
                                   iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            break;
            }
        case EPbsGetSubPlayerIndex:
            {
            aMsgHandleResult = iPlayer->PluginHandler()->SubPlayer();
            break;
            }
        case EPbsGetPlayerUid:
            {
            TPckgC<TInt> uidPkg((iPlayer->PluginHandler()->PluginUid()).iUid);
            aMessage.Write(0,uidPkg);
            break;
            }
        case EPbsGetCollectionPlaylist:
            {
            aMsgHandleResult = 0;
            if (iPlayer->Playlist())
                {
                ::CreateBufferL<CMPXCollectionPlaylist>(*(iPlayer->Playlist()),
                                                        iSyncBuffer);
                aMsgHandleResult = iSyncBuffer->Size();
                }
            break;
            }
        case EPbsGetFile:
            {
            const RFile& file = iPlayer->File();
            if (file.SubSessionHandle())
                {
                aMsgHandleResult = file.TransferToClient(aMessage,0); //message completed
                }
            else
                {
                TPckgC<TInt> handle(KErrNotFound);
                aMessage.Write(0, handle);
                }
            break;
            }
        case EPbsGetUri:
            {
            aMsgHandleResult=0;
            if (iPlayer->Uri().Length()>0)
                {
                MPXUser::CreateBufferL(iPlayer->Uri(),iSyncBuffer);
                aMsgHandleResult = iSyncBuffer->Size();
                }
            break;
            }
        case EPbsGetMedia:
            {
            SetAsync( aMessage );
            CMPXCommand* cmd( CMPXCommand::NewL( aMessage.Int1() ) );
            CleanupStack::PushL( cmd );
            iPlayer->MediaL( *this, *cmd );
            CleanupStack::PopAndDestroy( cmd );
            break;
            }
        case EPbsGetSupportedMimeTypes:
            {
            CDesCArray* mimeTypes =
               iPlayer->PluginHandler()->SupportedMimeTypesL();
            CleanupStack::PushL(mimeTypes);
            MPXUser::CreateBufferL((const MDesCArray*)mimeTypes, iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            CleanupStack::PopAndDestroy(mimeTypes);
            }
            break;
        case EPbsGetSupportedExtensions:
            {
            CDesCArray* exts =
              iPlayer->PluginHandler()->SupportedExtensionsL();
            CleanupStack::PushL(exts);
            MPXUser::CreateBufferL((const MDesCArray*)exts, iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            CleanupStack::PopAndDestroy(exts);
            }
            break;
        case EPbsGetSupportedSchemas:
            {
            CDesCArray* schemas =
                 iPlayer->PluginHandler()->SupportedSchemasL();
            CleanupStack::PushL(schemas);
            MPXUser::CreateBufferL((const MDesCArray*)schemas, iSyncBuffer);
            aMsgHandleResult = iSyncBuffer->Size();
            CleanupStack::PopAndDestroy(schemas);
            }
            break;
        case EPbsGetNextMessage:
            {
            ASSERT(iMessageQueue);
            iMessageQueue->SendNext(aMessage);
            iCompleteRequest=EFalse;
            break;
            }
        case EPbsCancelGetMessage:
            {
            ASSERT(iMessageQueue);
            iMessageQueue->Reset();
            break;
            }
        case EPbsCommand:
            {
            CMPXCommand* cmd( NULL );
            ::NewFromMessageL<CMPXMedia>(aMessage, 1, cmd);
            CleanupStack::PushL(cmd);
            iPlayer->CommandL(*cmd, *iMessageQueue);
            CleanupStack::PopAndDestroy(cmd);
            break;
            }
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        case EPbsInitFromFile64:
            {
            RFile64 file;
            User::LeaveIfError(file.AdoptFromClient(aMessage,0,1));
            iPlayer->Init64L(file);
            file.Close();
            break;
            }
        case EPbsInitStreamingFromFile64:
            {
            RFile64 file;
            User::LeaveIfError(file.AdoptFromClient(aMessage,0,1));
            iPlayer->InitStreaming64L(file, aMessage.Int2());           
            file.Close();
            break;
            }
        case EPbsGetFile64:
            {
            const RFile64& file = iPlayer->File64();
            if (file.SubSessionHandle())
                {
                aMsgHandleResult = file.TransferToClient(aMessage,0); //message completed
                }
            else
                {
                TPckgC<TInt> handle(KErrNotFound);
                aMessage.Write(0, handle);
                }
            break;
            }
#endif // SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        case EPbsSetPrimaryClient:
            {
            aMsgHandleResult = iPlayer->ClientList()->SetPrimaryClient(*iMessageQueue);            
            break;
            }
        default:
            {
            PanicClient(aMessage,KErrNotSupported);
            break;
            }
        }
    MPX_DEBUG1("<---CMPXPlaybackSession::DispatchMessageL");
    }
// -----------------------------------------------------------------------------
// CCollectionManagerTest::CreateCollectionL
// -----------------------------------------------------------------------------
//
TInt CCollectionManagerTest::CreateCollectionL( CStifItemParser& /* aItem */ )
    {
    _LIT( KMsg1, "Enter CreateCollectionL" );
    iLog->Log( KMsg1 );  
    RDebug::Print( KMsg1 );
    
    if( !iCollectionManager )
        {
        return KErrUnknown;
        }
    
    _LIT( KTestAlbumName, "TestAlbum" );
    HBufC* collectionName = KTestAlbumName().AllocL();
    RArray<TInt> types;
    types.AppendL( 1 );
    TInt32 properties = EMCPhoneMemoryCollection;

    TInt collectionId( KErrNotFound );
    TInt error( KErrNone );
    TRAP( error, collectionId = iCollectionManager->CreateCollectionL( *collectionName, types.Array(), properties ) );
    if( error != KErrNotSupported && error != KErrNone )
        {
        delete collectionName;
        collectionName = NULL;
        return error;
        }

    properties = EMCMmcCollection;
    TRAP( error, collectionId = iCollectionManager->CreateCollectionL( *collectionName, types.Array(), properties ) );
    if( error != KErrNotSupported && error != KErrNone )
        {
        delete collectionName;
        collectionName = NULL;
        return error;
        }

    MMediaCollectionInfo* mci = NULL;
    TRAP( error, iCollectionManager->CollectionInfoByIdLC( collectionId ) );
    if( error != KErrNotSupported && error != KErrNone )
        {
        delete collectionName;
        collectionName = NULL;
        return error;
        }

    if( mci )
        {
        delete collectionName;
        collectionName = NULL;
        return KErrCorrupt;
        }

    delete collectionName;
    collectionName = NULL;
    
    _LIT( KMsg2, "Exit CreateCollectionL" );
    iLog->Log( KMsg2 );  
    RDebug::Print( KMsg2 );
	
    return KErrNone;
    }
// ---------------------------------------------------------------------------
// rename a media object
// ---------------------------------------------------------------------------
//
void CMPXCollectionHelperImp::RenameL( const TDesC& aOldUri,
                                       const TDesC& aNewUri,
                                       TMPXGeneralCategory aItemCat )
    {
    MPX_FUNC("CMPXCollectionHelperImp::RenameL");
    MPX_DEBUG3("aOldUri = %S, aNewUri = %S", &aOldUri, &aNewUri);

    if (aItemCat != EMPXSong && aItemCat != EMPXPlaylist && aItemCat != EMPXAbstractAlbum)
        {
        User::Leave(KErrArgument);
        }

    // find the media using the old URI
    RArray<TMPXAttribute> attributes;
    CleanupClosePushL( attributes );
    attributes.AppendL(KMPXMediaGeneralId);
    attributes.AppendL(KMPXMediaMusicAlbumArtFileName);

    CMPXMedia* media = GetL(aOldUri, attributes.Array(), aItemCat);
    CleanupStack::PopAndDestroy(&attributes);
    CleanupStack::PushL(media);

    const TDesC& fileName(media->ValueText(KMPXMediaMusicAlbumArtFileName));
    
    // the songs have embedded albumart.
    if(fileName.CompareF(aOldUri) == 0)
        {
        // change the Art filename to the new Uri
        media->SetTextValueL(KMPXMediaMusicAlbumArtFileName, aNewUri);
        
        // Rename the thumbnail
        TRAPD(err, RenameThumbnailL(aOldUri, aNewUri));
        if(KErrNone != err)
            {
            MPX_DEBUG2("Thumbnail renames failed. Err: %d", err);
            }
        }

    // change file path to the new file path
    media->SetTextValueL(KMPXMediaGeneralUri, aNewUri);

    // ask harvester to rename the file if any of the following is true:
    // 1) renaming a song
    // 2) renaming a playlist scanned through file system.
    //
    //    There are 3 types of playlists. The ones created from the device
    //    are virtual playlists which have file extension .vir. There are
    //    no physical playlist files associated with them; hence not
    //    registered with harvester. For virtual playlists, IsPlaylistL
    //    will return EFalse because there is not a playlist plugin that
    //    deals with .vir playlist files.
    //
    //    The ones synced from PC through MTP have file extension .pla.
    //    There are 0-byte .pla files associated with them but they
    //    are not registered with harvester either. IsPlaylistL will also
    //    return EFalse because there is not a playlist plugin that deals
    //    with .pla.
    //
    //    The 3rd type of playlists is .m3u on the file system. They are
    //    added to the collection through file scan and registered with
    //    harvester. IsPlaylistL will return ETrue.
    if (aItemCat == EMPXSong || iHvsUtility->IsPlaylistL(aOldUri))
        {
        const TUid& collection =
             media->ValueTObjectL<TUid>(KMPXMediaGeneralCollectionId);
        iHvsUtility->RenameFileL( aOldUri, aNewUri, collection.iUid );
        }

    // Update collection via CMPXCommand
    //
    CMPXCommand* cmd = CMPXCommand::NewL();
    CleanupStack::PushL( cmd );
    cmd->SetTObjectValueL( KMPXCommandGeneralId, KMPXCommandIdCollectionSet );
    TUid colId (media->ValueTObjectL<TUid>(KMPXMediaGeneralCollectionId) );
    cmd->SetTObjectValueL( KMPXCommandGeneralCollectionId, colId.iUid );
    cmd->SetTObjectValueL( KMPXCommandGeneralDoSync, ETrue );
    cmd->SetCObjectValueL( KMPXCommandColSetMedia, media );
    iCollectionUtil->Collection().CommandL( *cmd );
    CleanupStack::PopAndDestroy( cmd );

    CleanupStack::PopAndDestroy(media);
    }
// ---------------------------------------------------------------------------
// Remove a file from the collection
// ---------------------------------------------------------------------------
//
void CMPXCollectionHelperImp::RemoveL( const TDesC& aFile,
                                       TMPXGeneralCategory aItemCat )
    {
    MPX_FUNC("CMPXCollectionHelperImp::RemoveL");
    MPX_DEBUG3("aFile %S, category %d", &aFile, aItemCat);

    if (aItemCat != EMPXSong && aItemCat != EMPXPlaylist)
        {
        User::Leave(KErrArgument);
        }

    //
    // ask harvester to remove the file if any of the following is true:
    // 1) removing a song
    // 2) removing a playlist scanned through file system.
    //
    //    There are 3 types of playlists. The ones created from the device
    //    are virtual playlists which have file extension .vir. There are
    //    no physical playlist files associated with them; hence not
    //    registered with harvester. For virtual playlists, IsPlaylistL
    //    will return EFalse because there is not a playlist plugin that
    //    deals with .vir playlist files.
    //
    //    The ones synced from PC through MTP have file extension .pla.
    //    There are 0-byte .pla files associated with them but they
    //    are not registered with harvester either. IsPlaylistL will also
    //    return EFalse because there is not a playlist plugin that deals
    //    with .pla.
    //
    //    The 3rd type of playlists is .m3u on the file system. They are
    //    added to the collection through file scan and registered with
    //    harvester. IsPlaylistL will return ETrue.
    //
    //    For now virtual playlists and synced playlists are assumed to
    //    be in the music collection for now until there is a generic way
    //    resolving collections aside from using file extension or UID.
    //
    TInt collection(iMusicCollectionId.iUid);
    if (aItemCat == EMPXSong || iHvsUtility->IsPlaylistL(aFile))
        {
        // Remove from the harvester
        collection = iHvsUtility->RemoveFileL( aFile );
        }

    // Remove from the collection
    // Construct a CMPXMedia object with URI, collection id, type and category
    //
    RArray<TInt> contID;
    CleanupClosePushL( contID );
    contID.AppendL( KMPXMediaIdGeneral );
    CMPXMedia* media = CMPXMedia::NewL( contID.Array() );
    CleanupStack::PushL( media );

    media->SetTextValueL( KMPXMediaGeneralUri, aFile );
    media->SetTObjectValueL<TUid>( KMPXMediaGeneralCollectionId, TUid::Uid( collection ) );
    media->SetTObjectValueL( KMPXMediaGeneralType, EMPXItem );
    media->SetTObjectValueL( KMPXMediaGeneralCategory, aItemCat );

    // Remove the item via CMPXCommand
    //
    CMPXCommand* cmd = CMPXCommand::NewL();
    CleanupStack::PushL( cmd );
    cmd->SetTObjectValueL( KMPXCommandGeneralCollectionId,
                           collection );
    cmd->SetTObjectValueL( KMPXCommandGeneralId,
                           KMPXCommandIdCollectionRemoveMedia );
    cmd->SetTObjectValueL( KMPXCommandGeneralDoSync, ETrue );
    cmd->SetCObjectValueL( KMPXCommandCollectionRemoveMedia, media );
    cmd->SetTObjectValueL( KMPXCommandCollectionRemoveMediaDeleteRecord,
                           ETrue );
    iCollectionUtil->Collection().CommandL( *cmd );
    CleanupStack::PopAndDestroy( cmd );

    CleanupStack::PopAndDestroy( media );
    CleanupStack::PopAndDestroy( &contID );
    }
// ----------------------------------------------------------------------------------------------------------
// Navigates to the given path
// ----------------------------------------------------------------------------------------------------------
//
void CTestCollectionPlugin::OpenL(const CMPXCollectionPath& aPath,
                                  const TArray<TMPXAttribute>& aAttrs,
                                  CMPXFilter* aFilter)
{
    LOG1(_L("CTestCollectionPlugin::OpenL"));
    LogPath( aPath );
    TMPXOpenMode openMode = aPath.OpenNextMode();
    TInt idIndex = aPath.Levels() - 1;
    LOG2(_L("TMPXOpendMode=%d"), openMode);
    LOG2(_L("aFilter=%x"), aFilter);

    RArray<TInt> supportedIds;
    CleanupClosePushL(supportedIds);
    supportedIds.AppendL(KMPXMediaIdContainer);
    supportedIds.AppendL(KMPXMediaIdGeneral);

    CMPXMedia* entries = CMPXMedia::NewL(supportedIds.Array());
    CleanupStack::PopAndDestroy(&supportedIds);
    CleanupStack::PushL(entries);
    entries->SetTObjectValueL<TMPXItemId>(TMPXAttribute(KMPXMediaIdGeneral,EMPXMediaGeneralId), aPath.Id(idIndex));

    if(aPath.Levels() == 1)
    {
        // Plugin's root level
        RArray<TInt> ids;
        CleanupClosePushL( ids );
        ids.Append( 11 );
        ids.Append( 12 );
        ids.Append( 13 );
        ids.Append( 990 );  // for Playback Framework Test
        RArray<TMPXAttribute> attrs;
        CleanupClosePushL( attrs );
        attrs.Append( KMPXMediaGeneralId );
        attrs.Append( KMPXMediaGeneralUri );
        attrs.Append( KMPXMediaGeneralTitle );

        CMPXMediaArray* array=CMPXMediaArray::NewL();
        CleanupStack::PushL( array );

        const TArray<TMPXAttribute>& tempRef = aAttrs.Count() == 0? attrs.Array() : aAttrs;
        AddMediaL(*array, ids, tempRef);
        FilterMediaArray(*array, aFilter);

        entries->SetCObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayContents),array);
        entries->SetTObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayCount),array->Count());

        iObs->HandleOpen (entries, KErrNone);
        CleanupStack::PopAndDestroy(3, &ids);   // attrs, array, ids
    }
    else if(aPath.Levels() == 2)
    {
        // Opening plugin's root menu
        TInt topLevId = aPath.Id(1);
        RArray<TInt> ids;
        CleanupClosePushL( ids );
        RArray<TMPXAttribute> attrs;
        CleanupClosePushL( attrs );
        CMPXMediaArray* array=CMPXMediaArray::NewL();
        CleanupStack::PushL( array );

        attrs.Append( KMPXMediaGeneralId );
        attrs.Append( KMPXMediaGeneralUri );
        attrs.Append( KMPXMediaGeneralTitle );
        if(topLevId == 11)
        {
            ids.Append( 211 );
            ids.Append( 212 );
            ids.Append( 213 );
        }
        else if(topLevId == 12)
        {
            ids.Append( 221 );
        }
        else if(topLevId == 13)
        {
            ids.Append( 231 );
            ids.Append( 232 );
        }
        else if(topLevId == 990)
        {
            ids.Append( 9901 );
            ids.Append( 9902 );
            ids.Append( 9903 );
            ids.Append( 9904 );
            ids.Append( 9905 );
            ids.Append( 9906 );
            ids.Append( 9907 );
        }
        const TArray<TMPXAttribute>& tempRef = aAttrs.Count() == 0? attrs.Array() : aAttrs;
        AddMediaL(*array, ids, tempRef);
        FilterMediaArray(*array, aFilter);

        entries->SetCObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayContents),array);
        entries->SetTObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayCount),array->Count());

        iObs->HandleOpen (entries, KErrNone);
        CleanupStack::PopAndDestroy(3, &ids);   // attrs, array, ids
    }
    else if(aPath.Levels() == 3)
    {
        // Opening plugin's 2nd
        TInt secLevId = aPath.Id(2);

        RArray<TInt> ids;
        CleanupClosePushL( ids );
        RArray<TMPXAttribute> attrs;
        CleanupClosePushL( attrs );
        CMPXMediaArray* array=CMPXMediaArray::NewL();
        CleanupStack::PushL( array );

        attrs.Append( KMPXMediaGeneralId );
        attrs.Append( KMPXMediaGeneralUri );
        attrs.Append( KMPXMediaGeneralTitle );
        switch( secLevId )
        {
        case 211:
            ids.Append( 3111 );
            break;
        case 212:
            ids.Append( 3121 );
            break;
        case 213:
            ids.Append( 3131 );
            break;
        case 221:
            // Empty
            break;
        case 231:
            ids.Append( 3311 );
            break;
        case 232:
            ids.Append( 3321 );
            break;
        };
        const TArray<TMPXAttribute>& tempRef = aAttrs.Count() == 0? attrs.Array() : aAttrs;
        AddMediaL(*array, ids, tempRef);
        FilterMediaArray(*array, aFilter);

        entries->SetCObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayContents),array);
        entries->SetTObjectValueL (TMPXAttribute(KMPXMediaIdContainer,EMPXMediaArrayCount),array->Count());

        iObs->HandleOpen (entries, KErrNone);
        CleanupStack::PopAndDestroy(3, &ids);   // attrs, array, ids
    }
    else
    {
        User::Leave( KErrNotFound );
    }
    CleanupStack::PopAndDestroy( entries );
}
void CRecordVideoFileCov::RunL()
	{
	TBuf<KTBufSize> buf;
	switch (iState)
		{		
		case EHwDeviceLoadImages:			
			buf.Format(_L("Loading test frame %d"),iCurrentFrame);
			iParent->InfoMessage(buf);
			if (iCurrentFrame<iNumFrames)
				{
				iImageDecoder->Convert(&iStatus, *iBitmaps[iCurrentFrame], iCurrentFrame);
				SetActive();
				iCurrentFrame++;
				}
			else
				{
				iCurrentFrame = 0;
				SetState(EHwDeviceInit);			
				}			
			break;
		case EHwDeviceInit:
			{	
			iParent->InfoMessage(_L("State EHwDeviceInit"));
			// Configure Encoder HwDevice
			TSize size = iBitmaps[iCurrentFrame]->SizeInPixels();
		
			// set video format.
			TUncompressedVideoFormat videoFormat;
			videoFormat.iDataFormat = ERgbFbsBitmap;
			videoFormat.iRgbFormat = EFbsBitmapColor16M;

			iParent->InfoMessage(_L("SetInputFormat"));
			// set encoder settings
			TRAP(iError, iVideoHwDevice->SetInputFormatL(videoFormat, size) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetInputFormat Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetSourceMemory"));
			TRAP(iError, iVideoHwDevice->SetSourceMemoryL(KMaxPictureRate, ETrue, ETrue) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetSourceMemory Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetChannelBitErrorRate"));
			TRAP(iError, iVideoHwDevice->SetChannelBitErrorRate(KChannelBitErrorLevel, KChannelBitErrorRate, KChannelBitErrorStdDeviation) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetChannelBitErrorRate Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetBufferOptions"));
			TRAP(iError, iVideoHwDevice->SetBufferOptionsL(KOptions) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetBufferOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetChannelPacketLossRate"));
			TRAP(iError, iVideoHwDevice->SetChannelPacketLossRate(KLevel,KLossRate,KLossBurstLength) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetChannelPacketLossRate Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetCodingStandardSpecificOptionsL"));
			TRAP(iError, iVideoHwDevice->SetCodingStandardSpecificOptionsL(KCodingOptionsPtr) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetCodingStandardSpecificOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetColorEnhancementOptionsL"));
			TRAP(iError, iVideoHwDevice->SetColorEnhancementOptionsL(KColorEnhancementOptions) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetColorEnhancementOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetComplexityLevel"));
			TRAP(iError, iVideoHwDevice->SetComplexityLevel(KComplexityLevel) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetComplexityLevel Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetCustomPreProcessOptionsL"));
			TRAP(iError, iVideoHwDevice->SetCustomPreProcessOptionsL(KCustomPreProcessOptions) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetCustomPreProcessOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetErrorProtectionLevelL"));
			TRAP(iError, iVideoHwDevice->SetErrorProtectionLevelL(KLevel,KBitRate,KStrength) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetErrorProtectionLevelL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetErrorProtectionLevelsL"));
			TRAP(iError, iVideoHwDevice->SetErrorProtectionLevelsL(KNumLevels,ETrue) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetErrorProtectionLevelsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetErrorsExpected"));
			TRAP(iError, iVideoHwDevice->SetErrorsExpected(ETrue,ETrue) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetErrorsExpected Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetFrameStabilisationOptionsL"));
			TRAP(iError, iVideoHwDevice->SetFrameStabilisationOptionsL(KOutputSize,ETrue) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetFrameStabilisationOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetGlobalReferenceOptions"));
			TRAP(iError, iVideoHwDevice->SetGlobalReferenceOptions(KMaxReferencePictures, KMaxPictureOrderDelay) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetGlobalReferenceOptions Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetInputCropOptionsL"));
			TRAP(iError, iVideoHwDevice->SetInputCropOptionsL(KRect) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetInputCropOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetLayerPromotionPointPeriod"));
			TRAP(iError, iVideoHwDevice->SetLayerPromotionPointPeriod(KLayer,KPeriod) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetLayerPromotionPointPeriod Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetLayerReferenceOptions"));
			TRAP(iError, iVideoHwDevice->SetLayerReferenceOptions(KLayer, KMaxReferencePictures , KMaxPictureOrderDelay ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetLayerReferenceOptions Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetMinRandomAccessRate"));
			TRAP(iError, iVideoHwDevice->SetMinRandomAccessRate(KMinRandomAccessRate ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetMinRandomAccessRate Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetNumBitrateLayersL"));
			TRAP(iError, iVideoHwDevice->SetNumBitrateLayersL(KNumBitLayers) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetNumBitrateLayersL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetOutputCropOptionsL"));
			TRAP(iError, iVideoHwDevice->SetOutputCropOptionsL(KRect) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetOutputCropOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetOutputPadOptionsL"));
			TRAP(iError, iVideoHwDevice->SetOutputPadOptionsL(KOutputSize, KPicturePos) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetOutputPadOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetOutputRectL"));
			TRAP(iError, iVideoHwDevice->SetOutputRectL(KRect) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetOutputRectL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetPreProcessTypesL"));
			TRAP(iError, iVideoHwDevice->SetPreProcessTypesL(KPreProcessTypes) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetPreProcessTypesL Failed"));
				SetState(EHwDeviceError);
				}
			TRateControlOptions KRateOptions;
			iParent->InfoMessage(_L("SetRateControlOptions"));
			TRAP(iError, iVideoHwDevice->SetRateControlOptions(KLayer, KRateOptions) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetRateControlOptions Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetRgbToYuvOptionsL"));
			TRAP(iError, iVideoHwDevice->SetRgbToYuvOptionsL(KRgbRange, KYuvOutput) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetRgbToYuvOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetRotateOptionsL"));
			TRAP(iError, iVideoHwDevice->SetRotateOptionsL(KRotationType) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetRotateOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetScalabilityLayerTypeL"));
			TRAP(iError, iVideoHwDevice->SetScalabilityLayerTypeL(KLayer,KScalabilityType ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetScalabilityLayerTypeL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetScaleOptionsL"));
			TRAP(iError, iVideoHwDevice->SetScaleOptionsL(KOutputSize,EFalse ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetScaleOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetSegmentTargetSize"));
			TRAP(iError, iVideoHwDevice->SetSegmentTargetSize(KLayer,KSizeBytes, KSizeMacroblocks ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetSegmentTargetSize Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetSourceCameraL"));
			TRAP(iError, iVideoHwDevice->SetSourceCameraL(KCameraHandle,KMaxPictureRate ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetSourceCameraL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetYuvToYuvOptionsL"));
			TRAP(iError, iVideoHwDevice->SetYuvToYuvOptionsL(KYuvInput,KYuvOutput ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetYuvToYuvOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("SetImplementationSpecificEncoderOptionsL"));
			TRAP(iError, iVideoHwDevice->SetImplementationSpecificEncoderOptionsL(KImplementationSpecificOptions ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetImplementationSpecificEncoderOptionsL Failed"));
				SetState(EHwDeviceError);
				}
			 CCompressedVideoFormat* Format=CCompressedVideoFormat::NewL(KVideoMimeType,KBlank) ;
			 TVideoDataUnitType DataUnitType=EDuCodedPicture ; 					
			 TVideoDataUnitEncapsulation DataEncapsulation=EDuElementaryStream;
			  
			iParent->InfoMessage(_L("SetOutputFormatL"));
			TRAP(iError, iVideoHwDevice->SetOutputFormatL(*Format,DataUnitType,DataEncapsulation,ETrue ) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetOutputFormatL Failed"));
				SetState(EHwDeviceError);
				}
			delete Format;
			iParent->InfoMessage(_L("Initialize HwDevice"));
			iVideoHwDevice->Initialize();
			break;
			}					
		case EHwDeviceStartEncode:
			{
			TRect Rect;
			iParent->InfoMessage(_L("GetFrameStabilisationOutput"));
			TRAP(iError, iVideoHwDevice->GetFrameStabilisationOutput(Rect ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("GetFrameStabilisationOutput Failed"));
				SetState(EHwDeviceError);
				}
			TUint NumFreeBuffers, TotalFreeBytes;
			iParent->InfoMessage(_L("GetOutputBufferStatus"));
			TRAP(iError, iVideoHwDevice->GetOutputBufferStatus(NumFreeBuffers, TotalFreeBytes ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("GetOutputBufferStatus Failed"));
				SetState(EHwDeviceError);
				}
			CMMFDevVideoRecord::TPictureCounters Counters;
			iParent->InfoMessage(_L("GetPictureCounters"));
			TRAP(iError, iVideoHwDevice->GetPictureCounters(Counters ) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("GetPictureCounters Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("NumComplexityLevels"));
			TRAP(iError, iVideoHwDevice->NumComplexityLevels() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("NumComplexityLevels Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("NumComplexityLevels"));
			TRAP(iError, iVideoHwDevice->NumComplexityLevels() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("NumComplexityLevels Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("PictureLoss"));
			TRAP(iError, iVideoHwDevice->PictureLoss() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("PictureLoss Failed"));
				SetState(EHwDeviceError);
				}
			
			iParent->InfoMessage(_L("PreProcessorInfoLC"));
			TRAP(iError, iVideoHwDevice->PreProcessorInfoLC() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("PreProcessorInfoLC Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("CancelSupplementalInfo"));
			TRAP(iError, iVideoHwDevice->CancelSupplementalInfo() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("CancelSupplementalInfo Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("CancelSupplementalInfo"));
			TRAP(iError, iVideoHwDevice->CancelSupplementalInfo() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("CancelSupplementalInfo Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("CodingStandardSpecificInitOutputLC"));
			TRAP(iError, iVideoHwDevice->CodingStandardSpecificInitOutputLC() );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("CodingStandardSpecificInitOutputLC Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("ImplementationSpecificInitOutputLC"));
			TRAP(iError, iVideoHwDevice->ImplementationSpecificInitOutputLC() );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("ImplementationSpecificInitOutputLC Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("CodingStandardSpecificSettingsOutputLC"));
			TRAP(iError, iVideoHwDevice->CodingStandardSpecificSettingsOutputLC() );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("CodingStandardSpecificSettingsOutputLC Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("ImplementationSpecificSettingsOutputLC"));
			TRAP(iError, iVideoHwDevice->ImplementationSpecificSettingsOutputLC() );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("ImplementationSpecificSettingsOutputLC Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("CommitL"));
			TRAP(iError, iVideoHwDevice->CommitL() );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("CommitL Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("Revert"));
			TRAP(iError, iVideoHwDevice->Revert() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("Revert Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("InputEnd"));
			TRAP(iError, iVideoHwDevice->InputEnd() );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("InputEnd Failed"));
				SetState(EHwDeviceError);
				}
			TBufC8<8> buffer;
			TPtr8  PictureSelection = buffer.Des();
			iParent->InfoMessage(_L("ReferencePictureSelection"));
			TRAP(iError, iVideoHwDevice->ReferencePictureSelection(PictureSelection) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("ReferencePictureSelection Failed"));
				SetState(EHwDeviceError);
				}
			TPtr8  SupplementalInfo = buffer.Des();
			iParent->InfoMessage(_L("SendSupplementalInfoL"));
			TRAP(iError, iVideoHwDevice->SendSupplementalInfoL(SupplementalInfo) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SendSupplementalInfoL Failed"));
				SetState(EHwDeviceError);
				}
			TTimeIntervalMicroSeconds TimeStamp;
			iParent->InfoMessage(_L("SendSupplementalInfoL"));
			TRAP(iError, iVideoHwDevice->SendSupplementalInfoL(SupplementalInfo,TimeStamp) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SendSupplementalInfoL Failed"));
				SetState(EHwDeviceError);
				}
			
			CVideoEncoderInfo* EncoderInfo=NULL;
			iParent->InfoMessage(_L("VideoEncoderInfoLC"));
			TRAP(iError, EncoderInfo=iVideoHwDevice->VideoEncoderInfoLC();CleanupStack::Pop(EncoderInfo) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("VideoEncoderInfoLC Failed"));
				SetState(EHwDeviceError);
				}
			delete EncoderInfo;
			
			iParent->InfoMessage(_L("Freeze"));
			TRAP(iError, iVideoHwDevice->Freeze());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("Freeze Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("ReleaseFreeze"));
			TRAP(iError, iVideoHwDevice->ReleaseFreeze());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("ReleaseFreeze Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("Pause"));
			TRAP(iError, iVideoHwDevice->Pause());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("Pause Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("Resume"));
			TRAP(iError, iVideoHwDevice->Resume());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("Resume Failed"));
				SetState(EHwDeviceError);
				}
			TTimeIntervalMicroSeconds Pos;
			iParent->InfoMessage(_L("RecordingPosition"));
			TRAP(iError, Pos=iVideoHwDevice->RecordingPosition());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("RecordingPosition Failed"));
				SetState(EHwDeviceError);
				}
			iParent->InfoMessage(_L("Stop"));
			TRAP(iError, iVideoHwDevice->Stop());
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("Stop Failed"));
				SetState(EHwDeviceError);
				}
			TUint FirstMacroblock=1, NumMacroblocks=2;
			TPictureId picId;
			iParent->InfoMessage(_L("SliceLoss"));
			TRAP(iError, iVideoHwDevice->SliceLoss(FirstMacroblock,NumMacroblocks,picId));
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SliceLoss Failed"));
				SetState(EHwDeviceError);
				}
			RArray<TPictureId> testIds;
			User::LeaveIfError(testIds.Append(KTestPictureId1));
			User::LeaveIfError(testIds.Append(KTestPictureId2));
			User::LeaveIfError(testIds.Append(KTestPictureId3));
			TArray<TPictureId> testIds2=testIds.Array();
			iParent->InfoMessage(_L("PictureLoss"));
			TRAP(iError, iVideoHwDevice->PictureLoss(testIds2) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("PictureLoss Failed"));
				SetState(EHwDeviceError);
				}
			testIds.Close();
			CSystemClockSource *time1 = NULL;
			iParent->InfoMessage(_L("SetClockSource"));
			TRAP(iError, iVideoHwDevice->SetClockSource(time1) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetClockSource Failed"));
				SetState(EHwDeviceError);
				}
			CMMFVideoPreProcHwDevice *inpDevice = NULL;
			iParent->InfoMessage(_L("SetInputDevice"));
			TRAP(iError, iVideoHwDevice->SetInputDevice(inpDevice) );
			if (iError!=KErrNone)
				{
				iParent->InfoMessage(_L("SetInputDevice Failed"));
				SetState(EHwDeviceError);
				}
			TUint layer=1;
			TUint numSteps=2;
			TInLayerScalabilityType scalabilityType=EInLScalabilityTemporal;
			RArray<TUint> bitRate;
			User::LeaveIfError(bitRate.Append(0));
			const TArray<TUint> bitRate2=bitRate.Array();
			iParent->InfoMessage(_L("SetInLayerScalabilityL"));
			TRAP(iError, iVideoHwDevice->SetInLayerScalabilityL(layer,numSteps,scalabilityType,bitRate2,bitRate2) );
			if (iError!=KErrNotSupported)
				{
				iParent->InfoMessage(_L("SetInLayerScalabilityL Failed"));
				SetState(EHwDeviceError);
				}
			bitRate.Close();
			iVideoHwDevice->Start();				
			TRAP(iError, EncodeNextFrameL());
			if (iError!=KErrNone)
				{
				SetState(EHwDeviceError);
				}

			break;
			}			
		case EHwDeviceEncodeNextFrame:
			{
			if (iCurrentFrame<iNumFrames)
				{
				
				TRAP(iError, EncodeNextFrameL());
				if (iError!=KErrNone)
					{
					SetState(EHwDeviceError);
					}
				}
			else
				{
				iParent->InfoMessage(_L("End of input frames"));

				iVideoHwDevice->InputEnd();
				}
			break;
			}		
		case EHwDeviceEncodeCheckData:			
			{
			SetState(EHwDeviceDone);
			break;
			}
		case EHwDeviceAllowToComplete:
			break;
		case EHwDeviceDone:
			{
			Cancel();
			CActiveScheduler::Stop();
			CloseRecordFile();
			break;
			}
		case EHwDeviceError:
			{
			buf.Format(_L("HwDevice Error %d"),iError);
			iParent->SetVerdict(buf, EFail);
			CActiveScheduler::Stop();
			CloseRecordFile();
			break;
			}
		default:
			{
			CleanupAndSetDeviceError(_L("Unknown CRecordVideoFileCov iState"));
			break;
			}
		}
	}
// ----------------------------------------------------------------------------
// Extended properties of the current file (async)
// ----------------------------------------------------------------------------
//
void CGlxMediaListsTestCollectionPlugin::MediaL(const CMPXCollectionPath& aPath,
		const TArray<TMPXAttribute>& aAttrs,
                        const TArray<TCapability>& /*aCaps*/,
                        CMPXAttributeSpecs* /*aSpecs*/)
    {
    __ASSERT_ALWAYS(!iMedia, Panic(EGlxPanicIllegalState));

    TInt error = KErrNone;
    CItem* item = NULL;
    TInt bitmapHandle = 0;

    RArray<TInt> supportedIds;
    CleanupClosePushL(supportedIds);
    iMedia = CMPXMedia::NewL(supportedIds.Array());
    CleanupStack::PopAndDestroy(&supportedIds);

    TArray<TInt> selection = aPath.Selection();
    TInt selectionCount = selection.Count();
    if (selectionCount > 1)
        {
        CMPXMediaArray* mediaArray = CMPXMediaArray::NewL();
        CleanupStack::PushL(mediaArray);

        for (TInt count = 0; count < selectionCount; ++count)
            {
            item = ItemL(aPath, selection[count]);

            if (item)
                {
                RArray<TInt> supportedIds;
                CleanupClosePushL(supportedIds);
                CMPXMedia* media = CMPXMedia::NewL(supportedIds.Array());
                CleanupStack::PopAndDestroy(&supportedIds);

                CleanupStack::PushL(media);

                (void)PopulateMediaWithItemL(media, item, aAttrs);

                mediaArray->AppendL(*media);

                CleanupStack::PopAndDestroy(media);
                }
            else
                {
                error = KErrNotFound;
                break;
                }
            }

        PopulateMediaWithArrayL(iMedia, mediaArray);

        CleanupStack::PopAndDestroy(mediaArray);
        }
    else
        {
	item = ItemL(aPath, aPath.Index());

        if (item)
            {
            bitmapHandle = PopulateMediaWithItemL(iMedia, item, aAttrs);
            }
        else
            {
            error = KErrNotFound;
            }
        }

    if ( (KErrNone == error) && bitmapHandle )
        {
        // Get thumbnail for the item
        TGlxThumbnailRequest request;
        request.iId = item->iId;
    	request.iSizeClass = TSize(60, 45);
    	request.iPriorityMode = TGlxThumbnailRequest::EPrioritizeSpeed;
    	request.iBitmapHandle = bitmapHandle;

       	iThumbnailCreator->FetchThumbnailL(request, *this);
        }
    else
        {
        /*****************************************************
        * Old synchronous code
        ******************************************************/
        // No thumbnail requested - send response now
        //iObs->HandleMedia(*iMedia, error);
        //delete iMedia;
        //iMedia = NULL;
        
        /*****************************************************
        * New Async Code. Instantiate callback mechanism
        ******************************************************/
        
    	AsyncNotifyL(iMedia, error, CGlxAsyncNotifier::EMedia);  
        }
    }
void CUnifiedCertStore::InitializeL()
	{
	AllocWorkingVarsL();
	
	// We want the list of all token types that support a readable or writable 
	// certstore interface
	RArray<TUid> uidArray;
	CleanupClosePushL(uidArray);
		
	User::LeaveIfError(uidArray.Append(TUid::Uid(KInterfaceWritableCertStore)));
	
	TCTFindTokenTypesByInterface filter(uidArray.Array());
	CCTTokenTypeInfo::ListL(iWorkingVars->iWritableTokenTypes, filter);

	uidArray.Reset();

	User::LeaveIfError(uidArray.Append(TUid::Uid(KInterfaceCertStore)));

	RCPointerArray<CCTTokenTypeInfo> tokenTypes;
	CleanupClosePushL(tokenTypes);

	TCTFindTokenTypesByInterface filter2(uidArray.Array());
	CCTTokenTypeInfo::ListL(tokenTypes, filter2);
	
  	// Check whether client specified order list has attributes in it
  	if(iOrderAttributes.Count() > 0)
  	    {
  	    ApplyOrderingL(tokenTypes);
  	    }

	// Make a note of all hardware token types
	TInt i = 0;
	TInt end = tokenTypes.Count();
	for (; i < end; i++)
		{
		TCTTokenTypeAttribute software;
		software.iUID = KCTSoftware;
		TInt find = tokenTypes[i]->Attributes().Find(software);
		// In the case (TInt)ETrue == KThirdPartyCertStore == 1  
		if (find != KErrNotFound && tokenTypes[i]->Attributes()[find].iVal != 
			(TInt)ETrue && tokenTypes[i]->Attributes()[find].iVal != KManufactureCertStore)
			{
			// This is a hardware type. Add its UID to the list.
			User::LeaveIfError(iHardwareTypeUids.Append(tokenTypes[i]->Type()));
			}
		}

	i = 0;
	while (i < end)
		{
		TInt j = 0;
		TInt jEnd = iWorkingVars->iWritableTokenTypes.Count();
		while (j < jEnd)
			{
			if (iWorkingVars->iWritableTokenTypes[j]->Type() == tokenTypes[i]->Type())
				{
				break;
				}
			j++;
			}
		if (j == jEnd)
			{
			User::LeaveIfError(iWorkingVars->iReadOnlyTokenTypes.Append(tokenTypes[i]));
			tokenTypes.Remove(i);
			end--;
			}
		else
			{
			i++;
			}
		}

	CleanupStack::PopAndDestroy(2);	// uidArray, tokenTypes
	
	iWorkingVars->iIndex = -1;

	TRequestStatus* status = &iStatus;
	User::RequestComplete(status, KErrNone);
	SetActive();
	}