<commit_before>/*************************************************************************
 *
 *  $RCSfile: accpage.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:11:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ACCPAGE_HXX
#define _ACCPAGE_HXX

#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif

/**
 * accessibility implementation for the page (SwPageFrm)
 * The page is _only_ visible in the page preview. For the regular
 * document view, it doesn't make sense to add this additional element
 * into the hierarchy. For the page preview, however, the page is the
 * important.
 */
class SwAccessiblePage : public SwAccessibleContext
{
    sal_Bool    bIsSelected;    // protected by base class mutex

    sal_Bool    IsSelected();

protected:

    // return the bounding box for the page in page preview mode
    SwRect GetBounds( /* const SwFrm *pFrm =0 */ );

    // Set states for getAccessibleStateSet.
    // This drived class additionaly sets
    // FOCUSABLE(1) and FOCUSED(+)
    virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );

    virtual void _InvalidateCursorPos();
    virtual void _InvalidateFocus();

    virtual ~SwAccessiblePage();

public:
    // convenience constructor to avoid typecast;
    // may only be called with SwPageFrm argument
    SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame );

    //
    // XAccessibleContext methods that need to be overridden
    //

    virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException);

    //
    // XServiceInfo
    //

    virtual ::rtl::OUString SAL_CALL getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService (
        const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames (void)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  XTypeProvider  ====================================================
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    virtual sal_Bool HasCursor();   // required by map to remember that object
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.600); FILE MERGED 2005/09/05 13:38:24 rt 1.5.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accpage.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:53:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _ACCPAGE_HXX
#define _ACCPAGE_HXX

#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif

/**
 * accessibility implementation for the page (SwPageFrm)
 * The page is _only_ visible in the page preview. For the regular
 * document view, it doesn't make sense to add this additional element
 * into the hierarchy. For the page preview, however, the page is the
 * important.
 */
class SwAccessiblePage : public SwAccessibleContext
{
    sal_Bool    bIsSelected;    // protected by base class mutex

    sal_Bool    IsSelected();

protected:

    // return the bounding box for the page in page preview mode
    SwRect GetBounds( /* const SwFrm *pFrm =0 */ );

    // Set states for getAccessibleStateSet.
    // This drived class additionaly sets
    // FOCUSABLE(1) and FOCUSED(+)
    virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );

    virtual void _InvalidateCursorPos();
    virtual void _InvalidateFocus();

    virtual ~SwAccessiblePage();

public:
    // convenience constructor to avoid typecast;
    // may only be called with SwPageFrm argument
    SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame );

    //
    // XAccessibleContext methods that need to be overridden
    //

    virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException);

    //
    // XServiceInfo
    //

    virtual ::rtl::OUString SAL_CALL getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService (
        const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames (void)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  XTypeProvider  ====================================================
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    virtual sal_Bool HasCursor();   // required by map to remember that object
};

#endif

<|endoftext|>


<commit_before>/* runner_common.cc
   Wolfgang Sourdeau, 10 December 2014
   Copyright (c) 2014 Datacratic.  All rights reserved.
*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "jml/arch/exception.h"

#include "runner_common.h"

using namespace std;
using namespace Datacratic;

namespace Datacratic {

std::string
strLaunchError(LaunchError error)
{
    switch (error) {
    case LaunchError::NONE: return "no error";
    case LaunchError::READ_STATUS_PIPE: return "read() on status pipe";
    case LaunchError::STATUS_PIPE_WRONG_LENGTH:
        return "wrong message size reading launch pipe";
    case LaunchError::SUBTASK_LAUNCH: return "exec() launching subtask";
    case LaunchError::SUBTASK_WAITPID: return "waitpid waiting for subtask";
    case LaunchError::WRONG_CHILD: return "waitpid() returned the wrong child";
    }
    throw ML::Exception("unknown error launch error code %d",
                        error);
}

std::string
statusStateAsString(ProcessState statusState)
{
    switch (statusState) {
    case ProcessState::UNKNOWN: return "UNKNOWN";
    case ProcessState::LAUNCHING: return "LAUNCHING";
    case ProcessState::RUNNING: return "RUNNING";
    case ProcessState::STOPPED: return "STOPPED";
    case ProcessState::DONE: return "DONE";
    }
    throw ML::Exception("unknown status %d", statusState);
}

}

/****************************************************************************/
/* PROCESS STATUS                                                           */
/****************************************************************************/

ProcessStatus::
ProcessStatus()
{
    // Doing it this way keeps ValGrind happy
    ::memset(this, 0, sizeof(*this));

    state = ProcessState::UNKNOWN;
    pid = -1;
    childStatus = -1;
    launchErrno = 0;
    launchErrorCode = LaunchError::NONE;
}

void
ProcessStatus::
setErrorCodes(int newLaunchErrno, LaunchError newErrorCode)
{
    launchErrno = newLaunchErrno;
    launchErrorCode = newErrorCode;
}

/****************************************************************************/
/* PROCESS FDS                                                              */
/****************************************************************************/

ProcessFds::
ProcessFds()
    : stdIn(::fileno(stdin)),
      stdOut(::fileno(stdout)),
      stdErr(::fileno(stderr)),
      statusFd(-1)
{
}

/* child api */
void
ProcessFds::
closeRemainingFds()
{
    struct rlimit limits;
    ::getrlimit(RLIMIT_NOFILE, &limits);

    for (int fd = 0; fd < limits.rlim_cur; fd++) {
        if ((fd != STDIN_FILENO || stdIn == -1)
            && fd != STDOUT_FILENO && fd != STDERR_FILENO
            && fd != statusFd) {
            ::close(fd);
        }
    }
}

void
ProcessFds::
dupToStdStreams()
{
    auto dupToStdStream = [&] (int oldFd, int newFd) {
        if (oldFd != newFd) {
            int rc = ::dup2(oldFd, newFd);
            if (rc == -1) {
                throw ML::Exception(errno,
                                    "ProcessFds::dupToStdStream dup2");
            }
        }
    };
    if (stdIn != -1) {
        dupToStdStream(stdIn, STDIN_FILENO);
    }
    dupToStdStream(stdOut, STDOUT_FILENO);
    dupToStdStream(stdErr, STDERR_FILENO);
}

/* parent & child api */
void
ProcessFds::
close()
{
    auto closeIfNotEqual = [&] (int & fd, int notValue) {
        if (fd != notValue) {
            ::close(fd);
        }
    };
    closeIfNotEqual(stdIn, STDIN_FILENO);
    closeIfNotEqual(stdOut, STDOUT_FILENO);
    closeIfNotEqual(stdErr, STDERR_FILENO);
    closeIfNotEqual(statusFd, -1);
}

void
ProcessFds::
encodeToBuffer(char * buffer, size_t bufferSize)
    const
{
    int written = ::sprintf(buffer, "%.8x/%.8x/%.8x/%.8x",
                            stdIn, stdOut, stdErr, statusFd);
    if (written < 0) {
        throw ML::Exception("encoding failed");
    }

    /* bufferSize must be equal to the number of bytes used above, plus 1 for
       '\0' */
    if (written >= bufferSize) {
        throw ML::Exception("buffer overflow");
    }
}

void
ProcessFds::
decodeFromBuffer(const char * buffer)
{
    int decoded = ::sscanf(buffer, "%x/%x/%x/%x",
                           &stdIn, &stdOut, &stdErr, &statusFd);
    if (decoded < 0) {
        throw ML::Exception(errno, "decoding failed");
    }
}

void
ProcessFds::
writeStatus(const ProcessStatus & status)
    const
{
    int res = ::write(statusFd, &status, sizeof(status));
    if (res == -1)
        throw ML::Exception(errno, "write");
    else if (res != sizeof(status))
        throw ML::Exception("writing of status is incomplete");
}
<commit_msg>Don't spam with system calls to close all FDs<commit_after>/* runner_common.cc
   Wolfgang Sourdeau, 10 December 2014
   Copyright (c) 2014 Datacratic.  All rights reserved.
*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "jml/arch/exception.h"

#include "runner_common.h"

using namespace std;
using namespace Datacratic;

