<commit_before>/*************************************************************************
 *
 *  $RCSfile: resultsetforquery.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-27 10:07:40 $
 *
 *  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 _COM_SUN_STAR_UCB_COMMAND_HPP_
#include <com/sun/star/ucb/Command.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XEXTENDEDTRANSLITERATION_HPP_
#include <com/sun/star/i18n/XExtendedTransliteration.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDPROCESSOR_HPP_
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _RESULTSETFORROOT_HXX
#include <provider/resultsetforquery.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_
#include <qe/QueryProcessor.hxx>
#endif
#ifndef INCLUDED_STL_ALGORITHM
#include <algorithm>
#define INCLUDED_STL_ALGORITHM
#endif
#ifndef INCLUDED_STL_SET
#include <set>
#define INCLUDED_STL_SET
#endif

using namespace std;
using namespace chelp;
using namespace xmlsearch::excep;
using namespace xmlsearch::qe;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
using namespace com::sun::star::i18n;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;

ResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >&  xMSF,
                                      const uno::Reference< XContentProvider >&  xProvider,
                                      sal_Int32 nOpenMode,
                                      const uno::Sequence< beans::Property >& seq,
                                      const uno::Sequence< NumberedSortingInfo >& seqSort,
                                      URLParameter& aURLParameter,
                                      Databases* pDatabases )
    : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),
      m_aURLParameter( aURLParameter ),
      m_pDatabases( pDatabases )
{
    Reference< XTransliteration > xTrans(
        xMSF->createInstance( rtl::OUString::createFromAscii( "com.sun.star.i18n.Transliteration" ) ),
        UNO_QUERY );
    Locale aLocale( aURLParameter.get_language(),
                    rtl::OUString(),
                    rtl::OUString() );
    if(xTrans.is())
        xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,
                           aLocale );

    unsigned int i;
    vector< vector< rtl::OUString > > queryList;

    {
        sal_Int32 idx;
        rtl::OUString query = m_aURLParameter.get_query();
        while( query.getLength() )
        {
            idx = query.indexOf( sal_Unicode( ' ' ) );
            if( idx == -1 )
                idx = query.getLength();

            vector< rtl::OUString > currentQuery;
            rtl::OUString tmp(query.copy( 0,idx ));
            rtl:: OUString toliterate = tmp;
            if(xTrans.is()) {
                Sequence<sal_Int32> aSeq;
                toliterate = xTrans->transliterate(
                    tmp,0,tmp.getLength(),aSeq);
            }
            currentQuery.push_back( toliterate );
            queryList.push_back( currentQuery );
            query = query.copy( 1 + idx );
        }
    }

    rtl::OUString scope = m_aURLParameter.get_scope();
    StaticModuleInformation* inf =
        m_pDatabases->getStaticInformationForModule( m_aURLParameter.get_module(),
                                                     m_aURLParameter.get_language() );

    if( inf )
    {
        if( scope.compareToAscii( "Heading" ) == 0 )
            scope = rtl::OUString::createFromAscii("title"); // inf->get_heading();
        else
            scope = inf->get_fulltext();
    }

    sal_Int32 hitCount = m_aURLParameter.get_hitCount();

    QueryResults* queryResults = 0;
    QueryHitIterator* it = 0;
    set< rtl::OUString > aSet,aCurrent,aResultSet;

    try
    {
        rtl::OUString idxDir =
            m_pDatabases->getInstallPathAsURL()                    +
            m_pDatabases->lang( m_aURLParameter.get_language() )   +
            rtl::OUString::createFromAscii( "/" )                  +
            m_aURLParameter.get_module()                           +
            rtl::OUString::createFromAscii( ".idx/" );

        if(queryList.size() > 1)
            hitCount = 2000;

        for( i = 0; i < queryList.size(); ++i )
        {
            QueryProcessor queryProcessor(idxDir);
            QueryStatement queryStatement(hitCount,queryList[i],scope);
            queryResults = queryProcessor.processQuery( queryStatement );

            it = 0;
            if( queryResults )
                it = queryResults->makeQueryHitIterator();

            aSet.clear();
            while( it && it->next() )
            {
                QueryHitData* qhd = it->getHit( 0 /*PrefixTranslator*/ );
                if(qhd)
                    aSet.insert(qhd->getDocument());
            }

            delete it;  // deletes also queryResults[i]

            // intersect
            if( i == 0 )
                aResultSet = aSet;
            else
            {
                aCurrent = aResultSet;
                aResultSet.clear();
                set_intersection( aSet.begin(),aSet.end(),
                                  aCurrent.begin(),aCurrent.end(),
                                  inserter(aResultSet,aResultSet.begin()));
            }
        }
    }
    catch( IOException )
    {
    }

    sal_Int32 replIdx = rtl::OUString::createFromAscii( "#HLP#" ).getLength();
    rtl::OUString replWith = rtl::OUString::createFromAscii( "vnd.sun.star.help://" );

    set< rtl::OUString >::const_iterator set_it = aResultSet.begin();
    while( set_it != aResultSet.end() )
    {
          m_aPath.push_back(replWith + set_it->copy(replIdx));
        ++set_it;
    }

    m_aItems.resize( m_aPath.size() );
    m_aIdents.resize( m_aPath.size() );

    Command aCommand;
    aCommand.Name = rtl::OUString::createFromAscii( "getPropertyValues" );
    aCommand.Argument <<= m_sProperty;

    for( m_nRow = 0; m_nRow < m_aPath.size(); ++m_nRow )
    {
        m_aPath[m_nRow] =
            m_aPath[m_nRow]                                          +
            rtl::OUString::createFromAscii( "?Language=" )           +
            m_aURLParameter.get_language()                           +
            rtl::OUString::createFromAscii( "&System=" )             +
            m_aURLParameter.get_system();

        uno::Reference< XContent > content = queryContent();
        if( content.is() )
        {
            uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );
            if( ! ( cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow] ) )
                ;
        }
    }
    m_nRow = -1;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.40); FILE MERGED 2005/09/05 17:19:33 rt 1.10.40.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: resultsetforquery.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:21:12 $
 *
 *  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 _COM_SUN_STAR_UCB_COMMAND_HPP_
#include <com/sun/star/ucb/Command.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XEXTENDEDTRANSLITERATION_HPP_
#include <com/sun/star/i18n/XExtendedTransliteration.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDPROCESSOR_HPP_
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _RESULTSETFORROOT_HXX
#include <provider/resultsetforquery.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_
#include <qe/QueryProcessor.hxx>
#endif
#ifndef INCLUDED_STL_ALGORITHM
#include <algorithm>
#define INCLUDED_STL_ALGORITHM
#endif
#ifndef INCLUDED_STL_SET
#include <set>
#define INCLUDED_STL_SET
#endif

using namespace std;
using namespace chelp;
using namespace xmlsearch::excep;
using namespace xmlsearch::qe;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
using namespace com::sun::star::i18n;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;

ResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >&  xMSF,
                                      const uno::Reference< XContentProvider >&  xProvider,
                                      sal_Int32 nOpenMode,
                                      const uno::Sequence< beans::Property >& seq,
                                      const uno::Sequence< NumberedSortingInfo >& seqSort,
                                      URLParameter& aURLParameter,
                                      Databases* pDatabases )
    : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),
      m_aURLParameter( aURLParameter ),
      m_pDatabases( pDatabases )
{
    Reference< XTransliteration > xTrans(
        xMSF->createInstance( rtl::OUString::createFromAscii( "com.sun.star.i18n.Transliteration" ) ),
        UNO_QUERY );
    Locale aLocale( aURLParameter.get_language(),
                    rtl::OUString(),
                    rtl::OUString() );
    if(xTrans.is())
        xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,
                           aLocale );

    unsigned int i;
    vector< vector< rtl::OUString > > queryList;

    {
        sal_Int32 idx;
        rtl::OUString query = m_aURLParameter.get_query();
        while( query.getLength() )
        {
            idx = query.indexOf( sal_Unicode( ' ' ) );
            if( idx == -1 )
                idx = query.getLength();

            vector< rtl::OUString > currentQuery;
            rtl::OUString tmp(query.copy( 0,idx ));
            rtl:: OUString toliterate = tmp;
            if(xTrans.is()) {
                Sequence<sal_Int32> aSeq;
                toliterate = xTrans->transliterate(
                    tmp,0,tmp.getLength(),aSeq);
            }
            currentQuery.push_back( toliterate );
            queryList.push_back( currentQuery );
            query = query.copy( 1 + idx );
        }
    }

    rtl::OUString scope = m_aURLParameter.get_scope();
    StaticModuleInformation* inf =
        m_pDatabases->getStaticInformationForModule( m_aURLParameter.get_module(),
                                                     m_aURLParameter.get_language() );

    if( inf )
    {
        if( scope.compareToAscii( "Heading" ) == 0 )
            scope = rtl::OUString::createFromAscii("title"); // inf->get_heading();
        else
            scope = inf->get_fulltext();
    }

    sal_Int32 hitCount = m_aURLParameter.get_hitCount();

    QueryResults* queryResults = 0;
    QueryHitIterator* it = 0;
    set< rtl::OUString > aSet,aCurrent,aResultSet;

    try
    {
        rtl::OUString idxDir =
            m_pDatabases->getInstallPathAsURL()                    +
            m_pDatabases->lang( m_aURLParameter.get_language() )   +
            rtl::OUString::createFromAscii( "/" )                  +
            m_aURLParameter.get_module()                           +
            rtl::OUString::createFromAscii( ".idx/" );

        if(queryList.size() > 1)
            hitCount = 2000;

        for( i = 0; i < queryList.size(); ++i )
        {
            QueryProcessor queryProcessor(idxDir);
            QueryStatement queryStatement(hitCount,queryList[i],scope);
            queryResults = queryProcessor.processQuery( queryStatement );

            it = 0;
            if( queryResults )
                it = queryResults->makeQueryHitIterator();

            aSet.clear();
            while( it && it->next() )
            {
                QueryHitData* qhd = it->getHit( 0 /*PrefixTranslator*/ );
                if(qhd)
                    aSet.insert(qhd->getDocument());
            }

            delete it;  // deletes also queryResults[i]

            // intersect
            if( i == 0 )
                aResultSet = aSet;
            else
            {
                aCurrent = aResultSet;
                aResultSet.clear();
                set_intersection( aSet.begin(),aSet.end(),
                                  aCurrent.begin(),aCurrent.end(),
                                  inserter(aResultSet,aResultSet.begin()));
            }
        }
    }
    catch( IOException )
    {
    }

    sal_Int32 replIdx = rtl::OUString::createFromAscii( "#HLP#" ).getLength();
    rtl::OUString replWith = rtl::OUString::createFromAscii( "vnd.sun.star.help://" );

    set< rtl::OUString >::const_iterator set_it = aResultSet.begin();
    while( set_it != aResultSet.end() )
    {
          m_aPath.push_back(replWith + set_it->copy(replIdx));
        ++set_it;
    }

    m_aItems.resize( m_aPath.size() );
    m_aIdents.resize( m_aPath.size() );

    Command aCommand;
    aCommand.Name = rtl::OUString::createFromAscii( "getPropertyValues" );
    aCommand.Argument <<= m_sProperty;

    for( m_nRow = 0; m_nRow < m_aPath.size(); ++m_nRow )
    {
        m_aPath[m_nRow] =
            m_aPath[m_nRow]                                          +
            rtl::OUString::createFromAscii( "?Language=" )           +
            m_aURLParameter.get_language()                           +
            rtl::OUString::createFromAscii( "&System=" )             +
            m_aURLParameter.get_system();

        uno::Reference< XContent > content = queryContent();
        if( content.is() )
        {
            uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );
            if( ! ( cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow] ) )
                ;
        }
    }
    m_nRow = -1;
}
<|endoftext|>


