<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// $Id$

//-----------------------------------------------------------------------------
/// \class AliMUONVDigitStore
///
/// Interface for a digit (or sdigit) container
///
/// It offers methods to Add, Find and Remove single elements, and
/// can create iterators to loop over (part of) the elements.
///
/// \author Laurent Aphecetche, Subatech
//-----------------------------------------------------------------------------

#include "AliMUONVDigitStore.h"

#include "AliLog.h"
#include "AliMUONVDigit.h"
#include <TClass.h>
#include <TString.h>
#include <TTree.h>

/// \cond CLASSIMP
ClassImp(AliMUONVDigitStore)
/// \endcond

//_____________________________________________________________________________
AliMUONVDigitStore::AliMUONVDigitStore()
{
  /// ctor
}

//_____________________________________________________________________________
AliMUONVDigitStore::~AliMUONVDigitStore()
{
  /// dtor
}

//_____________________________________________________________________________
Bool_t
AliMUONVDigitStore::Add(TObject* object)
{
  /// Add an object, if it is of type AliMUONVDigit
  if (object)
  {
    AliMUONVDigit* digit = dynamic_cast<AliMUONVDigit*>(object);
    if (digit)
    {
      AliMUONVDigit* added = Add(*digit,AliMUONVDigitStore::kIgnore);
      if (!added)
      {
        AliError("Could not add digit through Add(TObject*) method");
      }
      else
      {
        return kTRUE;
      }
    }
  }
  return kFALSE;
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::Add(Int_t detElemId,
                       Int_t manuId,
                       Int_t manuChannel,
                       Int_t cathode,
                       EReplacePolicy replace)
{
  /// Add a digit and return it
  AliMUONVDigit* digit = CreateDigit(detElemId,manuId,manuChannel,cathode);
  if (digit)
  {
    AliMUONVDigit* d = Add(*digit,replace);
    delete digit;
    return d;
  }
  return 0x0;
}

//____________________________________________________________________________
AliMUONVDigitStore*
AliMUONVDigitStore::Create(const char* digitstoreclassname)
{
  /// Create a concrete digitStore, given its classname

  TClass* classPtr = TClass::GetClass(digitstoreclassname);
  if (!classPtr || !classPtr->InheritsFrom("AliMUONVDigitStore"))
  {
    return 0x0;
  }

  AliMUONVDigitStore* digitStore =
    reinterpret_cast<AliMUONVDigitStore*>(classPtr->New());

  return digitStore;
}

//_____________________________________________________________________________
AliMUONVDigitStore*
AliMUONVDigitStore::Create(TTree& tree)
{
  /// Create store from the given tree (if possible).
  TString dataType = ( strcmp(tree.GetName(),"TreeD") == 0 ? "Digit" :
                       (strcmp(tree.GetName(),"TreeS")== 9 ? "SDigit" : "")
                       );
  return static_cast<AliMUONVDigitStore*>(AliMUONVStore::Create(tree,dataType.Data()));
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::FindObject(const TObject* object) const
{
  /// Find an object, if of AliMUONVDigit type.
  const AliMUONVDigit* digit = dynamic_cast<const AliMUONVDigit*>(object);
  if (digit)
  {
    return FindObject(digit->GetUniqueID());
  }
  return 0x0;
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::FindObject(UInt_t uniqueID) const
{
  /// Find digit by its uniqueID

  return FindObject(AliMUONVDigit::DetElemId(uniqueID),
                    AliMUONVDigit::ManuId(uniqueID),
                    AliMUONVDigit::ManuChannel(uniqueID),
                    AliMUONVDigit::Cathode(uniqueID));
}

//_____________________________________________________________________________
Int_t
AliMUONVDigitStore::GetSize(Int_t detElemId, Int_t cathode) const
{
  /// Return the number of digits we have for a given detection element
  TIter next(CreateIterator(detElemId,detElemId,cathode));
  AliMUONVDigit* digit;
  Int_t n(0);
  while ( ( digit = static_cast<AliMUONVDigit*>(next()) ) )
  {
    ++n;
  }
  return n;
}

<commit_msg>Fixing UNUSED_VALUE defect reported by Coverity<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// $Id$

//-----------------------------------------------------------------------------
/// \class AliMUONVDigitStore
///
/// Interface for a digit (or sdigit) container
///
/// It offers methods to Add, Find and Remove single elements, and
/// can create iterators to loop over (part of) the elements.
///
/// \author Laurent Aphecetche, Subatech
//-----------------------------------------------------------------------------

#include "AliMUONVDigitStore.h"

#include "AliLog.h"
#include "AliMUONVDigit.h"
#include <TClass.h>
#include <TString.h>
#include <TTree.h>

/// \cond CLASSIMP
ClassImp(AliMUONVDigitStore)
/// \endcond

//_____________________________________________________________________________
AliMUONVDigitStore::AliMUONVDigitStore()
{
  /// ctor
}

//_____________________________________________________________________________
AliMUONVDigitStore::~AliMUONVDigitStore()
{
  /// dtor
}

//_____________________________________________________________________________
Bool_t
AliMUONVDigitStore::Add(TObject* object)
{
  /// Add an object, if it is of type AliMUONVDigit
  if (object)
  {
    AliMUONVDigit* digit = dynamic_cast<AliMUONVDigit*>(object);
    if (digit)
    {
      AliMUONVDigit* added = Add(*digit,AliMUONVDigitStore::kIgnore);
      if (!added)
      {
        AliError("Could not add digit through Add(TObject*) method");
      }
      else
      {
        return kTRUE;
      }
    }
  }
  return kFALSE;
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::Add(Int_t detElemId,
                       Int_t manuId,
                       Int_t manuChannel,
                       Int_t cathode,
                       EReplacePolicy replace)
{
  /// Add a digit and return it
  AliMUONVDigit* digit = CreateDigit(detElemId,manuId,manuChannel,cathode);
  if (digit)
  {
    AliMUONVDigit* d = Add(*digit,replace);
    delete digit;
    return d;
  }
  return 0x0;
}

//____________________________________________________________________________
AliMUONVDigitStore*
AliMUONVDigitStore::Create(const char* digitstoreclassname)
{
  /// Create a concrete digitStore, given its classname

  TClass* classPtr = TClass::GetClass(digitstoreclassname);
  if (!classPtr || !classPtr->InheritsFrom("AliMUONVDigitStore"))
  {
    return 0x0;
  }

  AliMUONVDigitStore* digitStore =
    reinterpret_cast<AliMUONVDigitStore*>(classPtr->New());

  return digitStore;
}

//_____________________________________________________________________________
AliMUONVDigitStore*
AliMUONVDigitStore::Create(TTree& tree)
{
  /// Create store from the given tree (if possible).
  TString dataType = ( strcmp(tree.GetName(),"TreeD") == 0 ? "Digit" :
                       (strcmp(tree.GetName(),"TreeS")== 9 ? "SDigit" : "")
                       );
  return static_cast<AliMUONVDigitStore*>(AliMUONVStore::Create(tree,dataType.Data()));
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::FindObject(const TObject* object) const
{
  /// Find an object, if of AliMUONVDigit type.
  const AliMUONVDigit* digit = dynamic_cast<const AliMUONVDigit*>(object);
  if (digit)
  {
    return FindObject(digit->GetUniqueID());
  }
  return 0x0;
}

//_____________________________________________________________________________
AliMUONVDigit*
AliMUONVDigitStore::FindObject(UInt_t uniqueID) const
{
  /// Find digit by its uniqueID

  return FindObject(AliMUONVDigit::DetElemId(uniqueID),
                    AliMUONVDigit::ManuId(uniqueID),
                    AliMUONVDigit::ManuChannel(uniqueID),
                    AliMUONVDigit::Cathode(uniqueID));
}

//_____________________________________________________________________________
Int_t
AliMUONVDigitStore::GetSize(Int_t detElemId, Int_t cathode) const
{
  /// Return the number of digits we have for a given detection element
  TIter next(CreateIterator(detElemId,detElemId,cathode));
  Int_t n(0);
  while ( ( next() ) )
  {
    ++n;
  }
  return n;
}

<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include <qtest_kde.h>

#include "seekslidertest.h"
#include "../seekslider.h"
#include "../mediaobject.h"
#include <QtGui/QSlider>
#include <kurl.h>
#include <cstdlib>
#include <QtGui/QLabel>
#include "loadfakebackend.h"

using namespace Phonon;

void SeekSliderTest::initTestCase()
{
    Phonon::loadFakeBackend();
    ss = new SeekSlider;
    QVERIFY(ss != 0);
    qslider = ss->findChild<QSlider *>();
    qlabel = ss->findChild<QLabel *>();
    QVERIFY(qslider != 0);
    QVERIFY(qlabel != 0);
    media = new MediaObject(this);
}

void SeekSliderTest::testEnabled()
{
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(0);
    QVERIFY(!qslider->isEnabled());
}

void SeekSliderTest::setMedia()
{
    QVERIFY(media->state() == Phonon::LoadingState);
    KUrl url(testUrl());
    media->setCurrentSource(url);
    ss->setMediaObject(media);
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(0);
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(media);
    QVERIFY(!qslider->isEnabled());
}

void SeekSliderTest::playMedia()
{
    media->play();
    QSignalSpy stateSpy(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)));
    while (media->state() != Phonon::PlayingState) {
        QVERIFY(QTest::kWaitForSignal(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), 4000));
        QVERIFY(!stateSpy.isEmpty());
        switch (qvariant_cast<Phonon::State>(stateSpy.last().first())) {
        case Phonon::PlayingState:
        case Phonon::PausedState:
        case Phonon::BufferingState:
            QVERIFY(qslider->isEnabled());
            ss->setMediaObject(0);
            QVERIFY(!qslider->isEnabled());
            ss->setMediaObject(media);
            QVERIFY(qslider->isEnabled());
            break;
        case Phonon::ErrorState:
        case Phonon::StoppedState:
        case Phonon::LoadingState:
            QVERIFY(!qslider->isEnabled());
            break;
        }
    }
}

void SeekSliderTest::seekWithSlider()
{
    // click on the slider to seek
}

void SeekSliderTest::cleanupTestCase()
{
    delete media;
    qslider = 0;
    delete ss;
}

QTEST_KDEMAIN(SeekSliderTest, GUI)
#include "seekslidertest.moc"
// vim: ts=4
<commit_msg>use AudioPath + AudioOutput; a MediaObject alone is not required to behave correctly<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include <qtest_kde.h>

#include "seekslidertest.h"
#include "../seekslider.h"
#include "../mediaobject.h"
#include <QtGui/QSlider>
#include <kurl.h>
#include <cstdlib>
#include <QtGui/QLabel>
#include "loadfakebackend.h"
#include "../audiopath.h"
#include "../audiooutput.h"

using namespace Phonon;

void SeekSliderTest::initTestCase()
{
    Phonon::loadFakeBackend();
    ss = new SeekSlider;
    QVERIFY(ss != 0);
    qslider = ss->findChild<QSlider *>();
    qlabel = ss->findChild<QLabel *>();
    QVERIFY(qslider != 0);
    QVERIFY(qlabel != 0);
    media = new MediaObject(this);
    AudioPath *ap = new AudioPath(media);
    AudioOutput *ao = new AudioOutput(Phonon::MusicCategory, media);
    media->addAudioPath(ap);
    ap->addOutput(ao);
}

void SeekSliderTest::testEnabled()
{
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(0);
    QVERIFY(!qslider->isEnabled());
}

void SeekSliderTest::setMedia()
{
    QVERIFY(media->state() == Phonon::LoadingState);
    KUrl url(testUrl());
    media->setCurrentSource(url);
    ss->setMediaObject(media);
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(0);
    QVERIFY(!qslider->isEnabled());
    ss->setMediaObject(media);
    QVERIFY(!qslider->isEnabled());
}

void SeekSliderTest::playMedia()
{
    media->play();
    QSignalSpy stateSpy(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)));
    while (media->state() != Phonon::PlayingState) {
        QVERIFY(QTest::kWaitForSignal(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), 4000));
        QVERIFY(!stateSpy.isEmpty());
        switch (qvariant_cast<Phonon::State>(stateSpy.last().first())) {
        case Phonon::PlayingState:
        case Phonon::PausedState:
        case Phonon::BufferingState:
            QVERIFY(qslider->isEnabled());
            ss->setMediaObject(0);
            QVERIFY(!qslider->isEnabled());
            ss->setMediaObject(media);
            QVERIFY(qslider->isEnabled());
            break;
        case Phonon::ErrorState:
        case Phonon::StoppedState:
        case Phonon::LoadingState:
            QVERIFY(!qslider->isEnabled());
            break;
        }
    }
}

