<commit_before>#pragma once

#include "spinlock.h"
#include "log2.hh"

#include <cstddef>
#include <type_traits>

namespace locked_snzi
{
  class referenced
  {
    enum {
      LEVELS = ceil_log2_const(NCPU) + 1,
      FIRST_LEAF = (1 << (LEVELS - 1)) - 1
    };

    // A binary SNZI tree, indexed starting at the root.  For example,
    // for NCPU=8
    //              0
    //       1             2
    //    3     4       5     6
    //   7 8   9 10   11 12 13 14
    // The bottom level may be incomplete if NCPU is not a power of two.
    struct node
    {
      // XXX No padding for space reasons.  Would be better if we
      // could stride allocate this between different SNZIs.
      // XXX Could use a bit_spinlock and pack it into val.
      spinlock lock;
      uint64_t val;

      constexpr node() : lock("locked_snzi::referenced::node"), val(0) {}
    } nodes[FIRST_LEAF + NCPU];

    /// Return the parent of @c nodes[n].
    static inline std::size_t parent(std::size_t n)
    {
      return (n - 1)/2;
    }

    /// Return the first child of @c nodes[n].  The second child is
    /// the returned index plus one.
    static inline std::size_t first_child(std::size_t n)
    {
      return 2*n + 1;
    }

    /// Return the sibling of @c nodes[n].
    static inline std::size_t sibling(std::size_t n)
    {
      return ((n + 1) ^ 1) - 1;
    }

  public:
    referenced() : nodes{} { }

    referenced(const referenced &o) = delete;
    referenced(referenced &&o) = delete;
    referenced &operator=(const referenced &o) = delete;
    referenced &operator=(referenced &&o) = delete;

    typedef uint16_t cookie;
    static_assert(NCPU < (256 << sizeof(cookie)),
                  "cookie too small for NCPU");

    // XXX This is awkward.  Unlike all other referenced types, we
    // initialize the count to zero and require an initial_inc because
    // the caller needs the cookie.  This also screws up the transfer
    // method of sref<locked_snzi::referenced>.
    cookie initial_inc()
    {
      assert(nodes[0].val == 0);
      cookie leaf = myid();
      std::size_t node = leaf + FIRST_LEAF;
      while (true) {
        nodes[node].val = 1;
        if (node == 0)
          break;
        node = parent(node);
      }
      return leaf;
    }

    cookie inc()
    {
      cookie leaf = myid();
      std::size_t node = leaf + FIRST_LEAF;
      nodes[node].lock.acquire();
      while (true) {
        if (nodes[node].val++ || node == 0) {
          // Already non-zero or we've reached the root
          nodes[node].lock.release();
          return leaf;
        } else {
          // Transitioned from zero to non-zero
          std::size_t next = parent(node);
          nodes[next].lock.acquire();
          nodes[node].lock.release();
          node = next;
        }
      }
      return leaf;
    }

    void dec(cookie c)
    {
      std::size_t node = c + FIRST_LEAF;
      nodes[node].lock.acquire();
      while (true) {
        assert(nodes[node].val);
        if (--nodes[node].val) {
          // Still non-zero
          nodes[node].lock.release();
          return;
        } else if (node == 0) {
          // Transitioned from non-zero to zero at root
          nodes[node].lock.release();
          onzero();
          return;
        } else {
          // Transitioned from non-zero to zero
          std::size_t next = parent(node);
          nodes[next].lock.acquire();
          nodes[node].lock.release();
          node = next;
        }
      }
    }

  protected:
    virtual ~referenced() { }
    virtual void onzero() { delete this; }
  };
}

// XXX This specialization is unfortunate because it means that,
// unlike a regular pointer, sref cannot be applied to an incomplete
// type because we can't evaluate is_base_of.

template<class T>
class sref<T, typename std::enable_if<std::is_base_of<locked_snzi::referenced, T>::value>::type>
{
  T *ptr_;
  // XXX(Austin) Cookies are small.  Could possibly tuck away in
  // unused bits of ptr_.
  typename T::cookie cookie_;

  constexpr sref(T *ptr, typename T::cookie cookie) noexcept
    : ptr_(ptr), cookie_(cookie) { }

public:
  constexpr sref() noexcept : ptr_(nullptr), cookie_() { }

  sref(const sref &o) : ptr_(o.ptr_)
  {
    if (ptr_)
      cookie_ = ptr_->inc();
  }

  sref(sref &&o) noexcept : ptr_(o.ptr_), cookie_(o.cookie_)
  {
    o.ptr_ = nullptr;
  }

  ~sref()
  {
    if (ptr_)
      ptr_->dec(cookie_);
  }

  sref& operator=(const sref& o)
  {
    T *optr = o.ptr_;
    if (optr != ptr_) {
      typename T::cookie ocookie = 0;
      if (optr)
        ocookie = optr->inc();
      if (ptr_)
        ptr_->dec(cookie_);
      ptr_ = optr;
      cookie_ = ocookie;
    }
    return *this;
  }

  sref& operator=(sref&& o) {
    if (ptr_)
      ptr_->dec(cookie_);
    ptr_ = o.ptr_;
    cookie_ = o.cookie_;
    o.ptr_ = nullptr;
    return *this;
  }

  static sref transfer(T* p) {
    // XXX(Austin) This is a complete hack.  See comment on
    // initial_inc.
    typename T::cookie c = p->initial_inc();
    return sref(p, c);
  }

  explicit operator bool() const noexcept { return !!ptr_; }

  T * operator->() const noexcept { return ptr_; }
  T & operator*() const noexcept { return *ptr_; }
  T * get() const noexcept { return ptr_; }
};
<commit_msg>snzi: Disable specialized sref<commit_after>#pragma once

#include "spinlock.h"
#include "log2.hh"

#include <cstddef>
#include <type_traits>

namespace locked_snzi
{
  class referenced
  {
    enum {
      LEVELS = ceil_log2_const(NCPU) + 1,
      FIRST_LEAF = (1 << (LEVELS - 1)) - 1
    };

    // A binary SNZI tree, indexed starting at the root.  For example,
    // for NCPU=8
    //              0
    //       1             2
    //    3     4       5     6
    //   7 8   9 10   11 12 13 14
    // The bottom level may be incomplete if NCPU is not a power of two.
    struct node
    {
      // XXX No padding for space reasons.  Would be better if we
      // could stride allocate this between different SNZIs.
      // XXX Could use a bit_spinlock and pack it into val.
      spinlock lock;
      uint64_t val;

      constexpr node() : lock("locked_snzi::referenced::node"), val(0) {}
    } nodes[FIRST_LEAF + NCPU];

    /// Return the parent of @c nodes[n].
    static inline std::size_t parent(std::size_t n)
    {
      return (n - 1)/2;
    }

    /// Return the first child of @c nodes[n].  The second child is
    /// the returned index plus one.
    static inline std::size_t first_child(std::size_t n)
    {
      return 2*n + 1;
    }

    /// Return the sibling of @c nodes[n].
    static inline std::size_t sibling(std::size_t n)
    {
      return ((n + 1) ^ 1) - 1;
    }

  public:
    referenced() : nodes{} { }

    referenced(const referenced &o) = delete;
    referenced(referenced &&o) = delete;
    referenced &operator=(const referenced &o) = delete;
    referenced &operator=(referenced &&o) = delete;

    typedef uint16_t cookie;
    static_assert(NCPU < (256 << sizeof(cookie)),
                  "cookie too small for NCPU");

    // XXX This is awkward.  Unlike all other referenced types, we
    // initialize the count to zero and require an initial_inc because
    // the caller needs the cookie.  This also screws up the transfer
    // method of sref<locked_snzi::referenced>.
    cookie initial_inc()
    {
      assert(nodes[0].val == 0);
      cookie leaf = myid();
      std::size_t node = leaf + FIRST_LEAF;
      while (true) {
        nodes[node].val = 1;
        if (node == 0)
          break;
        node = parent(node);
      }
      return leaf;
    }

    cookie inc()
    {
      cookie leaf = myid();
      std::size_t node = leaf + FIRST_LEAF;
      nodes[node].lock.acquire();
      while (true) {
        if (nodes[node].val++ || node == 0) {
          // Already non-zero or we've reached the root
          nodes[node].lock.release();
          return leaf;
        } else {
          // Transitioned from zero to non-zero
          std::size_t next = parent(node);
          nodes[next].lock.acquire();
          nodes[node].lock.release();
          node = next;
        }
      }
      return leaf;
    }

    void dec(cookie c)
    {
      std::size_t node = c + FIRST_LEAF;
      nodes[node].lock.acquire();
      while (true) {
        assert(nodes[node].val);
        if (--nodes[node].val) {
          // Still non-zero
          nodes[node].lock.release();
          return;
        } else if (node == 0) {
          // Transitioned from non-zero to zero at root
          nodes[node].lock.release();
          onzero();
          return;
        } else {
          // Transitioned from non-zero to zero
          std::size_t next = parent(node);
          nodes[next].lock.acquire();
          nodes[node].lock.release();
          node = next;
        }
      }
    }

  protected:
    virtual ~referenced() { }
    virtual void onzero() { delete this; }
  };
}

#if 0
// XXX This specialization is unfortunate because it means that,
// unlike a regular pointer, sref cannot be applied to an incomplete
// type because we can't evaluate is_base_of.  Disable it since we're
// not using SNZI's.

template<class T>
class sref<T, typename std::enable_if<std::is_base_of<locked_snzi::referenced, T>::value>::type>
{
  T *ptr_;
  // XXX(Austin) Cookies are small.  Could possibly tuck away in
  // unused bits of ptr_.
  typename T::cookie cookie_;

  constexpr sref(T *ptr, typename T::cookie cookie) noexcept
    : ptr_(ptr), cookie_(cookie) { }

public:
  constexpr sref() noexcept : ptr_(nullptr), cookie_() { }

  sref(const sref &o) : ptr_(o.ptr_)
  {
    if (ptr_)
      cookie_ = ptr_->inc();
  }

  sref(sref &&o) noexcept : ptr_(o.ptr_), cookie_(o.cookie_)
  {
    o.ptr_ = nullptr;
  }