<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "../third_party/skcms/skcms.h"
#include "SkColorSpacePriv.h"
#include "SkData.h"
#include "SkImage.h"
#include "SkStream.h"

int main(int argc, char** argv) {
    const char* image_path = argc > 1 ? argv[1] : nullptr;
    if (!image_path) {
        SkDebugf("Please pass an image to convert as the first argument to this program.\n");
        return 1;
    }

    sk_sp<SkImage> image = SkImage::MakeFromEncoded(SkData::MakeFromFileName(image_path));
    if (!image) {
        SkDebugf("Couldn't decode %s as an SkImage.\n", image_path);
        return 1;
    }

    image = image->makeRasterImage();
    if (!image) {
        SkDebugf("Converting to raster image failed.\n");
        return 1;
    }

    SkPixmap pixmap;
    if (!image->peekPixels(&pixmap)) {
        SkDebugf("We really should be able to peek raster pixels.\n");
        return 1;
    }

    SkColorSpace* src_cs = image->colorSpace() ? image->colorSpace()
                                               : sk_srgb_singleton();
    skcms_ICCProfile src_profile;
    src_cs->toProfile(&src_profile);

    const char* dst_profile_path = argc > 2 ? argv[2] : nullptr;
    skcms_ICCProfile dst_profile = *skcms_sRGB_profile();
    if (dst_profile_path) {
        sk_sp<SkData> blob = SkData::MakeFromFileName(dst_profile_path);
        if (!skcms_Parse(blob->data(), blob->size(), &dst_profile)) {
            SkDebugf("Can't parse %s as an ICC profile.\n", dst_profile_path);
            return 1;
        }
    }

    skcms_PixelFormat fmt;
    switch (pixmap.colorType()) {
        case kRGBA_8888_SkColorType: fmt = skcms_PixelFormat_RGBA_8888; break;
        case kBGRA_8888_SkColorType: fmt = skcms_PixelFormat_BGRA_8888; break;
        default:
            SkDebugf("color type %d not yet supported, imgcvt.cpp needs an update.\n",
                     pixmap.colorType());
            return 1;
    }

    if (pixmap.alphaType() != kPremul_SkAlphaType) {
        SkDebugf("not premul, that's weird.\n");
        return 1;
    }
    auto alpha = skcms_AlphaFormat_PremulAsEncoded;

    if (pixmap.rowBytes() != (size_t)pixmap.width() * pixmap.info().bytesPerPixel()) {
        SkDebugf("not a tight pixmap, need a loop here\n");
        return 1;
    }

    skcms_Transform(pixmap.addr(),          fmt,alpha, &src_profile,
                    pixmap.writable_addr(), fmt,alpha, &dst_profile,
                    pixmap.width() * pixmap.height());
    pixmap.setColorSpace(SkColorSpace::Make(dst_profile));

    sk_sp<SkImage> transformed = SkImage::MakeRasterCopy(pixmap);
    sk_sp<SkData>  png = transformed->encodeToData();

    SkFILEWStream("transformed.png").write(png->data(), png->size());

    return 0;
}
<commit_msg>add profile->profile mode to imgcvt<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "../third_party/skcms/skcms.h"
#include "SkColorSpacePriv.h"
#include "SkData.h"
#include "SkImage.h"
#include "SkStream.h"

int main(int argc, char** argv) {
    const char* source_path = argc > 1 ? argv[1] : nullptr;
    if (!source_path) {
        SkDebugf("Please pass an image or profile to convert"
                 " as the first argument to this program.\n");
        return 1;
    }

    const char* dst_profile_path = argc > 2 ? argv[2] : nullptr;
    skcms_ICCProfile dst_profile = *skcms_sRGB_profile();
    if (dst_profile_path) {
        sk_sp<SkData> blob = SkData::MakeFromFileName(dst_profile_path);
        if (!skcms_Parse(blob->data(), blob->size(), &dst_profile)) {
            SkDebugf("Can't parse %s as an ICC profile.\n", dst_profile_path);
            return 1;
        }
    }

    auto blob = SkData::MakeFromFileName(source_path);

    skcms_ICCProfile src_profile;
    if (skcms_Parse(blob->data(), blob->size(), &src_profile)) {
        // Transform white, black, primaries, and primary complements.
        float src[] = {
           0,0,0,
           1,1,1,

           1,0,0,
           0,1,0,
           0,0,1,

           0,1,1,
           1,0,1,
           1,1,0,
        };
        float dst[24] = {0};

        if (!skcms_Transform(
                    src, skcms_PixelFormat_RGB_fff, skcms_AlphaFormat_Unpremul, &src_profile,
                    dst, skcms_PixelFormat_RGB_fff, skcms_AlphaFormat_Unpremul, &dst_profile,
                    8)) {
            SkDebugf("Cannot transform.\n");
            return 1;
        }
        for (int i = 0; i < 8; i++) {
            SkDebugf("(%g, %g, %g) --> (%+.4f, %+.4f, %+.4f)\n",
                     src[3*i+0], src[3*i+1], src[3*i+2],
                     dst[3*i+0], dst[3*i+1], dst[3*i+2]);
        }
        return 0;
    }

    sk_sp<SkImage> image = SkImage::MakeFromEncoded(blob);
    if (!image) {
        SkDebugf("Couldn't decode %s as an SkImage or an ICC profile.\n", source_path);
        return 1;
    }

    image = image->makeRasterImage();
    if (!image) {
        SkDebugf("Converting to raster image failed.\n");
        return 1;
    }

    SkPixmap pixmap;
    if (!image->peekPixels(&pixmap)) {
        SkDebugf("We really should be able to peek raster pixels.\n");
        return 1;
    }

    SkColorSpace* src_cs = image->colorSpace() ? image->colorSpace()
                                               : sk_srgb_singleton();
    src_cs->toProfile(&src_profile);

    skcms_PixelFormat fmt;
    switch (pixmap.colorType()) {
        case kRGBA_8888_SkColorType: fmt = skcms_PixelFormat_RGBA_8888; break;
        case kBGRA_8888_SkColorType: fmt = skcms_PixelFormat_BGRA_8888; break;
        default:
            SkDebugf("color type %d not yet supported, imgcvt.cpp needs an update.\n",
                     pixmap.colorType());
            return 1;
    }

    if (pixmap.alphaType() != kPremul_SkAlphaType) {
        SkDebugf("not premul, that's weird.\n");
        return 1;
    }
    auto alpha = skcms_AlphaFormat_PremulAsEncoded;

    if (pixmap.rowBytes() != (size_t)pixmap.width() * pixmap.info().bytesPerPixel()) {
        SkDebugf("not a tight pixmap, need a loop here\n");
        return 1;
    }

    skcms_Transform(pixmap.addr(),          fmt,alpha, &src_profile,
                    pixmap.writable_addr(), fmt,alpha, &dst_profile,
                    pixmap.width() * pixmap.height());
    pixmap.setColorSpace(SkColorSpace::Make(dst_profile));

    sk_sp<SkImage> transformed = SkImage::MakeRasterCopy(pixmap);
    sk_sp<SkData>  png = transformed->encodeToData();

    SkFILEWStream("transformed.png").write(png->data(), png->size());

    return 0;
}
<|endoftext|>


<commit_before>/*
 * FUNCTION:
 * sniff test.
 *
 * HISTORY:
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */

#include "odbcxx.h"

#include "Atom.h"

class AtomStorage
{
	private:
		ODBCConnection *db_conn;
		ODBCRecordSet *rs;
		bool column_cb(const char *colname, const char * colvalue)
		{
			printf ("%s = %s\n", colname, colvalue);
			return false;
		}
		bool row_cb(void)
		{
			printf ("---- New row found ----\n");
			rs->foreach_column(&AtomStorage::column_cb, this);
			return false;
		}
	public:
		AtomStorage(void);
		~AtomStorage();

		void storeAtom(Atom *);
		Atom * getAtom(Handle);
};

#include "Node.h"
#include "type_codes.h"

AtomStorage::AtomStorage(void)
{
	db_conn = new ODBCConnection("opencog", "linas", NULL);
}

AtomStorage::~AtomStorage()
{
	delete db_conn;
}

void AtomStorage::storeAtom(Atom *)
{

}

Atom * AtomStorage::getAtom(Handle h)
{
	rs = db_conn->exec("SELECT * FROM Atoms;");
	rs->foreach_row(&AtomStorage::row_cb, this);
	rs->release();
	return NULL;
}

int main ()
{
	AtomStorage *store = new AtomStorage();

	Atom *a = new Node(SCHEMA_NODE, "someNode");
printf ("hello\n");

	store->storeAtom(a);
	store->getAtom(a);

	return 0;
}

/* ============================= END OF FILE ================= */
<commit_msg>add a bit of insertion code.<commit_after>/*
 * FUNCTION:
 * sniff test.
 *
 * HISTORY:
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */

#include "odbcxx.h"

#include "Atom.h"

class AtomStorage
{
	private:
		ODBCConnection *db_conn;
		ODBCRecordSet *rs;
		bool column_cb(const char *colname, const char * colvalue)
		{
			printf ("%s = %s\n", colname, colvalue);
			return false;
		}
		bool row_cb(void)
		{
			printf ("---- New row found ----\n");
			rs->foreach_column(&AtomStorage::column_cb, this);
			return false;
		}
	public:
		AtomStorage(void);
		~AtomStorage();

