// This is called on the webcore thread, save the GL texture for recycle in
// the retired queue. They will be deleted in deleteUnusedTextures() in the UI
// thread.
// Return true when we found one texture to retire.
bool VideoLayerManager::recycleTextureMem()
{
    // Find the oldest texture int the m_videoLayerInfoMap, put it in m_retiredTextures
    int oldestTimeStamp = m_currentTimeStamp;
    int oldestLayerId = -1;

    InfoIterator end = m_videoLayerInfoMap.end();
#ifdef DEBUG
    XLOG("VideoLayerManager::recycleTextureMem m_videoLayerInfoMap contains");
    for (InfoIterator it = m_videoLayerInfoMap.begin(); it != end; ++it)
        XLOG("  layerId %d, textureId %d, videoSize %d, timeStamp %d ",
             it->first, it->second->textureId, it->second->videoSize, it->second->timeStamp);
#endif
    for (InfoIterator it = m_videoLayerInfoMap.begin(); it != end; ++it) {
        if (it->second->timeStamp < oldestTimeStamp) {
            oldestTimeStamp = it->second->timeStamp;
            oldestLayerId = it->first;
        }
    }

    bool foundTextureToRetire = (oldestLayerId != -1);
    if (foundTextureToRetire)
        removeLayerInternal(oldestLayerId);

    return foundTextureToRetire;
}
// When the video start, we know its texture info, so we register when we
// recieve the setSurfaceTexture call, this happens on UI thread.
void VideoLayerManager::registerTexture(const int layerId, const GLuint textureId)
{
    android::Mutex::Autolock lock(m_videoLayerInfoMapLock);
    // If the texture has been registered, then early return.
    if (m_videoLayerInfoMap.get(layerId)) {
        GLuint oldTextureId = m_videoLayerInfoMap.get(layerId)->textureId;
        if (oldTextureId != textureId)
            removeLayerInternal(layerId);
        else
            return;
    }
    // The old info is deleted and now complete the new info and store it.
    VideoLayerInfo* pInfo = new VideoLayerInfo();
    pInfo->textureId = textureId;
    memset(pInfo->surfaceMatrix, 0, sizeof(pInfo->surfaceMatrix));
    pInfo->videoSize = 0;
    pInfo->aspectRatio = DEFAULT_VIDEO_ASPECT_RATIO;
    m_currentTimeStamp++;
    pInfo->timeStamp = m_currentTimeStamp;
    pInfo->lastIconShownTime = 0;
    pInfo->iconState = Registered;

    m_videoLayerInfoMap.add(layerId, pInfo);
    ALOGV("GL texture %d regisered for layerId %d", textureId, layerId);

    return;
}
// This can be called in the webcore thread in the media player's dtor.
void VideoLayerManager::removeLayer(const int layerId)
{
    android::Mutex::Autolock lock(m_videoLayerInfoMapLock);
    removeLayerInternal(layerId);
}