  ~sref()
  {
    if (ptr_)
      ptr_->dec(cookie_);
  }

  sref& operator=(const sref& o)
  {
    T *optr = o.ptr_;
    if (optr != ptr_) {
      typename T::cookie ocookie = 0;
      if (optr)
        ocookie = optr->inc();
      if (ptr_)
        ptr_->dec(cookie_);
      ptr_ = optr;
      cookie_ = ocookie;
    }
    return *this;
  }

  sref& operator=(sref&& o) {
    if (ptr_)
      ptr_->dec(cookie_);
    ptr_ = o.ptr_;
    cookie_ = o.cookie_;
    o.ptr_ = nullptr;
    return *this;
  }

  static sref transfer(T* p) {
    // XXX(Austin) This is a complete hack.  See comment on
    // initial_inc.
    typename T::cookie c = p->initial_inc();
    return sref(p, c);
  }

  explicit operator bool() const noexcept { return !!ptr_; }

  T * operator->() const noexcept { return ptr_; }
  T & operator*() const noexcept { return *ptr_; }
  T * get() const noexcept { return ptr_; }
};
#endif
<|endoftext|>


<commit_before>/** \file
 *
 *  Copyright (c) 2012 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"

#include <jsonv/value.hpp>
#include <jsonv/parse.hpp>

TEST(parse_unicode_single)
{
    std::string s = jsonv::parse("\"\\u0004\"").as_string();
    ensure(s.size() == 1);
    ensure(s[0] == '\x04');
}

TEST(parse_unicode_inline)
{
    std::string s = jsonv::parse("\"é\"").as_string();
    ensure(s.size() == 2);
    ensure(s[0] == '\xc3');
    ensure(s[1] == '\xa9');
}

TEST(parse_unicode_multi)
{
    std::string s = jsonv::parse("\"\\u00e9\"").as_string();
    ensure(s.size() == 2);
    ensure(s[0] == '\xc3');
    ensure(s[1] == '\xa9');
}

TEST(parse_unicode_insanity)
{
    std::string s = jsonv::parse("\"\\uface\"").as_string();
    ensure(s.size() == 3);
    // The right answer according to Python: u'\uface'.encode('utf-8')
    const char vals[] = "\xef\xab\x8e";
    for (unsigned idx = 0; idx < 3; ++idx)
        ensure(s[idx] == vals[idx]);
}

// TODO: This test should be re-enabled when parsing options are supported.
/*TEST(parse_unicode_invalid_surrogates)
{
    std::string s = jsonv::parse("\"\\udead\\ubeef\"").as_string();
    ensure(s.size() == 6);
    // The right answer according to Python: u'\udead\ubeef'.encode('utf-8')
    const char vals[] = "\xed\xba\xad\xeb\xbb\xaf";
    for (unsigned idx = 0; idx < sizeof vals; ++idx)
        ensure(s[idx] == vals[idx]);
}*/
<commit_msg>Re-enables unit test parse_unicode_invalid_surrogates and adds parse_unicode_invalid_surrogates_cesu8 for the invalid case.<commit_after>/** \file
 *
 *  Copyright (c) 2012-2014 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"

#include <jsonv/value.hpp>
#include <jsonv/parse.hpp>

TEST(parse_unicode_single)
{
    std::string s = jsonv::parse("\"\\u0004\"").as_string();
    ensure(s.size() == 1);
    ensure(s[0] == '\x04');
}

TEST(parse_unicode_inline)
{
    std::string s = jsonv::parse("\"é\"").as_string();
    ensure(s.size() == 2);
    ensure(s[0] == '\xc3');
    ensure(s[1] == '\xa9');
}

TEST(parse_unicode_multi)
{
    std::string s = jsonv::parse("\"\\u00e9\"").as_string();
    ensure(s.size() == 2);
    ensure(s[0] == '\xc3');
    ensure(s[1] == '\xa9');
}

TEST(parse_unicode_insanity)
{
    std::string s = jsonv::parse("\"\\uface\"").as_string();
    ensure(s.size() == 3);
    // The right answer according to Python: u'\uface'.encode('utf-8')
    const char vals[] = "\xef\xab\x8e";
    for (unsigned idx = 0; idx < 3; ++idx)
        ensure(s[idx] == vals[idx]);
}

TEST(parse_unicode_invalid_surrogates)
{
    ensure_throws(jsonv::parse_error, jsonv::parse("\"\\udead\\ubeef\"").as_string());
}

TEST(parse_unicode_invalid_surrogates_cesu8)
{
    std::string s = jsonv::parse("\"\\udead\\ubeef\"",
                                 jsonv::parse_options().string_encoding(jsonv::parse_options::encoding::cesu8)
                                ).as_string();
    ensure(s.size() == 6);
    // The right answer according to Python: u'\udead\ubeef'.encode('utf-8')
    const char vals[] = "\xed\xba\xad\xeb\xbb\xaf";
    for (unsigned idx = 0; idx < sizeof vals; ++idx)
        ensure(s[idx] == vals[idx]);
}
<|endoftext|>


<commit_before>#include "Data.h"

#include <CCfits/CCfits>

using namespace CCfits;

Data Data::instance;

Data::Data()
{

}

// A function for reading in Kepler light curve data from a FITS file.
// This uses the C++ CFITSIO interface CCfits.
// See http://heasarc.gsfc.nasa.gov/docs/software/fitsio/ccfits/html/readtable.html for an example

void Data::load(const char* filename)
{
  // use the verbose mode to output any errors in reading files
  FITS::setVerboseMode(true);

  // Empty the vectors
  t.clear(); // the light curve time stamps in days from the first value
  y.clear(); // the light curve flux

  // set the names of the Kepler FITS file HDUs
  std::vector<string> hdus(3);
  hdus[0] = "PRIMARY";
  hdus[1] = "LIGHTCURVE"; // contains the light curve data
  hdus[2] = "APERTURE";

  // create the FITS class (false means that all data is *not* read on construction)
  std::auto_ptr<FITS> pInfile(new FITS(filename, Read, hdus, false));

  // create a table for the LIGHTCURVE HDU
  ExtHDU& table = pInfile->extension(hdus[1]);

  long nrows = table.rows(); // number of values in the light curve

  // read in the times (in days in the light curve file) and make epoch from first time stamp
  table.column("TIME").read( t, 1, nrows ); // read from first row (1) to last
  for ( std::vector<double>::iterator i=t.begin(); i != t.end(); ++i ) { *i -= t[0]; }

  // data times step
  dt = t[1];

  // read in the light curve data from the PDCSAP_FLUX data channel
  //  - there are other channels available, see http://archive.stsci.edu/kepler/manuals/archive_manual.pdf
  table.column("PDCSAP_FLUX").read( y, 1, nrows );

  // loop through light curve and remove any NaN or inf entries
  int j = 0, i = 0, size = y.size();
  for ( i=0; i < size; i++ ){
    if ( std::isnan(y[j]) || std::isinf(y[j]) ){
      y.erase(y.begin()+j);
      t.erase(t.begin()+j);
    }
    else{ j++; }
  }

  // calculate median of the data
  std::vector<double> yc;
  yc = y; // copy of y
  size_t newsize = yc.size();
  std::sort(yc.begin(), yc.end()); // sort for median
  if ( newsize % 2 == 0 ){ y_median = (yc[newsize/2 - 1] + yc[newsize/2]) / 2.; }
  else{ y_median = yc[newsize/2]; }

  // calculate the mean of the data
  y_mean = 0.;
  for ( i=0; i < (int)newsize; i++ ){ y_mean += y[i]; }
  y_mean /= (double)newsize;

  // remove the median from the data to rescale
  for ( i=0; i < (int)newsize; i++ ){ y[i] -= y_median; }
}

<commit_msg>Fixed data reading function so that NaNs do get removed<commit_after>#include "Data.h"

#include <CCfits/CCfits>
#include <cmath>

using namespace CCfits;

Data Data::instance;

Data::Data()
{

}

// A function for reading in Kepler light curve data from a FITS file.
// This uses the C++ CFITSIO interface CCfits.
// See http://heasarc.gsfc.nasa.gov/docs/software/fitsio/ccfits/html/readtable.html for an example

void Data::load(const char* filename)
{
  // use the verbose mode to output any errors in reading files
  FITS::setVerboseMode(true);

  // Empty the vectors
  t.clear(); // the light curve time stamps in days from the first value
  y.clear(); // the light curve flux

  // set the names of the Kepler FITS file HDUs
  std::vector<string> hdus(3);
  hdus[0] = "PRIMARY";
  hdus[1] = "LIGHTCURVE"; // contains the light curve data
  hdus[2] = "APERTURE";

  // create the FITS class (false means that all data is *not* read on construction)
  std::auto_ptr<FITS> pInfile(new FITS(filename, Read, hdus, false));

  // create a table for the LIGHTCURVE HDU
  ExtHDU& table = pInfile->extension(hdus[1]);

  long nrows = table.rows(); // number of values in the light curve

  // read in the times (in days in the light curve file) and make epoch from first time stamp
  table.column("TIME").read( t, 1, nrows ); // read from first row (1) to last
  for ( std::vector<double>::iterator i=t.begin(); i != t.end(); ++i ) { *i -= t[0]; }

  // data times step
  dt = t[1];

  // read in the light curve data from the PDCSAP_FLUX data channel
  //  - there are other channels available, see http://archive.stsci.edu/kepler/manuals/archive_manual.pdf
  table.column("PDCSAP_FLUX").read( y, 1, nrows );

  // loop through light curve and remove any NaN or inf entries
  std::vector<double>::iterator ity, itt;
  for (ity = y.begin(), itt = t.begin(); ity != y.end(); ){
    if ( isnan(*ity) || isinf(*ity) ){
      ity = y.erase(ity);
      itt = t.erase(itt);
    }
    else {
      ++ity;
      ++itt;
    }
  }

  // calculate median of the data
  std::vector<double> yc;
  yc = y; // copy of y
  size_t newsize = yc.size();
  std::sort(yc.begin(), yc.end()); // sort for median
  if ( newsize % 2 == 0 ){ y_median = (yc[newsize/2 - 1] + yc[newsize/2]) / 2.; }
  else{ y_median = yc[newsize/2]; }

  // calculate the mean of the data
  y_mean = 0.;
  for ( int i=0; i < (int)newsize; i++ ){ y_mean += y[i]; }
  y_mean /= (double)newsize;

  // remove the median from the data to rescale
  for ( int i=0; i < (int)newsize; i++ ){ y[i] -= y_median; }
}

<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "samplegeneratorjob.h"

// appleseed.renderer headers.
#include "renderer/kernel/rendering/progressive/samplecounter.h"
#include "renderer/kernel/rendering/accumulationframebuffer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/itilecallback.h"

// Standard headers.
#include <algorithm>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// SampleGeneratorJob class implementation.
//

namespace
{
    const size_t MinSampleCount     = 1024 * 4;     // minimum number of samples in one pass
    const size_t MaxSampleCount     = 1024 * 64;    // maximum number of samples in one pass
    const size_t MinSamplePassCount = 8;            // number of passes that will stick to the minimum number of samples
    const size_t SampleIncrement    = 1024 * 4;     // number of samples added at each pass
    const bool RoundRobinRender     = false;        // enable/disable Round Robin rendering

    size_t compute_sample_count(const size_t pass)
    {
        return
            pass < MinSamplePassCount ? MinSampleCount :
            min(
                MinSampleCount + (pass - MinSamplePassCount) * SampleIncrement,
                MaxSampleCount);
    }
}

SampleGeneratorJob::SampleGeneratorJob(
    Frame&                      frame,
    AccumulationFramebuffer&    framebuffer,
    ISampleGenerator*           sample_generator,
    SampleCounter&              sample_counter,
    ITileCallback*              tile_callback,
    JobQueue&                   job_queue,
    const size_t                job_index,
    const size_t                job_count,
    const size_t                pass,
    AbortSwitch&                abort_switch)
  : m_frame(frame)
  , m_framebuffer(framebuffer)
  , m_sample_generator(sample_generator)
  , m_sample_counter(sample_counter)
  , m_tile_callback(tile_callback)
  , m_job_queue(job_queue)
  , m_job_index(job_index)
  , m_job_count(job_count)
  , m_pass(pass)
  , m_abort_switch(abort_switch)
{
}

void SampleGeneratorJob::execute(const size_t thread_index)
{
    const size_t sample_count =
        m_sample_counter.reserve(compute_sample_count(m_pass));

    if (sample_count == 0)
        return;

    if (m_tile_callback)
    {
        m_tile_callback->pre_render(
            0,
            0,
            m_framebuffer.get_width(),
            m_framebuffer.get_height());
    }

    m_sample_generator->generate_samples(
        sample_count,
        m_framebuffer,
        m_abort_switch);

    if (!RoundRobinRender || m_pass % m_job_count == m_job_index)
        m_framebuffer.render_to_frame(m_frame);

    if (m_tile_callback)
        m_tile_callback->post_render(m_frame);

    if (!m_abort_switch.is_aborted())
    {
        m_job_queue.schedule(
            new SampleGeneratorJob(
                m_frame,
                m_framebuffer,
                m_sample_generator,
                m_sample_counter,
                m_tile_callback,
                m_job_queue,
                m_job_index,
                m_job_count,
                m_pass + 1,
                m_abort_switch));
    }
}

}   // namespace renderer
<commit_msg>tweaked the distribution of samples over rendering passes in the progressive renderer, and fixed a minor bug.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "samplegeneratorjob.h"

// appleseed.renderer headers.
#include "renderer/kernel/rendering/progressive/samplecounter.h"
#include "renderer/kernel/rendering/accumulationframebuffer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/itilecallback.h"

// Standard headers.
#include <algorithm>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// SampleGeneratorJob class implementation.
//

namespace
{
    const size_t MinSampleCount     = 1024 * 4;     // minimum number of samples in one pass
    const size_t MaxSampleCount     = 1024 * 128;   // maximum number of samples in one pass
    const size_t MinSamplePassCount = 6;            // number of passes that will stick to the minimum number of samples
    const size_t SampleIncrement    = 1024 * 8;     // number of samples added at each pass
    const bool RoundRobinRender     = false;        // enable/disable Round Robin rendering

    size_t compute_sample_count(const size_t pass)
    {
        return
            pass < MinSamplePassCount ? MinSampleCount :
            min(
                MinSampleCount + (pass - MinSamplePassCount + 1) * SampleIncrement,
                MaxSampleCount);
    }
}

SampleGeneratorJob::SampleGeneratorJob(
    Frame&                      frame,
    AccumulationFramebuffer&    framebuffer,
    ISampleGenerator*           sample_generator,
    SampleCounter&              sample_counter,
    ITileCallback*              tile_callback,
    JobQueue&                   job_queue,
    const size_t                job_index,
    const size_t                job_count,
    const size_t                pass,
    AbortSwitch&                abort_switch)
  : m_frame(frame)
  , m_framebuffer(framebuffer)
  , m_sample_generator(sample_generator)
  , m_sample_counter(sample_counter)
  , m_tile_callback(tile_callback)
  , m_job_queue(job_queue)
  , m_job_index(job_index)
  , m_job_count(job_count)
  , m_pass(pass)
  , m_abort_switch(abort_switch)
{
}

void SampleGeneratorJob::execute(const size_t thread_index)
{
    const size_t sample_count =
        m_sample_counter.reserve(compute_sample_count(m_pass));

    if (sample_count == 0)
        return;

    if (m_tile_callback)
    {
        m_tile_callback->pre_render(
            0,
            0,
            m_framebuffer.get_width(),
            m_framebuffer.get_height());
    }

    m_sample_generator->generate_samples(
        sample_count,
        m_framebuffer,
        m_abort_switch);

    if (!RoundRobinRender || m_pass % m_job_count == m_job_index)
        m_framebuffer.render_to_frame(m_frame);

    if (m_tile_callback)
        m_tile_callback->post_render(m_frame);

    if (!m_abort_switch.is_aborted())
    {
        m_job_queue.schedule(
            new SampleGeneratorJob(
                m_frame,
                m_framebuffer,
                m_sample_generator,
                m_sample_counter,
                m_tile_callback,
                m_job_queue,
                m_job_index,
                m_job_count,
                m_pass + 1,
                m_abort_switch));
    }
}

}   // namespace renderer
<|endoftext|>


<commit_before>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013, 2014 JCube001

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

#include <math.h>

#include "marg_filter.h"
#include "quaternion.h"

MARGFilter::MARGFilter() :
    Filter(),
    Eb_hat(Quaternion(0.0f, 1.0f, 0.0f, 0.0f)),
    Sw_b(Quaternion()),
    zeta(1.0f)
{
}

void MARGFilter::setGyroDriftGain(const float drift)
{
    zeta = sqrt(3.0f / 4.0f) * drift;
}

void MARGFilter::update(float wx, float wy, float wz,
                        float ax, float ay, float az,
                        float mx, float my, float mz)
{
    // Auxiliary variables to avoid repeated calculations
    const Quaternion two_SEq = 2.0f * SEq_hat;

    // Compute the magnetic flux in the earth frame
    const Quaternion Eh_hat = SEq_hat * Sm_hat * SEq_hat.conjugate();

    // Normalize the magnetic flux vector to have only x and z components
    Eb_hat = Quaternion(0.0f, sqrt((Eh_hat.x * Eh_hat.x) + (Eh_hat.y * Eh_hat.y)), 0.0f, Eh_hat.z);

    // Compute the gravity objective function
    const Quaternion f_g = SEq_hat.conjugate() * Eg_hat * SEq_hat
            - Quaternion(0.0f, ax, ay, az).normalized();

    // Compute the gravity Jacobian matrix
    // TODO

    // Compute the magnetic field objective function
    const Quaternion Sm_hat = Quaternion(0.0f, mx, my, mz).normalized();
    const Quaternion f_b = SEq_hat.conjugate() * Eb_hat * SEq_hat - Sm_hat;

    // Compute the magnetic field Jacobian matrix
    // TODO

    // Compute the normalized gradient descent (matrix multiplication)
    // TODO
    const Quaternion SEq_hat_dot =
            Quaternion().normalized;

    // Compute the angular estimated direction of gyroscope error then compute
    // and remove the gyroscope biases while computing the quaternion
    // derivative measured by the gyroscope
    Sw_b += zeta * (two_SEq.conjugate() * SEq_hat_dot) * deltaTime;
    const Quaternion SEq_dot_omega = 0.5f * SEq_hat * (Quaternion(0.0f, wx, wy, wz) - Sw_b);

    // Compute then integrate the estimated quaternion derivative
    SEq_hat += (SEq_dot_omega - (beta * SEq_hat_dot)) * deltaTime;

    // Normalize the output quaternion
    SEq_hat.normalize();
}

<commit_msg>Implemented the rest of the MARG filter<commit_after>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013, 2014 JCube001

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

#include <math.h>

#include "marg_filter.h"
#include "quaternion.h"

MARGFilter::MARGFilter() :
    Filter(),
    Eb_hat(Quaternion(0.0f, 1.0f, 0.0f, 0.0f)),
    Sw_b(Quaternion()),
    zeta(1.0f)
{
}

void MARGFilter::setGyroDriftGain(const float drift)
{
    zeta = sqrt(3.0f / 4.0f) * drift;
}

void MARGFilter::update(float wx, float wy, float wz,
                        float ax, float ay, float az,
                        float mx, float my, float mz)
{
    // Auxiliary variables to avoid repeated calculations
    const Quaternion two_SEq = 2.0f * SEq_hat;
    const Quaternion two_Eb = 2.0f * Eb_hat;
    const Quaternion two_Eb_x_SEq = two_Eb.x * SEq_hat;
    const Quaternion two_Eb_z_SEq = two_Eb.z * SEq_hat;

    // Compute the gravity objective function
    const Quaternion f_g = SEq_hat.conjugate() * Eg_hat * SEq_hat
            - Quaternion(0.0f, ax, ay, az).normalized();

    // Compute the gravity Jacobian matrix
    // Negative elements are negated in matrix multiplication
    const float J_11_or_24 = two_SEq.y;
    const float J_12_or_23 = two_SEq.z;
    const float J_13_or_22 = two_SEq.w;
    const float J_14_or_21 = two_SEq.x;
    const float J_32 = 2.0f * J_14_or_21;
    const float J_33 = 2.0f * J_11_or_24;

    // Compute the magnetic field objective function
    const Quaternion Sm_hat = Quaternion(0.0f, mx, my, mz).normalized();
    const Quaternion f_b = SEq_hat.conjugate() * Eb_hat * SEq_hat - Sm_hat;

    // Compute the magnetic field Jacobian matrix
    // Negative elements are negated in matrix multiplication
    const float J_41 = two_Eb_z_SEq.y;
    const float J_42 = two_Eb_z_SEq.z;
    const float J_43 = 2.0f * two_Eb_x_SEq.y + two_Eb_z_SEq.w;
    const float J_44 = 2.0f * two_Eb_x_SEq.z - two_Eb_z_SEq.x;
    const float J_51 = two_Eb_x_SEq.z - two_Eb_z_SEq.x;
    const float J_52 = two_Eb_x_SEq.y + two_Eb_z_SEq.w;
    const float J_53 = two_Eb_x_SEq.x + two_Eb_z_SEq.z;
    const float J_54 = two_Eb_x_SEq.w - two_Eb_z_SEq.y;
    const float J_61 = two_Eb_x_SEq.y;
    const float J_62 = two_Eb_x_SEq.z - 2.0f * two_Eb_z_SEq.x;
    const float J_63 = two_Eb_x_SEq.w - 2.0f * two_Eb_z_SEq.y;
    const float J_64 = two_Eb_x_SEq.x;

    // Compute the normalized gradient descent (matrix multiplication)
    const Quaternion SEq_hat_dot =
            Quaternion(J_14_or_21 * f_g.y - J_11_or_24 * f_g.x - J_41 * f_b.x - J_51 * f_b.y + J_61 * f_b.z,
                       J_12_or_23 * f_g.x + J_13_or_22 * f_g.y - J_32 * f_g.z + J_42 * f_b.x + J_52 * f_b.y + J_62 * f_b.z,
                       J_12_or_23 * f_g.y - J_33 * f_g.z - J_13_or_22 * f_g.x - J_43 * f_b.x + J_53 * f_b.y + J_63 * f_b.z,
                       J_14_or_21 * f_g.x + J_11_or_24 * f_g.y - J_44 * f_b.x - J_54 * f_b.y + J_64 * f_b.z).normalized();

    // Compute the angular estimated direction of gyroscope error then compute
    // and remove the gyroscope biases while computing the quaternion
    // derivative measured by the gyroscope
    Sw_b += zeta * (two_SEq.conjugate() * SEq_hat_dot) * deltaTime;
    const Quaternion SEq_dot_omega = 0.5f * SEq_hat * (Quaternion(0.0f, wx, wy, wz) - Sw_b);

    // Compute then integrate the estimated quaternion derivative
    SEq_hat += (SEq_dot_omega - (beta * SEq_hat_dot)) * deltaTime;

    // Normalize the output quaternion
    SEq_hat.normalize();

    // Compute the magnetic flux in the earth frame
    const Quaternion Eh_hat = SEq_hat * Sm_hat * SEq_hat.conjugate();

    // Normalize the magnetic flux vector to have only x and z components
    Eb_hat = Quaternion(0.0f, sqrt((Eh_hat.x * Eh_hat.x) + (Eh_hat.y * Eh_hat.y)), 0.0f, Eh_hat.z);
}

<|endoftext|>


<commit_before>#include "webcam.hpp"
#include <chrono>

using namespace cv;
using namespace std;

Mat ellipticKernel(int width, int height = -1) {
 if (height==-1) {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
 } else {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
 }
}

unsigned long long getMilliseconds() {
 return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}

void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
 int width, height;
 width = inout.size().width;
 height = inout.size().height;
 Mat downsample;
 resize(inout, downsample, Size(smallsize,smallsize));
 Mat kernel = ellipticKernel(factor);
 if (diler) {
  erode(downsample, downsample, kernel);
 } else {
  dilate(downsample, downsample, kernel);
 }
 if (eq) {
  equalizeHist(downsample, downsample);
 }
 resize(downsample, inout, Size(width, height));
}

int main (int argc, char** argv) {

 int tracker1, tracker2, tracker3;
 namedWindow("s",1);
 createTrackbar("1","s",&tracker1,100);
 createTrackbar("2","s",&tracker2,100);
 createTrackbar("3","s",&tracker3,100);

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 unsigned long long times[100];
 int f = 0;
 for (int i=0; i<100; i++)
  times[i] = 0;

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));

 Mat image;
 Mat channel[3];
 unsigned long long timenow = getMilliseconds();

 while (keepGoing) {
  image = cvQueryFrame(capture);
  times[0] += getMilliseconds() - timenow;
  timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
//  imshow("webcam", image);

// let's make multiple masks where 0=not mouth, 1=uncertain

// then multiply them together and multiply that with image
// and run haar classifier on image

  Mat gray, blurred_img;
  cvtColor(image, gray, CV_RGB2GRAY);
  blur(image, blurred_img, Size(50,50));
  times[1] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 200, 1, THRESH_BINARY);
  blur(canny*255, canny, Size(width/10, height/10));
  threshold(canny, canny, 220, 1, THRESH_BINARY);
  imshow("canny mask", gray.mul(canny));
*/

// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
  Mat flow;
  absdiff(blurred_img, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  morphFast(flow);
  threshold(flow, flow, 60, 1, THRESH_BINARY);
//  imshow("flow mask", gray.mul(flow));
  times[2] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask gets anything kind of dark (DK2) and dilates
  Mat kindofdark;
  equalizeHist(gray, kindofdark);
  threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
  morphFast(kindofdark, 100, 17, 0);
//  imshow("dark mask", gray.mul(kindofdark));
  times[3] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
  Mat notlips;
  Mat channels[3];
  split(image, channels);
  channels[2].convertTo(notlips, CV_32FC1);
  divide(notlips, gray, notlips, 1, CV_32FC1);
  //equalistHist is horrible for a red background
  //equalizeHist(notlips, notlips);
  threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
  notlips.convertTo(notlips, CV_8UC1);
  imshow("lip mask", notlips*255);
  Mat otherMorph = notlips.clone();
  int tx = tracker1+1-(tracker1%2);
  if (tx<3) tx=1;
  if (tx>90) tx=91;
  morphFast(notlips, 100, tx, 0, 0);
  int ty = tracker2+1-(tracker2%2);
  if (ty<3) ty=1;
  if (ty>90) ty=91;
  morphFast(notlips, 100, ty, 0, 1);
  imshow("lips2", notlips.mul(gray));
  morphFast(otherMorph, 100, tx, 0, 1);
  morphFast(otherMorph, 100, tx, 0, 0);
  imshow("lips3", otherMorph.mul(gray));
  waitKey(1);
*/

  Mat mask = flow.mul(kindofdark);
// open the mask
  Mat smallMask0, smallMask1;
  resize(mask, smallMask0, Size(width/5,height/5));
  Mat smallKernel = ellipticKernel(69,79);
  erode(smallMask0, smallMask1, smallKernel);
  dilate(smallMask1, smallMask1, smallKernel);
  bitwise_and(smallMask0, smallMask1, smallMask1);
  resize(smallMask1, mask, Size(width, height));
//  imshow("morph mask", gray.mul(mask));
  times[4] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg

/*
// actually dilation is slow and our current mask is already
// really nice :)
  Mat dilatedMask;
  dilate(smallMask1, dilatedMask, smallKernel);
  resize(dilatedMask, dilatedMask, Size(width, height));
  imshow("erosion", dilatedMask.mul(gray));
*/
  Mat mask_;
  subtract(1, mask ,mask_);
  Mat mask3, mask3_;
  channel[0] = mask;
  channel[1] = mask;
  channel[2] = mask;
  merge(channel, 3, mask3);
  channel[0] = mask_;
  channel[1] = mask_;
  channel[2] = mask_;
  merge(channel, 3, mask3_);

  background = background.mul(mask3) +
   (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
  times[5] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

//  imshow("background", background);

/*
  Moments lol = moments(gray, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
*/

  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  int scale = 3;
  Mat classifyThis;
  equalizeHist(gray, gray);//ew; watch out not to use this later
  resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
//  bilateralFilter(gray, classifyThis, 15, 10, 1);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
  Mat rectImage(width, height, CV_8UC1, Scalar(0));
  for (size_t i=0; i<mouths.size(); i++) {
   Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
//   rectangle(image, scaled, Scalar(255,0,0));
//   rectangle(rectImage, scaled, Scalar(1), 5);
  }
//  blur(rectImage, rectImage, Size(tracker2+1,tracker2+1));
//  threshold(rectImage, rectImage, tracker1, 1, THRESH_BINARY);
  times[6] += getMilliseconds() - timenow;
  timenow = getMilliseconds();
  imshow("MOUTH", gray.mul(rectImage));

  for (int i=0; i<7; i++) {
   printf("%llu , ", times[i]);
   times[i] = 0;
  }

  printf("\n");

  keepGoing = (waitKey(1)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>

using namespace cv;
using namespace std;

Mat ellipticKernel(int width, int height = -1) {
 if (height==-1) {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
 } else {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
 }
}

unsigned long long getMilliseconds() {
 return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}

void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
 int width, height;
 width = inout.size().width;
 height = inout.size().height;
 Mat downsample;
 resize(inout, downsample, Size(smallsize,smallsize));
 Mat kernel = ellipticKernel(factor);
 if (diler) {
  erode(downsample, downsample, kernel);
 } else {
  dilate(downsample, downsample, kernel);
 }
 if (eq) {
  equalizeHist(downsample, downsample);
 }
 resize(downsample, inout, Size(width, height));
}

int main (int argc, char** argv) {

 int tracker1, tracker2, tracker3;
 namedWindow("s",1);
 createTrackbar("1","s",&tracker1,100);
 createTrackbar("2","s",&tracker2,100);
 createTrackbar("3","s",&tracker3,100);

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 unsigned long long times[100];
 int f = 0;
 for (int i=0; i<100; i++)
  times[i] = 0;

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));

 Mat image;
 Mat channel[3];
 unsigned long long timenow = getMilliseconds();

 while (keepGoing) {
  image = cvQueryFrame(capture);
  times[0] += getMilliseconds() - timenow;
  timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
//  imshow("webcam", image);

// let's make multiple masks where 0=not mouth, 1=uncertain

// then multiply them together and multiply that with image
// and run haar classifier on image

  Mat gray, blurred_img;
  cvtColor(image, gray, CV_RGB2GRAY);
  blur(image, blurred_img, Size(50,50));
  times[1] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 200, 1, THRESH_BINARY);
  blur(canny*255, canny, Size(width/10, height/10));
  threshold(canny, canny, 220, 1, THRESH_BINARY);
  imshow("canny mask", gray.mul(canny));
*/

// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
  Mat flow;
  absdiff(blurred_img, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  morphFast(flow);
  threshold(flow, flow, 60, 1, THRESH_BINARY);
//  imshow("flow mask", gray.mul(flow));
  times[2] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask gets anything kind of dark (DK2) and dilates
  Mat kindofdark;
  equalizeHist(gray, kindofdark);
  threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
  morphFast(kindofdark, 100, 17, 0);
//  imshow("dark mask", gray.mul(kindofdark));
  times[3] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
  Mat notlips;
  Mat channels[3];
  split(image, channels);
  channels[2].convertTo(notlips, CV_32FC1);
  divide(notlips, gray, notlips, 1, CV_32FC1);
  //equalistHist is horrible for a red background
  //equalizeHist(notlips, notlips);
  threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
  notlips.convertTo(notlips, CV_8UC1);
  imshow("lip mask", notlips*255);
  Mat otherMorph = notlips.clone();
  int tx = tracker1+1-(tracker1%2);
  if (tx<3) tx=1;
  if (tx>90) tx=91;
  morphFast(notlips, 100, tx, 0, 0);
  int ty = tracker2+1-(tracker2%2);
  if (ty<3) ty=1;
  if (ty>90) ty=91;
  morphFast(notlips, 100, ty, 0, 1);
  imshow("lips2", notlips.mul(gray));
  morphFast(otherMorph, 100, tx, 0, 1);
  morphFast(otherMorph, 100, tx, 0, 0);
  imshow("lips3", otherMorph.mul(gray));
  waitKey(1);
*/

  Mat mask = flow.mul(kindofdark);
// open the mask
  Mat smallMask0, smallMask1;
  resize(mask, smallMask0, Size(width/5,height/5));
  Mat smallKernel = ellipticKernel(69,79);
  erode(smallMask0, smallMask1, smallKernel);
  dilate(smallMask1, smallMask1, smallKernel);
  bitwise_and(smallMask0, smallMask1, smallMask1);
  resize(smallMask1, mask, Size(width, height));
//  imshow("morph mask", gray.mul(mask));
  times[4] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg

/*
// actually dilation is slow and our current mask is already
// really nice :)
  Mat dilatedMask;
  dilate(smallMask1, dilatedMask, smallKernel);
  resize(dilatedMask, dilatedMask, Size(width, height));
  imshow("erosion", dilatedMask.mul(gray));
*/
  Mat mask_;
  subtract(1, mask ,mask_);
  Mat mask3, mask3_;
  channel[0] = mask;
  channel[1] = mask;
  channel[2] = mask;
  merge(channel, 3, mask3);
  channel[0] = mask_;
  channel[1] = mask_;
  channel[2] = mask_;
  merge(channel, 3, mask3_);

  background = background.mul(mask3) +
   (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
  times[5] += getMilliseconds() - timenow;
  timenow = getMilliseconds();

//  imshow("background", background);

/*
  Moments lol = moments(gray, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
*/

  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  int scale = 3;
  Mat classifyThis;
  equalizeHist(gray, gray);//ew; watch out not to use this later
  resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
//  bilateralFilter(gray, classifyThis, 15, 10, 1);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
  Mat rectImage(width, height, CV_8UC1, Scalar(0));
  for (size_t i=0; i<mouths.size(); i++) {
   Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
   rectangle(image, scaled, Scalar(255,0,0));
   rectangle(rectImage, scaled, Scalar(1), 5);
  }
//  blur(rectImage, rectImage, Size(tracker2+1,tracker2+1));
  threshold(rectImage, rectImage, tracker1, 1, THRESH_BINARY);
  times[6] += getMilliseconds() - timenow;
  timenow = getMilliseconds();
  imshow("MOUTH", rectImage);

  for (int i=0; i<7; i++) {
   printf("%llu , ", times[i]);
   times[i] = 0;
  }

  printf("\n");

  keepGoing = (waitKey(1)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
//

#include "MarbleThemeSelectView.h"

#include "global.h"
#include "MarbleDirs.h"
#include "MapWizard.h"
#include "MarbleDebug.h"

#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QDateTime>
#include <QtCore/QModelIndex>
#include <QtGui/QResizeEvent>
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
#include <QtGui/QStandardItemModel>

using namespace Marble;

class MarbleThemeSelectView::Private
{
public:
    explicit Private( MarbleThemeSelectView * const parent );
    void deleteDirectory( const QString& path );
    void deleteDataDirectories( const QString& path );
    void deletePreview( const QString& path );
    QString currentThemeName();
    QString currentThemePath();
private:
    MarbleThemeSelectView *m_parent;
};

MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent )
    : m_parent( parent )
{

}

void MarbleThemeSelectView::Private::deleteDirectory( const QString& path )
{
    QDir directory( path );
    foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) )
        QFile( path + filename ).remove();
    QDir().rmdir( path );
}

void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path )
{
    QDir directoryv( path );
    foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) )
    {
        QString filepath = path + "/" + filename;
        QFile file( filepath );
        if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) )
        {
            deleteDataDirectories( filepath );
            QDir().rmdir( filepath );
        }
        else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) )
            file.remove();
    }
}

