<commit_before>#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <mist/stream.h>
#include <mist/defines.h>

#include "input_av.h"

namespace Mist {
  inputAV::inputAV(Util::Config * cfg) : Input(cfg) {
    pFormatCtx = 0;
    capa["name"] = "AV";
    capa["decs"] = "Enables generic avformat/avcodec based input";
    capa["source_match"] = "/*";
    capa["priority"] = 1ll;
    capa["codecs"][0u][0u].null();
    capa["codecs"][0u][1u].null();
    capa["codecs"][0u][2u].null();
    av_register_all();
    AVCodec * cInfo = 0;
    while ((cInfo = av_codec_next(cInfo)) != 0){
      if (cInfo->type == AVMEDIA_TYPE_VIDEO){
        capa["codecs"][0u][0u].append(cInfo->name);
      }
      if (cInfo->type == AVMEDIA_TYPE_AUDIO){
        capa["codecs"][0u][1u].append(cInfo->name);
      }
      if (cInfo->type == AVMEDIA_TYPE_SUBTITLE){
        capa["codecs"][0u][3u].append(cInfo->name);
      }
    }
  }

  inputAV::~inputAV(){
    if (pFormatCtx){
      avformat_close_input(&pFormatCtx);
    }
  }

  bool inputAV::setup() {
    if (config->getString("input") == "-") {
      std::cerr << "Input from stdin not yet supported" << std::endl;
      return false;
    }
    if (!config->getString("streamname").size()){
      if (config->getString("output") == "-") {
        std::cerr << "Output to stdout not yet supported" << std::endl;
        return false;
      }
    }else{
      if (config->getString("output") != "-") {
        std::cerr << "File output in player mode not supported" << std::endl;
        return false;
      }
    }

    //make sure all av inputs are registered properly, just in case
    //setup() already does this, but under windows it doesn't remember that it has.
    //Very sad, that. We may need to get windows some medication for it.
    av_register_all();

    //close any already open files
    if (pFormatCtx){
      avformat_close_input(&pFormatCtx);
      pFormatCtx = 0;
    }

    //Open video file
    int ret = avformat_open_input(&pFormatCtx, config->getString("input").c_str(), NULL, NULL);
    if(ret != 0){
      char errstr[300];
      av_strerror(ret, errstr, 300);
      DEBUG_MSG(DLVL_FAIL, "Could not open file: %s", errstr);
      return false; // Couldn't open file
    }

    //Retrieve stream information
    ret = avformat_find_stream_info(pFormatCtx, NULL);
    if(ret < 0){
      char errstr[300];
      av_strerror(ret, errstr, 300);
      DEBUG_MSG(DLVL_FAIL, "Could not find stream info: %s", errstr);
      return false;
    }
    return true;
  }

  bool inputAV::readHeader() {
    //See whether a separate header file exists.
    if (readExistingHeader()){return true;}

    myMeta.tracks.clear();
    for(unsigned int i=0; i < pFormatCtx->nb_streams; ){
      AVStream * strm = pFormatCtx->streams[i++];
      myMeta.tracks[i].trackID = i;
      switch (strm->codec->codec_id){
        case AV_CODEC_ID_HEVC:
          myMeta.tracks[i].codec = "HEVC";
          break;
        case AV_CODEC_ID_H264:
          myMeta.tracks[i].codec = "H264";
          break;
        case AV_CODEC_ID_THEORA:
          myMeta.tracks[i].codec = "theora";
          break;
        case AV_CODEC_ID_VORBIS:
          myMeta.tracks[i].codec = "vorbis";
          break;
        case AV_CODEC_ID_OPUS:
          myMeta.tracks[i].codec = "opus";
          break;
        case AV_CODEC_ID_AAC:
          myMeta.tracks[i].codec = "AAC";
          break;
        case AV_CODEC_ID_MP3:
          myMeta.tracks[i].codec = "MP3";
          break;
        case AV_CODEC_ID_AC3:
        case AV_CODEC_ID_EAC3:
          myMeta.tracks[i].codec = "AC3";
          break;
        default:
          const AVCodecDescriptor *desc = av_codec_get_codec_descriptor(strm->codec);
          if (desc && desc->name){
            myMeta.tracks[i].codec = desc->name;
          }else{
            myMeta.tracks[i].codec = "?";
          }
          break;
      }
      if (strm->codec->extradata_size){
        myMeta.tracks[i].init = std::string((char*)strm->codec->extradata, strm->codec->extradata_size);
      }
      if(strm->codec->codec_type == AVMEDIA_TYPE_VIDEO){
        myMeta.tracks[i].type = "video";
        if (strm->avg_frame_rate.den && strm->avg_frame_rate.num){
          myMeta.tracks[i].fpks = (strm->avg_frame_rate.num * 1000) / strm->avg_frame_rate.den;
        }else{
          myMeta.tracks[i].fpks = 0;
        }
        myMeta.tracks[i].width = strm->codec->width;
        myMeta.tracks[i].height = strm->codec->height;
      }
      if(strm->codec->codec_type == AVMEDIA_TYPE_AUDIO){
        myMeta.tracks[i].type = "audio";
        myMeta.tracks[i].rate = strm->codec->sample_rate;
        switch (strm->codec->sample_fmt){
          case AV_SAMPLE_FMT_U8:
          case AV_SAMPLE_FMT_U8P:
            myMeta.tracks[i].size = 8;
            break;
          case AV_SAMPLE_FMT_S16:
          case AV_SAMPLE_FMT_S16P:
            myMeta.tracks[i].size = 16;
            break;
          case AV_SAMPLE_FMT_S32:
          case AV_SAMPLE_FMT_S32P:
          case AV_SAMPLE_FMT_FLT:
          case AV_SAMPLE_FMT_FLTP:
            myMeta.tracks[i].size = 32;
            break;
          case AV_SAMPLE_FMT_DBL:
          case AV_SAMPLE_FMT_DBLP:
            myMeta.tracks[i].size = 64;
            break;
          default:
            myMeta.tracks[i].size = 0;
            break;
        }
        myMeta.tracks[i].channels = strm->codec->channels;
      }
    }

    AVPacket packet;
    while(av_read_frame(pFormatCtx, &packet)>=0){
      AVStream * strm = pFormatCtx->streams[packet.stream_index];
      long long packTime = (packet.dts * 1000 * strm->time_base.num / strm->time_base.den);
      long long packOffset = 0;
      bool isKey = false;
      if (packTime < 0){
        packTime = 0;
      }
      if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != "audio"){
        isKey = true;
      }
      if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){
        packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num / strm->time_base.den);
      }
      myMeta.update(packTime, packOffset, packet.stream_index + 1, packet.size, packet.pos, isKey);
      av_free_packet(&packet);
    }

    myMeta.toFile(config->getString("input") + ".dtsh");

    seek(0);
    return true;
  }

  void inputAV::getNext(bool smart) {
    AVPacket packet;
    while (av_read_frame(pFormatCtx, &packet)>=0){
      //filter tracks we don't care about
      if (!selectedTracks.count(packet.stream_index + 1)){
        DEBUG_MSG(DLVL_HIGH, "Track %u not selected", packet.stream_index + 1);
        continue;
      }
      AVStream * strm = pFormatCtx->streams[packet.stream_index];
      long long packTime = (packet.dts * 1000 * strm->time_base.num / strm->time_base.den);
      long long packOffset = 0;
      bool isKey = false;
      if (packTime < 0){
        packTime = 0;
      }
      if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != "audio"){
        isKey = true;
      }
      if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){
        packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num / strm->time_base.den);
      }
      thisPacket.genericFill(packTime, packOffset, packet.stream_index + 1, (const char*)packet.data, packet.size, 0, isKey);
      av_free_packet(&packet);
      return;//success!
    }
    thisPacket.null();
    setup();
    //failure :-(
    DEBUG_MSG(DLVL_FAIL, "getNext failed");
  }

  void inputAV::seek(int seekTime) {
    int stream_index = av_find_default_stream_index(pFormatCtx);
    //Convert ts to frame
    unsigned long long reseekTime = av_rescale(seekTime, pFormatCtx->streams[stream_index]->time_base.den, pFormatCtx->streams[stream_index]->time_base.num);
    reseekTime /= 1000;
    unsigned long long seekStreamDuration = pFormatCtx->streams[stream_index]->duration;
    int flags = AVSEEK_FLAG_BACKWARD;
    if (reseekTime > 0 && reseekTime < seekStreamDuration){
      flags |= AVSEEK_FLAG_ANY; // H.264 I frames don't always register as "key frames" in FFmpeg
    }
    int ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, flags);
    if (ret < 0){
      ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, AVSEEK_FLAG_ANY);
    }
  }

  void inputAV::trackSelect(std::string trackSpec) {
    selectedTracks.clear();
    long long unsigned int index;
    while (trackSpec != "") {
      index = trackSpec.find(' ');
      selectedTracks.insert(atoi(trackSpec.substr(0, index).c_str()));
      if (index != std::string::npos) {
        trackSpec.erase(0, index + 1);
      } else {
        trackSpec = "";
      }
    }
    //inFile.selectTracks(selectedTracks);
  }
}