namespace Datacratic {

std::string
strLaunchError(LaunchError error)
{
    switch (error) {
    case LaunchError::NONE: return "no error";
    case LaunchError::READ_STATUS_PIPE: return "read() on status pipe";
    case LaunchError::STATUS_PIPE_WRONG_LENGTH:
        return "wrong message size reading launch pipe";
    case LaunchError::SUBTASK_LAUNCH: return "exec() launching subtask";
    case LaunchError::SUBTASK_WAITPID: return "waitpid waiting for subtask";
    case LaunchError::WRONG_CHILD: return "waitpid() returned the wrong child";
    }
    throw ML::Exception("unknown error launch error code %d",
                        error);
}

std::string
statusStateAsString(ProcessState statusState)
{
    switch (statusState) {
    case ProcessState::UNKNOWN: return "UNKNOWN";
    case ProcessState::LAUNCHING: return "LAUNCHING";
    case ProcessState::RUNNING: return "RUNNING";
    case ProcessState::STOPPED: return "STOPPED";
    case ProcessState::DONE: return "DONE";
    }
    throw ML::Exception("unknown status %d", statusState);
}

}

/****************************************************************************/
/* PROCESS STATUS                                                           */
/****************************************************************************/

ProcessStatus::
ProcessStatus()
{
    // Doing it this way keeps ValGrind happy
    ::memset(this, 0, sizeof(*this));

    state = ProcessState::UNKNOWN;
    pid = -1;
    childStatus = -1;
    launchErrno = 0;
    launchErrorCode = LaunchError::NONE;
}

void
ProcessStatus::
setErrorCodes(int newLaunchErrno, LaunchError newErrorCode)
{
    launchErrno = newLaunchErrno;
    launchErrorCode = newErrorCode;
}

/****************************************************************************/
/* PROCESS FDS                                                              */
/****************************************************************************/

ProcessFds::
ProcessFds()
    : stdIn(::fileno(stdin)),
      stdOut(::fileno(stdout)),
      stdErr(::fileno(stderr)),
      statusFd(-1)
{
}

/* child api */
void
ProcessFds::
closeRemainingFds()
{
#if 0
    struct rlimit limits;
    ::getrlimit(RLIMIT_NOFILE, &limits);

    for (int fd = 0; fd < limits.rlim_cur; fd++) {
        if ((fd != STDIN_FILENO || stdIn == -1)
            && fd != STDOUT_FILENO && fd != STDERR_FILENO
            && fd != statusFd) {
            ::close(fd);
        }
    }
#endif
}

void
ProcessFds::
dupToStdStreams()
{
    auto dupToStdStream = [&] (int oldFd, int newFd) {
        if (oldFd != newFd) {
            int rc = ::dup2(oldFd, newFd);
            if (rc == -1) {
                throw ML::Exception(errno,
                                    "ProcessFds::dupToStdStream dup2");
            }
        }
    };
    if (stdIn != -1) {
        dupToStdStream(stdIn, STDIN_FILENO);
    }
    dupToStdStream(stdOut, STDOUT_FILENO);
    dupToStdStream(stdErr, STDERR_FILENO);
}

/* parent & child api */
void
ProcessFds::
close()
{
    auto closeIfNotEqual = [&] (int & fd, int notValue) {
        if (fd != notValue) {
            ::close(fd);
        }
    };
    closeIfNotEqual(stdIn, STDIN_FILENO);
    closeIfNotEqual(stdOut, STDOUT_FILENO);
    closeIfNotEqual(stdErr, STDERR_FILENO);
    closeIfNotEqual(statusFd, -1);
}

void
ProcessFds::
encodeToBuffer(char * buffer, size_t bufferSize)
    const
{
    int written = ::sprintf(buffer, "%.8x/%.8x/%.8x/%.8x",
                            stdIn, stdOut, stdErr, statusFd);
    if (written < 0) {
        throw ML::Exception("encoding failed");
    }

    /* bufferSize must be equal to the number of bytes used above, plus 1 for
       '\0' */
    if (written >= bufferSize) {
        throw ML::Exception("buffer overflow");
    }
}

void
ProcessFds::
decodeFromBuffer(const char * buffer)
{
    int decoded = ::sscanf(buffer, "%x/%x/%x/%x",
                           &stdIn, &stdOut, &stdErr, &statusFd);
    if (decoded < 0) {
        throw ML::Exception(errno, "decoding failed");
    }
}

void
ProcessFds::
writeStatus(const ProcessStatus & status)
    const
{
    int res = ::write(statusFd, &status, sizeof(status));
    if (res == -1)
        throw ML::Exception(errno, "write");
    else if (res != sizeof(status))
        throw ML::Exception("writing of status is incomplete");
}
<|endoftext|>


<commit_before><commit_msg>coverity#736154 Dereference null return value<commit_after><|endoftext|>


<commit_before>/* Copyright (c) 2017-2021 hors<horsicq@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "subdevice.h"

SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
    if(nOffset>pDevice->size())
    {
        nOffset=pDevice->size();
    }

    if(nOffset<0)
    {
        nOffset=0;
    }

    if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
    {
        nSize=pDevice->size()-nOffset;
    }

    if(nSize+nOffset<0)
    {
        nSize=0;
    }

    this->g_pDevice=pDevice;
    this->g_nOffset=nOffset;
    this->g_nSize=nSize;

    //    reset();
    pDevice->seek(nOffset);
}

SubDevice::~SubDevice()
{
    if(isOpen())
    {
        _close();
    }
}

qint64 SubDevice::getInitOffset()
{
    return g_nOffset;
}

qint64 SubDevice::size() const
{
    return g_nSize;
}

//qint64 SubDevice::bytesAvailable() const
//{
//    return nSize;
//}

bool SubDevice::isSequential() const
{
    return false;
}

bool SubDevice::seek(qint64 nPos)
{
    bool bResult=false;

    if((nPos<g_nSize)&&(nPos>=0))
    {
        if(g_pDevice->seek(g_nOffset+nPos))
        {
            bResult=QIODevice::seek(nPos);
        }
    }

    return bResult;
}

bool SubDevice::reset()
{
    return seek(0);
}

bool SubDevice::open(QIODevice::OpenMode mode)
{
    setOpenMode(mode);

    return true;
}

bool SubDevice::atEnd() const
{
    return (bytesAvailable()==0);
}

void SubDevice::close()
{
    _close();
}

qint64 SubDevice::pos() const
{
//    return pDevice->pos()-nOffset;
    return QIODevice::pos();
}

void SubDevice::_close()
{
    setOpenMode(NotOpen);
}

qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->read(pData,nMaxSize);

    return nLen;
}

qint64 SubDevice::writeData(const char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->write(pData,nMaxSize);

    return nLen;
}

void SubDevice::setErrorString(const QString &sString)
{
    QIODevice::setErrorString(sString);
}
<commit_msg>Fix: 2022-01-09<commit_after>/* Copyright (c) 2017-2022 hors<horsicq@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "subdevice.h"

SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
    if(nOffset>pDevice->size())
    {
        nOffset=pDevice->size();
    }

    if(nOffset<0)
    {
        nOffset=0;
    }

    if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
    {
        nSize=pDevice->size()-nOffset;
    }

    if(nSize+nOffset<0)
    {
        nSize=0;
    }

    this->g_pDevice=pDevice;
    this->g_nOffset=nOffset;
    this->g_nSize=nSize;

    //    reset();
    pDevice->seek(nOffset);
}

SubDevice::~SubDevice()
{
    if(isOpen())
    {
        _close();
    }
}

qint64 SubDevice::getInitOffset()
{
    return g_nOffset;
}

qint64 SubDevice::size() const
{
    return g_nSize;
}

//qint64 SubDevice::bytesAvailable() const
//{
//    return nSize;
//}

bool SubDevice::isSequential() const
{
    return false;
}

bool SubDevice::seek(qint64 nPos)
{
    bool bResult=false;

    if((nPos<g_nSize)&&(nPos>=0))
    {
        if(g_pDevice->seek(g_nOffset+nPos))
        {
            bResult=QIODevice::seek(nPos);
        }
    }

    return bResult;
}

bool SubDevice::reset()
{
    return seek(0);
}

bool SubDevice::open(QIODevice::OpenMode mode)
{
    setOpenMode(mode);

    return true;
}

bool SubDevice::atEnd() const
{
    return (bytesAvailable()==0);
}

void SubDevice::close()
{
    _close();
}

qint64 SubDevice::pos() const
{
//    return pDevice->pos()-nOffset;
    return QIODevice::pos();
}

void SubDevice::_close()
{
    setOpenMode(NotOpen);
}

qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->read(pData,nMaxSize);

    return nLen;
}

qint64 SubDevice::writeData(const char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->write(pData,nMaxSize);

    return nLen;
}

void SubDevice::setErrorString(const QString &sString)
{
    QIODevice::setErrorString(sString);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parcss1.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:47:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PARCSS1_HXX
#define _PARCSS1_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

class Color;

/*  */