		void storeAtom(Atom *);
		Atom * getAtom(Handle);
};

#include "Node.h"
#include "TLB.h"
#include "type_codes.h"

AtomStorage::AtomStorage(void)
{
	db_conn = new ODBCConnection("opencog", "linas", NULL);
}

AtomStorage::~AtomStorage()
{
	delete db_conn;
}

void AtomStorage::storeAtom(Atom *atom)
{
	std::string cols = "INSERT INTO Atoms (";
	std::string vals = ") VALUES (";

	char buff[24];
	Handle h = TLB::getHandle(atom);
	snprintf(buff, 24, "%lu", (unsigned long) h);
	cols += "uuid";
	vals += buff;

	Type t = atom->getType();
	snprintf(buff, 24, "%u", t);
	cols += ", type";
	vals += ", ";
	vals += buff;

	Node *n = dynamic_cast<Node *>(atom);
	if (n)
	{
		cols += ", name";
		vals += ", '";
		vals += n->getName();
		vals += "'";
	}

	std::string qry = cols + vals + ");";
printf ("duude its %s\n", qry.c_str());
	db_conn->exec(qry.c_str());
}

Atom * AtomStorage::getAtom(Handle h)
{
	rs = db_conn->exec("SELECT * FROM Atoms;");
	rs->foreach_row(&AtomStorage::row_cb, this);
	rs->release();
	return NULL;
}

int main ()
{
	AtomStorage *store = new AtomStorage();

	Atom *a = new Node(SCHEMA_NODE, "someNode");
printf ("hello\n");

	store->storeAtom(a);
	store->getAtom(a);

	return 0;
}

/* ============================= END OF FILE ================= */
<|endoftext|>


<commit_before>#include "../includes/Scanner.h"
#include "../../Automat/includes/Automat.h"
#include "../../Symboltable/includes/Information.h"
#include <error.h>
#include <errno.h>

Scanner::Scanner(char* argv, char* argv2) {

	if (argv == NULL) {
		argv = "../input/in.txt";
		argv2 = "../output/out.txt";
	} else if (argv2 == NULL) {
		argv2 = "out.txt";
	}

	buffer = new Buffer(argv);
	filedesc = open(argv2, O_WRONLY | O_CREAT|O_TRUNC, 0666);

	symTable = new Symboltable();
	symTable->initSymbols();
	automat = new Automat();
	this->counter = 0;
}

void Scanner::writeInt(long int value, int filedesc){
								char intString[10000];
								int j = 0;
								sprintf(intString, "%ld", value);
								char * pointer = intString;
								while ( *(pointer+j) != '\0') {
																write(filedesc, pointer+j, 1);
																j++;
								}
}

char* Scanner::translateType(int type){

								switch (type) {
								case 1:
																translatedType = "Identifier     ";
																break;
								case 2:
																translatedType = "Integer        ";
																break;
								case 7:
																translatedType = "PLUS           ";
																break;
								case 8:
																translatedType = "MINUS          ";
																break;
								case 9:
																translatedType = "COLON          ";
																break;
								case 10:
																translatedType = "STAR           ";
																break;
								case 11:
																translatedType = "SMALLER        ";
																break;
								case 12:
																translatedType = "GREATER        ";
																break;
								case 13:
																translatedType = "EQUALS         ";
																break;
								case 14:
																translatedType = "ASSIGNMENT     ";
																break;
								case 15:
																translatedType = "WEIRDTHING     ";
																break;
								case 16:
																translatedType = "EXCLAMATION    ";
																break;
								case 17:
																translatedType = "ANDAND         ";
																break;
								case 18:
																translatedType = "SEMICOLON      ";
																break;
								case 19:
																translatedType = "STARTBRACKETA  ";
																break;
								case 20:
																translatedType = "ENDBRACKETA    ";
																break;
								case 21:
																translatedType = "STARTBRACKETB  ";
																break;
								case 22:
																translatedType = "ENDBRACKETB    ";
																break;
								case 23:
																translatedType = "STARTBRACKETC  ";
																break;
								case 24:
																translatedType = "ENDBRACKETC    ";
																break;
								}

								return translatedType;
}

Token* Scanner::nextToken() {
	char c;
	int automat_result;
	Token* token;
		do {
			// Lesen bis zum Lexem
			c = buffer->getChar();
			automat_result = automat->handle(c);
				if (c != '\0' && c != '\n' && c != ' ') {
					counter++;
				}

																// 0 -> Lexem to Token und Step Back
																// 20 -> Lexem to Token und kein Step Back
																// -1 -> Error Token
																// -99 -> End of File
				if (automat_result == 24) {
					counter = 0;
				}

		} while (automat_result != 0 && automat_result != 20 && automat_result != -1 && automat_result != -99);

								switch (automat_result) {
								case 0: {
																//TODO: Comment why we do this
																if (c != '\n' && c != ' ') {
																								counter--;
																}

																write(filedesc, "Token ", 6);
																write(filedesc, translateType(automat->gettype()), 15);
																write(filedesc, " Line: ", 7);
																writeInt(automat->getline(), filedesc);
																write(filedesc, " Column: ", 9);
																writeInt(automat->getcolumn() - counter, filedesc);
																buffer->stepBack(1);

																// Integer
																if (automat->gettype() == 2) {

																								buffer->stepBack(counter);
																								char number[counter];
																								for (size_t i = 0; i < counter; i++) {
																																number[i] = buffer->getChar();
																								}
																								long value = strtol(number, NULL, 10);
																								if (errno == ERANGE) {
																																error(0, ERANGE, "LINE: %d Column: %d", automat->getline(), automat->getcolumn() - counter);
																																errno = 0;
																																// TODO: CHECK WHAT TYPE ERROR IS
																																token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter);
																								}
																								token = new Token(Token::INTEGER, automat->getline(), automat->getcolumn() - counter, value);
																								write(filedesc, " ", 1);
																								write(filedesc, number, counter);
																}else{
																// Alles neben Integer
																	buffer->stepBack(counter);
																	char word[counter + 1];
																	for (size_t i = 0; i < counter; i++) {
																									word[i] = buffer->getChar();
																	}
																	word[counter] = '\0';
																	Information* myInformation = new Information(word);

																	// Identifier => in Symboltabelle eintragen
																	if (automat->gettype() == 1) {
																		myInformation->setType(Token::IDENTIFIER);
																	}

																	Key* myKey = symTable->insert(myInformation);
																	Information* info = symTable->lookup(myKey);
																	// Get Token Type from symTable --> information
																	token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info);
																	write(filedesc, " ", 1);
																	write(filedesc, word, counter);

																}

																write(filedesc, "\n", 1);
																counter = 0;
								}
								break;
								case 20: {
																// write chars into token....
																buffer->stepBack(counter);
																char word[counter + 1];
																for (size_t i = 0; i < counter; i++) {
																        word[i] = buffer->getChar();
																}
																word[counter] = '\0';
																Information* myInformation = new Information(word);
																Key* myKey = symTable->insert(myInformation);
																Information* info = symTable->lookup(myKey);
																token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info);
																write(filedesc, "Token ", 6);
																write(filedesc, translateType(automat->gettype()), 15);
																write(filedesc, " Line: ", 7);
																writeInt(automat->getline(), filedesc);
																write(filedesc, " Column: ", 9);
																writeInt(automat->getcolumn() - counter, filedesc);
																write(filedesc, "\n", 1);
																counter = 0;
								}
								break;
								case -1: {
																fprintf(stderr, "Error: Type: %d Line: %d Column: %d \n", automat->gettype(), automat->getline(), automat->getcolumn() - counter);
																// write error lexem into token
																buffer->stepBack(counter);
																char word[counter + 1];
																for (size_t i = 0; i < counter; i++) {
																								word[i] = buffer->getChar();
																}
																word[counter] = '\0';
																Information* myInformation = new Information(word);
																token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter, myInformation);
																counter = 0;
								}
								break;
								case -99: {
																cout << "End of Party. Good Night, sleep well ;)";
																cout << '\n';
																token = NULL;
								}
								break;
								default: {
																cout << "Unexpected Error. Exiting...";
																cout << '\n';
																token = NULL;
								}
								}
								return token;
}

Scanner::~Scanner() {
								// TODO Auto-generated destructor stub
								close(filedesc);
}
<commit_msg>refacot scanner<commit_after>#include "../includes/Scanner.h"
#include "../../Automat/includes/Automat.h"
#include "../../Symboltable/includes/Information.h"
#include <error.h>
#include <errno.h>

Scanner::Scanner(char* argv, char* argv2) {

	if (argv == NULL) {
		argv = "../input/in.txt";
		argv2 = "../output/out.txt";
	} else if (argv2 == NULL) {
		argv2 = "out.txt";
	}

	buffer = new Buffer(argv);
	filedesc = open(argv2, O_WRONLY | O_CREAT|O_TRUNC, 0666);

	symTable = new Symboltable();
	symTable->initSymbols();
	automat = new Automat();
	this->counter = 0;
}

void Scanner::writeInt(long int value, int filedesc){
								char intString[10000];
								int j = 0;
								sprintf(intString, "%ld", value);
								char * pointer = intString;
								while ( *(pointer+j) != '\0') {
																write(filedesc, pointer+j, 1);
																j++;
								}
}

char* Scanner::translateType(int type){

								switch (type) {
								case 1:
																translatedType = "Identifier     ";
																break;
								case 2:
																translatedType = "Integer        ";
																break;
								case 7:
																translatedType = "PLUS           ";
																break;
								case 8:
																translatedType = "MINUS          ";
																break;
								case 9:
																translatedType = "COLON          ";
																break;
								case 10:
																translatedType = "STAR           ";
																break;
								case 11:
																translatedType = "SMALLER        ";
																break;
								case 12:
																translatedType = "GREATER        ";
																break;
								case 13:
																translatedType = "EQUALS         ";
																break;
								case 14:
																translatedType = "ASSIGNMENT     ";
																break;
								case 15:
																translatedType = "WEIRDTHING     ";
																break;
								case 16:
																translatedType = "EXCLAMATION    ";
																break;
								case 17:
																translatedType = "ANDAND         ";
																break;
								case 18:
																translatedType = "SEMICOLON      ";
																break;
								case 19:
																translatedType = "STARTBRACKETA  ";
																break;
								case 20:
																translatedType = "ENDBRACKETA    ";
																break;
								case 21:
																translatedType = "STARTBRACKETB  ";
																break;
								case 22:
																translatedType = "ENDBRACKETB    ";
																break;
								case 23:
																translatedType = "STARTBRACKETC  ";
																break;
								case 24:
																translatedType = "ENDBRACKETC    ";
																break;
								}

								return translatedType;
}