<commit_msg>Updated MistInAV in line with recent libavformat deprecations<commit_after>#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <mist/stream.h>
#include <mist/defines.h>

#include "input_av.h"

namespace Mist {
  inputAV::inputAV(Util::Config * cfg) : Input(cfg) {
    pFormatCtx = 0;
    capa["name"] = "AV";
    capa["decs"] = "Enables generic avformat/avcodec based input";
    capa["source_match"] = "/*";
    capa["priority"] = 1ll;
    capa["codecs"][0u][0u].null();
    capa["codecs"][0u][1u].null();
    capa["codecs"][0u][2u].null();
    av_register_all();
    AVCodec * cInfo = 0;
    while ((cInfo = av_codec_next(cInfo)) != 0){
      if (cInfo->type == AVMEDIA_TYPE_VIDEO){
        capa["codecs"][0u][0u].append(cInfo->name);
      }
      if (cInfo->type == AVMEDIA_TYPE_AUDIO){
        capa["codecs"][0u][1u].append(cInfo->name);
      }
      if (cInfo->type == AVMEDIA_TYPE_SUBTITLE){
        capa["codecs"][0u][3u].append(cInfo->name);
      }
    }
  }

  inputAV::~inputAV(){
    if (pFormatCtx){
      avformat_close_input(&pFormatCtx);
    }
  }

  bool inputAV::setup() {
    if (config->getString("input") == "-") {
      std::cerr << "Input from stdin not yet supported" << std::endl;
      return false;
    }
    if (!config->getString("streamname").size()){
      if (config->getString("output") == "-") {
        std::cerr << "Output to stdout not yet supported" << std::endl;
        return false;
      }
    }else{
      if (config->getString("output") != "-") {
        std::cerr << "File output in player mode not supported" << std::endl;
        return false;
      }
    }

    //make sure all av inputs are registered properly, just in case
    //setup() already does this, but under windows it doesn't remember that it has.
    //Very sad, that. We may need to get windows some medication for it.
    av_register_all();

    //close any already open files
    if (pFormatCtx){
      avformat_close_input(&pFormatCtx);
      pFormatCtx = 0;
    }

    //Open video file
    int ret = avformat_open_input(&pFormatCtx, config->getString("input").c_str(), NULL, NULL);
    if(ret != 0){
      char errstr[300];
      av_strerror(ret, errstr, 300);
      DEBUG_MSG(DLVL_FAIL, "Could not open file: %s", errstr);
      return false; // Couldn't open file
    }

    //Retrieve stream information
    ret = avformat_find_stream_info(pFormatCtx, NULL);
    if(ret < 0){
      char errstr[300];
      av_strerror(ret, errstr, 300);
      DEBUG_MSG(DLVL_FAIL, "Could not find stream info: %s", errstr);
      return false;
    }
    return true;
  }

  bool inputAV::readHeader() {
    //See whether a separate header file exists.
    if (readExistingHeader()){return true;}

    myMeta.tracks.clear();
    for(unsigned int i=0; i < pFormatCtx->nb_streams; ){
      AVStream * strm = pFormatCtx->streams[i++];
      myMeta.tracks[i].trackID = i;
      switch (strm->codecpar->codec_id){
        case AV_CODEC_ID_HEVC:
          myMeta.tracks[i].codec = "HEVC";
          break;
        case AV_CODEC_ID_H264:
          myMeta.tracks[i].codec = "H264";
          break;
        case AV_CODEC_ID_THEORA:
          myMeta.tracks[i].codec = "theora";
          break;
        case AV_CODEC_ID_VORBIS:
          myMeta.tracks[i].codec = "vorbis";
          break;
        case AV_CODEC_ID_OPUS:
          myMeta.tracks[i].codec = "opus";
          break;
        case AV_CODEC_ID_AAC:
          myMeta.tracks[i].codec = "AAC";
          break;
        case AV_CODEC_ID_MP3:
          myMeta.tracks[i].codec = "MP3";
          break;
        case AV_CODEC_ID_AC3:
        case AV_CODEC_ID_EAC3:
          myMeta.tracks[i].codec = "AC3";
          break;
        default:
          const AVCodecDescriptor *desc = avcodec_descriptor_get(strm->codecpar->codec_id);
          if (desc && desc->name){
            myMeta.tracks[i].codec = desc->name;
          }else{
            myMeta.tracks[i].codec = "?";
          }
          break;
      }
      if (strm->codecpar->extradata_size){
        myMeta.tracks[i].init = std::string((char*)strm->codecpar->extradata, strm->codecpar->extradata_size);
      }
      if(strm->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){
        myMeta.tracks[i].type = "video";
        if (strm->avg_frame_rate.den && strm->avg_frame_rate.num){
          myMeta.tracks[i].fpks = (strm->avg_frame_rate.num * 1000) / strm->avg_frame_rate.den;
        }else{
          myMeta.tracks[i].fpks = 0;
        }
        myMeta.tracks[i].width = strm->codecpar->width;
        myMeta.tracks[i].height = strm->codecpar->height;
      }
      if(strm->codecpar->codec_type == AVMEDIA_TYPE_AUDIO){
        myMeta.tracks[i].type = "audio";
        myMeta.tracks[i].rate = strm->codecpar->sample_rate;
        myMeta.tracks[i].size = strm->codecpar->frame_size;
        myMeta.tracks[i].channels = strm->codecpar->channels;
      }
    }

    AVPacket packet;
    while(av_read_frame(pFormatCtx, &packet)>=0){
      AVStream * strm = pFormatCtx->streams[packet.stream_index];
      long long packTime = (packet.dts * 1000 * strm->time_base.num / strm->time_base.den);
      long long packOffset = 0;
      bool isKey = false;
      if (packTime < 0){
        packTime = 0;
      }
      if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != "audio"){
        isKey = true;
      }
      if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){
        packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num / strm->time_base.den);
      }
      myMeta.update(packTime, packOffset, packet.stream_index + 1, packet.size, packet.pos, isKey);
      av_packet_unref(&packet);
    }

    myMeta.toFile(config->getString("input") + ".dtsh");

    seek(0);
    return true;
  }

  void inputAV::getNext(bool smart) {
    AVPacket packet;
    while (av_read_frame(pFormatCtx, &packet)>=0){
      //filter tracks we don't care about
      if (!selectedTracks.count(packet.stream_index + 1)){
        DEBUG_MSG(DLVL_HIGH, "Track %u not selected", packet.stream_index + 1);
        continue;
      }
      AVStream * strm = pFormatCtx->streams[packet.stream_index];
      long long packTime = (packet.dts * 1000 * strm->time_base.num / strm->time_base.den);
      long long packOffset = 0;
      bool isKey = false;
      if (packTime < 0){
        packTime = 0;
      }
      if (packet.flags & AV_PKT_FLAG_KEY && myMeta.tracks[(long long)packet.stream_index + 1].type != "audio"){
        isKey = true;
      }
      if (packet.pts != AV_NOPTS_VALUE && packet.pts != packet.dts){
        packOffset = ((packet.pts - packet.dts) * 1000 * strm->time_base.num / strm->time_base.den);
      }
      thisPacket.genericFill(packTime, packOffset, packet.stream_index + 1, (const char*)packet.data, packet.size, 0, isKey);
      av_packet_unref(&packet);
      return;//success!
    }
    thisPacket.null();
    setup();
    //failure :-(
    DEBUG_MSG(DLVL_FAIL, "getNext failed");
  }

  void inputAV::seek(int seekTime) {
    int stream_index = av_find_default_stream_index(pFormatCtx);
    //Convert ts to frame
    unsigned long long reseekTime = av_rescale(seekTime, pFormatCtx->streams[stream_index]->time_base.den, pFormatCtx->streams[stream_index]->time_base.num);
    reseekTime /= 1000;
    unsigned long long seekStreamDuration = pFormatCtx->streams[stream_index]->duration;
    int flags = AVSEEK_FLAG_BACKWARD;
    if (reseekTime > 0 && reseekTime < seekStreamDuration){
      flags |= AVSEEK_FLAG_ANY; // H.264 I frames don't always register as "key frames" in FFmpeg
    }
    int ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, flags);
    if (ret < 0){
      ret = av_seek_frame(pFormatCtx, stream_index, reseekTime, AVSEEK_FLAG_ANY);
    }
  }

  void inputAV::trackSelect(std::string trackSpec) {
    selectedTracks.clear();
    long long unsigned int index;
    while (trackSpec != "") {
      index = trackSpec.find(' ');
      selectedTracks.insert(atoi(trackSpec.substr(0, index).c_str()));
      if (index != std::string::npos) {
        trackSpec.erase(0, index + 1);
      } else {
        trackSpec = "";
      }
    }
    //inFile.selectTracks(selectedTracks);
  }
}

<|endoftext|>


<commit_before>
#include "generator.h"
#include <iostream>

using namespace lars;
using namespace std;

Generator<int> fibonacci(int n){
  return Generator<int>([=](Yield<int> &yield){
    int a = 0, b = 1;
    for (int i=0;i<n;i++){
       int t = a + b;
       yield(t);
       a = b;
       b = t;
    }
  });
}