// Die Tokens des CSS1-Parsers
enum CSS1Token
{
    CSS1_NULL,
    CSS1_UNKOWN,

    CSS1_IDENT,
    CSS1_STRING,
    CSS1_NUMBER,
    CSS1_PERCENTAGE,
    CSS1_LENGTH,            // eine absolute Groesse in 1/100 MM
    CSS1_PIXLENGTH,         // eine Pixel-Groesse
    CSS1_EMS,
    CSS1_EMX,
    CSS1_HEXCOLOR,

    CSS1_DOT_W_WS,
    CSS1_DOT_WO_WS,
    CSS1_COLON,
    CSS1_SLASH,
    CSS1_PLUS,
    CSS1_MINUS,
    CSS1_OBRACE,
    CSS1_CBRACE,
    CSS1_SEMICOLON,
    CSS1_COMMA,
    CSS1_HASH,

    CSS1_IMPORT_SYM,
// Feature: PrintExt
    CSS1_PAGE_SYM,
// /Feature: PrintExt

    CSS1_IMPORTANT_SYM,

    CSS1_URL,
    CSS1_RGB
};

// die Zustaende des Parsers
enum CSS1ParserState
{
    CSS1_PAR_ACCEPTED = 0,
    CSS1_PAR_WORKING,
    CSS1_PAR_ERROR
};

/*  */

enum CSS1SelectorType
{
    CSS1_SELTYPE_ELEMENT,
    CSS1_SELTYPE_ELEM_CLASS,
    CSS1_SELTYPE_CLASS,
    CSS1_SELTYPE_ID,
    CSS1_SELTYPE_PSEUDO,
// Feature: PrintExt
    CSS1_SELTYPE_PAGE
// /Feature: PrintExt

};

// Die folegende Klasse beschreibt einen Simple-Selector, also
// - einen HTML-Element-Namen
// - einen HTML-Element-Namen mit Klasse (durch '.' getrennt)
// - eine Klasse (ohne Punkt)
// - eine mit ID=xxx gesetzte ID aus einem HTML-Dokument
// oder
// - ein Pseudo-Element
//
// Die Simple-Sektoren werden in einer Liste zu vollstaendigen
// Selektoren verkettet
class CSS1Selector
{
    CSS1SelectorType eType;     // Art des Selektors
    String aSelector;           // der Selektor selbst
    CSS1Selector *pNext;        // die naechste Komponente

public:

    CSS1Selector( CSS1SelectorType eTyp, const String &rSel )
        : eType(eTyp), aSelector( rSel ), pNext( 0 )
    {}

    ~CSS1Selector();

    CSS1SelectorType GetType() const { return eType; }
    const String& GetString() const { return aSelector; }

    void SetNext( CSS1Selector *pNxt ) { pNext = pNxt; }
    const CSS1Selector *GetNext() const { return pNext; }
};

/*  */

// Die folegende Klasse beschreibt einen Teil-Ausdruck einer
// CSS1-Deklaration sie besteht aus
//
// - dem Typ des Ausdrucks (entspricht dem Token)
// - dem eigentlichen Wert als String und ggf. double
//   der double-Wert enthaelt das Vorzeichen fuer NUMBER und LENGTH
// - und dem Operator, mit dem er mit dem *Vorganger*-Ausdruck
//   verknuepft ist.
//
struct CSS1Expression
{
    sal_Unicode cOp;        // Art der Verkuepfung mit dem Vorgaenger
    CSS1Token eType;        // der Typ des Wertes
    String aValue;          // und sein Wert als String
    double nValue;          // und als Zahl (TWIPs fuer LENGTH)
    CSS1Expression *pNext;  // die naechste Komponente

public:

    CSS1Expression( CSS1Token eTyp, const String &rVal,
                    double nVal, sal_Unicode cO = 0 )
        : cOp(cO), eType(eTyp), aValue(rVal), nValue(nVal), pNext(0)
    {}

    ~CSS1Expression();

    inline void Set( CSS1Token eTyp, const String &rVal, double nVal,
                     sal_Unicode cO = 0 );

    CSS1Token GetType() const { return eType; }
    const String& GetString() const { return aValue; }
    double GetNumber() const { return nValue; }
    inline sal_uInt32 GetULength() const;
    inline sal_Int32 GetSLength() const;
    sal_Unicode GetOp() const { return cOp; }

    sal_Bool GetURL( String& rURL ) const;
    sal_Bool GetColor( Color &rRGB ) const;

    void SetNext( CSS1Expression *pNxt ) { pNext = pNxt; }
    const CSS1Expression *GetNext() const { return pNext; }
};

inline void CSS1Expression::Set( CSS1Token eTyp, const String &rVal,
                                 double nVal, sal_Unicode cO )
{
    cOp = cO; eType = eTyp; aValue = rVal; nValue = nVal; pNext = 0;
}

inline sal_uInt32 CSS1Expression::GetULength() const
{
    return nValue < 0. ? 0UL : (sal_uInt32)(nValue + .5);
}

inline sal_Int32 CSS1Expression::GetSLength() const
{
    return (sal_Int32)(nValue + (nValue < 0. ? -.5 : .5 ));
}

/*  */

// Diese Klasse parst den Inhalt eines Style-Elements oder eine Style-Option
// und bereitet ihn ein wenig auf.
//
// Das Ergebnis des Parsers wird durch die Mehtoden SelectorParsed()
// und DeclarationParsed() an abgeleitete Parser uebergeben. Bsp:
//
// H1, H2 { font-weight: bold; text-align: right }
//  |  |                    |                  |
//  |  |                    |                  DeclP( 'text-align', 'right' )
//  |  |                    DeclP( 'font-weight', 'bold' )
//  |  SelP( 'H2', sal_False )
//  SelP( 'H1', sal_True )
//
class CSS1Parser
{
    sal_Bool bWhiteSpace : 1;           // White-Space gelesen?
    sal_Bool bEOF : 1;                  // Ende des "Files" ?

    sal_Unicode cNextCh;                // naechstes Zeichen

    xub_StrLen nInPos;                  // aktuelle Position im Input-String

    sal_uInt32 nlLineNr;                    // akt. Zeilen Nummer
    sal_uInt32 nlLinePos;               // akt. Spalten Nummer

    double nValue;                  // der Wert des Tokens als Zahl

    CSS1ParserState eState;         // der akteulle Zustand der Parsers
    CSS1Token nToken;               // das aktuelle Token

    String aIn;                     // der zu parsende String
    String aToken;                  // das Token als String

    // Parsen vorbereiten
    void InitRead( const String& rIn );

    // das naechste Zeichen holen
    sal_Unicode GetNextChar();

    // das naechste Token holen
    CSS1Token GetNextToken();

    // arbeitet der Parser noch?
    sal_Bool IsParserWorking() const { return CSS1_PAR_WORKING == eState; }

    sal_Bool IsEOF() const { return bEOF; }

    sal_uInt32 IncLineNr() { return ++nlLineNr; }
    sal_uInt32 IncLinePos() { return ++nlLinePos; }
    inline sal_uInt32 SetLineNr( sal_uInt32 nlNum );            // inline unten
    inline sal_uInt32 SetLinePos( sal_uInt32 nlPos );           // inline unten

    // Parsen von Teilen der Grammatik
    void ParseStyleSheet();
    void ParseRule();
    CSS1Selector *ParseSelector();
    CSS1Expression *ParseDeclaration( String& rProperty );

protected:

    // Den Inhalt eines HTML-Style-Elements parsen.
    // Fuer jeden Selektor und jede Deklaration wird
    // SelectorParsed() bzw. DeclarationParsed() aufgerufen.
    sal_Bool ParseStyleSheet( const String& rIn );

    // Den Inhalt einer HTML-Style-Option parsen.
    // Fr jede Deklaration wird DeclarationParsed() aufgerufen.
    sal_Bool ParseStyleOption( const String& rIn );

    // Diese Methode wird aufgerufen, wenn ein Selektor geparsed wurde
    // Wenn 'bFirst' gesetzt ist, beginnt mit dem Selektor eine neue
    // Deklaration. Wird sal_True zurueckgegeben, wird der Selektor
    // geloscht, sonst nicht.
    // Die Implementierung dieser Methode gibt nur sal_True zuruck.
    virtual sal_Bool SelectorParsed( const CSS1Selector *pSelector,
                                 sal_Bool bFirst );

    // Diese Methode wird fuer jede geparsete Property aufgerufen. Wird
    // sal_True zurueckgegeben wird der Selektor geloscht, sonst nicht.
    // Die Implementierung dieser Methode gibt nur sal_True zuruck.
    virtual sal_Bool DeclarationParsed( const String& rProperty,
                                    const CSS1Expression *pExpr );

public:

    CSS1Parser();
    virtual ~CSS1Parser();

    inline sal_uInt32   GetLineNr() const       { return nlLineNr; }
    inline sal_uInt32   GetLinePos() const      { return nlLinePos; }
};

inline sal_uInt32 CSS1Parser::SetLineNr( sal_uInt32 nlNum )
{
    sal_uInt32 nlOld = nlLineNr;
    nlLineNr = nlNum;
    return nlOld;
}

inline sal_uInt32 CSS1Parser::SetLinePos( sal_uInt32 nlPos )
{
    sal_uInt32 nlOld = nlLinePos;
    nlLinePos = nlPos;
    return nlOld;
}

#endif

<commit_msg>INTEGRATION: CWS swwarnings (1.2.710); FILE MERGED 2007/03/16 14:11:23 tl 1.2.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parcss1.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 09:50:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PARCSS1_HXX
#define _PARCSS1_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

class Color;

/*  */

// Die Tokens des CSS1-Parsers
enum CSS1Token
{
    CSS1_NULL,
    CSS1_UNKOWN,

    CSS1_IDENT,
    CSS1_STRING,
    CSS1_NUMBER,
    CSS1_PERCENTAGE,
    CSS1_LENGTH,            // eine absolute Groesse in 1/100 MM
    CSS1_PIXLENGTH,         // eine Pixel-Groesse
    CSS1_EMS,
    CSS1_EMX,
    CSS1_HEXCOLOR,

    CSS1_DOT_W_WS,
    CSS1_DOT_WO_WS,
    CSS1_COLON,
    CSS1_SLASH,
    CSS1_PLUS,
    CSS1_MINUS,
    CSS1_OBRACE,
    CSS1_CBRACE,
    CSS1_SEMICOLON,
    CSS1_COMMA,
    CSS1_HASH,

    CSS1_IMPORT_SYM,
// Feature: PrintExt
    CSS1_PAGE_SYM,
// /Feature: PrintExt

    CSS1_IMPORTANT_SYM,

    CSS1_URL,
    CSS1_RGB
};

// die Zustaende des Parsers
enum CSS1ParserState
{
    CSS1_PAR_ACCEPTED = 0,
    CSS1_PAR_WORKING,
    CSS1_PAR_ERROR
};

/*  */

enum CSS1SelectorType
{
    CSS1_SELTYPE_ELEMENT,
    CSS1_SELTYPE_ELEM_CLASS,
    CSS1_SELTYPE_CLASS,
    CSS1_SELTYPE_ID,
    CSS1_SELTYPE_PSEUDO,
// Feature: PrintExt
    CSS1_SELTYPE_PAGE
// /Feature: PrintExt

};

// Die folegende Klasse beschreibt einen Simple-Selector, also
// - einen HTML-Element-Namen
// - einen HTML-Element-Namen mit Klasse (durch '.' getrennt)
// - eine Klasse (ohne Punkt)
// - eine mit ID=xxx gesetzte ID aus einem HTML-Dokument
// oder
// - ein Pseudo-Element
//
// Die Simple-Sektoren werden in einer Liste zu vollstaendigen
// Selektoren verkettet
class CSS1Selector
{
    CSS1SelectorType eType;     // Art des Selektors
    String aSelector;           // der Selektor selbst
    CSS1Selector *pNext;        // die naechste Komponente

public:

    CSS1Selector( CSS1SelectorType eTyp, const String &rSel )
        : eType(eTyp), aSelector( rSel ), pNext( 0 )
    {}

    ~CSS1Selector();

    CSS1SelectorType GetType() const { return eType; }
    const String& GetString() const { return aSelector; }

    void SetNext( CSS1Selector *pNxt ) { pNext = pNxt; }
    const CSS1Selector *GetNext() const { return pNext; }
};

/*  */

// Die folegende Klasse beschreibt einen Teil-Ausdruck einer
// CSS1-Deklaration sie besteht aus
//
// - dem Typ des Ausdrucks (entspricht dem Token)
// - dem eigentlichen Wert als String und ggf. double
//   der double-Wert enthaelt das Vorzeichen fuer NUMBER und LENGTH
// - und dem Operator, mit dem er mit dem *Vorganger*-Ausdruck
//   verknuepft ist.
//
struct CSS1Expression
{
    sal_Unicode cOp;        // Art der Verkuepfung mit dem Vorgaenger
    CSS1Token eType;        // der Typ des Wertes
    String aValue;          // und sein Wert als String
    double nValue;          // und als Zahl (TWIPs fuer LENGTH)
    CSS1Expression *pNext;  // die naechste Komponente

public:

    CSS1Expression( CSS1Token eTyp, const String &rVal,
                    double nVal, sal_Unicode cO = 0 )
        : cOp(cO), eType(eTyp), aValue(rVal), nValue(nVal), pNext(0)
    {}

    ~CSS1Expression();

    inline void Set( CSS1Token eTyp, const String &rVal, double nVal,
                     sal_Unicode cO = 0 );

    CSS1Token GetType() const { return eType; }
    const String& GetString() const { return aValue; }
    double GetNumber() const { return nValue; }
    inline sal_uInt32 GetULength() const;
    inline sal_Int32 GetSLength() const;
    sal_Unicode GetOp() const { return cOp; }

    sal_Bool GetURL( String& rURL ) const;
    sal_Bool GetColor( Color &rRGB ) const;

    void SetNext( CSS1Expression *pNxt ) { pNext = pNxt; }
    const CSS1Expression *GetNext() const { return pNext; }
};

inline void CSS1Expression::Set( CSS1Token eTyp, const String &rVal,
                                 double nVal, sal_Unicode cO )
{
    cOp = cO; eType = eTyp; aValue = rVal; nValue = nVal; pNext = 0;
}

inline sal_uInt32 CSS1Expression::GetULength() const
{
    return nValue < 0. ? 0UL : (sal_uInt32)(nValue + .5);
}

inline sal_Int32 CSS1Expression::GetSLength() const
{
    return (sal_Int32)(nValue + (nValue < 0. ? -.5 : .5 ));
}

/*  */

// Diese Klasse parst den Inhalt eines Style-Elements oder eine Style-Option
// und bereitet ihn ein wenig auf.
//
// Das Ergebnis des Parsers wird durch die Mehtoden SelectorParsed()
// und DeclarationParsed() an abgeleitete Parser uebergeben. Bsp:
//
// H1, H2 { font-weight: bold; text-align: right }
//  |  |                    |                  |
//  |  |                    |                  DeclP( 'text-align', 'right' )
//  |  |                    DeclP( 'font-weight', 'bold' )
//  |  SelP( 'H2', sal_False )
//  SelP( 'H1', sal_True )
//
class CSS1Parser
{
    sal_Bool bWhiteSpace : 1;           // White-Space gelesen?
    sal_Bool bEOF : 1;                  // Ende des "Files" ?