Token* Scanner::nextToken() {

char c;
int automat_result;
Token* token;

	do {
		c = buffer->getChar();
		automat_result = automat->handle(c);

		if (c != '\0' && c != '\n' && c != ' ') {
			counter++;
		}

		if (automat_result == 24) {
			counter = 0;
		}

	} while (automat_result != 0 && automat_result != 20 && automat_result != -1 && automat_result != -99);

								switch (automat_result) {
								case 0: {
																//TODO: Comment why we do this
																if (c != '\n' && c != ' ') {
																								counter--;
																}

																write(filedesc, "Token ", 6);
																write(filedesc, translateType(automat->gettype()), 15);
																write(filedesc, " Line: ", 7);
																writeInt(automat->getline(), filedesc);
																write(filedesc, " Column: ", 9);
																writeInt(automat->getcolumn() - counter, filedesc);
																buffer->stepBack(1);

																// Integer
																if (automat->gettype() == 2) {

																								buffer->stepBack(counter);
																								char number[counter];
																								for (size_t i = 0; i < counter; i++) {
																																number[i] = buffer->getChar();
																								}
																								long value = strtol(number, NULL, 10);
																								if (errno == ERANGE) {
																																error(0, ERANGE, "LINE: %d Column: %d", automat->getline(), automat->getcolumn() - counter);
																																errno = 0;
																																// TODO: CHECK WHAT TYPE ERROR IS
																																token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter);
																								}
																								token = new Token(Token::INTEGER, automat->getline(), automat->getcolumn() - counter, value);
																								write(filedesc, " ", 1);
																								write(filedesc, number, counter);
																}else{
																// Alles neben Integer
																	buffer->stepBack(counter);
																	char word[counter + 1];
																	for (size_t i = 0; i < counter; i++) {
																									word[i] = buffer->getChar();
																	}
																	word[counter] = '\0';
																	Information* myInformation = new Information(word);

																	// Identifier => in Symboltabelle eintragen
																	if (automat->gettype() == 1) {
																		myInformation->setType(Token::IDENTIFIER);
																	}

																	Key* myKey = symTable->insert(myInformation);
																	Information* info = symTable->lookup(myKey);
																	// Get Token Type from symTable --> information
																	token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info);
																	write(filedesc, " ", 1);
																	write(filedesc, word, counter);

																}

																write(filedesc, "\n", 1);
																counter = 0;
								}
								break;
								case 20: {
																// write chars into token....
																buffer->stepBack(counter);
																char word[counter + 1];
																for (size_t i = 0; i < counter; i++) {
																        word[i] = buffer->getChar();
																}
																word[counter] = '\0';
																Information* myInformation = new Information(word);
																Key* myKey = symTable->insert(myInformation);
																Information* info = symTable->lookup(myKey);
																token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info);
																write(filedesc, "Token ", 6);
																write(filedesc, translateType(automat->gettype()), 15);
																write(filedesc, " Line: ", 7);
																writeInt(automat->getline(), filedesc);
																write(filedesc, " Column: ", 9);
																writeInt(automat->getcolumn() - counter, filedesc);
																write(filedesc, "\n", 1);
																counter = 0;
								}
								break;
								case -1: {
																fprintf(stderr, "Error: Type: %d Line: %d Column: %d \n", automat->gettype(), automat->getline(), automat->getcolumn() - counter);
																// write error lexem into token
																buffer->stepBack(counter);
																char word[counter + 1];
																for (size_t i = 0; i < counter; i++) {
																								word[i] = buffer->getChar();
																}
																word[counter] = '\0';
																Information* myInformation = new Information(word);
																token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter, myInformation);
																counter = 0;
								}
								break;
								case -99: {
																cout << "End of Party. Good Night, sleep well ;)";
																cout << '\n';
																token = NULL;
								}
								break;
								default: {
																cout << "Unexpected Error. Exiting...";
																cout << '\n';
																token = NULL;
								}
								}
								return token;
}

Scanner::~Scanner() {
								// TODO Auto-generated destructor stub
								close(filedesc);
}
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/Utilities.h"
#include "cinder/gl/Texture.h"

#include "Resources.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ClipboardBasicApp : public App {
  public:
	void keyDown( KeyEvent event ) override;
	void draw() override;
};

void ClipboardBasicApp::keyDown( KeyEvent event )
{
#if ! defined( CINDER_COCOA_TOUCH )
	if( event.getChar() == 'c' && event.isAccelDown() ) {
		Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
		// to copy the contents of the window, you might do something like
		// Clipboard::setImage( copyWindowSurface() );
	}
#endif
}

void ClipboardBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::setMatricesWindow( getWindowSize() );
	gl::enableAlphaBlending();

	if( Clipboard::hasImage() )
		gl::draw( gl::Texture::create( Clipboard::getImage() ) );
	else if( Clipboard::hasString() )
		gl::drawString( Clipboard::getString(), vec2( 0, getWindowCenter().y ) );
	else
		gl::drawString( "Clipboard contents unknown", vec2( 0, getWindowCenter().y ) );
}

CINDER_APP( ClipboardBasicApp, RendererGl )
<commit_msg>Testing for race condition in Clipboard sample<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/Utilities.h"
#include "cinder/gl/Texture.h"

#include "Resources.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ClipboardBasicApp : public App {
  public:
	void keyDown( KeyEvent event ) override;
	void draw() override;
};

void ClipboardBasicApp::keyDown( KeyEvent event )
{
#if ! defined( CINDER_COCOA_TOUCH )
	if( event.getChar() == 'c' && event.isAccelDown() ) {
		Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
		// to copy the contents of the window, you might do something like
		// Clipboard::setImage( copyWindowSurface() );
	}
#endif
}

void ClipboardBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::setMatricesWindow( getWindowSize() );
	gl::enableAlphaBlending();

	if( Clipboard::hasImage() ) {
		auto img = Clipboard::getImage();
		// be aware of a race condition here; the clipboard might have changed between hasImage() and getImage()
		// so we test for null 'img'
		if( img )
			gl::draw( gl::Texture::create( img ) );
	}
	else if( Clipboard::hasString() )
		gl::drawString( Clipboard::getString(), vec2( 0, getWindowCenter().y ) );
	else
		gl::drawString( "Clipboard contents unknown", vec2( 0, getWindowCenter().y ) );
}

CINDER_APP( ClipboardBasicApp, RendererGl )
<|endoftext|>


<commit_before>#include "disassembly/flowgraphutil_dyninst.hpp"
#include "disassembly/dyninstfeaturegenerator.hpp"

DyninstFeatureGenerator::DyninstFeatureGenerator(
  Dyninst::ParseAPI::Function* function) {
  BuildFlowgraph(function, &graph_);
  std::vector<address> nodes;
  graph_.GetNodes(&nodes);
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 1));
  }
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 2));
  }
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 3));
  }

  std::vector<MnemTuple> tuples;
  BuildMnemonicNgrams(function, &tuples);
  for (const auto& tuple : tuples) {
    mnem_tuples_.push(tuple);
  }
}

// Given a Dyninst function, create the set of instruction 3-grams.
void DyninstFeatureGenerator::BuildMnemonicNgrams(
  Dyninst::ParseAPI::Function* function,
  std::vector<MnemTuple>* tuples) const {
  std::vector<std::pair<address, std::string>> sequence;
  // Make sure that reading the mnemonics from Dyninst is synchronized.
  // TODO(thomasdullien): Latest DynInst should allow concurrent reading, so
  // the mutex is gone here. If crashes or problems come up, we need to re-
  // introduce it.
  {
    // Iterate over each block and extract the instructions.
    for (const auto& block : function->blocks()) {
      Dyninst::ParseAPI::Block::Insns block_instructions;
      block->getInsns(block_instructions);
      for (const auto& instruction : block_instructions) {
        auto& op = instruction.second->getOperation();
        sequence.push_back(std::make_pair(instruction.first, op.format()));
      }
    }
  }
  // Sort instructions by address;
  std::sort(sequence.begin(), sequence.end());
  // Construct the 3-tuples.
  for (uint64_t index = 0; index + 2 < sequence.size(); ++index) {
    tuples->emplace_back(std::make_tuple(
      sequence[index].second,
      sequence[index+1].second,
      sequence[index+2].second));
  }
}

bool DyninstFeatureGenerator::HasMoreSubgraphs() const {
  return !nodes_and_distance_.empty();
}

std::pair<Flowgraph*, address> DyninstFeatureGenerator::GetNextSubgraph() {
  address node = nodes_and_distance_.front().first;
  uint32_t distance = nodes_and_distance_.front().second;
  nodes_and_distance_.pop();
  return std::make_pair(graph_.GetSubgraph(node, distance, 30), node);
}

bool DyninstFeatureGenerator::HasMoreMnemonics() const {
  return !mnem_tuples_.empty();
}

MnemTuple DyninstFeatureGenerator::GetNextMnemTuple() {
  MnemTuple tuple = mnem_tuples_.front();
  mnem_tuples_.pop();
  return tuple;
}
<commit_msg>Added comments to the feature generator indicating that code needs to be removed<commit_after>#include "disassembly/flowgraphutil_dyninst.hpp"
#include "disassembly/dyninstfeaturegenerator.hpp"

DyninstFeatureGenerator::DyninstFeatureGenerator(
  Dyninst::ParseAPI::Function* function) {
  // TODO(thomasdullien): We should probably get rid of the Dyninst-specific
  // feature generator, and just eat the performance hit from building a
  // FlowgraphWithInstructions object directly. Hashing performance is not so
  // important, and it would remove unhealthy code duplication between this
  // file and flowgraphwithinstructions.cpp.
  BuildFlowgraph(function, &graph_);
  std::vector<address> nodes;
  graph_.GetNodes(&nodes);
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 1));
  }
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 2));
  }
  for (const auto& node : nodes) {
    nodes_and_distance_.push(std::make_pair(node, 3));
  }

  std::vector<MnemTuple> tuples;
  BuildMnemonicNgrams(function, &tuples);
  for (const auto& tuple : tuples) {
    mnem_tuples_.push(tuple);
  }
}