int main(){
  for(int i:fibonacci(10)) std::cout << i << std::endl;
}

<commit_msg>update fibonacci.cpp<commit_after>
#include "generator.h"
#include <iostream>

using namespace lars;
using namespace std;

Generator<int> fibonacci(int n){
  return Generator<int>([=](Yield<int> &yield){
    int a = 0, b = 1;
    for (int i=0;i<n;i++){
       int t = a + b;
       yield(t);
       a = b;
       b = t;
    }
  });
}

int main(){
  for(int i:fibonacci(10)) std::cout << i << std::endl;
}

<|endoftext|>


<commit_before>//Fibonacci sequence printer!
#include <iostream>
using namespace std;

int main()
{
	int n,i;
	cout<<"Welcome to Fibbonacci Sequence Printer!"<<endl;
	cout<<"Pleas enter the number of terms, you want printed out: "<<endl;
	cin>>n;
	cout<<"First "<<n<<" terms of Fibonacci sequence are:"<<endl;
	unsigned long fibo(int);
	for(i=0;i<=n;i++)
	{
		cout<<"Term("<<i<<")="<<fibo(i)<<endl;
	}
	cout<<"The Sum of terms of the number you entered:"<<endl<<"Fib("<<n<<")="<<fibo(i)+fibo(i-1)-1;

	cin.get();
	cin.ignore();
	return 0;

}

long fibo(int x)
{
	if(x==0) return 0;
	if(x==1) return 1;
	else return fibo(x-2)+fibo(x-1);
}
<commit_msg>Delete fibonacci.cpp<commit_after><|endoftext|>


<commit_before>#include <moveit/collision_detection_fcl/collision_detector_fcl_plugin_loader.h>
#include <pluginlib/class_list_macros.h>

namespace collision_detection
{
bool CollisionDetectorFCLPluginLoader::initialize(const planning_scene::PlanningScenePtr& scene,
                                                     bool exclusive) const
{
  scene->setActiveCollisionDetector(CollisionDetectorAllocatorFCL::create(), exclusive);
  return true;
}
}

PLUGINLIB_EXPORT_CLASS(collision_detection::CollisionDetectorFCLPluginLoader, collision_detection::CollisionPlugin)
<commit_msg>clang format<commit_after>#include <moveit/collision_detection_fcl/collision_detector_fcl_plugin_loader.h>
#include <pluginlib/class_list_macros.h>

namespace collision_detection
{
bool CollisionDetectorFCLPluginLoader::initialize(const planning_scene::PlanningScenePtr& scene, bool exclusive) const
{
  scene->setActiveCollisionDetector(CollisionDetectorAllocatorFCL::create(), exclusive);
  return true;
}
}

PLUGINLIB_EXPORT_CLASS(collision_detection::CollisionDetectorFCLPluginLoader, collision_detection::CollisionPlugin)
<|endoftext|>


<commit_before>#include "tests.h"

using namespace swoole;

TEST(coroutine_base, create)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        *(long *) arg = Coroutine::get_current_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    ASSERT_EQ(cid, _cid);
}

TEST(coroutine_base, get_current)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        auto co = Coroutine::get_current();
        *(long *) arg = co->get_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    ASSERT_EQ(cid, _cid);
}

TEST(coroutine_base, yield_resume)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        long cid = Coroutine::get_current_cid();
        Coroutine *co = Coroutine::get_by_cid(cid);
        co->yield();
        *(long *) arg = Coroutine::get_current_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    Coroutine::get_by_cid(cid)->resume();
    ASSERT_EQ(cid, _cid);
}
<commit_msg>test: add coroutine core test (#3209)<commit_after>#include "tests.h"

using namespace swoole;

TEST(coroutine_base, create)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        *(long *) arg = Coroutine::get_current_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    ASSERT_EQ(cid, _cid);
}

TEST(coroutine_base, get_current)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        auto co = Coroutine::get_current();
        *(long *) arg = co->get_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    ASSERT_EQ(cid, _cid);
}

TEST(coroutine_base, yield_resume)
{
    long _cid;
    long cid = Coroutine::create([](void *arg)
    {
        long cid = Coroutine::get_current_cid();
        Coroutine *co = Coroutine::get_by_cid(cid);
        co->yield();
        *(long *) arg = Coroutine::get_current_cid();
    }, &_cid);

    ASSERT_GT(cid, 0);
    Coroutine::get_by_cid(cid)->resume();
    ASSERT_EQ(cid, _cid);
}

TEST(coroutine_base, get_cid)
{
    Coroutine::create([](void *arg)
    {
        auto co = Coroutine::get_current();
        long cid = co->get_cid();

        ASSERT_GT(cid, 0);
    });
}

TEST(coroutine_base, get_origin)
{
    Coroutine::create([](void *arg)
    {
        auto *co = Coroutine::get_current();

        Coroutine::create([](void *arg)
        {
            auto current_co = Coroutine::get_current();
            auto origin_co = current_co->get_origin();

            ASSERT_EQ(arg, origin_co);
        }, co);
    });
}

TEST(coroutine_base, get_origin_cid)
{
    Coroutine::create([](void *arg)
    {
        auto _cid = Coroutine::get_current_cid();

        Coroutine::create([](void *arg)
        {
            auto origin_cid = Coroutine::get_current()->get_origin_cid();

            ASSERT_EQ(*(long *) arg, origin_cid);
        }, &_cid);
    });
}

TEST(coroutine_base, is_end)
{
    Coroutine::create([](void *_arg)
    {
        auto co = Coroutine::get_current();
        ASSERT_FALSE(co->is_end());
    });
}

TEST(coroutine_base, set_task)
{
    Coroutine::create([](void *_arg)
    {
        int task;
        auto co = Coroutine::get_current();
        co->set_task(&task);
        void *actual = co->get_task();
        ASSERT_EQ(actual, &task);
    });
}

TEST(coroutine_base, get_current_task)
{
    Coroutine::create([](void *_arg)
    {
        int task;
        auto co = Coroutine::get_current();
        co->set_task(&task);
        void *actual = co->get_task();
        ASSERT_EQ(actual, Coroutine::get_current_task());
    });
}

TEST(coroutine_base, get_current_cid)
{
    Coroutine::create([](void *_arg)
    {
        auto co = Coroutine::get_current();
        auto actual = co->get_cid();
        ASSERT_EQ(actual, Coroutine::get_current_cid());
    });
}

TEST(coroutine_base, get_by_cid)
{
    Coroutine::create([](void *_arg)
    {
        auto actual = Coroutine::get_current();
        auto cid = actual->get_cid();
        ASSERT_EQ(actual, Coroutine::get_by_cid(cid));
    });
}

TEST(coroutine_base, get_task_by_cid)
{
    Coroutine::create([](void *_arg)
    {
        int task;
        auto co = Coroutine::get_current();
        co->set_task(&task);
        auto actual = co->get_task();
        ASSERT_EQ(actual, Coroutine::get_task_by_cid(co->get_cid()));
    });
}

TEST(coroutine_base, get_last_cid)
{
    Coroutine::create([](void *_arg)
    {
    });
    Coroutine::create([](void *_arg)
    {
    });
    long cid = Coroutine::create([](void *_arg)
    {
    });

    ASSERT_EQ(Coroutine::get_last_cid(), cid);
}

TEST(coroutine_base, count)
{
    Coroutine::create([](void *_arg)
    {
        ASSERT_EQ(Coroutine::count(), 1);
        Coroutine::create([](void *_arg)
        {
            ASSERT_EQ(Coroutine::count(), 2);
        });
    });
    ASSERT_EQ(Coroutine::count(), 0);
}

TEST(coroutine_base, get_peak_num)
{
    Coroutine::create([](void *_arg)
    {
        Coroutine::create([](void *_arg)
        {
            ASSERT_GE(Coroutine::get_peak_num(), 2);
        });
    });
}
<|endoftext|>


<commit_before>#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
    ofBackground(0,0,0);
    ofSetBackgroundAuto(false);
    isFullScreen = false;
    ofSetFrameRate(30);

    masterCounter = 0;
    direction = 1; //count up

    // OSC STUFF
    receiver.setup(PORT);
	current_msg_string = 0;
    mainMix = 0;
}