    sal_Unicode cNextCh;                // naechstes Zeichen

    xub_StrLen nInPos;                  // aktuelle Position im Input-String

    sal_uInt32 nlLineNr;                    // akt. Zeilen Nummer
    sal_uInt32 nlLinePos;               // akt. Spalten Nummer

    double nValue;                  // der Wert des Tokens als Zahl

    CSS1ParserState eState;         // der akteulle Zustand der Parsers
    CSS1Token nToken;               // das aktuelle Token

    String aIn;                     // der zu parsende String
    String aToken;                  // das Token als String

    // Parsen vorbereiten
    void InitRead( const String& rIn );

    // das naechste Zeichen holen
    sal_Unicode GetNextChar();

    // das naechste Token holen
    CSS1Token GetNextToken();

    // arbeitet der Parser noch?
    sal_Bool IsParserWorking() const { return CSS1_PAR_WORKING == eState; }

    sal_Bool IsEOF() const { return bEOF; }

    sal_uInt32 IncLineNr() { return ++nlLineNr; }
    sal_uInt32 IncLinePos() { return ++nlLinePos; }
    inline sal_uInt32 SetLineNr( sal_uInt32 nlNum );            // inline unten
    inline sal_uInt32 SetLinePos( sal_uInt32 nlPos );           // inline unten

    // Parsen von Teilen der Grammatik
    void ParseRule();
    CSS1Selector *ParseSelector();
    CSS1Expression *ParseDeclaration( String& rProperty );

protected:

    void ParseStyleSheet();

    // Den Inhalt eines HTML-Style-Elements parsen.
    // Fuer jeden Selektor und jede Deklaration wird
    // SelectorParsed() bzw. DeclarationParsed() aufgerufen.
    sal_Bool ParseStyleSheet( const String& rIn );

    // Den Inhalt einer HTML-Style-Option parsen.
    // F�r jede Deklaration wird DeclarationParsed() aufgerufen.
    sal_Bool ParseStyleOption( const String& rIn );

    // Diese Methode wird aufgerufen, wenn ein Selektor geparsed wurde
    // Wenn 'bFirst' gesetzt ist, beginnt mit dem Selektor eine neue
    // Deklaration. Wird sal_True zurueckgegeben, wird der Selektor
    // geloscht, sonst nicht.
    // Die Implementierung dieser Methode gibt nur sal_True zuruck.
    virtual sal_Bool SelectorParsed( const CSS1Selector *pSelector,
                                 sal_Bool bFirst );

    // Diese Methode wird fuer jede geparsete Property aufgerufen. Wird
    // sal_True zurueckgegeben wird der Selektor geloscht, sonst nicht.
    // Die Implementierung dieser Methode gibt nur sal_True zuruck.
    virtual sal_Bool DeclarationParsed( const String& rProperty,
                                    const CSS1Expression *pExpr );

public:

    CSS1Parser();
    virtual ~CSS1Parser();

    inline sal_uInt32   GetLineNr() const       { return nlLineNr; }
    inline sal_uInt32   GetLinePos() const      { return nlLinePos; }
};

inline sal_uInt32 CSS1Parser::SetLineNr( sal_uInt32 nlNum )
{
    sal_uInt32 nlOld = nlLineNr;
    nlLineNr = nlNum;
    return nlOld;
}

inline sal_uInt32 CSS1Parser::SetLinePos( sal_uInt32 nlPos )
{
    sal_uInt32 nlOld = nlLinePos;
    nlLinePos = nlPos;
    return nlOld;
}

#endif

<|endoftext|>


<commit_before>#include <iostream>

#include "stream.hpp"

using namespace std;

int main()
{
    Stream<int>::range(5)
    .filter([] (int num)
    {
        return num % 2 == 0;
    })
    .take(5)
    .map<float>([] (int num)
    {
         return (float)num + 0.5f;
    })
    .walk([] (float num)
    {
        cout << num << endl;
    });
}
<commit_msg>comments for the example<commit_after>#include <iostream>

#include "stream.hpp"

using namespace std;

int main()
{
    Stream<int>::range(5) // build a stream from 5 to infinity
    .filter([] (int num) // only accept even numbers
    {
        return num % 2 == 0;
    })
    .take(5) // only take 5 even numbers
    .map<float>([] (int num) // add 0.5 to each number and convert the stream to a float stream
    {
         return (float)num + 0.5f;
    })
    .walk([] (float num) // list the results
    {
        cout << num << endl;
    });
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/audio_processing/aec3/block_processor.h"

#include <memory>
#include <sstream>
#include <string>
#include <vector>

#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/mock/mock_echo_remover.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_controller.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/checks.h"
#include "rtc_base/random.h"
#include "test/gmock.h"
#include "test/gtest.h"

namespace webrtc {
namespace {

using testing::AtLeast;
using testing::Return;
using testing::StrictMock;
using testing::_;

// Verifies that the basic BlockProcessor functionality works and that the API
// methods are callable.
void RunBasicSetupAndApiCallTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(NumBandsForRate(sample_rate_hz),
                                        std::vector<float>(kBlockSize, 0.f));

  block_processor->BufferRender(block);
  block_processor->ProcessCapture(false, false, &block);
  block_processor->UpdateEchoLeakageStatus(false);
}

#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
void RunRenderBlockSizeVerificationTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(
      NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));

  EXPECT_DEATH(block_processor->BufferRender(block), "");
}

void RunCaptureBlockSizeVerificationTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(
      NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));

  EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}

void RunRenderNumBandsVerificationTest(int sample_rate_hz) {
  const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
                                     ? NumBandsForRate(sample_rate_hz) + 1
                                     : 1;
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(wrong_num_bands,
                                        std::vector<float>(kBlockSize, 0.f));

  EXPECT_DEATH(block_processor->BufferRender(block), "");
}

void RunCaptureNumBandsVerificationTest(int sample_rate_hz) {
  const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
                                     ? NumBandsForRate(sample_rate_hz) + 1
                                     : 1;
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(wrong_num_bands,
                                        std::vector<float>(kBlockSize, 0.f));

  EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
#endif

std::string ProduceDebugText(int sample_rate_hz) {
  std::ostringstream ss;
  ss << "Sample rate: " << sample_rate_hz;
  return ss.str();
}

}  // namespace

// Verifies that the delay controller functionality is properly integrated with
// the render delay buffer inside block processor.
// TODO(peah): Activate the unittest once the required code has been landed.
TEST(BlockProcessor, DISABLED_DelayControllerIntegration) {
  constexpr size_t kNumBlocks = 310;
  constexpr size_t kDelayInSamples = 640;
  constexpr size_t kDelayHeadroom = 1;
  constexpr size_t kDelayInBlocks =
      kDelayInSamples / kBlockSize - kDelayHeadroom;
  Random random_generator(42U);
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
        render_delay_buffer_mock(
            new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
    EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, SetDelay(kDelayInBlocks))
        .Times(AtLeast(1));
    EXPECT_CALL(*render_delay_buffer_mock, MaxDelay()).WillOnce(Return(30));
    EXPECT_CALL(*render_delay_buffer_mock, Delay())
        .Times(kNumBlocks + 1)
        .WillRepeatedly(Return(0));
    std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
        EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock)));

    std::vector<std::vector<float>> render_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    std::vector<std::vector<float>> capture_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    DelayBuffer<float> signal_delay_buffer(kDelayInSamples);
    for (size_t k = 0; k < kNumBlocks; ++k) {
      RandomizeSampleVector(&random_generator, render_block[0]);
      signal_delay_buffer.Delay(render_block[0], capture_block[0]);
      block_processor->BufferRender(render_block);
      block_processor->ProcessCapture(false, false, &capture_block);
    }
  }
}