void SeekSliderTest::seekWithSlider()
{
    // click on the slider to seek
}

void SeekSliderTest::cleanupTestCase()
{
    delete media;
    qslider = 0;
    delete ss;
}

QTEST_KDEMAIN(SeekSliderTest, GUI)
#include "seekslidertest.moc"
// vim: ts=4
<|endoftext|>


<commit_before>#if _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif

#include <chrono>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <stdio.h>
#include "LogVisor/LogVisor.hpp"

/* ANSI sequences */
#define RED "\x1b[1;31m"
#define YELLOW "\x1b[1;33m"
#define GREEN "\x1b[1;32m"
#define MAGENTA "\x1b[1;35m"
#define CYAN "\x1b[1;36m"
#define BOLD "\x1b[1m"
#define NORMAL "\x1b[0m"

#if _WIN32
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#endif

namespace LogVisor
{

static std::unordered_map<std::thread::id, const char*> ThreadMap;
void RegisterThreadName(const char* name)
{
    ThreadMap[std::this_thread::get_id()] = name;
#if __APPLE__
    pthread_setname_np(name);
#elif __linux__
    pthread_setname_np(pthread_self(), name);
#elif _MSC_VER
    struct
    {
        DWORD dwType; // Must be 0x1000.
        LPCSTR szName; // Pointer to name (in user addr space).
        DWORD dwThreadID; // Thread ID (-1=caller thread).
        DWORD dwFlags; // Reserved for future use, must be zero.
    } info = {0x1000, name, (DWORD)-1, 0};
    __try
    {
        RaiseException(0x406D1388, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
    }
#endif
}

std::vector<std::unique_ptr<ILogger>> MainLoggers;
std::atomic_size_t ErrorCount(0);
static std::chrono::steady_clock MonoClock;
static std::chrono::steady_clock::time_point GlobalStart = MonoClock.now();
static inline std::chrono::steady_clock::duration CurrentUptime()
{return MonoClock.now() - GlobalStart;}
std::atomic_uint_fast64_t FrameIndex(0);

#if _WIN32
static HANDLE Term = 0;
#else
static const char* Term = nullptr;
#endif
static bool XtermColor = false;
struct ConsoleLogger : public ILogger
{
    std::mutex m;
    ConsoleLogger()
    {
#if _WIN32
        if (!Term)
            Term = GetStdHandle(STD_ERROR_HANDLE);
#else
        if (!Term)
        {
            Term = getenv("TERM");
            if (Term && !strncmp(Term, "xterm", 5))
            {
                XtermColor = true;
                putenv((char*)"TERM=xterm-16color");
            }
        }
#endif
    }

    static void _reportHead(const char* modName, const char* sourceInfo, Level severity)
    {
        std::chrono::steady_clock::duration tm = CurrentUptime();
        double tmd = tm.count() *
            std::chrono::steady_clock::duration::period::num /
            (double)std::chrono::steady_clock::duration::period::den;
        std::thread::id thrId = std::this_thread::get_id();
        const char* thrName = nullptr;
        if (ThreadMap.find(thrId) != ThreadMap.end())
            thrName = ThreadMap[thrId];

#if _WIN32
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, "[");
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN);
        fprintf(stderr, "%5.4f ", tmd);
        uint64_t fi = FrameIndex.load();
        if (fi)
            fprintf(stderr, "(%llu) ", fi);
        switch (severity)
        {
        case Info:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE);
            fprintf(stderr, "INFO");
            break;
        case Warning:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
            fprintf(stderr, "WARNING");
            break;
        case Error:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED);
            fprintf(stderr, "ERROR");
            break;
        case FatalError:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED);
            fprintf(stderr, "FATAL ERROR");
            break;
        default:
            break;
        };
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, " %s", modName);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
        if (sourceInfo)
            fprintf(stderr, " {%s}", sourceInfo);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE);
        if (thrName)
            fprintf(stderr, " (%s)", thrName);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, "] ");
        SetConsoleTextAttribute(Term, FOREGROUND_WHITE);