//--------------------------------------------------------------
void testApp::update(){

    // hide old messages
	for(int i = 0; i < NUM_MSG_STRINGS; i++){
		if(timers[i] < ofGetElapsedTimef()){
			msg_strings[i] = "";
		}
	}

	// check for waiting messages
	while(receiver.hasWaitingMessages()){
		// get the next message
		ofxOscMessage m;
		receiver.getNextMessage(&m);

		// check for mouse moved message
		if(m.getAddress() == "/main/mix"){
			// both the arguments are int32's
			mainMix = m.getArgAsFloat(0);
            ofLogNotice("you are the master of the universe"+ofToString(m.getArgAsFloat(0)));
		}
		// check for mouse button message
		else{
			// unrecognized message: display on the bottom of the screen
			string msg_string;
			msg_string = m.getAddress();
			msg_string += ": ";
			for(int i = 0; i < m.getNumArgs(); i++){
				// get the argument type
				msg_string += m.getArgTypeName(i);
				msg_string += ":";
				// display the argument - make sure we get the right type
				if(m.getArgType(i) == OFXOSC_TYPE_INT32){
					msg_string += ofToString(m.getArgAsInt32(i));
				}
				else if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){
					msg_string += ofToString(m.getArgAsFloat(i));
				}
				else if(m.getArgType(i) == OFXOSC_TYPE_STRING){
					msg_string += m.getArgAsString(i);
				}
				else{
					msg_string += "unknown";
				}
			}
			// add to the list of strings to display
			msg_strings[current_msg_string] = msg_string;
			timers[current_msg_string] = ofGetElapsedTimef() + 5.0f;
			current_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS;
			// clear the next line
			msg_strings[current_msg_string] = "";
		}

	}

    // FUN STUFF
    masterCounter+=direction;
    if (masterCounter > 2000) {
        direction = -1;
    }
    if (masterCounter < -2000) {
        direction = 1;
    }

}

//--------------------------------------------------------------
void testApp::draw(){
    //normalize mouse (within the window space...
    float daMouseX = float(mouseX)/float(ofGetWidth());
    float daMouseY = float(mouseY)/ofGetHeight();
   // ofLogNotice(ofToString(daMouseX));

    //Abstract line stuff
    for (int i = 0; i < ofGetWidth(); i++) {
        int r = daMouseX*sin(masterCounter)/4;
        int g = i/4;
        int b = daMouseX*daMouseY*i/4;
        ofSetColor(r, g, b); //Replace this with pixel colors from feed
        ofLine(i, ofGetHeight()/2, i*sin(i)*mouseY, i*cos(i)*/*mouseY*30*/masterCounter);
    }

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>initial audio reactivity established. mainMix controls *someVariable*<commit_after>#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
    ofBackground(0,0,0);
    ofSetBackgroundAuto(false);
    isFullScreen = false;
    ofSetFrameRate(30);

    masterCounter = 0;
    direction = 1; //count up

    // OSC STUFF
    receiver.setup(PORT);
	current_msg_string = 0;
    mainMix = 0;
}

//--------------------------------------------------------------
void testApp::update(){

    // hide old messages
	for(int i = 0; i < NUM_MSG_STRINGS; i++){
		if(timers[i] < ofGetElapsedTimef()){
			msg_strings[i] = "";
		}
	}

	// check for waiting messages
	while(receiver.hasWaitingMessages()){
		// get the next message
		ofxOscMessage m;
		receiver.getNextMessage(&m);

		// check for mouse moved message
		if(m.getAddress() == "/main/mix"){
			// both the arguments are int32's
			mainMix = m.getArgAsFloat(0);
            ofLogNotice("mainMix: "+ofToString(m.getArgAsFloat(0)));
		}
		// check for mouse button message
		else{
			// unrecognized message: display on the bottom of the screen
			string msg_string;
			msg_string = m.getAddress();
			msg_string += ": ";
			for(int i = 0; i < m.getNumArgs(); i++){
				// get the argument type
				msg_string += m.getArgTypeName(i);
				msg_string += ":";
				// display the argument - make sure we get the right type
				if(m.getArgType(i) == OFXOSC_TYPE_INT32){
					msg_string += ofToString(m.getArgAsInt32(i));
				}
				else if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){
					msg_string += ofToString(m.getArgAsFloat(i));
				}
				else if(m.getArgType(i) == OFXOSC_TYPE_STRING){
					msg_string += m.getArgAsString(i);
				}
				else{
					msg_string += "unknown";
				}
			}
			// add to the list of strings to display
			msg_strings[current_msg_string] = msg_string;
			timers[current_msg_string] = ofGetElapsedTimef() + 5.0f;
			current_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS;
			// clear the next line
			msg_strings[current_msg_string] = "";
		}

	}

    // FUN STUFF
    masterCounter+=direction;
    if (masterCounter > 2000) {
        direction = -1;
    }
    if (masterCounter < -2000) {
        direction = 1;
    }

}

//--------------------------------------------------------------
void testApp::draw(){
    //normalize mouse (within the window space...
    float daMouseX = float(mouseX)/float(ofGetWidth());
    float daMouseY = float(mouseY)/ofGetHeight();
   // ofLogNotice(ofToString(daMouseX));

    //Abstract line stuff
    for (int i = 0; i < ofGetWidth(); i++) {
        int r = daMouseX*sin(masterCounter)/4;
        int g = i/4;
        int b = daMouseX*daMouseY*i/4;
        ofSetColor(r, g, b); //Replace this with pixel colors from feed
        ofLine(i, ofGetHeight()/2, i*sin(i), i*cos(i)*mainMix*/*mouseY*30*/masterCounter);
    }

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){
    if (key == 'f' || 'F') {
        isFullScreen = !isFullScreen;
        ofSetFullscreen(isFullScreen);
    }

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


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

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
//  FORWARD_DECLARE_INTERFACE(awt,XControlContainer)
FORWARD_DECLARE_INTERFACE(uno,Any)
//  class ::com::sun::star::uno::Any;

//==================================================================
class FmInterfaceItem : public SfxPoolItem
{
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  xInterface;

public:
    TYPEINFO();

    FmInterfaceItem( const sal_uInt16 nId, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxInterface )
        :SfxPoolItem( nId )
        ,xInterface( rxInterface )
    {}

    inline FmInterfaceItem&  operator=( const FmInterfaceItem &rCpy );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, sal_uInt16) const;
    virtual SvStream&       Store(SvStream &, sal_uInt16 nItemVersion ) const;

    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >         GetInterface() const { return xInterface; }
};

inline FmInterfaceItem& FmInterfaceItem::operator=( const FmInterfaceItem &rCpy )
{
    xInterface = rCpy.xInterface;

    return *this;
}

#endif // _SVX_FMITEMS_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.5.1252); FILE MERGED 2008/04/01 15:51:09 thb 1.5.1252.2: #i85898# Stripping all external header guards 2008/03/31 14:22:19 rt 1.5.1252.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fmitems.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_FMITEMS_HXX
#define _SVX_FMITEMS_HXX

#include <svtools/poolitem.hxx>
#include <comphelper/uno3.hxx>
//  FORWARD_DECLARE_INTERFACE(awt,XControlContainer)
FORWARD_DECLARE_INTERFACE(uno,Any)
//  class ::com::sun::star::uno::Any;

//==================================================================
class FmInterfaceItem : public SfxPoolItem
{
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  xInterface;

public:
    TYPEINFO();

    FmInterfaceItem( const sal_uInt16 nId, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxInterface )
        :SfxPoolItem( nId )
        ,xInterface( rxInterface )
    {}

    inline FmInterfaceItem&  operator=( const FmInterfaceItem &rCpy );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, sal_uInt16) const;
    virtual SvStream&       Store(SvStream &, sal_uInt16 nItemVersion ) const;

    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >         GetInterface() const { return xInterface; }
};

inline FmInterfaceItem& FmInterfaceItem::operator=( const FmInterfaceItem &rCpy )
{
    xInterface = rCpy.xInterface;

    return *this;
}

#endif // _SVX_FMITEMS_HXX

<|endoftext|>


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

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

class SwWrtShell;

class SwBreakDlg: public SvxStandardDialog
{
    SwWrtShell     &rSh;
    RadioButton     aLineBtn;
    RadioButton     aColumnBtn;
    RadioButton     aPageBtn;
    FixedText       aPageCollText;
    ListBox         aPageCollBox;
    CheckBox        aPageNumBox;
    NumericField    aPageNumEdit;
    FixedLine       aBreakFL;

    OKButton        aOkBtn;
    CancelButton    aCancelBtn;
    HelpButton      aHelpBtn;

    String          aTemplate;
    USHORT          nKind;
    USHORT          nPgNum;

    BOOL            bHtmlMode;

    DECL_LINK( ClickHdl, void * );
    DECL_LINK( PageNumHdl, CheckBox * );
    DECL_LINK( PageNumModifyHdl, Edit * );
    DECL_LINK( OkHdl, Button * );

    void CheckEnable();

protected:
    virtual void Apply();

public:
    SwBreakDlg( Window *pParent, SwWrtShell &rSh );
    ~SwBreakDlg();

    String  GetTemplateName() { return aTemplate; }
    USHORT  GetKind() { return nKind; }
    USHORT  GetPageNumber() { return nPgNum; }
};

#endif

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

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

class SwWrtShell;

class SwBreakDlg: public SvxStandardDialog
{
    SwWrtShell     &rSh;
    RadioButton     aLineBtn;
    RadioButton     aColumnBtn;
    RadioButton     aPageBtn;
    FixedText       aPageCollText;
    ListBox         aPageCollBox;
    CheckBox        aPageNumBox;
    NumericField    aPageNumEdit;
    FixedLine       aBreakFL;

    OKButton        aOkBtn;
    CancelButton    aCancelBtn;
    HelpButton      aHelpBtn;

    String          aTemplate;
    USHORT          nKind;
    USHORT          nPgNum;