// Verifies that BlockProcessor submodules are called in a proper manner.
TEST(BlockProcessor, DISABLED_SubmoduleIntegration) {
  constexpr size_t kNumBlocks = 310;
  Random random_generator(42U);
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
        render_delay_buffer_mock(
            new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
    std::unique_ptr<
        testing::StrictMock<webrtc::test::MockRenderDelayController>>
        render_delay_controller_mock(
            new StrictMock<webrtc::test::MockRenderDelayController>());
    std::unique_ptr<testing::StrictMock<webrtc::test::MockEchoRemover>>
        echo_remover_mock(new StrictMock<webrtc::test::MockEchoRemover>());

    EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
        .Times(kNumBlocks - 1)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, UpdateBuffers()).Times(kNumBlocks);
    EXPECT_CALL(*render_delay_buffer_mock, SetDelay(9)).Times(AtLeast(1));
    EXPECT_CALL(*render_delay_buffer_mock, Delay())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(0));
    EXPECT_CALL(*render_delay_controller_mock, GetDelay(_, _))
        .Times(kNumBlocks)
        .WillRepeatedly(Return(9));
    EXPECT_CALL(*render_delay_controller_mock, AlignmentHeadroomSamples())
        .Times(kNumBlocks);
    EXPECT_CALL(*echo_remover_mock, ProcessCapture(_, _, _, _, _))
        .Times(kNumBlocks);
    EXPECT_CALL(*echo_remover_mock, UpdateEchoLeakageStatus(_))
        .Times(kNumBlocks);

    std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
        EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock),
        std::move(render_delay_controller_mock), std::move(echo_remover_mock)));

    std::vector<std::vector<float>> render_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    std::vector<std::vector<float>> capture_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    DelayBuffer<float> signal_delay_buffer(640);
    for (size_t k = 0; k < kNumBlocks; ++k) {
      RandomizeSampleVector(&random_generator, render_block[0]);
      signal_delay_buffer.Delay(render_block[0], capture_block[0]);
      block_processor->BufferRender(render_block);
      block_processor->ProcessCapture(false, false, &capture_block);
      block_processor->UpdateEchoLeakageStatus(false);
    }
  }
}

TEST(BlockProcessor, BasicSetupAndApiCalls) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunBasicSetupAndApiCallTest(rate);
  }
}

#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
TEST(BlockProcessor, VerifyRenderBlockSizeCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunRenderBlockSizeVerificationTest(rate);
  }
}

TEST(BlockProcessor, VerifyCaptureBlockSizeCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunCaptureBlockSizeVerificationTest(rate);
  }
}

TEST(BlockProcessor, VerifyRenderNumBandsCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunRenderNumBandsVerificationTest(rate);
  }
}

// TODO(peah): Verify the check for correct number of bands in the capture
// signal.
TEST(BlockProcessor, VerifyCaptureNumBandsCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunCaptureNumBandsVerificationTest(rate);
  }
}

// Verifiers that the verification for null ProcessCapture input works.
TEST(BlockProcessor, NullProcessCaptureParameter) {
  EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
                   BlockProcessor::Create(EchoCanceller3Config(), 8000))
                   ->ProcessCapture(false, false, nullptr),
               "");
}

// Verifies the check for correct sample rate.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_WrongSampleRate) {
  EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
                   BlockProcessor::Create(EchoCanceller3Config(), 8001)),
               "");
}

#endif

}  // namespace webrtc
<commit_msg>Temporarily disabled failing death test.<commit_after>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/audio_processing/aec3/block_processor.h"

#include <memory>
#include <sstream>
#include <string>
#include <vector>

#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/mock/mock_echo_remover.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_controller.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/checks.h"
#include "rtc_base/random.h"
#include "test/gmock.h"
#include "test/gtest.h"

namespace webrtc {
namespace {

using testing::AtLeast;
using testing::Return;
using testing::StrictMock;
using testing::_;

// Verifies that the basic BlockProcessor functionality works and that the API
// methods are callable.
void RunBasicSetupAndApiCallTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(NumBandsForRate(sample_rate_hz),
                                        std::vector<float>(kBlockSize, 0.f));

  block_processor->BufferRender(block);
  block_processor->ProcessCapture(false, false, &block);
  block_processor->UpdateEchoLeakageStatus(false);
}

#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
void RunRenderBlockSizeVerificationTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(
      NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));

  EXPECT_DEATH(block_processor->BufferRender(block), "");
}

void RunCaptureBlockSizeVerificationTest(int sample_rate_hz) {
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(
      NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));

  EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}

void RunRenderNumBandsVerificationTest(int sample_rate_hz) {
  const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
                                     ? NumBandsForRate(sample_rate_hz) + 1
                                     : 1;
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(wrong_num_bands,
                                        std::vector<float>(kBlockSize, 0.f));

  EXPECT_DEATH(block_processor->BufferRender(block), "");
}

void RunCaptureNumBandsVerificationTest(int sample_rate_hz) {
  const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
                                     ? NumBandsForRate(sample_rate_hz) + 1
                                     : 1;
  std::unique_ptr<BlockProcessor> block_processor(
      BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
  std::vector<std::vector<float>> block(wrong_num_bands,
                                        std::vector<float>(kBlockSize, 0.f));

  EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
#endif

std::string ProduceDebugText(int sample_rate_hz) {
  std::ostringstream ss;
  ss << "Sample rate: " << sample_rate_hz;
  return ss.str();
}

}  // namespace

// Verifies that the delay controller functionality is properly integrated with
// the render delay buffer inside block processor.
// TODO(peah): Activate the unittest once the required code has been landed.
TEST(BlockProcessor, DISABLED_DelayControllerIntegration) {
  constexpr size_t kNumBlocks = 310;
  constexpr size_t kDelayInSamples = 640;
  constexpr size_t kDelayHeadroom = 1;
  constexpr size_t kDelayInBlocks =
      kDelayInSamples / kBlockSize - kDelayHeadroom;
  Random random_generator(42U);
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
        render_delay_buffer_mock(
            new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
    EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, SetDelay(kDelayInBlocks))
        .Times(AtLeast(1));
    EXPECT_CALL(*render_delay_buffer_mock, MaxDelay()).WillOnce(Return(30));
    EXPECT_CALL(*render_delay_buffer_mock, Delay())
        .Times(kNumBlocks + 1)
        .WillRepeatedly(Return(0));
    std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
        EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock)));

    std::vector<std::vector<float>> render_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    std::vector<std::vector<float>> capture_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    DelayBuffer<float> signal_delay_buffer(kDelayInSamples);
    for (size_t k = 0; k < kNumBlocks; ++k) {
      RandomizeSampleVector(&random_generator, render_block[0]);
      signal_delay_buffer.Delay(render_block[0], capture_block[0]);
      block_processor->BufferRender(render_block);
      block_processor->ProcessCapture(false, false, &capture_block);
    }
  }
}

// Verifies that BlockProcessor submodules are called in a proper manner.
TEST(BlockProcessor, DISABLED_SubmoduleIntegration) {
  constexpr size_t kNumBlocks = 310;
  Random random_generator(42U);
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
        render_delay_buffer_mock(
            new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
    std::unique_ptr<
        testing::StrictMock<webrtc::test::MockRenderDelayController>>
        render_delay_controller_mock(
            new StrictMock<webrtc::test::MockRenderDelayController>());
    std::unique_ptr<testing::StrictMock<webrtc::test::MockEchoRemover>>
        echo_remover_mock(new StrictMock<webrtc::test::MockEchoRemover>());

    EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
        .Times(kNumBlocks - 1)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*render_delay_buffer_mock, UpdateBuffers()).Times(kNumBlocks);
    EXPECT_CALL(*render_delay_buffer_mock, SetDelay(9)).Times(AtLeast(1));
    EXPECT_CALL(*render_delay_buffer_mock, Delay())
        .Times(kNumBlocks)
        .WillRepeatedly(Return(0));
    EXPECT_CALL(*render_delay_controller_mock, GetDelay(_, _))
        .Times(kNumBlocks)
        .WillRepeatedly(Return(9));
    EXPECT_CALL(*render_delay_controller_mock, AlignmentHeadroomSamples())
        .Times(kNumBlocks);
    EXPECT_CALL(*echo_remover_mock, ProcessCapture(_, _, _, _, _))
        .Times(kNumBlocks);
    EXPECT_CALL(*echo_remover_mock, UpdateEchoLeakageStatus(_))
        .Times(kNumBlocks);

    std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
        EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock),
        std::move(render_delay_controller_mock), std::move(echo_remover_mock)));

    std::vector<std::vector<float>> render_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    std::vector<std::vector<float>> capture_block(
        NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
    DelayBuffer<float> signal_delay_buffer(640);
    for (size_t k = 0; k < kNumBlocks; ++k) {
      RandomizeSampleVector(&random_generator, render_block[0]);
      signal_delay_buffer.Delay(render_block[0], capture_block[0]);
      block_processor->BufferRender(render_block);
      block_processor->ProcessCapture(false, false, &capture_block);
      block_processor->UpdateEchoLeakageStatus(false);
    }
  }
}