// Given a Dyninst function, create the set of instruction 3-grams.
void DyninstFeatureGenerator::BuildMnemonicNgrams(
  Dyninst::ParseAPI::Function* function,
  std::vector<MnemTuple>* tuples) const {
  std::vector<std::pair<address, std::string>> sequence;
  // Make sure that reading the mnemonics from Dyninst is synchronized.
  // TODO(thomasdullien): Latest DynInst should allow concurrent reading, so
  // the mutex is gone here. If crashes or problems come up, we need to re-
  // introduce it.
  {
    // Iterate over each block and extract the instructions.
    for (const auto& block : function->blocks()) {
      Dyninst::ParseAPI::Block::Insns block_instructions;
      block->getInsns(block_instructions);
      for (const auto& instruction : block_instructions) {
        auto& op = instruction.second->getOperation();
        sequence.push_back(std::make_pair(instruction.first, op.format()));
      }
    }
  }
  // Sort instructions by address;
  std::sort(sequence.begin(), sequence.end());
  // Construct the 3-tuples.
  for (uint64_t index = 0; index + 2 < sequence.size(); ++index) {
    tuples->emplace_back(std::make_tuple(
      sequence[index].second,
      sequence[index+1].second,
      sequence[index+2].second));
  }
}

bool DyninstFeatureGenerator::HasMoreSubgraphs() const {
  return !nodes_and_distance_.empty();
}

std::pair<Flowgraph*, address> DyninstFeatureGenerator::GetNextSubgraph() {
  address node = nodes_and_distance_.front().first;
  uint32_t distance = nodes_and_distance_.front().second;
  nodes_and_distance_.pop();
  return std::make_pair(graph_.GetSubgraph(node, distance, 30), node);
}

bool DyninstFeatureGenerator::HasMoreMnemonics() const {
  return !mnem_tuples_.empty();
}

MnemTuple DyninstFeatureGenerator::GetNextMnemTuple() {
  MnemTuple tuple = mnem_tuples_.front();
  mnem_tuples_.pop();
  return tuple;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//
#include "Sound.h"
#include "Player.h"
#include "NodeDefinition.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../audio/AudioEngine.h"

#include "../video/AsyncVideoDecoder.h"
#include "../video/FFMpegDecoder.h"

#include <iostream>
#include <sstream>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace boost::python;
using namespace std;

namespace avg {

NodeDefinition Sound::getNodeDefinition()
{
    return NodeDefinition("sound", Node::buildNode<Sound>)
        .extendDefinition(Node::getNodeDefinition())
        .addArg(Arg<string>("href", "", false, offsetof(Sound, m_href)))
        .addArg(Arg<bool>("loop", false, false, offsetof(Sound, m_bLoop)))
        ;
}

Sound::Sound (const ArgList& Args, Player * pPlayer, bool bFromXML)
    : Node(pPlayer),
      m_Filename(""),
      m_pEOFCallback(0),
      m_pDecoder(0),
      m_Volume(1.0),
      m_State(Unloaded)
{
    Args.setMembers(this);
    m_Filename = m_href;
    if (m_Filename != "") {
        initFilename(getPlayer(), m_Filename);
    }
    VideoDecoderPtr pSyncDecoder(new FFMpegDecoder());
    m_pDecoder = new AsyncVideoDecoder(pSyncDecoder);

    getPlayer()->registerFrameListener(this);
}

Sound::~Sound ()
{
    getPlayer()->unregisterFrameListener(this);
    if (m_pDecoder) {
        delete m_pDecoder;
        m_pDecoder = 0;
    }
    if (m_pEOFCallback) {
        Py_DECREF(m_pEOFCallback);
    }
}

long long Sound::getDuration() const
{
    if (m_State != Unloaded) {
        return m_pDecoder->getDuration();
    } else {
        AVG_TRACE(Logger::WARNING,
               "Error in Sound::getDuration: Sound not loaded.");
        return -1;
    }
}

long long Sound::getCurTime() const
{
    if (m_State != Unloaded) {
        return m_pDecoder->getCurTime();
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Sound::GetCurTime: Sound not loaded.");
        return -1;
    }
}

void Sound::seekToTime(long long Time)
{
    if (m_State != Unloaded) {
        seek(Time);
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Sound::SeekToTime: Sound "+getID()+" not loaded.");
    }
}

bool Sound::getLoop() const
{
    return m_bLoop;
}

void Sound::setEOFCallback(PyObject * pEOFCallback)
{
    if (m_pEOFCallback) {
        Py_DECREF(m_pEOFCallback);
    }
    Py_INCREF(pEOFCallback);
    m_pEOFCallback = pEOFCallback;
}

void Sound::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine)
{
    checkReload();
    Node::setRenderingEngines(pDisplayEngine, pAudioEngine);
    if (m_State != Unloaded) {
        SoundState state = m_State;
        m_State = Unloaded;
        changeSoundState(state);
    }
}

void Sound::disconnect()
{
    changeSoundState(Unloaded);
    Node::disconnect();
}

void Sound::play()
{
    changeSoundState(Playing);
}

void Sound::stop()
{
    changeSoundState(Unloaded);
}

void Sound::pause()
{
    changeSoundState(Paused);
}

const string& Sound::getHRef() const
{
    return m_Filename;
}

void Sound::setHRef(const string& href)
{
    m_href = href;
    checkReload();
}

double Sound::getVolume()
{
    return m_Volume;
}

void Sound::setVolume(double Volume)
{
    if (Volume < 0) {
        Volume = 0;
    }
    m_Volume = Volume;
    if (m_pDecoder) {
        m_pDecoder->setVolume(Volume);
    }
}

void Sound::checkReload()
{
    string fileName (m_href);
    if (m_href != "") {
        initFilename(getPlayer(), fileName);
        if (fileName != m_Filename) {
            SoundState oldState = m_State;
            changeSoundState(Unloaded);
            m_Filename = fileName;
            if (oldState != Unloaded) {
                changeSoundState(Paused);
            }
        }
    } else {
        changeSoundState(Unloaded);
        m_Filename = "";
    }
}

string Sound::getTypeStr ()
{
    return "Sound";
}

void Sound::onFrameEnd()
{
    if (m_State == Playing && m_pDecoder->isEOF(SS_AUDIO)) {
        onEOF();
    }
}

int Sound::fillAudioBuffer(AudioBufferPtr pBuffer)
{
    if (m_State == Playing) {
        return m_pDecoder->fillAudioBuffer(pBuffer);
    } else {
        return 0;
    }
}

void Sound::changeSoundState(SoundState NewSoundState)
{
    if (isDisplayAvailable()) {
        long long CurTime = getPlayer()->getFrameTime();
        if (NewSoundState != m_State) {
            if (m_State == Unloaded) {
                m_StartTime = CurTime;
                m_PauseTime = 0;
                open();
            }
            if (NewSoundState == Paused) {
                m_PauseStartTime = CurTime;
            } else if (NewSoundState == Playing && m_State == Paused) {
                m_PauseTime += CurTime-m_PauseStartTime;
            } else if (NewSoundState == Unloaded) {
                close();
            }
        }
    }
    m_State = NewSoundState;
}

void Sound::seek(long long DestTime)
{
    m_pDecoder->seek(DestTime);
    m_StartTime = getPlayer()->getFrameTime() - DestTime;
    m_PauseTime = 0;
    m_PauseStartTime = getPlayer()->getFrameTime();
}

void Sound::open()
{
    m_pDecoder->open(m_Filename, getAudioEngine()->getParams(), OGL_NONE, true);
    m_pDecoder->setVolume(m_Volume);
    if (getAudioEngine()) {
        getAudioEngine()->addSource(this);
    }
}

void Sound::close()
{
    if (getAudioEngine()) {
        getAudioEngine()->removeSource(this);
    }
    m_pDecoder->close();
}

void Sound::onEOF()
{
    seek(0);
    if (!m_bLoop) {
        changeSoundState(Paused);
    }
    if (m_pEOFCallback) {
        PyObject * arglist = Py_BuildValue("()");
        PyObject * result = PyEval_CallObject(m_pEOFCallback, arglist);
        Py_DECREF(arglist);
        if (!result) {
            throw error_already_set();
        }
        Py_DECREF(result);
    }
}

}
<commit_msg>Added sound volume xml attribute.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//
#include "Sound.h"
#include "Player.h"
#include "NodeDefinition.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../audio/AudioEngine.h"

#include "../video/AsyncVideoDecoder.h"
#include "../video/FFMpegDecoder.h"

#include <iostream>
#include <sstream>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace boost::python;
using namespace std;

namespace avg {

NodeDefinition Sound::getNodeDefinition()
{
    return NodeDefinition("sound", Node::buildNode<Sound>)
        .extendDefinition(Node::getNodeDefinition())
        .addArg(Arg<string>("href", "", false, offsetof(Sound, m_href)))
        .addArg(Arg<bool>("loop", false, false, offsetof(Sound, m_bLoop)))
        .addArg(Arg<double>("volume", 1.0, false, offsetof(Sound, m_Volume)))
        ;
}

Sound::Sound (const ArgList& Args, Player * pPlayer, bool bFromXML)
    : Node(pPlayer),
      m_Filename(""),
      m_pEOFCallback(0),
      m_pDecoder(0),
      m_Volume(1.0),
      m_State(Unloaded)
{
    Args.setMembers(this);
    m_Filename = m_href;
    if (m_Filename != "") {
        initFilename(getPlayer(), m_Filename);
    }
    VideoDecoderPtr pSyncDecoder(new FFMpegDecoder());
    m_pDecoder = new AsyncVideoDecoder(pSyncDecoder);

    getPlayer()->registerFrameListener(this);
}

Sound::~Sound ()
{
    getPlayer()->unregisterFrameListener(this);
    if (m_pDecoder) {
        delete m_pDecoder;
        m_pDecoder = 0;
    }
    if (m_pEOFCallback) {
        Py_DECREF(m_pEOFCallback);
    }
}

long long Sound::getDuration() const
{
    if (m_State != Unloaded) {
        return m_pDecoder->getDuration();
    } else {
        AVG_TRACE(Logger::WARNING,
               "Error in Sound::getDuration: Sound not loaded.");
        return -1;
    }
}

long long Sound::getCurTime() const
{
    if (m_State != Unloaded) {
        return m_pDecoder->getCurTime();
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Sound::GetCurTime: Sound not loaded.");
        return -1;
    }
}

void Sound::seekToTime(long long Time)
{
    if (m_State != Unloaded) {
        seek(Time);
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Sound::SeekToTime: Sound "+getID()+" not loaded.");
    }
}

bool Sound::getLoop() const
{
    return m_bLoop;
}

void Sound::setEOFCallback(PyObject * pEOFCallback)
{
    if (m_pEOFCallback) {
        Py_DECREF(m_pEOFCallback);
    }
    Py_INCREF(pEOFCallback);
    m_pEOFCallback = pEOFCallback;
}

void Sound::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine)
{
    checkReload();
    Node::setRenderingEngines(pDisplayEngine, pAudioEngine);
    if (m_State != Unloaded) {
        SoundState state = m_State;
        m_State = Unloaded;
        changeSoundState(state);
    }
}