    BOOL            bHtmlMode;

    DECL_LINK( ClickHdl, void * );
    DECL_LINK( PageNumHdl, CheckBox * );
    DECL_LINK( PageNumModifyHdl, Edit * );
    DECL_LINK( OkHdl, Button * );

    void CheckEnable();

protected:
    virtual void Apply();

public:
    SwBreakDlg( Window *pParent, SwWrtShell &rSh );
    ~SwBreakDlg();

    String  GetTemplateName() { return aTemplate; }
    USHORT  GetKind() { return nKind; }
    USHORT  GetPageNumber() { return nPgNum; }
};

#endif

<|endoftext|>


<commit_before>//
// $Id$
//

#include "AVGImage.h"
#include "AVGDFBDisplayEngine.h"
#include "AVGPlayer.h"

#include <paintlib/plbitmap.h>
#include <paintlib/planybmp.h>
#include <paintlib/plpngenc.h>
#include <paintlib/planydec.h>
#include <paintlib/Filter/plfilterresizebilinear.h>
#include <paintlib/Filter/plfilterfliprgb.h>
#include <paintlib/Filter/plfilterfill.h>

#include <nsMemory.h>
#include <xpcom/nsComponentManagerUtils.h>

#include <iostream>
#include <sstream>

using namespace std;

NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);

AVGImage * AVGImage::create()
{
    return createNode<AVGImage>("@c-base.org/avgimage;1");
}

AVGImage::AVGImage ()
    : m_pBmp(0)
{
    NS_INIT_ISUPPORTS();
}

AVGImage::~AVGImage ()
{
    if (m_pBmp) {
        delete m_pBmp;
    }
}

NS_IMETHODIMP
AVGImage::GetType(PRInt32 *_retval)
{
    *_retval = NT_IMAGE;
    return NS_OK;
}

void AVGImage::init (const std::string& id, int x, int y, int z,
       int width, int height, double opacity, const std::string& filename,
       AVGDFBDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer)
{
    AVGNode::init(id, pEngine, pParent, pPlayer);

    m_Filename = filename;
    AVG_TRACE(AVGPlayer::DEBUG_MEMORY, "Loading " << m_Filename << endl);
    m_pBmp = getEngine()->createSurface();

    PLAnyPicDecoder decoder;
    decoder.MakeBmpFromFile(m_Filename.c_str(), m_pBmp);
    m_pBmp->ApplyFilter(PLFilterFlipRGB());

    initVisible(x, y, z,  width, height, opacity);

    PLPoint size = PLPoint(getRelViewport().Width(), getRelViewport().Height());
    if (m_pBmp->GetWidth() != size.x || m_pBmp->GetHeight() != size.y) {
        m_pBmp->ApplyFilter (PLFilterResizeBilinear(size.x, size.y));
    }
}

void AVGImage::render (const PLRect& Rect)
{
//    cerr << "render " << getID() << endl;

    PLRect SrcRect(0, 0, getRelViewport().Width(), getRelViewport().Height());
    if (getRelViewport().tl.x < 0) {
        SrcRect.tl.x = -getRelViewport().tl.x;
    }
    if (getRelViewport().tl.x < 0) {
        SrcRect.tl.y = -getRelViewport().tl.y;
    }
    getEngine()->render(m_pBmp, &SrcRect, getAbsViewport().tl, getEffectiveOpacity());
}

bool AVGImage::obscures (const PLRect& Rect, int z)
{
    return (getEffectiveOpacity() > 0.999 && !m_pBmp->HasAlpha() &&
            getZ() > z && getAbsViewport().Contains(Rect));
}

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

PLPoint AVGImage::getPreferredMediaSize()
{
    return m_pBmp->GetSize();
}

<commit_msg>Fixed neg. coordinate bug.<commit_after>//
// $Id$
//

#include "AVGImage.h"
#include "AVGDFBDisplayEngine.h"
#include "AVGPlayer.h"

#include <paintlib/plbitmap.h>
#include <paintlib/planybmp.h>
#include <paintlib/plpngenc.h>
#include <paintlib/planydec.h>
#include <paintlib/Filter/plfilterresizebilinear.h>
#include <paintlib/Filter/plfilterfliprgb.h>
#include <paintlib/Filter/plfilterfill.h>

#include <nsMemory.h>
#include <xpcom/nsComponentManagerUtils.h>

#include <iostream>
#include <sstream>

using namespace std;

NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);

AVGImage * AVGImage::create()
{
    return createNode<AVGImage>("@c-base.org/avgimage;1");
}

AVGImage::AVGImage ()
    : m_pBmp(0)
{
    NS_INIT_ISUPPORTS();
}

AVGImage::~AVGImage ()
{
    if (m_pBmp) {
        delete m_pBmp;
    }
}

NS_IMETHODIMP
AVGImage::GetType(PRInt32 *_retval)
{
    *_retval = NT_IMAGE;
    return NS_OK;
}

void AVGImage::init (const std::string& id, int x, int y, int z,
       int width, int height, double opacity, const std::string& filename,
       AVGDFBDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer)
{
    AVGNode::init(id, pEngine, pParent, pPlayer);

    m_Filename = filename;
    AVG_TRACE(AVGPlayer::DEBUG_MEMORY, "Loading " << m_Filename << endl);
    m_pBmp = getEngine()->createSurface();

    PLAnyPicDecoder decoder;
    decoder.MakeBmpFromFile(m_Filename.c_str(), m_pBmp);
    m_pBmp->ApplyFilter(PLFilterFlipRGB());

    initVisible(x, y, z,  width, height, opacity);

    PLPoint size = PLPoint(getRelViewport().Width(), getRelViewport().Height());
    if (m_pBmp->GetWidth() != size.x || m_pBmp->GetHeight() != size.y) {
        m_pBmp->ApplyFilter (PLFilterResizeBilinear(size.x, size.y));
    }
}

void AVGImage::render (const PLRect& Rect)
{
//    cerr << "render " << getID() << endl;

    PLRect SrcRect(0, 0, getRelViewport().Width(), getRelViewport().Height());
    if (getRelViewport().tl.x < 0) {
        SrcRect.tl.x = -getRelViewport().tl.x;
    }
    if (getRelViewport().tl.y < 0) {
        SrcRect.tl.y = -getRelViewport().tl.y;
    }
    getEngine()->render(m_pBmp, &SrcRect, getAbsViewport().tl, getEffectiveOpacity());
}

bool AVGImage::obscures (const PLRect& Rect, int z)
{
    return (getEffectiveOpacity() > 0.999 && !m_pBmp->HasAlpha() &&
            getZ() > z && getAbsViewport().Contains(Rect));
}

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

PLPoint AVGImage::getPreferredMediaSize()
{
    return m_pBmp->GetSize();
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMultimedia module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "player.h"

#include "playercontrols.h"
#include "playlistmodel.h"

#include <qabstractmediaservice.h>
#include <qmediaplaylist.h>
#include <qmediametadata.h>
#include <qmediawidgetendpoint.h>

#include <QtGui>

#define USE_VIDEOWIDGET

Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
    , colorDialog(0)
{
    player = new QMediaPlayer;
    metaData = new QMediaMetadata(player);

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferingChanged(bool)), this, SLOT(bufferingChanged(bool)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));

#ifdef USE_VIDEOWIDGET
    videoWidget = new QVideoWidget(player);

    connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),
            this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));
#else
    QWidget *videoWidget = player->service()->createEndpoint<QMediaWidgetEndpoint *>();

    if (videoWidget) {
        qDebug() << "service supports video widgets, nice";
        player->service()->setVideoOutput(videoWidget);
    } else {
        coverLabel = new QLabel;
    }
#endif
    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(player->mediaPlaylist());

    playlistView = new QTableView;
    playlistView->setModel(playlistModel);
    playlistView->setCurrentIndex(playlistModel->index(player->playlistPosition(), 0));

    connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));

    slider = new QSlider(Qt::Horizontal);
    slider->setRange(0, player->duration() / 1000);

    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));

    QPushButton *openButton = new QPushButton(tr("Open"));

    connect(openButton, SIGNAL(clicked()), this, SLOT(open()));

    PlayerControls *controls = new PlayerControls;
    controls->setState(player->state());
    controls->setVolume(player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, SIGNAL(play()), player, SLOT(play()));
    connect(controls, SIGNAL(pause()), player, SLOT(pause()));
    connect(controls, SIGNAL(stop()), player, SLOT(stop()));
    connect(controls, SIGNAL(next()), player, SLOT(advance()));
    connect(controls, SIGNAL(previous()), player, SLOT(back()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
            controls, SLOT(setState(QMediaPlayer::State)));
    connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
    connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));

    QPushButton *fullscreenButton = new QPushButton(tr("Fullscreen"));
    fullscreenButton->setCheckable(true);

    connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));
    connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));

    fullscreenButton->setEnabled(videoWidget != 0);

    QPushButton *colorButton = new QPushButton(tr("Color Options..."));
    if (videoWidget)
        connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
    else
        colorButton->setEnabled(false);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(fullscreenButton);
    controlLayout->addWidget(colorButton);

    QBoxLayout *layout = new QVBoxLayout;
    if (videoWidget) {
        QSplitter *splitter = new QSplitter(Qt::Vertical);

        splitter->addWidget(videoWidget);
        splitter->addWidget(playlistView);

        /*
        connect(player, SIGNAL(videoAvailabilityChanged(bool)), videoWidget, SLOT(setVisible(bool)));
        videoWidget->setMinimumSize(64,64);
        videoWidget->setVisible(false);*/

        layout->addWidget(splitter);
    } else {
        layout->addWidget(coverLabel, 0, Qt::AlignCenter);
        layout->addWidget(playlistView);
    }
    layout->addWidget(slider);
    layout->addLayout(controlLayout);

    setLayout(layout);

    metadataChanged();
}