#else
        if (XtermColor)
        {
            fprintf(stderr, BOLD "[");
            fprintf(stderr, GREEN "%5.4f ", tmd);
            uint_fast64_t fIdx = FrameIndex.load();
            if (fIdx)
                fprintf(stderr, "(%lu) ", fIdx);
            switch (severity)
            {
            case Info:
                fprintf(stderr, BOLD CYAN "INFO");
                break;
            case Warning:
                fprintf(stderr, BOLD YELLOW "WARNING");
                break;
            case Error:
                fprintf(stderr, RED BOLD "ERROR");
                break;
            case FatalError:
                fprintf(stderr, BOLD RED "FATAL ERROR");
                break;
            default:
                break;
            };
            fprintf(stderr, NORMAL BOLD " %s", modName);
            if (sourceInfo)
                fprintf(stderr, BOLD YELLOW " {%s}", sourceInfo);
            if (thrName)
                fprintf(stderr, BOLD MAGENTA " (%s)", thrName);
            fprintf(stderr, NORMAL BOLD "] " NORMAL);
        }
        else
        {
            fprintf(stderr, "[");
            fprintf(stderr, "%5.4f ", tmd);
            uint_fast64_t fIdx = FrameIndex.load();
            if (fIdx)
                fprintf(stderr, "(%lu) ", fIdx);
            switch (severity)
            {
            case Info:
                fprintf(stderr, "INFO");
                break;
            case Warning:
                fprintf(stderr, "WARNING");
                break;
            case Error:
                fprintf(stderr, "ERROR");
                break;
            case FatalError:
                fprintf(stderr, "FATAL ERROR");
                break;
            default:
                break;
            };
            fprintf(stderr, " %s", modName);
            if (sourceInfo)
                fprintf(stderr, " {%s}", sourceInfo);
            if (thrName)
                fprintf(stderr, " (%s)", thrName);
            fprintf(stderr, "] ");
        }
#endif
    }

    void report(const char* modName, Level severity,
                const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        _reportHead(modName, nullptr, severity);
        vfprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void report(const char* modName, Level severity,
                const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        _reportHead(modName, nullptr, severity);
        vfwprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfwprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }
};

void RegisterConsoleLogger()
{
    /* Determine if console logger already added */
    for (auto& logger : MainLoggers)
    {
        if (typeid(logger.get()) == typeid(ConsoleLogger))
            return;
    }

    /* Otherwise construct new console logger */
    MainLoggers.emplace_back(new ConsoleLogger);
}

struct FileLogger : public ILogger
{
    FILE* fp;
    std::mutex m;
    virtual void openFile()=0;
    virtual void closeFile() {fclose(fp);}

    void _reportHead(const char* modName, const char* sourceInfo, Level severity)
    {
        std::chrono::steady_clock::duration tm = CurrentUptime();
        double tmd = tm.count() *
            std::chrono::steady_clock::duration::period::num /
            (double)std::chrono::steady_clock::duration::period::den;
        std::thread::id thrId = std::this_thread::get_id();
        const char* thrName = nullptr;
        if (ThreadMap.find(thrId) != ThreadMap.end())
            thrName = ThreadMap[thrId];

        fprintf(fp, "[");
        switch (severity)
        {
        case Info:
            fprintf(fp, "INFO");
            break;
        case Warning:
            fprintf(fp, "WARNING");
            break;
        case Error:
            fprintf(fp, "ERROR");
            break;
        case FatalError:
            fprintf(fp, "FATAL ERROR");
            break;
        default:
            break;
        };
        fprintf(fp, " %s", modName);
        if (sourceInfo)
            fprintf(stderr, " {%s}", sourceInfo);
        if (thrName)
            fprintf(fp, " (%s)", thrName);
        fprintf(fp, " %5.4f", tmd);
        uint_fast64_t fIdx = FrameIndex.load();
        if (fIdx)
            fprintf(fp, " (%llu)", fIdx);
        fprintf(fp, "] ");
    }

    void report(const char* modName, Level severity,
                const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        _reportHead(modName, nullptr, severity);
        vfprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void report(const char* modName, Level severity,
                const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        _reportHead(modName, nullptr, severity);
        vfwprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfwprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }
};

struct FileLogger8 : public FileLogger
{
    const char* m_filepath;
    FileLogger8(const char* filepath) : m_filepath(filepath) {}
    void openFile() {fp = fopen(m_filepath, "a");}
};

void RegisterFileLogger(const char* filepath)
{
    /* Determine if file logger already added */
    for (auto& logger : MainLoggers)
    {
        FileLogger8* filelogger = dynamic_cast<FileLogger8*>(logger.get());
        if (filelogger)
        {
            if (!strcmp(filepath, filelogger->m_filepath))
                return;
        }
    }

    /* Otherwise construct new file logger */
    MainLoggers.emplace_back(new FileLogger8(filepath));
}

#if LOG_UCS2

struct FileLogger16 : public FileLogger
{
    const wchar_t* m_filepath;
    FileLogger16(const wchar_t* filepath) : m_filepath(filepath) {}
    void openFile() {fp = _wfopen(m_filepath, L"a");}
};

void RegisterFileLogger(const wchar_t* filepath)
{
    /* Determine if file logger already added */
    for (auto& logger : MainLoggers)
    {
        FileLogger16* filelogger = dynamic_cast<FileLogger16*>(logger.get());
        if (filelogger)
        {
            if (!wcscmp(filepath, filelogger->m_filepath))
                return;
        }
    }

    /* Otherwise construct new file logger */
    MainLoggers.emplace_back(new FileLogger16(filepath));
}

#endif

}
<commit_msg>added inttypes<commit_after>#if _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif

#include <chrono>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <stdio.h>
#include <inttypes.h>
#include "LogVisor/LogVisor.hpp"

/* ANSI sequences */
#define RED "\x1b[1;31m"
#define YELLOW "\x1b[1;33m"
#define GREEN "\x1b[1;32m"
#define MAGENTA "\x1b[1;35m"
#define CYAN "\x1b[1;36m"
#define BOLD "\x1b[1m"
#define NORMAL "\x1b[0m"

#if _WIN32
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#endif