void Sound::disconnect()
{
    changeSoundState(Unloaded);
    Node::disconnect();
}

void Sound::play()
{
    changeSoundState(Playing);
}

void Sound::stop()
{
    changeSoundState(Unloaded);
}

void Sound::pause()
{
    changeSoundState(Paused);
}

const string& Sound::getHRef() const
{
    return m_Filename;
}

void Sound::setHRef(const string& href)
{
    m_href = href;
    checkReload();
}

double Sound::getVolume()
{
    return m_Volume;
}

void Sound::setVolume(double Volume)
{
    if (Volume < 0) {
        Volume = 0;
    }
    m_Volume = Volume;
    if (m_pDecoder) {
        m_pDecoder->setVolume(Volume);
    }
}

void Sound::checkReload()
{
    string fileName (m_href);
    if (m_href != "") {
        initFilename(getPlayer(), fileName);
        if (fileName != m_Filename) {
            SoundState oldState = m_State;
            changeSoundState(Unloaded);
            m_Filename = fileName;
            if (oldState != Unloaded) {
                changeSoundState(Paused);
            }
        }
    } else {
        changeSoundState(Unloaded);
        m_Filename = "";
    }
}

string Sound::getTypeStr ()
{
    return "Sound";
}

void Sound::onFrameEnd()
{
    if (m_State == Playing && m_pDecoder->isEOF(SS_AUDIO)) {
        onEOF();
    }
}

int Sound::fillAudioBuffer(AudioBufferPtr pBuffer)
{
    if (m_State == Playing) {
        return m_pDecoder->fillAudioBuffer(pBuffer);
    } else {
        return 0;
    }
}

void Sound::changeSoundState(SoundState NewSoundState)
{
    if (isDisplayAvailable()) {
        long long CurTime = getPlayer()->getFrameTime();
        if (NewSoundState != m_State) {
            if (m_State == Unloaded) {
                m_StartTime = CurTime;
                m_PauseTime = 0;
                open();
            }
            if (NewSoundState == Paused) {
                m_PauseStartTime = CurTime;
            } else if (NewSoundState == Playing && m_State == Paused) {
                m_PauseTime += CurTime-m_PauseStartTime;
            } else if (NewSoundState == Unloaded) {
                close();
            }
        }
    }
    m_State = NewSoundState;
}

void Sound::seek(long long DestTime)
{
    m_pDecoder->seek(DestTime);
    m_StartTime = getPlayer()->getFrameTime() - DestTime;
    m_PauseTime = 0;
    m_PauseStartTime = getPlayer()->getFrameTime();
}

void Sound::open()
{
    m_pDecoder->open(m_Filename, getAudioEngine()->getParams(), OGL_NONE, true);
    m_pDecoder->setVolume(m_Volume);
    if (getAudioEngine()) {
        getAudioEngine()->addSource(this);
    }
}

void Sound::close()
{
    if (getAudioEngine()) {
        getAudioEngine()->removeSource(this);
    }
    m_pDecoder->close();
}

void Sound::onEOF()
{
    seek(0);
    if (!m_bLoop) {
        changeSoundState(Paused);
    }
    if (m_pEOFCallback) {
        PyObject * arglist = Py_BuildValue("()");
        PyObject * result = PyEval_CallObject(m_pEOFCallback, arglist);
        Py_DECREF(arglist);
        if (!result) {
            throw error_already_set();
        }
        Py_DECREF(result);
    }
}

}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Video.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "FFMpegDecoder.h"
#include "ISurface.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"
#include "../graphics/Filterflipuv.h"

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

bool Video::m_bInitialized = false;

Video::Video ()
    : m_href(""),
      m_Filename(""),
      m_bLoop(false),
      m_bEOF(false),
      m_pDecoder(0)
{
}

Video::Video (const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_Filename(""),
      m_bEOF(false),
      m_pDecoder(0)
{
    m_href = getDefaultedStringAttr (xmlNode, "href", "");
    m_bLoop = getDefaultedBoolAttr (xmlNode, "loop", false);
    m_Filename = m_href;
    if (m_Filename != "") {
        initFilename(getPlayer(), m_Filename);
    }
}

Video::~Video ()
{
    if (m_pDecoder) {
        delete m_pDecoder;
    }
}

int Video::getNumFrames() const
{
    if (getVideoState() != Unloaded) {
        return m_pDecoder->getNumFrames();
    } else {
        AVG_TRACE(Logger::WARNING,
               "Error in Video::getNumFrames: Video not loaded.");
        return -1;
    }
}

int Video::getCurFrame() const
{
    if (getVideoState() != Unloaded) {
        return m_CurFrame;
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Video::GetCurFrame: Video not loaded.");
        return -1;
    }
}

void Video::seekToFrame(int num)
{
    if (getVideoState() != Unloaded) {
        seek(num);
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Video::SeekToFrame: Video "+getID()+" not loaded.");
    }
}

bool Video::getLoop() const
{
    return m_bLoop;
}

void Video::setDisplayEngine(DisplayEngine * pEngine)
{
    m_pDecoder = new FFMpegDecoder();
    VideoBase::setDisplayEngine(pEngine);
}

void Video::disconnect()
{
    stop();
    VideoBase::disconnect();
    delete m_pDecoder;
    m_pDecoder = 0;
}

const string& Video::getHRef() const
{
    return m_Filename;
}

void Video::setHRef(const string& href)
{
    string fileName (href);
    m_href = href;
    if (m_href != "") {
        initFilename(getPlayer(), fileName);
        if (fileName != m_Filename) {
            changeVideoState(Unloaded);
            m_Filename = fileName;
            changeVideoState(Paused);
        }
    } else {
        changeVideoState(Unloaded);
        m_Filename = "";
    }
}

string Video::getTypeStr ()
{
    return "Video";
}

void Video::seek(int DestFrame)
{
    m_pDecoder->seek(DestFrame);
    m_CurFrame = DestFrame;
    setFrameAvailable(false);
}

void Video::open(IntPoint* pSize, DisplayEngine::YCbCrMode ycbcrMode)
{
    m_CurFrame = 0;
    m_pDecoder->open(m_Filename, ycbcrMode);
    *pSize = m_pDecoder->getSize();
    m_bEOF = false;
}

void Video::close()
{
    m_pDecoder->close();
}

PixelFormat Video::getPixelFormat()
{
    return m_pDecoder->getPixelFormat();
}

double Video::getFPS()
{
    return m_pDecoder->getFPS();
}

static ProfilingZone RenderProfilingZone("    Video::render");

bool Video::renderToSurface(ISurface * pSurface)
{
    ScopeTimer Timer(RenderProfilingZone);
    DisplayEngine::YCbCrMode ycbcrMode = getEngine()->getYCbCrMode();
    PixelFormat PF = m_pDecoder->getPixelFormat();
    if (PF == YCbCr420p || PF == YCbCrJ420p) {
        m_bEOF = m_pDecoder->renderToYCbCr420p(pSurface->lockBmp(0),
                pSurface->lockBmp(1), pSurface->lockBmp(2));
    } else {
        BitmapPtr pBmp = pSurface->lockBmp();
        m_bEOF = m_pDecoder->renderToBmp(pBmp);
        if (ycbcrMode== DisplayEngine::OGL_MESA) {
            FilterFlipUV().applyInPlace(pBmp);
        }
    }
    pSurface->unlockBmps();
    if (!m_bEOF) {
        getEngine()->surfaceChanged(pSurface);
    }
    if (getVideoState() == Playing) {
        advancePlayback();
    }
    return !m_bEOF;
}

bool Video::canRenderToBackbuffer(int BPP)
{
    return m_pDecoder->canRenderToBuffer(BPP);
}

void Video::advancePlayback()
{
    m_CurFrame++;
    if (m_bEOF) {
        if (m_bLoop) {
            seek(0);
        } else {
            changeVideoState(Paused);
        }
    }
}

}
<commit_msg>Fixed mesa video decoding.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Video.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "FFMpegDecoder.h"
#include "ISurface.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"
#include "../graphics/Filterflipuv.h"

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

bool Video::m_bInitialized = false;

Video::Video ()
    : m_href(""),
      m_Filename(""),
      m_bLoop(false),
      m_bEOF(false),
      m_pDecoder(0)
{
}

Video::Video (const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_Filename(""),
      m_bEOF(false),
      m_pDecoder(0)
{
    m_href = getDefaultedStringAttr (xmlNode, "href", "");
    m_bLoop = getDefaultedBoolAttr (xmlNode, "loop", false);
    m_Filename = m_href;
    if (m_Filename != "") {
        initFilename(getPlayer(), m_Filename);
    }
}

Video::~Video ()
{
    if (m_pDecoder) {
        delete m_pDecoder;
    }
}

int Video::getNumFrames() const
{
    if (getVideoState() != Unloaded) {
        return m_pDecoder->getNumFrames();
    } else {
        AVG_TRACE(Logger::WARNING,
               "Error in Video::getNumFrames: Video not loaded.");
        return -1;
    }
}

int Video::getCurFrame() const
{
    if (getVideoState() != Unloaded) {
        return m_CurFrame;
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Video::GetCurFrame: Video not loaded.");
        return -1;
    }
}

void Video::seekToFrame(int num)
{
    if (getVideoState() != Unloaded) {
        seek(num);
    } else {
        AVG_TRACE(Logger::WARNING,
                "Error in Video::SeekToFrame: Video "+getID()+" not loaded.");
    }
}

bool Video::getLoop() const
{
    return m_bLoop;
}

void Video::setDisplayEngine(DisplayEngine * pEngine)
{
    m_pDecoder = new FFMpegDecoder();
    VideoBase::setDisplayEngine(pEngine);
}

void Video::disconnect()
{
    stop();
    VideoBase::disconnect();
    delete m_pDecoder;
    m_pDecoder = 0;
}

const string& Video::getHRef() const
{
    return m_Filename;
}

void Video::setHRef(const string& href)
{
    string fileName (href);
    m_href = href;
    if (m_href != "") {
        initFilename(getPlayer(), fileName);
        if (fileName != m_Filename) {
            changeVideoState(Unloaded);
            m_Filename = fileName;
            changeVideoState(Paused);
        }
    } else {
        changeVideoState(Unloaded);
        m_Filename = "";
    }
}

string Video::getTypeStr ()
{
    return "Video";
}

void Video::seek(int DestFrame)
{
    m_pDecoder->seek(DestFrame);
    m_CurFrame = DestFrame;
    setFrameAvailable(false);
}

void Video::open(IntPoint* pSize, DisplayEngine::YCbCrMode ycbcrMode)
{
    m_CurFrame = 0;
    m_pDecoder->open(m_Filename, ycbcrMode);
    *pSize = m_pDecoder->getSize();
    m_bEOF = false;
}

void Video::close()
{
    m_pDecoder->close();
}

PixelFormat Video::getPixelFormat()
{
    return m_pDecoder->getPixelFormat();
}

double Video::getFPS()
{
    return m_pDecoder->getFPS();
}

static ProfilingZone RenderProfilingZone("    Video::render");

bool Video::renderToSurface(ISurface * pSurface)
{
    ScopeTimer Timer(RenderProfilingZone);
    DisplayEngine::YCbCrMode ycbcrMode = getEngine()->getYCbCrMode();
    PixelFormat PF = m_pDecoder->getPixelFormat();
    if (PF == YCbCr420p || PF == YCbCrJ420p) {
        m_bEOF = m_pDecoder->renderToYCbCr420p(pSurface->lockBmp(0),
                pSurface->lockBmp(1), pSurface->lockBmp(2));
    } else {
        BitmapPtr pBmp = pSurface->lockBmp();
        m_bEOF = m_pDecoder->renderToBmp(pBmp);
        if (ycbcrMode == DisplayEngine::OGL_MESA && pBmp->getPixelFormat() == YCbCr422) {
            FilterFlipUV().applyInPlace(pBmp);
        }
    }
    pSurface->unlockBmps();
    if (!m_bEOF) {
        getEngine()->surfaceChanged(pSurface);
    }
    if (getVideoState() == Playing) {
        advancePlayback();
    }
    return !m_bEOF;
}

bool Video::canRenderToBackbuffer(int BPP)
{
    return m_pDecoder->canRenderToBuffer(BPP);
}

void Video::advancePlayback()
{
    m_CurFrame++;
    if (m_bEOF) {
        if (m_bLoop) {
            seek(0);
        } else {
            changeVideoState(Paused);
        }
    }
}

}
<|endoftext|>