void MarbleThemeSelectView::Private::deletePreview( const QString& path )
{
    QDir directoryv( path, "preview.*" );
    foreach( QString filename, directoryv.entryList() )
        QFile( path + "/" + filename ).remove();
}

QString MarbleThemeSelectView::Private::currentThemeName()
{
    QModelIndex index = m_parent->currentIndex();
    const QAbstractItemModel *model = index.model();

    QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() );
    return ( model->data( columnIndex )).toString();
}

QString MarbleThemeSelectView::Private::currentThemePath()
{
    QModelIndex index = m_parent-> currentIndex();
    const QAbstractItemModel  *model = index.model();

    QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() );
    return ( model->data( columnIndex )).toString();
}

MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent)
    : QListView( parent ),
      m_settings( "kde.org", "Marble Desktop Globe" ),
      d( new Private( this ) )
{
    bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
    if ( smallScreen ) {
        setViewMode( QListView::ListMode );
        setIconSize( QSize( 64, 64 ) );
    } else {
        setViewMode( QListView::IconMode );
        setIconSize( QSize( 136, 136 ) );
        setFlow( QListView::LeftToRight );
        setWrapping( true );
        setResizeMode( QListView::Fixed );
        setUniformItemSizes( true );
    }
    setMovement( QListView::Static );
    setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    setEditTriggers( QAbstractItemView::NoEditTriggers );
    setSelectionMode( QAbstractItemView::SingleSelection );
    loadFavorites();

    connect( this, SIGNAL( activated( QModelIndex ) ),
                   SLOT( selectedMapTheme( QModelIndex ) ) );
    connect( this, SIGNAL( customContextMenuRequested( QPoint ) ),
                   SLOT( showContextMenu( QPoint ) ) );
}