namespace LogVisor
{

static std::unordered_map<std::thread::id, const char*> ThreadMap;
void RegisterThreadName(const char* name)
{
    ThreadMap[std::this_thread::get_id()] = name;
#if __APPLE__
    pthread_setname_np(name);
#elif __linux__
    pthread_setname_np(pthread_self(), name);
#elif _MSC_VER
    struct
    {
        DWORD dwType; // Must be 0x1000.
        LPCSTR szName; // Pointer to name (in user addr space).
        DWORD dwThreadID; // Thread ID (-1=caller thread).
        DWORD dwFlags; // Reserved for future use, must be zero.
    } info = {0x1000, name, (DWORD)-1, 0};
    __try
    {
        RaiseException(0x406D1388, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
    }
#endif
}

std::vector<std::unique_ptr<ILogger>> MainLoggers;
std::atomic_size_t ErrorCount(0);
static std::chrono::steady_clock MonoClock;
static std::chrono::steady_clock::time_point GlobalStart = MonoClock.now();
static inline std::chrono::steady_clock::duration CurrentUptime()
{return MonoClock.now() - GlobalStart;}
std::atomic_uint_fast64_t FrameIndex(0);

#if _WIN32
static HANDLE Term = 0;
#else
static const char* Term = nullptr;
#endif
static bool XtermColor = false;
struct ConsoleLogger : public ILogger
{
    std::mutex m;
    ConsoleLogger()
    {
#if _WIN32
        if (!Term)
            Term = GetStdHandle(STD_ERROR_HANDLE);
#else
        if (!Term)
        {
            Term = getenv("TERM");
            if (Term && !strncmp(Term, "xterm", 5))
            {
                XtermColor = true;
                putenv((char*)"TERM=xterm-16color");
            }
        }
#endif
    }

    static void _reportHead(const char* modName, const char* sourceInfo, Level severity)
    {
        std::chrono::steady_clock::duration tm = CurrentUptime();
        double tmd = tm.count() *
            std::chrono::steady_clock::duration::period::num /
            (double)std::chrono::steady_clock::duration::period::den;
        std::thread::id thrId = std::this_thread::get_id();
        const char* thrName = nullptr;
        if (ThreadMap.find(thrId) != ThreadMap.end())
            thrName = ThreadMap[thrId];

#if _WIN32
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, "[");
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN);
        fprintf(stderr, "%5.4f ", tmd);
        uint64_t fi = FrameIndex.load();
        if (fi)
            fprintf(stderr, "(%" PRIu64 ") ", fi);
        switch (severity)
        {
        case Info:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE);
            fprintf(stderr, "INFO");
            break;
        case Warning:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
            fprintf(stderr, "WARNING");
            break;
        case Error:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED);
            fprintf(stderr, "ERROR");
            break;
        case FatalError:
            SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED);
            fprintf(stderr, "FATAL ERROR");
            break;
        default:
            break;
        };
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, " %s", modName);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
        if (sourceInfo)
            fprintf(stderr, " {%s}", sourceInfo);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE);
        if (thrName)
            fprintf(stderr, " (%s)", thrName);
        SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE);
        fprintf(stderr, "] ");
        SetConsoleTextAttribute(Term, FOREGROUND_WHITE);
#else
        if (XtermColor)
        {
            fprintf(stderr, BOLD "[");
            fprintf(stderr, GREEN "%5.4f ", tmd);
            uint_fast64_t fIdx = FrameIndex.load();
            if (fIdx)
                fprintf(stderr, "(%lu) ", fIdx);
            switch (severity)
            {
            case Info:
                fprintf(stderr, BOLD CYAN "INFO");
                break;
            case Warning:
                fprintf(stderr, BOLD YELLOW "WARNING");
                break;
            case Error:
                fprintf(stderr, RED BOLD "ERROR");
                break;
            case FatalError:
                fprintf(stderr, BOLD RED "FATAL ERROR");
                break;
            default:
                break;
            };
            fprintf(stderr, NORMAL BOLD " %s", modName);
            if (sourceInfo)
                fprintf(stderr, BOLD YELLOW " {%s}", sourceInfo);
            if (thrName)
                fprintf(stderr, BOLD MAGENTA " (%s)", thrName);
            fprintf(stderr, NORMAL BOLD "] " NORMAL);
        }
        else
        {
            fprintf(stderr, "[");
            fprintf(stderr, "%5.4f ", tmd);
            uint_fast64_t fIdx = FrameIndex.load();
            if (fIdx)
                fprintf(stderr, "(%lu) ", fIdx);
            switch (severity)
            {
            case Info:
                fprintf(stderr, "INFO");
                break;
            case Warning:
                fprintf(stderr, "WARNING");
                break;
            case Error:
                fprintf(stderr, "ERROR");
                break;
            case FatalError:
                fprintf(stderr, "FATAL ERROR");
                break;
            default:
                break;
            };
            fprintf(stderr, " %s", modName);
            if (sourceInfo)
                fprintf(stderr, " {%s}", sourceInfo);
            if (thrName)
                fprintf(stderr, " (%s)", thrName);
            fprintf(stderr, "] ");
        }
#endif
    }

    void report(const char* modName, Level severity,
                const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        _reportHead(modName, nullptr, severity);
        vfprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void report(const char* modName, Level severity,
                const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        _reportHead(modName, nullptr, severity);
        vfwprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfwprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }
};

void RegisterConsoleLogger()
{
    /* Determine if console logger already added */
    for (auto& logger : MainLoggers)
    {
        if (typeid(logger.get()) == typeid(ConsoleLogger))
            return;
    }

    /* Otherwise construct new console logger */
    MainLoggers.emplace_back(new ConsoleLogger);
}

struct FileLogger : public ILogger
{
    FILE* fp;
    std::mutex m;
    virtual void openFile()=0;
    virtual void closeFile() {fclose(fp);}

    void _reportHead(const char* modName, const char* sourceInfo, Level severity)
    {
        std::chrono::steady_clock::duration tm = CurrentUptime();
        double tmd = tm.count() *
            std::chrono::steady_clock::duration::period::num /
            (double)std::chrono::steady_clock::duration::period::den;
        std::thread::id thrId = std::this_thread::get_id();
        const char* thrName = nullptr;
        if (ThreadMap.find(thrId) != ThreadMap.end())
            thrName = ThreadMap[thrId];

        fprintf(fp, "[");
        switch (severity)
        {
        case Info:
            fprintf(fp, "INFO");
            break;
        case Warning:
            fprintf(fp, "WARNING");
            break;
        case Error:
            fprintf(fp, "ERROR");
            break;
        case FatalError:
            fprintf(fp, "FATAL ERROR");
            break;
        default:
            break;
        };
        fprintf(fp, " %s", modName);
        if (sourceInfo)
            fprintf(stderr, " {%s}", sourceInfo);
        if (thrName)
            fprintf(fp, " (%s)", thrName);
        fprintf(fp, " %5.4f", tmd);
        uint_fast64_t fIdx = FrameIndex.load();
        if (fIdx)
            fprintf(fp, " (%" PRIu64 ")", fIdx);
        fprintf(fp, "] ");
    }

    void report(const char* modName, Level severity,
                const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        _reportHead(modName, nullptr, severity);
        vfprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void report(const char* modName, Level severity,
                const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        _reportHead(modName, nullptr, severity);
        vfwprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const char* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }

    void reportSource(const char* modName, Level severity,
                      const char* file, unsigned linenum,
                      const wchar_t* format, va_list ap)
    {
        std::unique_lock<std::mutex> lk(m);
        openFile();
        char sourceInfo[128];
        snprintf(sourceInfo, 128, "%s:%u", file, linenum);
        _reportHead(modName, sourceInfo, severity);
        vfwprintf(fp, format, ap);
        fprintf(fp, "\n");
        closeFile();
    }
};

struct FileLogger8 : public FileLogger
{
    const char* m_filepath;
    FileLogger8(const char* filepath) : m_filepath(filepath) {}
    void openFile() {fp = fopen(m_filepath, "a");}
};

void RegisterFileLogger(const char* filepath)
{
    /* Determine if file logger already added */
    for (auto& logger : MainLoggers)
    {
        FileLogger8* filelogger = dynamic_cast<FileLogger8*>(logger.get());
        if (filelogger)
        {
            if (!strcmp(filepath, filelogger->m_filepath))
                return;
        }
    }

    /* Otherwise construct new file logger */
    MainLoggers.emplace_back(new FileLogger8(filepath));
}

#if LOG_UCS2

struct FileLogger16 : public FileLogger
{
    const wchar_t* m_filepath;
    FileLogger16(const wchar_t* filepath) : m_filepath(filepath) {}
    void openFile() {fp = _wfopen(m_filepath, L"a");}
};

void RegisterFileLogger(const wchar_t* filepath)
{
    /* Determine if file logger already added */
    for (auto& logger : MainLoggers)
    {
        FileLogger16* filelogger = dynamic_cast<FileLogger16*>(logger.get());
        if (filelogger)
        {
            if (!wcscmp(filepath, filelogger->m_filepath))
                return;
        }
    }

    /* Otherwise construct new file logger */
    MainLoggers.emplace_back(new FileLogger16(filepath));
}

#endif

}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	VS1063 VLSI Audio Codec ドライバー
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "G13/port.hpp"
#include "common/csi_io.hpp"
#include "common/delay.hpp"
#include "common/format.hpp"
#include "ff12a/src/ff.h"