<commit_before>#ifndef UTILS_HPP
#define UTILS_HPP

#include <glm/glm.hpp>

#include <SDL.h>
#include <SDL_ttf.h>

#include <cmath>
#include <string>
#include <iostream>

namespace trac0r {

SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,
                       const SDL_Color &color) {
    auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);
    auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);
    SDL_FreeSurface(text_surface);

    return text_tex;
}

void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {
    int tex_width;
    int tex_height;

    SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);
    SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};
    SDL_RenderCopy(renderer, texture, 0, &rect);
}

// Möller-Trumbore intersection algorithm
// (see https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm)
bool intersect_ray_triangle(const glm::vec3 &origin, const glm::vec3 &dir, const glm::vec3 &v0, glm::vec3 &v1, glm::vec3 &v2, float &dist) {
    // Calculate edges of triangle from v0.
    auto e0 = v1 - v0;
    auto e1 = v2 - v0;

    // Calculate determinant to check whether the ray is in the newly calculated plane made up from e0 and e1.
    auto pvec = glm::cross(dir, e1);
    auto det = glm::dot(e0, pvec);

    // Check whether determinant is close to 0. If that is the case, the ray is in the same plane as the triangle itself which means that they can't collide. This effectively disables backface culling for which we would instead only check whether det < epsilon.
    auto epsilon = std::numeric_limits<float>::epsilon();
    if (det > -epsilon && det < epsilon)
        return false;

    auto inv_det = 1.f / det;

    // Calculate distance from v0 to ray origin
    auto tvec = origin - v0;

    // Calculate u parameter and test bound
    auto u = glm::dot(tvec, pvec) * inv_det;

    // Check whether the intersection lies outside of the triangle
    if (u < 0.f || u > 1.f)
        return false;

    // Prepare to test v parameter
    auto qvec = glm::cross(tvec, e0);

    // Calculate v parameter and test bound
    auto v = glm::dot(dir, qvec) * inv_det;

    // Check whether the intersection lies outside of the triangle
    if (v < 0.f || u + v > 1.f)
        return false;

    auto t = glm::dot(e1, qvec) * inv_det;

    if (t > epsilon) {
        dist = t;
        return true;
    }

    // If we end up here, there was no hit
    return false;
}

uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
    uint32_t new_color = a << 24 | r << 16 | g << 8 | b;
    return new_color;
}

uint32_t pack_color_argb(glm::i8vec4 color) {
    uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;
    return new_color;
}

uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
    uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;
    return packed_color;
}

uint32_t pack_color_rgba(glm::i8vec4 color) {
    uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;
    return packed_color;
}

uint32_t pack_color_rgba(glm::vec4 color) {
    uint32_t packed_color = int(std::round(color.r * 255)) << 24 |
                            int(std::round(color.g * 255)) << 16 |
                            int(std::round(color.b * 255)) << 8 | int(std::round(color.a * 255));
    return packed_color;
}

uint32_t pack_color_argb(glm::vec4 color) {
    uint32_t packed_color = int(std::round(color.a * 255)) << 24 |
                            int(std::round(color.r * 255)) << 16 |
                            int(std::round(color.g * 255)) << 8 | int(std::round(color.b * 255));
    return packed_color;
}

glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {
    glm::i8vec4 unpacked_color;
    unpacked_color.r = packed_color_rgba >> 24 & 0xFF;
    unpacked_color.g = packed_color_rgba >> 16 & 0xFF;
    unpacked_color.b = packed_color_rgba >> 8 & 0xFF;
    unpacked_color.a = packed_color_rgba & 0xFF;
    return unpacked_color;
}

glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {
    glm::i8vec4 unpacked_color;
    unpacked_color.a = packed_color_argb >> 24 & 0xFF;
    unpacked_color.r = packed_color_argb >> 16 & 0xFF;
    unpacked_color.g = packed_color_argb >> 8 & 0xFF;
    unpacked_color.b = packed_color_argb & 0xFF;
    return unpacked_color;
}

glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {
    glm::i8vec4 unpacked_color;
    unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) / 255.f;
    unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) / 255.f;
    unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) / 255.f;
    unpacked_color.a = (packed_color_rgba & 0xFF) / 255.f;
    return unpacked_color;
}

glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {
    glm::vec4 unpacked_color;
    unpacked_color.a = (packed_color_argb >> 24 & 0xFF) / 255.f;
    unpacked_color.r = (packed_color_argb >> 16 & 0xFF) / 255.f;
    unpacked_color.g = (packed_color_argb >> 8 & 0xFF) / 255.f;
    unpacked_color.b = (packed_color_argb & 0xFF) / 255.f;
    return unpacked_color;
}
}

#endif /* end of include guard: UTILS_HPP */
<commit_msg>Better formatting<commit_after>#ifndef UTILS_HPP
#define UTILS_HPP

#include <glm/glm.hpp>

#include <SDL.h>
#include <SDL_ttf.h>

#include <cmath>
#include <string>
#include <iostream>

namespace trac0r {

SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,
                       const SDL_Color &color) {
    auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);
    auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);
    SDL_FreeSurface(text_surface);

    return text_tex;
}

void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {
    int tex_width;
    int tex_height;

    SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);
    SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};
    SDL_RenderCopy(renderer, texture, 0, &rect);
}

// Möller-Trumbore intersection algorithm
// (see https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm)
bool intersect_ray_triangle(const glm::vec3 &origin, const glm::vec3 &dir, const glm::vec3 &v0,
                            glm::vec3 &v1, glm::vec3 &v2, float &dist) {
    // Calculate edges of triangle from v0.
    auto e0 = v1 - v0;
    auto e1 = v2 - v0;

    // Calculate determinant to check whether the ray is in the newly calculated plane made up from
    // e0 and e1.
    auto pvec = glm::cross(dir, e1);
    auto det = glm::dot(e0, pvec);

    // Check whether determinant is close to 0. If that is the case, the ray is in the same plane as
    // the triangle itself which means that they can't collide. This effectively disables backface
    // culling for which we would instead only check whether det < epsilon.
    auto epsilon = std::numeric_limits<float>::epsilon();
    if (det > -epsilon && det < epsilon)
        return false;

    auto inv_det = 1.f / det;

    // Calculate distance from v0 to ray origin
    auto tvec = origin - v0;

    // Calculate u parameter and test bound
    auto u = glm::dot(tvec, pvec) * inv_det;

    // Check whether the intersection lies outside of the triangle
    if (u < 0.f || u > 1.f)
        return false;

    // Prepare to test v parameter
    auto qvec = glm::cross(tvec, e0);

    // Calculate v parameter and test bound
    auto v = glm::dot(dir, qvec) * inv_det;

    // Check whether the intersection lies outside of the triangle
    if (v < 0.f || u + v > 1.f)
        return false;

    auto t = glm::dot(e1, qvec) * inv_det;

    if (t > epsilon) {
        dist = t;
        return true;
    }

    // If we end up here, there was no hit
    return false;
}

uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
    uint32_t new_color = a << 24 | r << 16 | g << 8 | b;
    return new_color;
}

uint32_t pack_color_argb(glm::i8vec4 color) {
    uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;
    return new_color;
}

uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
    uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;
    return packed_color;
}

uint32_t pack_color_rgba(glm::i8vec4 color) {
    uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;
    return packed_color;
}

uint32_t pack_color_rgba(glm::vec4 color) {
    uint32_t packed_color = int(std::round(color.r * 255)) << 24 |
                            int(std::round(color.g * 255)) << 16 |
                            int(std::round(color.b * 255)) << 8 | int(std::round(color.a * 255));
    return packed_color;
}

uint32_t pack_color_argb(glm::vec4 color) {
    uint32_t packed_color = int(std::round(color.a * 255)) << 24 |
                            int(std::round(color.r * 255)) << 16 |
                            int(std::round(color.g * 255)) << 8 | int(std::round(color.b * 255));
    return packed_color;
}

glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {
    glm::i8vec4 unpacked_color;
    unpacked_color.r = packed_color_rgba >> 24 & 0xFF;
    unpacked_color.g = packed_color_rgba >> 16 & 0xFF;
    unpacked_color.b = packed_color_rgba >> 8 & 0xFF;
    unpacked_color.a = packed_color_rgba & 0xFF;
    return unpacked_color;
}

glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {
    glm::i8vec4 unpacked_color;
    unpacked_color.a = packed_color_argb >> 24 & 0xFF;
    unpacked_color.r = packed_color_argb >> 16 & 0xFF;
    unpacked_color.g = packed_color_argb >> 8 & 0xFF;
    unpacked_color.b = packed_color_argb & 0xFF;
    return unpacked_color;
}

glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {
    glm::i8vec4 unpacked_color;
    unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) / 255.f;
    unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) / 255.f;
    unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) / 255.f;
    unpacked_color.a = (packed_color_rgba & 0xFF) / 255.f;
    return unpacked_color;
}

glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {
    glm::vec4 unpacked_color;
    unpacked_color.a = (packed_color_argb >> 24 & 0xFF) / 255.f;
    unpacked_color.r = (packed_color_argb >> 16 & 0xFF) / 255.f;
    unpacked_color.g = (packed_color_argb >> 8 & 0xFF) / 255.f;
    unpacked_color.b = (packed_color_argb & 0xFF) / 255.f;
    return unpacked_color;
}
}

#endif /* end of include guard: UTILS_HPP */
<|endoftext|>


<commit_before>#include "worker.hpp"

using namespace headers;

static bool IPv4HdrVerification(ipv4* ipv4_hdr, uint16_t f_len){
	// Do header verification (rfc 1812)
	// Step 1
	if(f_len < 20){
		return false;
	}

	// Step 2
	if(IPv4HdrChecksum(ipv4_hdr) != ipv4_hdr->checksum){
		logDebug("IPv4 verification failed");
		return false;
	}

	// Step 3
	if(ipv4_hdr->version() != 4){
		return false;
	}

	// Step 4
	if(ipv4_hdr->ihl() < 5){
		return false;
	}

	// Step 5
	if(ntohs(ipv4_hdr->total_length) < ipv4_hdr->ihl()*4){
		return false;
	}

	// Check for TTL > 1
	if(ipv4_hdr->ttl <= 1){
		return false;
	}

	return true;
};

void Worker::process(){
	// TODO
	// ICMP STUFF

	frame f;
	while(1){
		if(!ingressQ->try_dequeue(f)){
			return;
		}

		logDebug("Worker::process Processing packet now\n");

		// Cast all the things
		ether* ether_hdr = reinterpret_cast<ether*>(f.buf_ptr);
		ipv4* ipv4_hdr = reinterpret_cast<ipv4*>(f.buf_ptr + sizeof(ether));

		//Interface& interface = interfaces->at(f.iface & frame::IFACE_ID);
		shared_ptr<Interface> iface_ptr;
		for(auto i : interfaces){
			if(i->netmapIndex == (f.iface & frame::IFACE_ID)){
				iface_ptr = i;
				break;
			}
		}
		if(iface_ptr == nullptr){
			fatal("Worker::process something went wrong: netmap interface not found in netlink context");
		}

		if(ether_hdr->ethertype == htons(0x0800)){
			if(!IPv4HdrVerification(ipv4_hdr, f.len)){
				logDebug("Worker::process Discarding frame - Header verification failed");
				f.iface = frame::IFACE_DISCARD;
			} else {
				// Check if the packet is targeted at the router
				if(count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(), ipv4_hdr->d_ip)){
					logDebug("Worker::process Frame is destined at the host");
					f.iface |= frame::IFACE_HOST;
					continue;
				}

				// From here on, all checks were successful
				ipv4_hdr->ttl--;
				ipv4_hdr->checksum++;

				// Route the packet
				nh_index index = cur_lpm->route(ntohl(ipv4_hdr->d_ip));

				// Check if the index is invalid
				if(index == RoutingTable::route::NH_INVALID){
					fatal("Worker::process next hop is invalid");
				} else {
					logDebug("Worker::process frame will use next hop " + int2strHex(index));
				}

				// Look up the next hop
				ARPTable::nextHop nh;
				if(!(index & RoutingTable::route::NH_DIRECTLY_CONNECTED)){
					nh = cur_arp_table->nextHops[index];
				} else {
					//nh = cur_arp_table->directlyConnected.at(ntohl(ipv4_hdr->d_ip));
					auto it = cur_arp_table->directlyConnected.find(ntohl(ipv4_hdr->d_ip));
					if(it != cur_arp_table->directlyConnected.end()){
						nh = it->second;
					} else {
						nh.mac = ARPTable::nextHop::invalidMac;
						nh.netmapInterface = index ^ RoutingTable::route::NH_DIRECTLY_CONNECTED;
					}
				}

				// Is the next hop valid?
				if(!nh){
					// Let the manager handle this
					logDebug("Worker::process There is no MAC for this IP ("
							+ ip_to_str(htonl(ipv4_hdr->d_ip)) + ")");
					logDebug("Worker::process Interface for ARP: " + int2str(nh.netmapInterface));
					if(nh.netmapInterface == uint16_t_max){
						abort();
					}
					f.iface = nh.netmapInterface;
					f.iface |= frame::IFACE_NOMAC;
				} else {
					// Set MAC addresses
					logDebug("Worker::process There is nothing special about this frame");
					ether_hdr->d_mac = nh.mac;
					ether_hdr->s_mac = iface_ptr->mac;
					f.iface = nh.netmapInterface;
				}
				egressQ->try_enqueue(f);
			}
		} else if(ether_hdr->ethertype == htons(0x0806)){
			logDebug("Worker::process This frame contains some kind of ARP payload");
			f.iface |= frame::IFACE_ARP;
			egressQ->try_enqueue(f);
		} else {
			// This router currently doesn't support L3 Protocol $foo
			std::stringstream stream;
			stream << std::hex << htons(ether_hdr->ethertype);
			logDebug("Worker::process L3 protocol is currently not supported, given: "
					+ stream.str());
			f.iface = frame::IFACE_DISCARD;
			egressQ->try_enqueue(f);
		}
	}
};
<commit_msg>use bulk dequeue in worker<commit_after>#include "worker.hpp"

using namespace headers;

static bool IPv4HdrVerification(ipv4* ipv4_hdr, uint16_t f_len){
	// Do header verification (rfc 1812)
	// Step 1
	if(f_len < 20){
		return false;
	}

	// Step 2
	if(IPv4HdrChecksum(ipv4_hdr) != ipv4_hdr->checksum){
		logDebug("IPv4 verification failed");
		return false;
	}

	// Step 3
	if(ipv4_hdr->version() != 4){
		return false;
	}

	// Step 4
	if(ipv4_hdr->ihl() < 5){
		return false;
	}

	// Step 5
	if(ntohs(ipv4_hdr->total_length) < ipv4_hdr->ihl()*4){
		return false;
	}

	// Check for TTL > 1
	if(ipv4_hdr->ttl <= 1){
		return false;
	}

	return true;
};

void Worker::process(){
	// TODO
	// ICMP STUFF

#define WORKER_BULK_SIZE 64
	frame f[WORKER_BULK_SIZE];

	while(1){
		size_t numFrames = ingressQ->try_dequeue_bulk(f, WORKER_BULK_SIZE);
		if(!numFrames){
			return;
		}

		for(size_t i=0; i<numFrames; i++){
			logDebug("Worker::process Processing packet now\n");

			// Cast all the things
			ether* ether_hdr = reinterpret_cast<ether*>(f[i].buf_ptr);
			ipv4* ipv4_hdr = reinterpret_cast<ipv4*>(f[i].buf_ptr + sizeof(ether));

			//Interface& interface = interfaces->at(f.iface & frame::IFACE_ID);
			shared_ptr<Interface> iface_ptr;
			for(auto iface : interfaces){
				if(iface->netmapIndex == (f[i].iface & frame::IFACE_ID)){
					iface_ptr = iface;
					break;
				}
			}
			if(iface_ptr == nullptr){
				fatal("Worker::process something went wrong: netmap interface not found in netlink context");
			}

			if(ether_hdr->ethertype == htons(0x0800)){
				if(!IPv4HdrVerification(ipv4_hdr, f[i].len)){
					logDebug("Worker::process Discarding frame - Header verification failed");
					f[i].iface = frame::IFACE_DISCARD;
				} else {
					// Check if the packet is targeted at the router
					if(count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(), ipv4_hdr->d_ip)){
						logDebug("Worker::process Frame is destined at the host");
						f[i].iface |= frame::IFACE_HOST;
						continue;
					}

					// From here on, all checks were successful
					ipv4_hdr->ttl--;
					ipv4_hdr->checksum++;

					// Route the packet
					nh_index index = cur_lpm->route(ntohl(ipv4_hdr->d_ip));

					// Check if the index is invalid
					if(index == RoutingTable::route::NH_INVALID){
						fatal("Worker::process next hop is invalid");
					} else {
						logDebug("Worker::process frame will use next hop " + int2strHex(index));
					}

					// Look up the next hop
					ARPTable::nextHop nh;
					if(!(index & RoutingTable::route::NH_DIRECTLY_CONNECTED)){
						nh = cur_arp_table->nextHops[index];
					} else {
						//nh = cur_arp_table->directlyConnected.at(ntohl(ipv4_hdr->d_ip));
						auto it = cur_arp_table->directlyConnected.find(ntohl(ipv4_hdr->d_ip));
						if(it != cur_arp_table->directlyConnected.end()){
							nh = it->second;
						} else {
							nh.mac = ARPTable::nextHop::invalidMac;
							nh.netmapInterface = index ^ RoutingTable::route::NH_DIRECTLY_CONNECTED;
						}
					}

					// Is the next hop valid?
					if(!nh){
						// Let the manager handle this
						logDebug("Worker::process There is no MAC for this IP ("
								+ ip_to_str(htonl(ipv4_hdr->d_ip)) + ")");
						logDebug("Worker::process Interface for ARP: " + int2str(nh.netmapInterface));
						if(nh.netmapInterface == uint16_t_max){
							abort();
						}
						f[i].iface = nh.netmapInterface;
						f[i].iface |= frame::IFACE_NOMAC;
					} else {
						// Set MAC addresses
						logDebug("Worker::process There is nothing special about this frame");
						ether_hdr->d_mac = nh.mac;
						ether_hdr->s_mac = iface_ptr->mac;
						f[i].iface = nh.netmapInterface;
					}
					egressQ->try_enqueue(f[i]);
				}
			} else if(ether_hdr->ethertype == htons(0x0806)){
				logDebug("Worker::process This frame contains some kind of ARP payload");
				f[i].iface |= frame::IFACE_ARP;
				egressQ->try_enqueue(f[i]);
			} else {
				// This router currently doesn't support L3 Protocol $foo
				std::stringstream stream;
				stream << std::hex << htons(ether_hdr->ethertype);
				logDebug("Worker::process L3 protocol is currently not supported, given: "
						+ stream.str());
				f[i].iface = frame::IFACE_DISCARD;
				egressQ->try_enqueue(f[i]);
			}
		}
	}
};
<|endoftext|>