MarbleThemeSelectView::~MarbleThemeSelectView()
{
    delete d;
}

void MarbleThemeSelectView::resizeEvent( QResizeEvent *event )
{
    QListView::resizeEvent(event);

    QSize size = gridSize();
    size.setWidth( event->size().width() );
    setGridSize(size);
}

void MarbleThemeSelectView::selectedMapTheme( QModelIndex index )
{
    const QAbstractItemModel *model = index.model();

    QModelIndex  columnIndex = model->index( index.row(), 1, QModelIndex() );
    QString currentmaptheme = ( model->data( columnIndex )).toString();
    mDebug() << currentmaptheme;
    emit selectMapTheme( currentmaptheme );
}

void MarbleThemeSelectView::mapWizard()
{
    emit showMapWizard();
}

void MarbleThemeSelectView::uploadDialog()
{
    emit showUploadDialog();
}

void MarbleThemeSelectView::showContextMenu( const QPoint& pos )
{
    QMenu menu;
    menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) );
    if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() )
        menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) );
    menu.addAction( tr( "&Upload Map..." ), this, SLOT( uploadDialog() ) );
    QAction *favAction = menu.addAction( tr( "&Favorite" ), this, SLOT( toggleFavorite() ) );
    favAction->setCheckable( true );
    if( currentIsFavorite() )
        favAction->setChecked( true );
    else
        favAction->setChecked( false );
    menu.exec( mapToGlobal( pos ) );
}

void MarbleThemeSelectView::deleteMap()
{
    if(QMessageBox::warning( this,
                             tr( "Marble" ),
                             tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ),
                             QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes )
    {
        QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path());
        d->deleteDirectory( mapthemedir.path() + "/legend/" );
        d->deleteDataDirectories( mapthemedir.path() + "/" );
	d->deletePreview( mapthemedir.path() + "/" );
        QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove();
        QFile( mapthemedir.path() + "/legend.html" ).remove();
        QDir().rmdir( mapthemedir.path() );
    }
}

void MarbleThemeSelectView::toggleFavorite()
{
    QModelIndex index = currentIndex();
    QAbstractItemModel *model = this->model();
    QModelIndex columnIndex = model->index( index.row(), 0 );

    if( currentIsFavorite() )
    {
        m_settings.beginGroup( "Favorites" );
        m_settings.remove( model->data( columnIndex ).toString() );
    }
    else
    {
        m_settings.beginGroup( "Favorites" );
        m_settings.setValue( model->data( columnIndex ).toString(), QDateTime::currentDateTime() );
    }
    m_settings.endGroup();
    model->sort( 0 );
}