extern "C" {
	char sci_getch(void);
	uint16_t sci_length();
}

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  VS1063 テンプレートクラス
		@param[in]	CSI	CSI(SPI) 制御クラス
		@param[in]	SEL	/xCS 制御クラス
		@param[in]	DCS /xDCS 制御クラス
		@param[in]	REQ	DREQ 入力クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class CSI, class SEL, class DCS, class REQ>
	class VS1063 {

		CSI&	csi_;

		uint8_t	frame_;

		uint8_t buff_[256];

		/// VS1063a コマンド表
		enum class CMD {
			MODE,			///< モード制御
			STATUS,			///< ステータス
			BASS,			///< 内臓の低音／高音強調
			CLOCKF,			///< クロック周波数＋逓倍器
			DECODE_TIME,	///< 再生時間［秒］
			AUDATA,			///< 各種オーディオ・データ
			WRAM,			///< RAM リード／ライト
			WRAMADDR,		///< RAM リード／ライト・アドレス
			HDAT0,			///< ストリーム・ヘッダ・データ０
			HDAT1,			///< ストリーム・ヘッダ・データ１
			AIADDR,			///< アプリケーション開始アドレス
			VOL,			///< ボリューム制御
			AICTRL0,   		///< アプリケーション制御レジスタ０
			AICTRL1,		///< アプリケーション制御レジスタ１
			AICTRL2,		///< アプリケーション制御レジスタ２
			AICTRL3			///< アプリケーション制御レジスタ３
		};

		inline void sleep_() { asm("nop"); }

		inline bool get_status_()
		{
			return REQ::P();
		}

		inline void wait_ready_()
		{
			while(REQ::P() == 0) sleep_();
		}

		void write_(CMD cmd, uint16_t data)
		{
			wait_ready_();

			SEL::P = 0;
			csi_.xchg(0x02);	// Write command (0x02)
			csi_.xchg(static_cast<uint8_t>(cmd));
			csi_.xchg(data >> 8);
			csi_.xchg(data & 0xff);
			SEL::P = 1;
		}

		uint16_t read_(CMD cmd)
		{
			wait_ready_();

			uint16_t data;
			SEL::P = 0;
			csi_.xchg(0x03);	// Read command (0x03)
			csi_.xchg(static_cast<uint8_t>(cmd));
			data  = static_cast<uint16_t>(CSI::xchg()) << 8;
			data |= csi_.xchg();
			SEL::P = 1;
			return data;
		}

		bool probe_mp3_(FIL* fp)
		{
			UINT len;
			if(f_read(fp, buff_, 10, &len) != FR_OK) {
				return false;
			}
			if(len != 10) {
				return false;
			}

			if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ;
			else {
				return false;
			}

			// skip TAG
			uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21;
			ofs |= static_cast<uint32_t>(buff_[7]) << 14;
			ofs |= static_cast<uint32_t>(buff_[8]) << 7;
			ofs |= static_cast<uint32_t>(buff_[9]);
			f_lseek(fp, ofs);

			utils::format("Find ID3 tag skip: %d\n") % ofs;

			return true;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		VS1063(CSI& csi) : csi_(csi), frame_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  開始（初期化）
		*/
		//-----------------------------------------------------------------//
		void start()
		{
			SEL::PM = 0;
			SEL::PU = 0;

			DCS::PM = 0;
			DCS::PU = 0;

			REQ::PM = 1;
			REQ::PU = 0;

			SEL::P = 1;  // /xCS = H
			DCS::P = 1;  // /xDCS = H

			uint8_t intr_level = 0;
			if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) {
				utils::format("CSI1 Start fail ! (Clock spped over range)\n");
				return;
			}

///	   		write_(CMD::MODE, 0x4840);
	   		write_(CMD::MODE, 0x4800);
			write_(CMD::VOL,  0x4040);  // volume

			write_(CMD::CLOCKF, 0x9800);  // 12.288MHz
//			write_(CMD::CLOCKF, 0x8BE8);  // 12MHz OSC 補正

			utils::delay::milli_second(10);

			if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) {
				utils::format("CSI1 Start fail ! (Clock spped over range)\n");
				return;
			}
			utils::delay::milli_second(10);

			set_volume(255);
		}

		//----------------------------------------------------------------//
		/*!
			@brief  サービス
		*/
		//----------------------------------------------------------------//
		bool service(FIL* fp)
		{
			UINT len;
			if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) {
				return false;
			}
			if(len == 0) return false;

			const uint8_t* p = buff_;
			while(len > 0) {
				while(get_status_() == 0) ;
				uint16_t l = 32;
				if(l > len) l = len;
				csi_.send(p, l);
				p += l;
				len -= l;
			}

			++frame_;
			if(frame_ >= 40) {
				device::P4.B3 = !device::P4.B3();
				frame_ = 0;
			}

			if(sci_length()) {
				auto ch = sci_getch();
				if(ch == '>') {
					return false;
				}
			}
			return true;
		}

		//----------------------------------------------------------------//
		/*!
			@brief  再生
			@param[in]	fp	ファイル・ディスクリプタ
			@return エラーなら「false」
		*/
		//----------------------------------------------------------------//
		bool play(FIL* fp)
		{
			if(fp == nullptr) return false;

			// ファイル・フォーマットを確認
			if(!probe_mp3_(fp)) {
				f_close(fp);
				return false;
			}

			{
				frame_ = 0;
				DCS::P = 0;
				while(service(fp)) {
					sleep_();
				}
				DCS::P = 1;
			}

			f_close(fp);

			return true;
		}

		//----------------------------------------------------------------//
		/*!
			@brief  ボリュームを設定
			@param[in]	ボリューム（２５５が最大、０が最小）
		*/
		//----------------------------------------------------------------//
		void set_volume(uint8_t vol)
		{
			vol ^= 0xff;
			write_(CMD::VOL, (vol << 8) | vol);
		}

		//----------------------------------------------------------------//
		/*!
			@brief  ボリュームを取得
			@return	ボリューム（２５５が最大、０が最小）
		*/
		//----------------------------------------------------------------//
		uint8_t get_volume()
		{
			return (read_(CMD::VOL) & 255) ^ 0xff;
		}
	};
}
<commit_msg>update ctrl<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	VS1063 VLSI Audio Codec ドライバー
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "G13/port.hpp"
#include "common/csi_io.hpp"
#include "common/delay.hpp"
#include "common/format.hpp"
#include "ff12a/src/ff.h"