Player::~Player()
{
    delete player;
}

void Player::open()
{
    QStringList fileNames = QFileDialog::getOpenFileNames();

    foreach (QString const &fileName, fileNames) {
#ifndef Q_OS_WIN
        player->mediaPlaylist()->appendItem(
                QMediaResource(QUrl(QLatin1String("file://") + fileName)));
#else
        player->mediaPlaylist()->appendItem(
                QMediaResource(QUrl(QLatin1String("file:///") + fileName)));
#endif
    }
}

void Player::durationChanged(qint64 duration)
{
    slider->setMaximum(duration / 1000);
}

void Player::positionChanged(qint64 progress)
{
    slider->setValue(progress / 1000);
}

void Player::metadataChanged()
{
    qDebug() << "update metadata" << metaData->metadata(QLatin1String("title")).toString();
    if (metaData->metadataAvailable()) {
        setTrackInfo(QString("%1 - %2")
                .arg(metaData->metadata(QLatin1String("Artist")).toString())
                .arg(metaData->metadata(QLatin1String("Title")).toString()));

        if (coverLabel) {
            QMediaResource cover;
            foreach (const QMediaResource &resource, metaData->resources()) {
                if (resource.role() == QMediaResource::CoverArtRole
                        && (cover.isNull()
                        || resource.resolution().height() > cover.resolution().height())) {
                    cover = resource;
                }
            }
            coverLabel->setPixmap(!cover.isNull()
                    ? QPixmap(cover.uri().toString())
                    : QPixmap());
        }
    }
}

void Player::jump(const QModelIndex &index)
{
    if (index.isValid()) {
        player->setPlaylistPosition(index.row());
    }
}

void Player::playlistPositionChanged(int currentItem)
{
    playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}

void Player::seek(int seconds)
{
    player->setPosition(seconds * 1000);
}

void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
    switch (status) {
    case QMediaPlayer::UnknownMediaStatus:
    case QMediaPlayer::NoMedia:
    case QMediaPlayer::LoadedMedia:
    case QMediaPlayer::PrimedMedia:
        unsetCursor();
        setStatusInfo(QString());
        break;
    case QMediaPlayer::LoadingMedia:
        setCursor(QCursor(Qt::BusyCursor));
        setStatusInfo(tr("Loading..."));
        break;
    case QMediaPlayer::StalledMedia:
        setCursor(QCursor(Qt::BusyCursor));
        break;
    case QMediaPlayer::EndOfMedia:
        unsetCursor();
        setStatusInfo(QString());
        QApplication::alert(this);
        break;
    case QMediaPlayer::InvalidMedia:
        unsetCursor();
        setStatusInfo(player->errorString());
        break;
    }
}

void Player::bufferingChanged(bool buffering)
{
    if (buffering)
        statusChanged(player->mediaStatus());
}

void Player::bufferingProgress(int progress)
{
    setStatusInfo(tr("Buffering %4%%").arg(progress));
}

void Player::setTrackInfo(const QString &info)
{
    trackInfo = info;

    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);

}

void Player::setStatusInfo(const QString &info)
{
    statusInfo = info;

    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::setFullscreen(bool fullscreen)
{
    videoWidget->setDisplayMode(
            fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);
}

void Player::displayModeChanged(QVideoWidget::DisplayMode mode)
{
    emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);
}

void Player::showColorDialog()
{
    if (!colorDialog) {
        QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
        brightnessSlider->setRange(-100, 100);
        brightnessSlider->setValue(videoWidget->brightness());
        connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
        connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));

        QSlider *contrastSlider = new QSlider(Qt::Horizontal);
        contrastSlider->setRange(-100, 100);
        contrastSlider->setValue(videoWidget->contrast());
        connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
        connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));

        QSlider *hueSlider = new QSlider(Qt::Horizontal);
        hueSlider->setRange(-100, 100);
        hueSlider->setValue(videoWidget->hue());
        connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
        connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));

        QSlider *saturationSlider = new QSlider(Qt::Horizontal);
        saturationSlider->setRange(-100, 100);
        saturationSlider->setValue(videoWidget->saturation());
        connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
        connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));

        QFormLayout *layout = new QFormLayout;
        layout->addRow(tr("Brightness"), brightnessSlider);
        layout->addRow(tr("Contrast"), contrastSlider);
        layout->addRow(tr("Hue"), hueSlider);
        layout->addRow(tr("Saturation"), saturationSlider);

        colorDialog = new QDialog(this);
        colorDialog->setWindowTitle(tr("Color Options"));
        colorDialog->setLayout(layout);
    }
    colorDialog->show();
}
<commit_msg>Compile with QT_NO_CURSOR defined.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMultimedia module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "player.h"

#include "playercontrols.h"
#include "playlistmodel.h"

#include <qabstractmediaservice.h>
#include <qmediaplaylist.h>
#include <qmediametadata.h>
#include <qmediawidgetendpoint.h>

#include <QtGui>

#define USE_VIDEOWIDGET

Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
    , colorDialog(0)
{
    player = new QMediaPlayer;
    metaData = new QMediaMetadata(player);

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferingChanged(bool)), this, SLOT(bufferingChanged(bool)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));

#ifdef USE_VIDEOWIDGET
    videoWidget = new QVideoWidget(player);

    connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),
            this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));
#else
    QWidget *videoWidget = player->service()->createEndpoint<QMediaWidgetEndpoint *>();

    if (videoWidget) {
        qDebug() << "service supports video widgets, nice";
        player->service()->setVideoOutput(videoWidget);
    } else {
        coverLabel = new QLabel;
    }
#endif
    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(player->mediaPlaylist());

    playlistView = new QTableView;
    playlistView->setModel(playlistModel);
    playlistView->setCurrentIndex(playlistModel->index(player->playlistPosition(), 0));

    connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));

    slider = new QSlider(Qt::Horizontal);
    slider->setRange(0, player->duration() / 1000);

    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));

    QPushButton *openButton = new QPushButton(tr("Open"));

    connect(openButton, SIGNAL(clicked()), this, SLOT(open()));

    PlayerControls *controls = new PlayerControls;
    controls->setState(player->state());
    controls->setVolume(player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, SIGNAL(play()), player, SLOT(play()));
    connect(controls, SIGNAL(pause()), player, SLOT(pause()));
    connect(controls, SIGNAL(stop()), player, SLOT(stop()));
    connect(controls, SIGNAL(next()), player, SLOT(advance()));
    connect(controls, SIGNAL(previous()), player, SLOT(back()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
            controls, SLOT(setState(QMediaPlayer::State)));
    connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
    connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));

    QPushButton *fullscreenButton = new QPushButton(tr("Fullscreen"));
    fullscreenButton->setCheckable(true);

    connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));
    connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));

    fullscreenButton->setEnabled(videoWidget != 0);

    QPushButton *colorButton = new QPushButton(tr("Color Options..."));
    if (videoWidget)
        connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
    else
        colorButton->setEnabled(false);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(fullscreenButton);
    controlLayout->addWidget(colorButton);

    QBoxLayout *layout = new QVBoxLayout;
    if (videoWidget) {
        QSplitter *splitter = new QSplitter(Qt::Vertical);

        splitter->addWidget(videoWidget);
        splitter->addWidget(playlistView);

        /*
        connect(player, SIGNAL(videoAvailabilityChanged(bool)), videoWidget, SLOT(setVisible(bool)));
        videoWidget->setMinimumSize(64,64);
        videoWidget->setVisible(false);*/

        layout->addWidget(splitter);
    } else {
        layout->addWidget(coverLabel, 0, Qt::AlignCenter);
        layout->addWidget(playlistView);
    }
    layout->addWidget(slider);
    layout->addLayout(controlLayout);

    setLayout(layout);

    metadataChanged();
}

Player::~Player()
{
    delete player;
}

void Player::open()
{
    QStringList fileNames = QFileDialog::getOpenFileNames();

    foreach (QString const &fileName, fileNames) {
#ifndef Q_OS_WIN
        player->mediaPlaylist()->appendItem(
                QMediaResource(QUrl(QLatin1String("file://") + fileName)));
#else
        player->mediaPlaylist()->appendItem(
                QMediaResource(QUrl(QLatin1String("file:///") + fileName)));
#endif
    }
}

void Player::durationChanged(qint64 duration)
{
    slider->setMaximum(duration / 1000);
}