void MarbleThemeSelectView::loadFavorites()
{
    m_settings.beginGroup( "Favorites" );
    if( !m_settings.contains( "initialized" ) ) {
        m_settings.setValue( "initialized", true );
        QDateTime currentDateTime = QDateTime::currentDateTime();
        m_settings.setValue( "Atlas", currentDateTime );
        m_settings.setValue( "OpenStreetMap", currentDateTime );
        m_settings.setValue( "Satellite View", currentDateTime );
    }
    m_settings.endGroup();
}

bool MarbleThemeSelectView::currentIsFavorite()
{
    QModelIndex index = currentIndex();
    const QAbstractItemModel  *model = index.model();
    QModelIndex nameIndex = model->index( index.row(), 0, QModelIndex() );
    m_settings.beginGroup( "Favorites" );
    bool favorite = m_settings.contains( model->data( nameIndex ).toString() );
    m_settings.endGroup();
    return favorite;
}

#include "MarbleThemeSelectView.moc"
<commit_msg>Use the activate signal only on Maemo, old behavior elsewhere.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
//

#include "MarbleThemeSelectView.h"

#include "global.h"
#include "MarbleDirs.h"
#include "MapWizard.h"
#include "MarbleDebug.h"

#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QDateTime>
#include <QtCore/QModelIndex>
#include <QtGui/QResizeEvent>
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
#include <QtGui/QStandardItemModel>

using namespace Marble;

class MarbleThemeSelectView::Private
{
public:
    explicit Private( MarbleThemeSelectView * const parent );
    void deleteDirectory( const QString& path );
    void deleteDataDirectories( const QString& path );
    void deletePreview( const QString& path );
    QString currentThemeName();
    QString currentThemePath();
private:
    MarbleThemeSelectView *m_parent;
};

MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent )
    : m_parent( parent )
{

}

void MarbleThemeSelectView::Private::deleteDirectory( const QString& path )
{
    QDir directory( path );
    foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) )
        QFile( path + filename ).remove();
    QDir().rmdir( path );
}

void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path )
{
    QDir directoryv( path );
    foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) )
    {
        QString filepath = path + "/" + filename;
        QFile file( filepath );
        if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) )
        {
            deleteDataDirectories( filepath );
            QDir().rmdir( filepath );
        }
        else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) )
            file.remove();
    }
}

void MarbleThemeSelectView::Private::deletePreview( const QString& path )
{
    QDir directoryv( path, "preview.*" );
    foreach( QString filename, directoryv.entryList() )
        QFile( path + "/" + filename ).remove();
}

QString MarbleThemeSelectView::Private::currentThemeName()
{
    QModelIndex index = m_parent->currentIndex();
    const QAbstractItemModel *model = index.model();

    QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() );
    return ( model->data( columnIndex )).toString();
}

QString MarbleThemeSelectView::Private::currentThemePath()
{
    QModelIndex index = m_parent-> currentIndex();
    const QAbstractItemModel  *model = index.model();

    QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() );
    return ( model->data( columnIndex )).toString();
}

MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent)
    : QListView( parent ),
      m_settings( "kde.org", "Marble Desktop Globe" ),
      d( new Private( this ) )
{
    bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
    if ( smallScreen ) {
        setViewMode( QListView::ListMode );
        setIconSize( QSize( 64, 64 ) );
    } else {
        setViewMode( QListView::IconMode );
        setIconSize( QSize( 136, 136 ) );
        setFlow( QListView::LeftToRight );
        setWrapping( true );
        setResizeMode( QListView::Fixed );
        setUniformItemSizes( true );
    }
    setMovement( QListView::Static );
    setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    setEditTriggers( QAbstractItemView::NoEditTriggers );
    setSelectionMode( QAbstractItemView::SingleSelection );
    loadFavorites();

#ifdef Q_WS_MAEMO_5
    // The pressed signal on Maemo interfers with touch-based
    // scrolling, leading to sluggish behavior
    connect( this, SIGNAL( activated( QModelIndex ) ),
                   SLOT( selectedMapTheme( QModelIndex ) ) );
#else //  Q_WS_MAEMO_5
    connect( this, SIGNAL( pressed( QModelIndex ) ),
                   SLOT( selectedMapTheme( QModelIndex ) ) );
#endif //  Q_WS_MAEMO_5
    connect( this, SIGNAL( customContextMenuRequested( QPoint ) ),
                   SLOT( showContextMenu( QPoint ) ) );
}

MarbleThemeSelectView::~MarbleThemeSelectView()
{
    delete d;
}

void MarbleThemeSelectView::resizeEvent( QResizeEvent *event )
{
    QListView::resizeEvent(event);

    QSize size = gridSize();
    size.setWidth( event->size().width() );
    setGridSize(size);
}

void MarbleThemeSelectView::selectedMapTheme( QModelIndex index )
{
    const QAbstractItemModel *model = index.model();

    QModelIndex  columnIndex = model->index( index.row(), 1, QModelIndex() );
    QString currentmaptheme = ( model->data( columnIndex )).toString();
    mDebug() << currentmaptheme;
    emit selectMapTheme( currentmaptheme );
}

void MarbleThemeSelectView::mapWizard()
{
    emit showMapWizard();
}

void MarbleThemeSelectView::uploadDialog()
{
    emit showUploadDialog();
}

void MarbleThemeSelectView::showContextMenu( const QPoint& pos )
{
    QMenu menu;
    menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) );
    if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() )
        menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) );
    menu.addAction( tr( "&Upload Map..." ), this, SLOT( uploadDialog() ) );
    QAction *favAction = menu.addAction( tr( "&Favorite" ), this, SLOT( toggleFavorite() ) );
    favAction->setCheckable( true );
    if( currentIsFavorite() )
        favAction->setChecked( true );
    else
        favAction->setChecked( false );
    menu.exec( mapToGlobal( pos ) );
}

void MarbleThemeSelectView::deleteMap()
{
    if(QMessageBox::warning( this,
                             tr( "Marble" ),
                             tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ),
                             QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes )
    {
        QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path());
        d->deleteDirectory( mapthemedir.path() + "/legend/" );
        d->deleteDataDirectories( mapthemedir.path() + "/" );
	d->deletePreview( mapthemedir.path() + "/" );
        QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove();
        QFile( mapthemedir.path() + "/legend.html" ).remove();
        QDir().rmdir( mapthemedir.path() );
    }
}

void MarbleThemeSelectView::toggleFavorite()
{
    QModelIndex index = currentIndex();
    QAbstractItemModel *model = this->model();
    QModelIndex columnIndex = model->index( index.row(), 0 );

    if( currentIsFavorite() )
    {
        m_settings.beginGroup( "Favorites" );
        m_settings.remove( model->data( columnIndex ).toString() );
    }
    else
    {
        m_settings.beginGroup( "Favorites" );
        m_settings.setValue( model->data( columnIndex ).toString(), QDateTime::currentDateTime() );
    }
    m_settings.endGroup();
    model->sort( 0 );
}

void MarbleThemeSelectView::loadFavorites()
{
    m_settings.beginGroup( "Favorites" );
    if( !m_settings.contains( "initialized" ) ) {
        m_settings.setValue( "initialized", true );
        QDateTime currentDateTime = QDateTime::currentDateTime();
        m_settings.setValue( "Atlas", currentDateTime );
        m_settings.setValue( "OpenStreetMap", currentDateTime );
        m_settings.setValue( "Satellite View", currentDateTime );
    }
    m_settings.endGroup();
}

bool MarbleThemeSelectView::currentIsFavorite()
{
    QModelIndex index = currentIndex();
    const QAbstractItemModel  *model = index.model();
    QModelIndex nameIndex = model->index( index.row(), 0, QModelIndex() );
    m_settings.beginGroup( "Favorites" );
    bool favorite = m_settings.contains( model->data( nameIndex ).toString() );
    m_settings.endGroup();
    return favorite;
}

#include "MarbleThemeSelectView.moc"
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativevaluespacepublishermetaobject_p.h"

QT_BEGIN_NAMESPACE

QDeclarativeValueSpacePublisherMetaObject::QDeclarativeValueSpacePublisherMetaObject(QDeclarativeValueSpacePublisher *parent)
    : metaObject(0)
    , object(parent)
{
    metaObjectBuilder.setSuperClass(parent->metaObject());
    metaObjectBuilder.setClassName(parent->metaObject()->className());
    metaObjectBuilder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
    metaObject = metaObjectBuilder.toMetaObject();
    signalOffset = metaObject->methodOffset();
    propertyOffset = metaObject->propertyCount();
    d = metaObject->d;
}

QDeclarativeValueSpacePublisherMetaObject::~QDeclarativeValueSpacePublisherMetaObject()
{
    qFree(metaObject);
}

int QDeclarativeValueSpacePublisherMetaObject::createProperty(const char *name, const char *type)
{
    int id = metaObjectBuilder.propertyCount();
    metaObjectBuilder.addSignal("__" + QByteArray::number(id) + "()");
    metaObjectBuilder.addProperty(name, type, id);

    qFree(metaObject);
    metaObject = metaObjectBuilder.toMetaObject();
    d = metaObject->d;

    dynamicProperties.insert(id, QPair<QString, QVariant>(QString::fromUtf8(name), QVariant()));

    return propertyOffset + id;
}

int QDeclarativeValueSpacePublisherMetaObject::metaCall(QMetaObject::Call c, int id, void **a)
{
    if ((c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty)
        && id >= propertyOffset) {
        if (c == QMetaObject::ReadProperty) {
            *reinterpret_cast<QVariant*>(a[0]) = dynamicProperties[id - propertyOffset].second;
        } else if (c == QMetaObject::WriteProperty) {
            dynamicProperties[id - propertyOffset].second = *reinterpret_cast<QVariant*>(a[0]);
            activate(object, signalOffset + id, 0);
        }
        return -1;
    } else {
        return object->qt_metacall(c, id, a);
    }
}

QT_END_NAMESPACE
<commit_msg>qFree is deprecated, use ::free instead.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativevaluespacepublishermetaobject_p.h"

QT_BEGIN_NAMESPACE

QDeclarativeValueSpacePublisherMetaObject::QDeclarativeValueSpacePublisherMetaObject(QDeclarativeValueSpacePublisher *parent)
    : metaObject(0)
    , object(parent)
{
    metaObjectBuilder.setSuperClass(parent->metaObject());
    metaObjectBuilder.setClassName(parent->metaObject()->className());
    metaObjectBuilder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
    metaObject = metaObjectBuilder.toMetaObject();
    signalOffset = metaObject->methodOffset();
    propertyOffset = metaObject->propertyCount();
    d = metaObject->d;
}

QDeclarativeValueSpacePublisherMetaObject::~QDeclarativeValueSpacePublisherMetaObject()
{
    ::free(metaObject);
}

int QDeclarativeValueSpacePublisherMetaObject::createProperty(const char *name, const char *type)
{
    int id = metaObjectBuilder.propertyCount();
    metaObjectBuilder.addSignal("__" + QByteArray::number(id) + "()");
    metaObjectBuilder.addProperty(name, type, id);

    ::free(metaObject);
    metaObject = metaObjectBuilder.toMetaObject();
    d = metaObject->d;

    dynamicProperties.insert(id, QPair<QString, QVariant>(QString::fromUtf8(name), QVariant()));

    return propertyOffset + id;
}

int QDeclarativeValueSpacePublisherMetaObject::metaCall(QMetaObject::Call c, int id, void **a)
{
    if ((c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty)
        && id >= propertyOffset) {
        if (c == QMetaObject::ReadProperty) {
            *reinterpret_cast<QVariant*>(a[0]) = dynamicProperties[id - propertyOffset].second;
        } else if (c == QMetaObject::WriteProperty) {
            dynamicProperties[id - propertyOffset].second = *reinterpret_cast<QVariant*>(a[0]);
            activate(object, signalOffset + id, 0);
        }
        return -1;
    } else {
        return object->qt_metacall(c, id, a);
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include "Chunk.h"
#include "DataBuffer.h"
#include <algorithm>

namespace Minecraft {

Chunk::Chunk()
{
    for (s32 y = 0; y < 16; ++y) {
        for (s32 z = 0; z < 16; ++z) {
            for (s32 x = 0; x < 16; ++x) {
                std::size_t index = y * 16 * 16 + z * 16 + x;

                m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(0, 0);
            }
        }
    }
}

void Chunk::Load(DataBuffer& in, ChunkColumnMetadata* meta, s32 chunkIndex) {
    for (s32 y = 0; y < 16; ++y) {
        for (s32 z = 0; z < 16; ++z) {
            for (s32 x = 0; x < 16; ++x) {
                s16 data;

                in >> data;
                std::reverse((u8*)&data, (u8*)&data + sizeof(s16));

                std::size_t index = y * 16 * 16 + z * 16 + x;

                m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(data);
            }
        }
    }
}

BlockPtr Chunk::GetBlock(Vector3i chunkPosition) {
    if (chunkPosition.y < 0) return BlockRegistry::GetInstance()->GetBlock(0, 0);

    std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x);
    return m_Blocks[index];
}

void Chunk::SetBlock(Vector3i chunkPosition, BlockPtr block) {
    std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x);
    m_Blocks[index] = block;
}

ChunkColumn::ChunkColumn(ChunkColumnMetadata metadata)
    : m_Metadata(metadata)
{
    for (std::size_t i = 0; i < m_Chunks.size(); ++i)
        m_Chunks[i] = nullptr;
}

BlockPtr ChunkColumn::GetBlock(Vector3i position) {
    s32 chunkIndex = (s32)(position.y / 16);
    Vector3i relativePosition(position.x, position.y % 16, position.z);

    if (!m_Chunks[chunkIndex]) return nullptr;

    return m_Chunks[chunkIndex]->GetBlock(relativePosition);
}

DataBuffer& operator>>(DataBuffer& in, ChunkColumn& column) {
    ChunkColumnMetadata* meta = &column.m_Metadata;

    for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
        // The section mask says whether or not there is data in this chunk.
        if (meta->sectionmask & (1 << i)) {
            column.m_Chunks[i] = std::make_shared<Chunk>();

            column.m_Chunks[i]->Load(in, meta, i);
        } else {
            // Air section, leave null
            column.m_Chunks[i] = nullptr;
        }
    }

    static const s64 lightSize = 16 * 16 * 16 / 2;

    for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
        // Block light data
        if (meta->sectionmask & (1 << i))
            in.SetReadOffset(in.GetReadOffset() + lightSize);
    }

    if (meta->skylight) {
        for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
            // Skylight data
            if (meta->sectionmask & (1 << i))
                in.SetReadOffset(in.GetReadOffset() + lightSize);
        }
    }

    if (meta->continuous)
        in.SetReadOffset(in.GetReadOffset() + 256);

    return in;
}

} // ns Minecraft
<commit_msg>Fix GetBlock on null chunks in a valid ChunkColumn<commit_after>#include "Chunk.h"
#include "DataBuffer.h"
#include <algorithm>

namespace Minecraft {

Chunk::Chunk()
{
    for (s32 y = 0; y < 16; ++y) {
        for (s32 z = 0; z < 16; ++z) {
            for (s32 x = 0; x < 16; ++x) {
                std::size_t index = y * 16 * 16 + z * 16 + x;

                m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(0, 0);
            }
        }
    }
}

void Chunk::Load(DataBuffer& in, ChunkColumnMetadata* meta, s32 chunkIndex) {
    for (s32 y = 0; y < 16; ++y) {
        for (s32 z = 0; z < 16; ++z) {
            for (s32 x = 0; x < 16; ++x) {
                s16 data;

                in >> data;
                std::reverse((u8*)&data, (u8*)&data + sizeof(s16));

                std::size_t index = y * 16 * 16 + z * 16 + x;

                m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(data);
            }
        }
    }
}

BlockPtr Chunk::GetBlock(Vector3i chunkPosition) {
    if (chunkPosition.y < 0) return BlockRegistry::GetInstance()->GetBlock(0, 0);

    std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x);
    return m_Blocks[index];
}

void Chunk::SetBlock(Vector3i chunkPosition, BlockPtr block) {
    std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x);
    m_Blocks[index] = block;
}

ChunkColumn::ChunkColumn(ChunkColumnMetadata metadata)
    : m_Metadata(metadata)
{
    for (std::size_t i = 0; i < m_Chunks.size(); ++i)
        m_Chunks[i] = nullptr;
}

BlockPtr ChunkColumn::GetBlock(Vector3i position) {
    s32 chunkIndex = (s32)(position.y / 16);
    Vector3i relativePosition(position.x, position.y % 16, position.z);

    if (!m_Chunks[chunkIndex]) return BlockRegistry::GetInstance()->GetBlock(0, 0);

    return m_Chunks[chunkIndex]->GetBlock(relativePosition);
}

DataBuffer& operator>>(DataBuffer& in, ChunkColumn& column) {
    ChunkColumnMetadata* meta = &column.m_Metadata;

    for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
        // The section mask says whether or not there is data in this chunk.
        if (meta->sectionmask & (1 << i)) {
            column.m_Chunks[i] = std::make_shared<Chunk>();

            column.m_Chunks[i]->Load(in, meta, i);
        } else {
            // Air section, leave null
            column.m_Chunks[i] = nullptr;
        }
    }

    static const s64 lightSize = 16 * 16 * 16 / 2;

    for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
        // Block light data
        if (meta->sectionmask & (1 << i))
            in.SetReadOffset(in.GetReadOffset() + lightSize);
    }

    if (meta->skylight) {
        for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) {
            // Skylight data
            if (meta->sectionmask & (1 << i))
                in.SetReadOffset(in.GetReadOffset() + lightSize);
        }
    }

    if (meta->continuous)
        in.SetReadOffset(in.GetReadOffset() + 256);

    return in;
}

} // ns Minecraft
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005 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 "mediaobject.h"
#include "mediaobject_p.h"
#include "factory.h"
#include "bytestreaminterface.h"
#include "mediaobjectinterface.h"

#include <kdebug.h>

#define PHONON_CLASSNAME MediaObject
#define PHONON_INTERFACENAME MediaObjectInterface

namespace Phonon
{
PHONON_HEIR_IMPL( AbstractMediaProducer )

MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent )
	: AbstractMediaProducer( dd, parent )
{
}

PHONON_INTERFACE_GETTER( KUrl, url, d->url )
PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime )

qint64 MediaObject::totalTime() const
{
	K_D( const MediaObject );
	if( !d->backendObject )
		return -1;
	MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject );
	if( iface )
		return iface->totalTime();
	else
	{
		ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject );
		if( iface2 )
			return iface2->totalTime();
	}
	return -1;
}

qint64 MediaObject::remainingTime() const
{
	K_D( const MediaObject );
	if( !d->backendObject )
		return -1;
	qint64 ret;
	if( !BACKEND_GET( qint64, ret, "remainingTime" ) )
		ret = totalTime() - currentTime();
	if( ret < 0 )
		return -1;
	return ret;
}

void MediaObject::setUrl( const KUrl& url )
{
	K_D( MediaObject );
	d->url = url;
	if( iface() )
	{
		stop(); // first call stop as that often is the expected state
		                    // for setting a new URL
		INTERFACE_CALL1( setUrl, url );
		//FIXME: the stateChanged signal will be emitted. Perhaps it should be
		//disabled for the setUrl call and then replayed when it didn't go into
		//ErrorState
		if( state() == Phonon::ErrorState )
		{
			d->deleteIface();
			//at this point MediaObject uses a ByteStream
			//instead and sends the data it receives from the KIO Job via writeBuffer.
			//This essentially makes all media frameworks read data via KIO...
			d->setupKioStreaming();
		}
	}
}

void MediaObject::stop()
{
	AbstractMediaProducer::stop();
	K_D( MediaObject );
	if( d->kiojob )
	{
		d->kiojob->kill();
		// if( do pre-buffering )
		d->setupKioJob();
	}
}

PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 )