extern "C" {
	char sci_getch(void);
	uint16_t sci_length();
}

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  VS1063 テンプレートクラス
		@param[in]	CSI	CSI(SPI) 制御クラス
		@param[in]	SEL	/xCS 制御クラス
		@param[in]	DCS /xDCS 制御クラス
		@param[in]	REQ	DREQ 入力クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class CSI, class SEL, class DCS, class REQ>
	class VS1063 {

		CSI&	csi_;

		uint8_t	frame_;

		uint8_t buff_[256];

		/// VS1063a コマンド表
		enum class CMD {
			MODE,			///< モード制御
			STATUS,			///< ステータス
			BASS,			///< 内臓の低音／高音強調
			CLOCKF,			///< クロック周波数＋逓倍器
			DECODE_TIME,	///< 再生時間［秒］
			AUDATA,			///< 各種オーディオ・データ
			WRAM,			///< RAM リード／ライト
			WRAMADDR,		///< RAM リード／ライト・アドレス
			HDAT0,			///< ストリーム・ヘッダ・データ０
			HDAT1,			///< ストリーム・ヘッダ・データ１
			AIADDR,			///< アプリケーション開始アドレス
			VOL,			///< ボリューム制御
			AICTRL0,   		///< アプリケーション制御レジスタ０
			AICTRL1,		///< アプリケーション制御レジスタ１
			AICTRL2,		///< アプリケーション制御レジスタ２
			AICTRL3			///< アプリケーション制御レジスタ３
		};

		bool	pause_;

		inline void sleep_() { asm("nop"); }

		inline bool get_status_()
		{
			return REQ::P();
		}

		inline void wait_ready_()
		{
			while(REQ::P() == 0) sleep_();
		}

		void write_(CMD cmd, uint16_t data)
		{
			wait_ready_();

			SEL::P = 0;
			csi_.xchg(0x02);	// Write command (0x02)
			csi_.xchg(static_cast<uint8_t>(cmd));
			csi_.xchg(data >> 8);
			csi_.xchg(data & 0xff);
			SEL::P = 1;
		}

		uint16_t read_(CMD cmd)
		{
			wait_ready_();

			uint16_t data;
			SEL::P = 0;
			csi_.xchg(0x03);	// Read command (0x03)
			csi_.xchg(static_cast<uint8_t>(cmd));
			data  = static_cast<uint16_t>(CSI::xchg()) << 8;
			data |= csi_.xchg();
			SEL::P = 1;
			return data;
		}

		bool probe_mp3_(FIL* fp)
		{
			UINT len;
			if(f_read(fp, buff_, 10, &len) != FR_OK) {
				return false;
			}
			if(len != 10) {
				return false;
			}

			if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ;
			else {
				return false;
			}

			// skip TAG
			uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21;
			ofs |= static_cast<uint32_t>(buff_[7]) << 14;
			ofs |= static_cast<uint32_t>(buff_[8]) << 7;
			ofs |= static_cast<uint32_t>(buff_[9]);
			f_lseek(fp, ofs);

			utils::format("Find ID3 tag skip: %d\n") % ofs;

			return true;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		VS1063(CSI& csi) : csi_(csi), frame_(0), pause_(false) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  開始（初期化）
		*/
		//-----------------------------------------------------------------//
		void start()
		{
			SEL::PM = 0;
			SEL::PU = 0;

			DCS::PM = 0;
			DCS::PU = 0;

			REQ::PM = 1;
			REQ::PU = 0;

			SEL::P = 1;  // /xCS = H
			DCS::P = 1;  // /xDCS = H

			uint8_t intr_level = 0;
			if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) {
				utils::format("CSI1 Start fail ! (Clock spped over range)\n");
				return;
			}

///	   		write_(CMD::MODE, 0x4840);
	   		write_(CMD::MODE, 0x4800);
			write_(CMD::VOL,  0x4040);  // volume

			write_(CMD::CLOCKF, 0x9800);  // 12.288MHz
//			write_(CMD::CLOCKF, 0x8BE8);  // 12MHz OSC 補正

			utils::delay::milli_second(10);

			if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) {
				utils::format("CSI1 Start fail ! (Clock spped over range)\n");
				return;
			}
			utils::delay::milli_second(10);

			set_volume(255);
		}

		//----------------------------------------------------------------//
		/*!
			@brief  サービス
		*/
		//----------------------------------------------------------------//
		bool service(FIL* fp)
		{
			UINT len;
			if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) {
				return false;
			}
			if(len == 0) return false;

			const uint8_t* p = buff_;
			while(len > 0) {
				while(get_status_() == 0) ;
				uint16_t l = 32;
				if(l > len) l = len;
				csi_.send(p, l);
				p += l;
				len -= l;
			}

			return true;
		}

		//----------------------------------------------------------------//
		/*!
			@brief  再生
			@param[in]	fp	ファイル・ディスクリプタ
			@return エラーなら「false」
		*/
		//----------------------------------------------------------------//
		bool play(FIL* fp)
		{
			if(fp == nullptr) return false;

			// ファイル・フォーマットを確認
			if(!probe_mp3_(fp)) {
				f_close(fp);
				return false;
			}

			{
				frame_ = 0;
				pause_ = false;
				DCS::P = 0;
				while(1) {
					if(!pause_) {
						if(!service(fp)) break;

						++frame_;
						if(frame_ >= 40) {
							device::P4.B3 = !device::P4.B3();
							frame_ = 0;
						}
					} else {
						if(frame_ < 192) {
							device::P4.B3 = (frame_ >> 5) & 1;
						} else {
							device::P4.B3 = 1;
						}
						utils::delay::milli_second(2);
						++frame_;
					}

					if(sci_length()) {
						auto ch = sci_getch();
						if(ch == '>') {
							break;
						} else if(ch == ' ') {
							pause_ = !pause_;
						}
					}
				}
				DCS::P = 1;
			}

			f_close(fp);

			return true;
		}

		//----------------------------------------------------------------//
		/*!
			@brief  ボリュームを設定
			@param[in]	ボリューム（２５５が最大、０が最小）
		*/
		//----------------------------------------------------------------//
		void set_volume(uint8_t vol)
		{
			vol ^= 0xff;
			write_(CMD::VOL, (vol << 8) | vol);
		}

		//----------------------------------------------------------------//
		/*!
			@brief  ボリュームを取得
			@return	ボリューム（２５５が最大、０が最小）
		*/
		//----------------------------------------------------------------//
		uint8_t get_volume()
		{
			return (read_(CMD::VOL) & 255) ^ 0xff;
		}
	};
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WebKitPrefix.h"
<commit_msg>Touch a file in WebKitWin to cause it to build<commit_after>/*
 * Copyright (C) 2008 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WebKitPrefix.h"
<|endoftext|>


<commit_before>#include "BetaRand.h"

BetaRand::BetaRand(double shape1, double shape2)
{
    setParameters(shape1, shape2);
}

std::string BetaRand::name()
{
    return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}

void BetaRand::setParameters(double shape1, double shape2)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);

    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);

    if (alpha + beta > 30)
    {
        /// we use log(Gamma(x)) in order to avoid too big numbers
        double logGammaX = std::log(X.getInverseGammaFunction());
        double logGammaY = std::log(Y.getInverseGammaFunction());
        pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY;
        pdfCoef = std::exp(pdfCoef);
    }
    else {
        pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    }
    setVariateConstants();
}

void BetaRand::setAlpha(double shape1)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);
    pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setBeta(double shape2)
{
    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);
    pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

double BetaRand::f(double x) const
{
    if (x < 0 || x > 1)
        return 0;
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) < MIN_POSITIVE)
        return pdfCoef * std::pow(x - x * x, alpha - 1);
    double rv = std::pow(x, alpha - 1);
    rv *= std::pow(1 - x, beta - 1);
    return pdfCoef * rv;
}

double BetaRand::F(double x) const
{
    if (x <= 0)
        return 0;
    if (x >= 1)
        return 1;
    return RandMath::integral([this] (double t)
    {
        return BetaRand::f(t);
    },
    0, x);
}

double BetaRand::variate() const
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (!RandMath::areEqual(alpha, beta) || alpha < 1)
        return variateForDifferentParameters();
    if (alpha == 1)
        return UniformRand::standardVariate();
    if (alpha <= edgeForGenerators)
        return variateForSmallEqualParameters();
    return variateForLargeEqualParameters();
}

void BetaRand::sample(QVector<double> &outputData)
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (!RandMath::areEqual(alpha, beta) || alpha < 1) {
        for (double &var : outputData)
            var = variateForDifferentParameters();
    }
    else if (alpha == 1) {
        for (double &var : outputData)
            var = UniformRand::standardVariate();
    }
    else if (alpha <= edgeForGenerators) {
        for (double &var : outputData)
            var = variateForSmallEqualParameters();
    }
    else {
        for (double &var : outputData)
            var = variateForLargeEqualParameters();
    }
}

double BetaRand::variateForSmallEqualParameters() const
{
    double alpha = X.getShape();
    int iter = 0;
    do {
        double u1 = UniformRand::standardVariate();
        double u2 = UniformRand::standardVariate();
        if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
            return u1;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForLargeEqualParameters() const
{
    int iter = 0;
    do {
        double n = N.variate();
        if (n < 0 || n > 1)
            continue;
        double u = UniformRand::standardVariate();
        if (u < N.f(n) / (variateCoef * f(n)))
            return n;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForDifferentParameters() const
{
    double x = X.variate();
    return x / (x + Y.variate());
}

void BetaRand::setVariateConstants()
{
    double alpha = X.getShape();
    /// We need to storage variate coefficient only if alpha = beta and large enough
    if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE)
    {
        double t = 1.0 / (alpha + alpha + 1);
        variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t);
        variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1);
        variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)

        N.setMean(0.5);
        N.setVar(0.25 * t);
    }
}

double BetaRand::E() const
{
    return X.getShape() / (X.getShape() + Y.getShape());
}

double BetaRand::Var() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double denominator = alpha + beta;
    denominator *= denominator * (denominator + 1);
    return alpha * beta / denominator;
}

double BetaRand::Quantile(double p) const
{
    if (p < 0 || p > 1)
        return NAN;
    double root = p;
    if (RandMath::findRoot([this, p] (double x)
    {
        return BetaRand::F(x) - p;
    },
    0, 1, root))
        return root;
    return NAN;
}

double BetaRand::Mode() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    return (alpha - 1) / (alpha + beta - 2);
}

double BetaRand::Skewness() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double skewness = (alpha + beta + 1) / (alpha * beta);
    skewness = std::sqrt(skewness);
    skewness *= (alpha - beta);
    skewness /= (alpha + beta + 2);
    return skewness + skewness;
}

double BetaRand::ExcessKurtosis() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double sum = alpha + beta;
    double kurtosis = alpha - beta;
    kurtosis *= kurtosis;
    kurtosis *= (sum + 1);
    kurtosis /= (alpha * beta * (sum + 2));
    --kurtosis;
    kurtosis /= (sum + 3);
    return 6 * kurtosis;
}
<commit_msg>Update BetaRand.cpp<commit_after>#include "BetaRand.h"

BetaRand::BetaRand(double shape1, double shape2)
{
    setParameters(shape1, shape2);
}

std::string BetaRand::name()
{
    return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}

void BetaRand::setParameters(double shape1, double shape2)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);

    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);

    if (alpha + beta > 30)
    {
        /// we use log(Gamma(x)) in order to avoid too big numbers
        double logGammaX = std::log(X.getInverseGammaFunction());
        double logGammaY = std::log(Y.getInverseGammaFunction());
        pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY;
        pdfCoef = std::exp(pdfCoef);
    }
    else {
        pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    }
    setVariateConstants();
}

void BetaRand::setAlpha(double shape1)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);
    pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setBeta(double shape2)
{
    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);
    pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

double BetaRand::f(double x) const
{
    if (x < 0 || x > 1)
        return 0;
    double alpha = X.getShape(), beta = Y.getShape();
    if (RandMath::areEqual(alpha, beta))
        return pdfCoef * std::pow(x - x * x, alpha - 1);
    double rv = std::pow(x, alpha - 1);
    rv *= std::pow(1 - x, beta - 1);
    return pdfCoef * rv;
}

double BetaRand::F(double x) const
{
    if (x <= 0)
        return 0;
    if (x >= 1)
        return 1;
    return RandMath::integral([this] (double t)
    {
        return BetaRand::f(t);
    },
    0, x);
}

double BetaRand::variate() const
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (!RandMath::areEqual(alpha, beta) || alpha < 1)
        return variateForDifferentParameters();
    if (alpha == 1)
        return UniformRand::standardVariate();
    if (alpha <= edgeForGenerators)
        return variateForSmallEqualParameters();
    return variateForLargeEqualParameters();
}

void BetaRand::sample(QVector<double> &outputData)
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (!RandMath::areEqual(alpha, beta) || alpha < 1) {
        for (double &var : outputData)
            var = variateForDifferentParameters();
    }
    else if (alpha == 1) {
        for (double &var : outputData)
            var = UniformRand::standardVariate();
    }
    else if (alpha <= edgeForGenerators) {
        for (double &var : outputData)
            var = variateForSmallEqualParameters();
    }
    else {
        for (double &var : outputData)
            var = variateForLargeEqualParameters();
    }
}

double BetaRand::variateForSmallEqualParameters() const
{
    double alpha = X.getShape();
    int iter = 0;
    do {
        double u1 = UniformRand::standardVariate();
        double u2 = UniformRand::standardVariate();
        if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
            return u1;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForLargeEqualParameters() const
{
    int iter = 0;
    do {
        double n = N.variate();
        if (n < 0 || n > 1)
            continue;
        double u = UniformRand::standardVariate();
        if (u < N.f(n) / (variateCoef * f(n)))
            return n;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForDifferentParameters() const
{
    double x = X.variate();
    return x / (x + Y.variate());
}

void BetaRand::setVariateConstants()
{
    double alpha = X.getShape();
    /// We need to storage variate coefficient only if alpha = beta and large enough
    if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE)
    {
        double t = 1.0 / (alpha + alpha + 1);
        variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t);
        variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1);
        variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)

        N.setMean(0.5);
        N.setVar(0.25 * t);
    }
}

double BetaRand::E() const
{
    return X.getShape() / (X.getShape() + Y.getShape());
}

double BetaRand::Var() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double denominator = alpha + beta;
    denominator *= denominator * (denominator + 1);
    return alpha * beta / denominator;
}

double BetaRand::Quantile(double p) const
{
    if (p < 0 || p > 1)
        return NAN;
    double root = p;
    if (RandMath::findRoot([this, p] (double x)
    {
        return BetaRand::F(x) - p;
    },
    0, 1, root))
        return root;
    return NAN;
}

double BetaRand::Mode() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    return (alpha - 1) / (alpha + beta - 2);
}

double BetaRand::Skewness() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double skewness = (alpha + beta + 1) / (alpha * beta);
    skewness = std::sqrt(skewness);
    skewness *= (alpha - beta);
    skewness /= (alpha + beta + 2);
    return skewness + skewness;
}

double BetaRand::ExcessKurtosis() const
{
    double alpha = X.getShape();
    double beta = Y.getShape();
    double sum = alpha + beta;
    double kurtosis = alpha - beta;
    kurtosis *= kurtosis;
    kurtosis *= (sum + 1);
    kurtosis /= (alpha * beta * (sum + 2));
    --kurtosis;
    kurtosis /= (sum + 3);
    return 6 * kurtosis;
}
<|endoftext|>


<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <boost/python.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;

extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;

namespace
{

  bool listen_on(session& s, int min_, int max_, char const* interface)
  {
      allow_threading_guard guard;
      return s.listen_on(std::make_pair(min_, max_), interface);
  }

  struct invoke_extension_factory
  {
      invoke_extension_factory(object const& callback)
        : cb(callback)
      {}

      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
      {
          lock_gil lock;
          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
      }

      object cb;
  };

  void add_extension(session& s, object const& e)
  {
      allow_threading_guard guard;
      s.add_extension(invoke_extension_factory(e));
  }

  torrent_handle add_torrent(session& s, torrent_info const& ti
    , boost::filesystem::path const& save, entry const& resume
    , storage_mode_t storage_mode, bool paused)
  {
    allow_threading_guard guard;
    return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
  }

} // namespace unnamed

void bind_session()
{
    class_<session_status>("session_status", session_status_doc)
        .def_readonly(
            "has_incoming_connections", &session_status::has_incoming_connections
          , session_status_has_incoming_connections_doc
        )
        .def_readonly(
            "upload_rate", &session_status::upload_rate
          , session_status_upload_rate_doc
        )
        .def_readonly(
            "download_rate", &session_status::download_rate
          , session_status_download_rate_doc
        )
        .def_readonly(
            "payload_upload_rate", &session_status::payload_upload_rate
          , session_status_payload_upload_rate_doc
        )
        .def_readonly(
            "payload_download_rate", &session_status::payload_download_rate
          , session_status_payload_download_rate_doc
        )
        .def_readonly(
            "total_download", &session_status::total_download
          , session_status_total_download_doc
        )
        .def_readonly(
            "total_upload", &session_status::total_upload
          , session_status_total_upload_doc
        )
        .def_readonly(
            "total_payload_download", &session_status::total_payload_download
          , session_status_total_payload_download_doc
        )
        .def_readonly(
            "total_payload_upload", &session_status::total_payload_upload
          , session_status_total_payload_upload_doc
        )
        .def_readonly(
            "num_peers", &session_status::num_peers
          , session_status_num_peers_doc
        )
#ifndef TORRENT_DISABLE_DHT
        .def_readonly(
            "dht_nodes", &session_status::dht_nodes
          , session_status_dht_nodes_doc
        )
        .def_readonly(
            "dht_cache_nodes", &session_status::dht_node_cache
          , session_status_cache_nodes_doc
        )
        .def_readonly(
            "dht_torrents", &session_status::dht_torrents
          , session_status_dht_torrents_doc
        )
#endif
        ;

    enum_<storage_mode_t>("storage_mode_t")
        .value("storage_mode_allocate", storage_mode_allocate)
        .value("storage_mode_compact", storage_mode_compact)
        .value("storage_mode_sparse", storage_mode_sparse)
    ;

    enum_<session::options_t>("options_t")
        .value("none", session::none)
        .value("delete_files", session::delete_files)
    ;

    class_<session, boost::noncopyable>("session", session_doc, no_init)
        .def(
            init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
        )
        .def(
            "listen_on", &listen_on
          , (arg("min"), "max", arg("interface") = (char const*)0)
          , session_listen_on_doc
        )
        .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
        .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
        .def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
        .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
        .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
        .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
#endif
        .def(
            "add_torrent", &add_torrent
          , (
                arg("resume_data") = entry(), arg("compact_mode") = true
                , arg("paused") = false
            )
          , session_add_torrent_doc
        )
        .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc)
        .def(
            "set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
          , session_set_download_rate_limit_doc
        )
        .def(
            "download_rate_limit", allow_threads(&session::download_rate_limit)
          , session_download_rate_limit_doc
        )

        .def(
            "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
          , session_set_upload_rate_limit_doc
        )
        .def(
            "upload_rate_limit", allow_threads(&session::upload_rate_limit)
          , session_upload_rate_limit_doc
        )

        .def(
            "set_max_uploads", allow_threads(&session::set_max_uploads)
          , session_set_max_uploads_doc
        )
        .def(
            "set_max_connections", allow_threads(&session::set_max_connections)
          , session_set_max_connections_doc
        )
        .def(
            "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
          , session_set_max_half_open_connections_doc
        )
        .def(
            "num_connections", allow_threads(&session::num_connections)
          , session_num_connections_doc
        )
        .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
        .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
        .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
        .def(
            "set_severity_level", allow_threads(&session::set_severity_level)
          , session_set_severity_level_doc
        )
        .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
        .def("add_extension", &add_extension)
        .def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
        .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
        .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
#ifndef TORRENT_DISABLE_DHT
        .def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
        .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc)
        .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
        .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc)
        .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
        ;

    register_ptr_to_python<std::auto_ptr<alert> >();
}

<commit_msg>python binding fix<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <boost/python.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;

extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;

namespace
{

  bool listen_on(session& s, int min_, int max_, char const* interface)
  {
      allow_threading_guard guard;
      return s.listen_on(std::make_pair(min_, max_), interface);
  }

  struct invoke_extension_factory
  {
      invoke_extension_factory(object const& callback)
        : cb(callback)
      {}

      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
      {
          lock_gil lock;
          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
      }

      object cb;
  };

  void add_extension(session& s, object const& e)
  {
      allow_threading_guard guard;
      s.add_extension(invoke_extension_factory(e));
  }

  torrent_handle add_torrent(session& s, torrent_info const& ti
    , boost::filesystem::path const& save, entry const& resume
    , storage_mode_t storage_mode, bool paused)
  {
    allow_threading_guard guard;
    return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
  }

} // namespace unnamed

void bind_session()
{
    class_<session_status>("session_status", session_status_doc)
        .def_readonly(
            "has_incoming_connections", &session_status::has_incoming_connections
          , session_status_has_incoming_connections_doc
        )
        .def_readonly(
            "upload_rate", &session_status::upload_rate
          , session_status_upload_rate_doc
        )
        .def_readonly(
            "download_rate", &session_status::download_rate
          , session_status_download_rate_doc
        )
        .def_readonly(
            "payload_upload_rate", &session_status::payload_upload_rate
          , session_status_payload_upload_rate_doc
        )
        .def_readonly(
            "payload_download_rate", &session_status::payload_download_rate
          , session_status_payload_download_rate_doc
        )
        .def_readonly(
            "total_download", &session_status::total_download
          , session_status_total_download_doc
        )
        .def_readonly(
            "total_upload", &session_status::total_upload
          , session_status_total_upload_doc
        )
        .def_readonly(
            "total_payload_download", &session_status::total_payload_download
          , session_status_total_payload_download_doc
        )
        .def_readonly(
            "total_payload_upload", &session_status::total_payload_upload
          , session_status_total_payload_upload_doc
        )
        .def_readonly(
            "num_peers", &session_status::num_peers
          , session_status_num_peers_doc
        )
#ifndef TORRENT_DISABLE_DHT
        .def_readonly(
            "dht_nodes", &session_status::dht_nodes
          , session_status_dht_nodes_doc
        )
        .def_readonly(
            "dht_cache_nodes", &session_status::dht_node_cache
          , session_status_cache_nodes_doc
        )
        .def_readonly(
            "dht_torrents", &session_status::dht_torrents
          , session_status_dht_torrents_doc
        )
#endif
        ;

    enum_<storage_mode_t>("storage_mode_t")
        .value("storage_mode_allocate", storage_mode_allocate)
        .value("storage_mode_compact", storage_mode_compact)
        .value("storage_mode_sparse", storage_mode_sparse)
    ;

    enum_<session::options_t>("options_t")
        .value("none", session::none)
        .value("delete_files", session::delete_files)
    ;

    class_<session, boost::noncopyable>("session", session_doc, no_init)
        .def(
            init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
        )
        .def(
            "listen_on", &listen_on
          , (arg("min"), "max", arg("interface") = (char const*)0)
          , session_listen_on_doc
        )
        .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
        .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
        .def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
        .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
        .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
        .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
#endif
        .def(
            "add_torrent", &add_torrent
          , (
                arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse,
                arg("paused") = false
            )
          , session_add_torrent_doc
        )
        .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc)
        .def(
            "set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
          , session_set_download_rate_limit_doc
        )
        .def(
            "download_rate_limit", allow_threads(&session::download_rate_limit)
          , session_download_rate_limit_doc
        )

        .def(
            "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
          , session_set_upload_rate_limit_doc
        )
        .def(
            "upload_rate_limit", allow_threads(&session::upload_rate_limit)
          , session_upload_rate_limit_doc
        )

        .def(
            "set_max_uploads", allow_threads(&session::set_max_uploads)
          , session_set_max_uploads_doc
        )
        .def(
            "set_max_connections", allow_threads(&session::set_max_connections)
          , session_set_max_connections_doc
        )
        .def(
            "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
          , session_set_max_half_open_connections_doc
        )
        .def(
            "num_connections", allow_threads(&session::num_connections)
          , session_num_connections_doc
        )
        .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
        .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
        .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
        .def(
            "set_severity_level", allow_threads(&session::set_severity_level)
          , session_set_severity_level_doc
        )
        .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
        .def("add_extension", &add_extension)
        .def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
        .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
        .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
#ifndef TORRENT_DISABLE_DHT
        .def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
        .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc)
        .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
        .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc)
        .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
        ;

    register_ptr_to_python<std::auto_ptr<alert> >();
}

<|endoftext|>