void Player::positionChanged(qint64 progress)
{
    slider->setValue(progress / 1000);
}

void Player::metadataChanged()
{
    qDebug() << "update metadata" << metaData->metadata(QLatin1String("title")).toString();
    if (metaData->metadataAvailable()) {
        setTrackInfo(QString("%1 - %2")
                .arg(metaData->metadata(QLatin1String("Artist")).toString())
                .arg(metaData->metadata(QLatin1String("Title")).toString()));

        if (coverLabel) {
            QMediaResource cover;
            foreach (const QMediaResource &resource, metaData->resources()) {
                if (resource.role() == QMediaResource::CoverArtRole
                        && (cover.isNull()
                        || resource.resolution().height() > cover.resolution().height())) {
                    cover = resource;
                }
            }
            coverLabel->setPixmap(!cover.isNull()
                    ? QPixmap(cover.uri().toString())
                    : QPixmap());
        }
    }
}

void Player::jump(const QModelIndex &index)
{
    if (index.isValid()) {
        player->setPlaylistPosition(index.row());
    }
}

void Player::playlistPositionChanged(int currentItem)
{
    playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}

void Player::seek(int seconds)
{
    player->setPosition(seconds * 1000);
}

void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
    switch (status) {
    case QMediaPlayer::UnknownMediaStatus:
    case QMediaPlayer::NoMedia:
    case QMediaPlayer::LoadedMedia:
    case QMediaPlayer::PrimedMedia:
#ifndef QT_NO_CURSOR
        unsetCursor();
#endif
        setStatusInfo(QString());
        break;
    case QMediaPlayer::LoadingMedia:
#ifndef QT_NO_CURSOR
        setCursor(QCursor(Qt::BusyCursor));
#endif
        setStatusInfo(tr("Loading..."));
        break;
    case QMediaPlayer::StalledMedia:
        setCursor(QCursor(Qt::BusyCursor));
        break;
    case QMediaPlayer::EndOfMedia:
#ifndef QT_NO_CURSOR
        unsetCursor();
#endif
        setStatusInfo(QString());
        QApplication::alert(this);
        break;
    case QMediaPlayer::InvalidMedia:
#ifndef QT_NO_CURSOR
        unsetCursor();
#endif
        setStatusInfo(player->errorString());
        break;
    }
}

void Player::bufferingChanged(bool buffering)
{
    if (buffering)
        statusChanged(player->mediaStatus());
}

void Player::bufferingProgress(int progress)
{
    setStatusInfo(tr("Buffering %4%%").arg(progress));
}

void Player::setTrackInfo(const QString &info)
{
    trackInfo = info;

    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);

}

void Player::setStatusInfo(const QString &info)
{
    statusInfo = info;

    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::setFullscreen(bool fullscreen)
{
    videoWidget->setDisplayMode(
            fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);
}

void Player::displayModeChanged(QVideoWidget::DisplayMode mode)
{
    emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);
}

void Player::showColorDialog()
{
    if (!colorDialog) {
        QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
        brightnessSlider->setRange(-100, 100);
        brightnessSlider->setValue(videoWidget->brightness());
        connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
        connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));

        QSlider *contrastSlider = new QSlider(Qt::Horizontal);
        contrastSlider->setRange(-100, 100);
        contrastSlider->setValue(videoWidget->contrast());
        connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
        connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));

        QSlider *hueSlider = new QSlider(Qt::Horizontal);
        hueSlider->setRange(-100, 100);
        hueSlider->setValue(videoWidget->hue());
        connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
        connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));

        QSlider *saturationSlider = new QSlider(Qt::Horizontal);
        saturationSlider->setRange(-100, 100);
        saturationSlider->setValue(videoWidget->saturation());
        connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
        connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));

        QFormLayout *layout = new QFormLayout;
        layout->addRow(tr("Brightness"), brightnessSlider);
        layout->addRow(tr("Contrast"), contrastSlider);
        layout->addRow(tr("Hue"), hueSlider);
        layout->addRow(tr("Saturation"), saturationSlider);

        colorDialog = new QDialog(this);
        colorDialog->setWindowTitle(tr("Color Options"));
        colorDialog->setLayout(layout);
    }
    colorDialog->show();
}
<|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    threads.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2014 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <log4cplus/config.hxx>

#include <exception>
#include <ostream>
#include <cerrno>

#ifdef LOG4CPLUS_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef LOG4CPLUS_HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif

#ifdef LOG4CPLUS_HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef LOG4CPLUS_HAVE_UNISTD_H
#include <unistd.h>
#endif

#if defined(LOG4CPLUS_USE_PTHREADS)
#  include <pthread.h>
#  include <sched.h>
#  include <signal.h>
#elif defined (LOG4CPLUS_USE_WIN32_THREADS)
#  include <process.h>
#endif
#include <log4cplus/config/windowsh-inc.h>
#include <log4cplus/thread/syncprims-pub-impl.h>
#include <log4cplus/tstring.h>
#include <log4cplus/internal/cygwin-win32.h>
#include <log4cplus/streams.h>

#ifndef LOG4CPLUS_SINGLE_THREADED

#include <log4cplus/thread/threads.h>
#include <log4cplus/thread/impl/threads-impl.h>
#include <log4cplus/thread/impl/tls.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <log4cplus/internal/internal.h>

#endif // LOG4CPLUS_SINGLE_THREADED

namespace log4cplus { namespace thread {

LOG4CPLUS_EXPORT
void
blockAllSignals()
{
#if defined (LOG4CPLUS_USE_PTHREADS)
    // Block all signals.
    sigset_t signal_set;
    sigfillset (&signal_set);
    pthread_sigmask (SIG_BLOCK, &signal_set, 0);
#endif
}

LOG4CPLUS_EXPORT
void
yield()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
    sched_yield();
#elif defined(_WIN32)
    if (! SwitchToThread ())
        Sleep (0);
#endif
}

#if defined(LOG4CPLUS_SINGLE_THREADED)
static log4cplus::tstring thread_name(LOG4CPLUS_TEXT("single"))
    LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);
static log4cplus::tstring thread_name2(thread_name)
    LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);
#endif

LOG4CPLUS_EXPORT
log4cplus::tstring const &
getCurrentThreadName()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::tstring & name = log4cplus::internal::get_thread_name_str ();
    if (LOG4CPLUS_UNLIKELY (name.empty ()))
    {
        log4cplus::tostringstream tmp;
        tmp << impl::getCurrentThreadId ();
        name = tmp.str ();
    }
#else
    log4cplus::tstring & name = thread_name;
    if (LOG4CPLUS_UNLIKELY(name.empty()))
    {
        name = LOG4CPLUS_TEXT("single");
    }
#endif

    return name;
}

namespace
{

static
bool
get_current_thread_name_alt (log4cplus::tostream * s)
{
    log4cplus::tostream & os = *s;

#if defined (LOG4CPLUS_USE_PTHREADS) && defined (__linux__) \
    && defined (LOG4CPLUS_HAVE_GETTID)
    pid_t tid = syscall (SYS_gettid);
    os << tid;

#elif defined (__CYGWIN__)
    unsigned long tid = cygwin::get_current_win32_thread_id ();
    os << tid;

#else
    os << getCurrentThreadName ();

#endif

    return true;
}

} // namespace

LOG4CPLUS_EXPORT
log4cplus::tstring const &
getCurrentThreadName2()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::tstring & name = log4cplus::internal::get_thread_name2_str ();
    if (LOG4CPLUS_UNLIKELY (name.empty ()))
    {
        log4cplus::tostringstream tmp;
        get_current_thread_name_alt (&tmp);
        name = tmp.str ();
    }

#else
    log4cplus::tstring & name = thread_name2;
    if (LOG4CPLUS_UNLIKELY(name.empty()))
    {
        name = getCurrentThreadName();
    }

#endif

    return name;
}

LOG4CPLUS_EXPORT void setCurrentThreadName(const log4cplus::tstring & name)
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::internal::get_thread_name_str() = name;
#else
    thread_name = name;
#endif
}

LOG4CPLUS_EXPORT void setCurrentThreadName2(const log4cplus::tstring & name)
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::internal::get_thread_name2_str() = name;
#else
    thread_name2 = name;
#endif
}

#ifndef LOG4CPLUS_SINGLE_THREADED

//
//
//

AbstractThread::AbstractThread ()
{ }

bool
AbstractThread::isRunning() const
{
    return (flags & fRUNNING) != 0;
}

void
AbstractThread::start()
{
    try
    {
        addReference ();
        flags |= fRUNNING;
        thread.reset (
            new std::thread ([this] () {
                    blockAllSignals ();
                    AbstractThreadPtr thread_ptr (this);
                    this->removeReference ();
                    helpers::LogLog * loglog = helpers::LogLog::getLogLog();
                    try
                    {
                        this->run ();
                    }
                    catch (std::exception const & e)
                    {
                        tstring err (LOG4CPLUS_TEXT ("threadStartFunc()")
                            LOG4CPLUS_TEXT ("- run() terminated with an exception: "));
                        err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());
                        loglog->warn(err);
                    }
                    catch(...)
                    {
                        loglog->warn(LOG4CPLUS_TEXT("threadStartFunc()")
                            LOG4CPLUS_TEXT ("- run() terminated with an exception."));
                    }
                    this->flags &= ~fRUNNING;
                    threadCleanup ();
                }));
    }
    catch (...)
    {
        flags &= ~fRUNNING;
        removeReference ();
        throw;
    }
}