void MediaObjectPrivate::setupKioJob()
{
	K_Q( MediaObject );
	Q_ASSERT( backendObject );

	kiojob = KIO::get( url, false, false );
	kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) );
	QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)),
			q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) );
	QObject::connect( kiojob, SIGNAL(result(KJob*)),
			q, SLOT(_k_bytestreamResult(KJob*)) );
	QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)),
			q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) );

	QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) );
	QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) );
	QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) );

	QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) );
	QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) );

	pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point
	//connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT(
}

void MediaObjectPrivate::setupKioStreaming()
{
	K_Q( MediaObject );
	Q_ASSERT( backendObject == 0 );
	backendObject = Factory::self()->createByteStream( q );
	if( backendObject )
	{
		QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) );
		//setupIface for ByteStream
		if( kiojob )
			kiojob->kill();
		setupKioJob();
		static_cast<AbstractMediaProducer*>( q )->setupIface();
	}
}

void MediaObjectPrivate::_k_bytestreamNeedData()
{
	if( kiojob->isSuspended() )
		kiojob->resume();
}

void MediaObjectPrivate::_k_bytestreamEnoughData()
{
	if( !kiojob->isSuspended() )
		kiojob->suspend();
}

void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data )
{
	ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
	bs->writeData( data );
}

void MediaObjectPrivate::_k_bytestreamResult( KJob* job )
{
	ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
	bs->endOfData();
	kiojob = 0;

	if( job->error() )
	{
		//TODO
	}
}

void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size )
{
	pBACKEND_CALL1( "setStreamSize", quint64, size );
}

void MediaObjectPrivate::_k_cleanupByteStream()
{
	if( kiojob )
	{
		kiojob->kill();
		kiojob = 0;
	}
}

bool MediaObjectPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" );
	return AbstractMediaProducerPrivate::aboutToDeleteIface();
}

// setupIface is not called for ByteStream
void MediaObject::setupIface()
{
	K_D( MediaObject );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;
	AbstractMediaProducer::setupIface();

	connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) );
	connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) );
	connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) );

	// set up attributes
	if( !d->url.isEmpty() )
		INTERFACE_CALL1( setUrl, d->url );
	if( state() == Phonon::ErrorState )
	{
		d->deleteIface();
		//at this point MediaObject uses a ByteStream
		//instead and sends the data it receives from the KIO Job via writeBuffer.
		//This essentially makes all media frameworks read data via KIO...
		d->setupKioStreaming();
		return;
	}
	BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime );
}

} //namespace Phonon

#include "mediaobject.moc"

// vim: sw=4 ts=4 tw=80 noet
<commit_msg>fixed a missing check on MediaObject<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005 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 "mediaobject.h"
#include "mediaobject_p.h"
#include "factory.h"
#include "bytestreaminterface.h"
#include "mediaobjectinterface.h"

#include <kdebug.h>

#define PHONON_CLASSNAME MediaObject
#define PHONON_INTERFACENAME MediaObjectInterface

namespace Phonon
{
PHONON_HEIR_IMPL( AbstractMediaProducer )

MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent )
	: AbstractMediaProducer( dd, parent )
{
}

PHONON_INTERFACE_GETTER( KUrl, url, d->url )
PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime )

qint64 MediaObject::totalTime() const
{
	K_D( const MediaObject );
	if( !d->backendObject )
		return -1;
	MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject );
	if( iface )
		return iface->totalTime();
	else
	{
		ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject );
		if( iface2 )
			return iface2->totalTime();
	}
	return -1;
}

qint64 MediaObject::remainingTime() const
{
	K_D( const MediaObject );
	if( !d->backendObject )
		return -1;
	qint64 ret;
	if( !BACKEND_GET( qint64, ret, "remainingTime" ) )
		ret = totalTime() - currentTime();
	if( ret < 0 )
		return -1;
	return ret;
}

void MediaObject::setUrl( const KUrl& url )
{
	K_D( MediaObject );
	d->url = url;
	if( iface() )
	{
		stop(); // first call stop as that often is the expected state
		                    // for setting a new URL
		INTERFACE_CALL1( setUrl, url );
		//FIXME: the stateChanged signal will be emitted. Perhaps it should be
		//disabled for the setUrl call and then replayed when it didn't go into
		//ErrorState
		if( state() == Phonon::ErrorState )
		{
			d->deleteIface();
			//at this point MediaObject uses a ByteStream
			//instead and sends the data it receives from the KIO Job via writeBuffer.
			//This essentially makes all media frameworks read data via KIO...
			d->setupKioStreaming();
		}
	}
}

void MediaObject::stop()
{
	AbstractMediaProducer::stop();
	K_D( MediaObject );
	if( d->kiojob )
	{
		d->kiojob->kill();
		// if( do pre-buffering )
		d->setupKioJob();
	}
}

PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 )

void MediaObjectPrivate::setupKioJob()
{
	K_Q( MediaObject );
	Q_ASSERT( backendObject );

	kiojob = KIO::get( url, false, false );
	kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) );
	QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)),
			q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) );
	QObject::connect( kiojob, SIGNAL(result(KJob*)),
			q, SLOT(_k_bytestreamResult(KJob*)) );
	QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)),
			q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) );

	QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) );
	QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) );
	QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) );

	QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) );
	QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) );

	pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point
	//connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT(
}

void MediaObjectPrivate::setupKioStreaming()
{
	K_Q( MediaObject );
	Q_ASSERT( backendObject == 0 );
	backendObject = Factory::self()->createByteStream( q );
	if( backendObject )
	{
		QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) );
		//setupIface for ByteStream
		if( kiojob )
			kiojob->kill();
		setupKioJob();
		static_cast<AbstractMediaProducer*>( q )->setupIface();
	}
}

void MediaObjectPrivate::_k_bytestreamNeedData()
{
	if( kiojob && kiojob->isSuspended() )
		kiojob->resume();
}

void MediaObjectPrivate::_k_bytestreamEnoughData()
{
	if( !kiojob->isSuspended() )
		kiojob->suspend();
}

void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data )
{
	ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
	bs->writeData( data );
}

void MediaObjectPrivate::_k_bytestreamResult( KJob* job )
{
	ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject );
	bs->endOfData();
	kiojob = 0;

	if( job->error() )
	{
		//TODO
	}
}

void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size )
{
	pBACKEND_CALL1( "setStreamSize", quint64, size );
}

void MediaObjectPrivate::_k_cleanupByteStream()
{
	if( kiojob )
	{
		kiojob->kill();
		kiojob = 0;
	}
}

bool MediaObjectPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" );
	return AbstractMediaProducerPrivate::aboutToDeleteIface();
}

// setupIface is not called for ByteStream
void MediaObject::setupIface()
{
	K_D( MediaObject );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;
	AbstractMediaProducer::setupIface();

	connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) );
	connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) );
	connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) );

	// set up attributes
	if( !d->url.isEmpty() )
		INTERFACE_CALL1( setUrl, d->url );
	if( state() == Phonon::ErrorState )
	{
		d->deleteIface();
		//at this point MediaObject uses a ByteStream
		//instead and sends the data it receives from the KIO Job via writeBuffer.
		//This essentially makes all media frameworks read data via KIO...
		d->setupKioStreaming();
		return;
	}
	BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime );
}

} //namespace Phonon

#include "mediaobject.moc"

// vim: sw=4 ts=4 tw=80 noet
<|endoftext|>


<commit_before>#ifndef MGF_SCANNER_HPP
#define MGF_SCANNER_HPP

#if ! defined(yyFlexLexerOnce)
#include <mgf/FlexLexer.hpp>
#endif

// Override the interface for yylex since we namespaced it
#undef YY_DECL
#define YY_DECL int mgf::Scanner::yylex()

// Include Bison for types / tokens
#include <mgf/Parser.tab.hh>

namespace mgf
{
    class Parser;
    //typename Parser::semantic_type;

    /***
     * \brief The lexer that tokenize the input
     */
    class Scanner : public yyFlexLexer
    {
        public:
            /**
             * \brief Construct from a input
             * \param in MGF imput
             */
            Scanner(std::istream& in);
            Scanner(const Scanner&) = delete;
            Scanner& operator=(const Scanner&) = delete;

            /**
             * \breief save the pointer to yylval so we can change it, and invoke scanner
             * \parap lval For Lex/bison
             * \return 0if all input is parse, MGF_END_IONS if end of ion, else, error
             */
            int yylex(mgf::Parser::semantic_type *lval);

        protected:

        private:
            /**
             * \breief Scanning function created by Flex; make this private to force usage
             * of the overloaded method so we can get a pointer to Bison's yylval
             */
            int yylex();
            /* yyval ptr */
            mgf::Parser::semantic_type *yylval; ///< For Lex/bison
    };
}
#endif
<commit_msg>add doc to Scanner<commit_after>#ifndef MGF_SCANNER_HPP
#define MGF_SCANNER_HPP

#if ! defined(yyFlexLexerOnce)
#include <mgf/FlexLexer.hpp>
#endif

// Override the interface for yylex since we namespaced it
#undef YY_DECL
#define YY_DECL int mgf::Scanner::yylex()

// Include Bison for types / tokens
#include <mgf/Parser.tab.hh>

namespace mgf
{
    class Parser;
    //typename Parser::semantic_type;

    /**
     * \brief The lexer that tokenize the input
     */
    class Scanner : public yyFlexLexer
    {
        public:
            /**
             * \brief Construct from a input
             * \param in MGF imput
             */
            Scanner(std::istream& in);
            Scanner(const Scanner&) = delete;
            Scanner& operator=(const Scanner&) = delete;

            /**
             * \breief save the pointer to yylval so we can change it, and invoke scanner
             * \parap lval For Lex/bison
             * \return 0if all input is parse, MGF_END_IONS if end of ion, else, error
             */
            int yylex(mgf::Parser::semantic_type *lval);

        protected:

        private:
            /**
             * \breief Scanning function created by Flex; make this private to force usage
             * of the overloaded method so we can get a pointer to Bison's yylval
             */
            int yylex();
            /* yyval ptr */
            mgf::Parser::semantic_type *yylval; ///< For Lex/bison
    };
}
#endif
<|endoftext|>