TEST(BlockProcessor, BasicSetupAndApiCalls) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunBasicSetupAndApiCallTest(rate);
  }
}

#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// TODO(gustaf): Re-enable the test once the issue with memory leaks during
// DEATH tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_VerifyRenderBlockSizeCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunRenderBlockSizeVerificationTest(rate);
  }
}

TEST(BlockProcessor, VerifyCaptureBlockSizeCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunCaptureBlockSizeVerificationTest(rate);
  }
}

TEST(BlockProcessor, VerifyRenderNumBandsCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunRenderNumBandsVerificationTest(rate);
  }
}

// TODO(peah): Verify the check for correct number of bands in the capture
// signal.
TEST(BlockProcessor, VerifyCaptureNumBandsCheck) {
  for (auto rate : {8000, 16000, 32000, 48000}) {
    SCOPED_TRACE(ProduceDebugText(rate));
    RunCaptureNumBandsVerificationTest(rate);
  }
}

// Verifiers that the verification for null ProcessCapture input works.
TEST(BlockProcessor, NullProcessCaptureParameter) {
  EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
                   BlockProcessor::Create(EchoCanceller3Config(), 8000))
                   ->ProcessCapture(false, false, nullptr),
               "");
}

// Verifies the check for correct sample rate.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_WrongSampleRate) {
  EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
                   BlockProcessor::Create(EchoCanceller3Config(), 8001)),
               "");
}

#endif

}  // namespace webrtc
<|endoftext|>


<commit_before>//*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                                License Agreement
//                       For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_HYBRIDTRACKER_H_
#define __OPENCV_HYBRIDTRACKER_H_

#include "opencv2/core/core.hpp"
#include "opencv2/core/operations.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/ml/ml.hpp"

#ifdef __cplusplus

namespace cv
{

// Motion model for tracking algorithm. Currently supports objects that do not move much.
// To add Kalman filter
struct CV_EXPORTS CvMotionModel
{
	enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2};

	CvMotionModel()
	{
	}

	float low_pass_gain; 	// low pass gain
	CvEMParams em_params;	// EM parameters
};

// Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters.
struct CV_EXPORTS CvMeanShiftTrackerParams
{
	enum {	H = 0, HS = 1, HSV = 2	};
	CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS,
			CvTermCriteria term_crit = CvTermCriteria())
	{
	}

	int tracking_type;
	float h_range[];
	float s_range[];
	float v_range[];
	CvTermCriteria term_crit;
};

// Feature tracking parameters
struct CV_EXPORTS CvFeatureTrackerParams
{
	enum {	SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 };
	CvFeatureTrackerParams(int feature_type = 0, int window_size = 0)
	{
		feature_type = 0;
		window_size = 0;
	}

	int feature_type; // Feature type to use
	int window_size; // Window size in pixels around which to search for new window
};

// Hybrid Tracking parameters for specifying weights of individual trackers and motion model.
struct CV_EXPORTS CvHybridTrackerParams
{
	CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5,
			CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(),
			CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(),
			CvMotionModel model = CvMotionModel())
	{
	}

	float ft_tracker_weight;
	float ms_tracker_weight;
	CvFeatureTrackerParams ft_params;
	CvMeanShiftTrackerParams ms_params;
	CvEMParams em_params;
	int motion_model;
	float low_pass_gain;
};

// Performs Camshift using parameters from MeanShiftTrackerParams
class CV_EXPORTS CvMeanShiftTracker
{
private:
	Mat hsv, hue;
	Mat backproj;
	Mat mask, maskroi;
	MatND hist;
	Rect prev_trackwindow;
	RotatedRect prev_trackbox;
	Point2f prev_center;

public:
	CvMeanShiftTrackerParams params;

	CvMeanShiftTracker();
	CvMeanShiftTracker(CvMeanShiftTrackerParams _params = CvMeanShiftTrackerParams());
	~CvMeanShiftTracker();
	void newTrackingWindow(Mat image, Rect selection);
	RotatedRect updateTrackingWindow(Mat image);
	Mat getHistogramProjection(int type);
	void setTrackingWindow(Rect _window);
	Rect getTrackingWindow();
	RotatedRect getTrackingEllipse();
	Point2f getTrackingCenter();
};

// Performs SIFT/SURF feature tracking using parameters from FeatureTrackerParams
class CV_EXPORTS CvFeatureTracker
{
private:
	FeatureDetector* detector;
	DescriptorExtractor* descriptor;
	DescriptorMatcher* matcher;
	vector<DMatch> matches;

	Mat prev_image;
	Mat prev_image_bw;
	Rect prev_trackwindow;
	Point2d prev_center;

	int ittr;
	vector<Point2f> features[2];

public:
	Mat disp_matches;
	CvFeatureTrackerParams params;

	CvFeatureTracker();
	CvFeatureTracker(CvFeatureTrackerParams params = CvFeatureTrackerParams(0,0));
	~CvFeatureTracker();
	void newTrackingWindow(Mat image, Rect selection);
	Rect updateTrackingWindow(Mat image);
	Rect updateTrackingWindowWithSIFT(Mat image);
	Rect updateTrackingWindowWithFlow(Mat image);
	void setTrackingWindow(Rect _window);
	Rect getTrackingWindow();
	Point2f getTrackingCenter();
};

// Performs Hybrid Tracking and combines individual trackers using EM or filters
class CV_EXPORTS CvHybridTracker
{
private:
	CvMeanShiftTracker* mstracker;
	CvFeatureTracker* fttracker;

	CvMat* samples;
	CvMat* labels;
	CvEM em_model;

	Rect prev_window;
	Point2f prev_center;
	Mat prev_proj;
	RotatedRect trackbox;

	int ittr;
	Point2f curr_center;

	inline float getL2Norm(Point2f p1, Point2f p2);
	Mat getDistanceProjection(Mat image, Point2f center);
	Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center);
	void updateTrackerWithEM(Mat image);
	void updateTrackerWithLowPassFilter(Mat image);

public:
	CvHybridTrackerParams params;
	CvHybridTracker();
	CvHybridTracker(CvHybridTrackerParams params = CvHybridTrackerParams());
	~CvHybridTracker();

	void newTracker(Mat image, Rect selection);
	void updateTracker(Mat image);
	Rect getTrackingWindow();
};

typedef CvMotionModel MotionModel;
typedef CvMeanShiftTrackerParams MeanShiftTrackerParams;
typedef CvFeatureTrackerParams FeatureTrackerParams;
typedef CvHybridTrackerParams HybridTrackerParams;
typedef CvMeanShiftTracker MeanShiftTracker;
typedef CvFeatureTracker FeatureTracker;
typedef CvHybridTracker HybridTracker;
}

#endif

#endif
<commit_msg>fixed hybrid tracker build problems on Windows<commit_after>//*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                                License Agreement
//                       For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_HYBRIDTRACKER_H_
#define __OPENCV_HYBRIDTRACKER_H_

#include "opencv2/core/core.hpp"
#include "opencv2/core/operations.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/ml/ml.hpp"

#ifdef __cplusplus

namespace cv
{

// Motion model for tracking algorithm. Currently supports objects that do not move much.
// To add Kalman filter
struct CV_EXPORTS CvMotionModel
{
	enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2};

	CvMotionModel()
	{
	}

	float low_pass_gain; 	// low pass gain
	CvEMParams em_params;	// EM parameters
};

// Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters.
struct CV_EXPORTS CvMeanShiftTrackerParams
{
	enum {	H = 0, HS = 1, HSV = 2	};
	CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS,
			CvTermCriteria term_crit = CvTermCriteria())
	{
	}

	int tracking_type;
	vector<float> h_range;
	vector<float> s_range;
	vector<float> v_range;
	CvTermCriteria term_crit;
};