void
AbstractThread::join () const
{
    if (! thread
        || (flags & fJOINED) == fJOINED)
        throw std::logic_error ("this thread is not running");

    thread->join ();
    flags |= +fJOINED;
}

AbstractThread::~AbstractThread()
{
    if ((flags & fJOINED) == 0)
        thread->detach ();
}

#endif // LOG4CPLUS_SINGLE_THREADED

} } // namespace log4cplus { namespace thread {
<commit_msg>threads.cxx: Add AbstractThreadPtr parameter to thread's lambda to remove the addReference()/removeReference() dance.<commit_after>// Module:  Log4CPLUS
// File:    threads.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2014 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <log4cplus/config.hxx>

#include <exception>
#include <ostream>
#include <cerrno>

#ifdef LOG4CPLUS_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef LOG4CPLUS_HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif

#ifdef LOG4CPLUS_HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef LOG4CPLUS_HAVE_UNISTD_H
#include <unistd.h>
#endif

#if defined(LOG4CPLUS_USE_PTHREADS)
#  include <pthread.h>
#  include <sched.h>
#  include <signal.h>
#elif defined (LOG4CPLUS_USE_WIN32_THREADS)
#  include <process.h>
#endif
#include <log4cplus/config/windowsh-inc.h>
#include <log4cplus/thread/syncprims-pub-impl.h>
#include <log4cplus/tstring.h>
#include <log4cplus/internal/cygwin-win32.h>
#include <log4cplus/streams.h>

#ifndef LOG4CPLUS_SINGLE_THREADED

#include <log4cplus/thread/threads.h>
#include <log4cplus/thread/impl/threads-impl.h>
#include <log4cplus/thread/impl/tls.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <log4cplus/internal/internal.h>

#endif // LOG4CPLUS_SINGLE_THREADED

namespace log4cplus { namespace thread {

LOG4CPLUS_EXPORT
void
blockAllSignals()
{
#if defined (LOG4CPLUS_USE_PTHREADS)
    // Block all signals.
    sigset_t signal_set;
    sigfillset (&signal_set);
    pthread_sigmask (SIG_BLOCK, &signal_set, 0);
#endif
}

LOG4CPLUS_EXPORT
void
yield()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
    sched_yield();
#elif defined(_WIN32)
    if (! SwitchToThread ())
        Sleep (0);
#endif
}

#if defined(LOG4CPLUS_SINGLE_THREADED)
static log4cplus::tstring thread_name(LOG4CPLUS_TEXT("single"))
    LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);
static log4cplus::tstring thread_name2(thread_name)
    LOG4CPLUS_INIT_PRIORITY (LOG4CPLUS_INIT_PRIORITY_BASE - 1);
#endif

LOG4CPLUS_EXPORT
log4cplus::tstring const &
getCurrentThreadName()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::tstring & name = log4cplus::internal::get_thread_name_str ();
    if (LOG4CPLUS_UNLIKELY (name.empty ()))
    {
        log4cplus::tostringstream tmp;
        tmp << impl::getCurrentThreadId ();
        name = tmp.str ();
    }
#else
    log4cplus::tstring & name = thread_name;
    if (LOG4CPLUS_UNLIKELY(name.empty()))
    {
        name = LOG4CPLUS_TEXT("single");
    }
#endif

    return name;
}

namespace
{

static
bool
get_current_thread_name_alt (log4cplus::tostream * s)
{
    log4cplus::tostream & os = *s;

#if defined (LOG4CPLUS_USE_PTHREADS) && defined (__linux__) \
    && defined (LOG4CPLUS_HAVE_GETTID)
    pid_t tid = syscall (SYS_gettid);
    os << tid;

#elif defined (__CYGWIN__)
    unsigned long tid = cygwin::get_current_win32_thread_id ();
    os << tid;

#else
    os << getCurrentThreadName ();

#endif

    return true;
}

} // namespace

LOG4CPLUS_EXPORT
log4cplus::tstring const &
getCurrentThreadName2()
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::tstring & name = log4cplus::internal::get_thread_name2_str ();
    if (LOG4CPLUS_UNLIKELY (name.empty ()))
    {
        log4cplus::tostringstream tmp;
        get_current_thread_name_alt (&tmp);
        name = tmp.str ();
    }

#else
    log4cplus::tstring & name = thread_name2;
    if (LOG4CPLUS_UNLIKELY(name.empty()))
    {
        name = getCurrentThreadName();
    }

#endif

    return name;
}

LOG4CPLUS_EXPORT void setCurrentThreadName(const log4cplus::tstring & name)
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::internal::get_thread_name_str() = name;
#else
    thread_name = name;
#endif
}

LOG4CPLUS_EXPORT void setCurrentThreadName2(const log4cplus::tstring & name)
{
#if ! defined (LOG4CPLUS_SINGLE_THREADED)
    log4cplus::internal::get_thread_name2_str() = name;
#else
    thread_name2 = name;
#endif
}

#ifndef LOG4CPLUS_SINGLE_THREADED

//
//
//

AbstractThread::AbstractThread ()
{ }

bool
AbstractThread::isRunning() const
{
    return (flags & fRUNNING) != 0;
}

void
AbstractThread::start()
{
    try
    {
        flags |= fRUNNING;
        thread.reset (
            new std::thread ([this] (AbstractThreadPtr const & thread_ptr) {
                    (void) thread_ptr;
                    blockAllSignals ();
                    helpers::LogLog * loglog = helpers::LogLog::getLogLog();
                    try
                    {
                        this->run ();
                    }
                    catch (std::exception const & e)
                    {
                        tstring err (LOG4CPLUS_TEXT ("threadStartFunc()")
                            LOG4CPLUS_TEXT ("- run() terminated with an exception: "));
                        err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());
                        loglog->warn(err);
                    }
                    catch(...)
                    {
                        loglog->warn(LOG4CPLUS_TEXT("threadStartFunc()")
                            LOG4CPLUS_TEXT ("- run() terminated with an exception."));
                    }
                    this->flags &= ~fRUNNING;
                    threadCleanup ();
                }, AbstractThreadPtr (this)));
    }
    catch (...)
    {
        flags &= ~fRUNNING;
        throw;
    }
}

void
AbstractThread::join () const
{
    if (! thread
        || (flags & fJOINED) == fJOINED)
        throw std::logic_error ("this thread is not running");

    thread->join ();
    flags |= +fJOINED;
}

AbstractThread::~AbstractThread()
{
    if ((flags & fJOINED) == 0)
        thread->detach ();
}

#endif // LOG4CPLUS_SINGLE_THREADED

} } // namespace log4cplus { namespace thread {
<|endoftext|>


<commit_before>// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <cstdio>
#include <string>

#include "rocksdb/db.h"
#include "rocksdb/slice.h"
#include "rocksdb/options.h"

using namespace rocksdb;

std::string kDBPath = "/tmp/rocksdb_simple_example";

int main() {
  DB* db;
  Options options;
  // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
  options.IncreaseParallelism();
  options.OptimizeLevelStyleCompaction();
  // create the DB if it's not already present
  options.create_if_missing = true;

  // open DB
  Status s = DB::Open(options, kDBPath, &db);
  assert(s.ok());

  // Put key-value
  s = db->Put(WriteOptions(), "key", "value");
  assert(s.ok());
  std::string value;
  // get value
  s = db->Get(ReadOptions(), "key", &value);
  assert(s.ok());
  assert(value == "value");

  delete db;

  return 0;
}
<commit_msg>Added WriteBatch block to simple_example.cc<commit_after>// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <cstdio>
#include <string>

#include "rocksdb/db.h"
#include "rocksdb/slice.h"
#include "rocksdb/options.h"

using namespace rocksdb;

std::string kDBPath = "/tmp/rocksdb_simple_example";

int main() {
  DB* db;
  Options options;
  // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
  options.IncreaseParallelism();
  options.OptimizeLevelStyleCompaction();
  // create the DB if it's not already present
  options.create_if_missing = true;

  // open DB
  Status s = DB::Open(options, kDBPath, &db);
  assert(s.ok());

  // Put key-value
  s = db->Put(WriteOptions(), "key1", "value");
  assert(s.ok());
  std::string value;
  // get value
  s = db->Get(ReadOptions(), "key1", &value);
  assert(s.ok());
  assert(value == "value");

  // atomically apply a set of updates
  {
    WriteBatch batch;
    batch.Delete("key1");
    batch.Put("key2", value);
    s = db->Write(WriteOptions(), &batch);
  }

  s = db->Get(ReadOptions(), "key1", &value);
  assert(s.IsNotFound());

  db->Get(ReadOptions(), "key2", &value);
  assert(value == "value");

  delete db;

  return 0;
}
<|endoftext|>