// Feature tracking parameters
struct CV_EXPORTS CvFeatureTrackerParams
{
	enum {	SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 };
	CvFeatureTrackerParams(int feature_type = 0, int window_size = 0)
	{
		feature_type = 0;
		window_size = 0;
	}

	int feature_type; // Feature type to use
	int window_size; // Window size in pixels around which to search for new window
};

// Hybrid Tracking parameters for specifying weights of individual trackers and motion model.
struct CV_EXPORTS CvHybridTrackerParams
{
	CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5,
			CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(),
			CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(),
			CvMotionModel model = CvMotionModel())
	{
	}

	float ft_tracker_weight;
	float ms_tracker_weight;
	CvFeatureTrackerParams ft_params;
	CvMeanShiftTrackerParams ms_params;
	CvEMParams em_params;
	int motion_model;
	float low_pass_gain;
};

// Performs Camshift using parameters from MeanShiftTrackerParams
class CV_EXPORTS CvMeanShiftTracker
{
private:
	Mat hsv, hue;
	Mat backproj;
	Mat mask, maskroi;
	MatND hist;
	Rect prev_trackwindow;
	RotatedRect prev_trackbox;
	Point2f prev_center;

public:
	CvMeanShiftTrackerParams params;

	CvMeanShiftTracker();
	CvMeanShiftTracker(CvMeanShiftTrackerParams _params = CvMeanShiftTrackerParams());
	~CvMeanShiftTracker();
	void newTrackingWindow(Mat image, Rect selection);
	RotatedRect updateTrackingWindow(Mat image);
	Mat getHistogramProjection(int type);
	void setTrackingWindow(Rect _window);
	Rect getTrackingWindow();
	RotatedRect getTrackingEllipse();
	Point2f getTrackingCenter();
};

// Performs SIFT/SURF feature tracking using parameters from FeatureTrackerParams
class CV_EXPORTS CvFeatureTracker
{
private:
	FeatureDetector* detector;
	DescriptorExtractor* descriptor;
	DescriptorMatcher* matcher;
	vector<DMatch> matches;

	Mat prev_image;
	Mat prev_image_bw;
	Rect prev_trackwindow;
	Point2d prev_center;

	int ittr;
	vector<Point2f> features[2];

public:
	Mat disp_matches;
	CvFeatureTrackerParams params;

	CvFeatureTracker();
	CvFeatureTracker(CvFeatureTrackerParams params = CvFeatureTrackerParams(0,0));
	~CvFeatureTracker();
	void newTrackingWindow(Mat image, Rect selection);
	Rect updateTrackingWindow(Mat image);
	Rect updateTrackingWindowWithSIFT(Mat image);
	Rect updateTrackingWindowWithFlow(Mat image);
	void setTrackingWindow(Rect _window);
	Rect getTrackingWindow();
	Point2f getTrackingCenter();
};

// Performs Hybrid Tracking and combines individual trackers using EM or filters
class CV_EXPORTS CvHybridTracker
{
private:
	CvMeanShiftTracker* mstracker;
	CvFeatureTracker* fttracker;

	CvMat* samples;
	CvMat* labels;
	CvEM em_model;

	Rect prev_window;
	Point2f prev_center;
	Mat prev_proj;
	RotatedRect trackbox;

	int ittr;
	Point2f curr_center;

	inline float getL2Norm(Point2f p1, Point2f p2);
	Mat getDistanceProjection(Mat image, Point2f center);
	Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center);
	void updateTrackerWithEM(Mat image);
	void updateTrackerWithLowPassFilter(Mat image);

public:
	CvHybridTrackerParams params;
	CvHybridTracker();
	CvHybridTracker(CvHybridTrackerParams params = CvHybridTrackerParams());
	~CvHybridTracker();

	void newTracker(Mat image, Rect selection);
	void updateTracker(Mat image);
	Rect getTrackingWindow();
};

typedef CvMotionModel MotionModel;
typedef CvMeanShiftTrackerParams MeanShiftTrackerParams;
typedef CvFeatureTrackerParams FeatureTrackerParams;
typedef CvHybridTrackerParams HybridTrackerParams;
typedef CvMeanShiftTracker MeanShiftTracker;
typedef CvFeatureTracker FeatureTracker;
typedef CvHybridTracker HybridTracker;
}

#endif

#endif
<|endoftext|>


<commit_before>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkImageStatisticsWidget.h"

#include "QmitkStatisticsModelToStringConverter.h"
#include "QmitkImageStatisticsTreeModel.h"

#include <QSortFilterProxyModel>
#include <QClipboard>

QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent)
{
  m_Controls.setupUi(this);
  m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent);
  CreateConnections();
  m_ProxyModel = new QSortFilterProxyModel(this);
  m_Controls.treeViewStatistics->setEnabled(false);
  m_Controls.treeViewStatistics->setModel(m_ProxyModel);
  m_ProxyModel->setSourceModel(m_imageStatisticsModel);
  connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable);
  connect(m_imageStatisticsModel,
          &QmitkImageStatisticsTreeModel::modelChanged,
          m_Controls.treeViewStatistics,
          &QTreeView::expandAll);
}

void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage)
{
  m_imageStatisticsModel->SetDataStorage(newDataStorage);
}

void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
  m_imageStatisticsModel->SetImageNodes(nodes);
}

void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
  m_imageStatisticsModel->SetMaskNodes(nodes);
}

void QmitkImageStatisticsWidget::Reset()
{
  m_imageStatisticsModel->Clear();
  m_Controls.treeViewStatistics->setEnabled(false);
  m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false);
}

void QmitkImageStatisticsWidget::CreateConnections()
{
	connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked);
}

void QmitkImageStatisticsWidget::OnDataAvailable()
{
  m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true);
  m_Controls.treeViewStatistics->setEnabled(true);
}

void QmitkImageStatisticsWidget::OnClipboardButtonClicked()
{
  QmitkStatisticsModelToStringConverter converter;
  converter.SetTableModel(m_imageStatisticsModel);
  converter.SetRootIndex(m_Controls.treeViewStatistics->rootIndex());
  converter.SetIncludeHeaderData(true);

  QString clipboardAsString = converter.GetString();
  QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard);
}
<commit_msg>Change column delimiter to tab<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkImageStatisticsWidget.h"

#include "QmitkStatisticsModelToStringConverter.h"
#include "QmitkImageStatisticsTreeModel.h"

#include <QSortFilterProxyModel>
#include <QClipboard>

QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent)
{
  m_Controls.setupUi(this);
  m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent);
  CreateConnections();
  m_ProxyModel = new QSortFilterProxyModel(this);
  m_Controls.treeViewStatistics->setEnabled(false);
  m_Controls.treeViewStatistics->setModel(m_ProxyModel);
  m_ProxyModel->setSourceModel(m_imageStatisticsModel);
  connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable);
  connect(m_imageStatisticsModel,
          &QmitkImageStatisticsTreeModel::modelChanged,
          m_Controls.treeViewStatistics,
          &QTreeView::expandAll);
}

void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage)
{
  m_imageStatisticsModel->SetDataStorage(newDataStorage);
}

void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
  m_imageStatisticsModel->SetImageNodes(nodes);
}

void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
  m_imageStatisticsModel->SetMaskNodes(nodes);
}

void QmitkImageStatisticsWidget::Reset()
{
  m_imageStatisticsModel->Clear();
  m_Controls.treeViewStatistics->setEnabled(false);
  m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false);
}

void QmitkImageStatisticsWidget::CreateConnections()
{
	connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked);
}

void QmitkImageStatisticsWidget::OnDataAvailable()
{
  m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true);
  m_Controls.treeViewStatistics->setEnabled(true);
}

void QmitkImageStatisticsWidget::OnClipboardButtonClicked()
{
  QmitkStatisticsModelToStringConverter converter;
  converter.SetColumnDelimiter('\t');
  converter.SetTableModel(m_imageStatisticsModel);
  converter.SetRootIndex(m_Controls.treeViewStatistics->rootIndex());
  converter.SetIncludeHeaderData(true);

  QString clipboardAsString = converter.GetString();
  QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard);
}
<|endoftext|>