MainWindow::MainWindow()
{

    Layout = new QVBoxLayout;
    GameScene = new QGraphicsScene();
    GameScene->setSceneRect(0,0,950,500);

    GameView = new QGraphicsView(GameScene);
    ToolBar = new QToolBar();


    ScoreLabel = new QLabel("Score: ");
    ToolBar->addWidget(ScoreLabel);

    Score = new QLabel("0000");
    Score->setFrameStyle( QFrame::StyledPanel | QFrame::Plain );
    Score->setAlignment( Qt::AlignCenter );
    ToolBar->addWidget(Score);
    ToolBar->addSeparator();

    Health = new QLabel("Health");
    ToolBar->addWidget(Health);

    HealthBar = new QProgressBar();
    HealthBar->setValue(100);
    HealthBar->setTextVisible(false);
    ToolBar->addWidget(HealthBar);
    ToolBar->addSeparator();

    Start = new QPushButton("START");
    ToolBar->addWidget(Start);
    ToolBar->addSeparator();

    Pause = new QPushButton("PAUSE");


    Quit = new QPushButton("QUIT");
    ToolBar->addWidget(Quit);
    ToolBar->addSeparator();

    Layout->addWidget(GameView);
    Layout->addWidget(ToolBar);

    timeInterval = 5;
    timeCounter = 0;
    timer  = new QTimer(this);
    timer->setInterval(timeInterval);

    setLayout(Layout);

    StartView = new QGraphicsPixmapItem();
    StartPic = new QPixmap("Images/Game_StartScreen.png");
    StartPicScaled = StartPic->scaled( 1000, 550, Qt::IgnoreAspectRatio, Qt::FastTransformation );
    StartView->setPixmap(StartPicScaled);
    GameScene->addItem(StartView);
    StartView->setPos(-13, -19);

    NameBox = new QTextEdit();
    NameBox->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    NameBox->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    NameBox->setFixedHeight(20);
    NameBox->setFixedWidth(200);
    GameScene->addWidget(NameBox);
    NameBox->move(705,422);


    //////////////////////////        Allocate Main Player Object        /////////////////////////
    tommy  = new Tommy();
    HorsePic = new QPixmap("Images/HORSE_1.png");
    HorsePic2 = new QPixmap("Images/HORSE_2.png");
    HorseScaled  = HorsePic->scaled( 150, 150, Qt::IgnoreAspectRatio, Qt::FastTransformation );
    HorseScaled2 = HorsePic2->scaled( 150, 150, Qt::IgnoreAspectRatio, Qt::FastTransformation );
    leftPosition = false;

    //////////////////////////        Object Logistics        /////////////////////////
    bearExists = false;
    BearCounter = 0;
    numBears = 0;
    MAX_BEARS = 3;
    bearVelocty = .75;
    srand( time(NULL));
    bearStartX = rand()%800 + 800;
    DPSexists = false;
    DPSlimit = 40;
    DPScounter = 0;
    treeExists = false;
    treeCounter = 0;
    treeVelocity = 1.5;
    devilExists  = false;
    devilCounter = 0;
    fireballExists = false;
    duckExists = false;
    duckCounter = 0;
    bookExists = false;
    scoreFactor = .00001;
    tStart = clock();


    //////////////////////////        Connections         /////////////////////////
    connect(Start, SIGNAL(clicked()), this, SLOT( start() ));
    connect(Quit, SIGNAL(clicked()), this, SLOT( exit() ));
    connect(Pause, SIGNAL(clicked()), this, SLOT( pause() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( scoreCounter() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( imageRotate() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( objectAnimate() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( jumpRegulator() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( tommyJump() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( fireballShoot() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( bookDrop() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( tommyCollision() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( addItems() ));
    connect(timer, SIGNAL(timeout()), this, SLOT( speedUpdater() ));
    setFocus();

}
static int
do_test (void)
{
  pthread_t th;
  int old, rc;
  int ret = 0;
  int fd[2];

  rc = pipe (fd);
  if (rc < 0)
    error (EXIT_FAILURE, errno, "couldn't create pipe");

  rc = pthread_create (&th, NULL, tf, NULL);
  if (rc)
    error (EXIT_FAILURE, rc, "couldn't create thread");

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "1st pthread_setcanceltype failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED && old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "1st pthread_setcanceltype returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  close (fd[0]);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after close failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED)
    {
      error (0, 0, "pthread_setcanceltype after close returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  close (fd[1]);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after 2nd close failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "pthread_setcanceltype after 2nd close returned invalid value %d",
	     old);
      ret = 1;
    }

  struct sigaction sa = { .sa_handler = handler, .sa_flags = 0 };
  sigemptyset (&sa.sa_mask);
  sigaction (SIGALRM, &sa, NULL);

  struct itimerval it;
  it.it_value.tv_sec = 1;
  it.it_value.tv_usec = 0;
  it.it_interval = it.it_value;
  setitimer (ITIMER_REAL, &it, NULL);

  clobber_lots_of_regs ();
  pause ();

  memset (&it, 0, sizeof (it));
  setitimer (ITIMER_REAL, &it, NULL);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after pause failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED)
    {
      error (0, 0, "pthread_setcanceltype after pause returned invalid value %d",
	     old);
      ret = 1;
    }

  it.it_value.tv_sec = 1;
  it.it_value.tv_usec = 0;
  it.it_interval = it.it_value;
  setitimer (ITIMER_REAL, &it, NULL);

  clobber_lots_of_regs ();
  pause ();

  memset (&it, 0, sizeof (it));
  setitimer (ITIMER_REAL, &it, NULL);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after 2nd pause failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "pthread_setcanceltype after 2nd pause returned invalid value %d",
	     old);
      ret = 1;
    }

  char fname[] = "/tmp/tst-cancel19-dir-XXXXXX\0foo/bar";
  char *enddir = strchr (fname, '\0');
  if (mkdtemp (fname) == NULL)
    {
      error (0, errno, "mkdtemp failed");
      ret = 1;
    }
  *enddir = '/';

  clobber_lots_of_regs ();
  creat (fname, 0400);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after creat failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED)
    {
      error (0, 0, "pthread_setcanceltype after creat returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  creat (fname, 0400);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after 2nd creat failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "pthread_setcanceltype after 2nd creat returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  open (fname, O_CREAT, 0400);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after open failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED)
    {
      error (0, 0, "pthread_setcanceltype after open returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  open (fname, O_CREAT, 0400);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after 2nd open failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "pthread_setcanceltype after 2nd open returned invalid value %d",
	     old);
      ret = 1;
    }

  *enddir = '\0';
  rmdir (fname);

  clobber_lots_of_regs ();
  select (-1, NULL, NULL, NULL, NULL);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after select failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_DEFERRED)
    {
      error (0, 0, "pthread_setcanceltype after select returned invalid value %d",
	     old);
      ret = 1;
    }

  clobber_lots_of_regs ();
  select (-1, NULL, NULL, NULL, NULL);

  rc = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &old);
  if (rc)
    {
      error (0, rc, "pthread_setcanceltype after 2nd select failed");
      ret = 1;
    }
  if (old != PTHREAD_CANCEL_ASYNCHRONOUS)
    {
      error (0, 0, "pthread_setcanceltype after 2nd select returned invalid value %d",
	     old);
      ret = 1;
    }

  pthread_join (th, NULL);

  return ret;
}
Exemple #3
0
int main(int ac, char **av)
{
  int     ch, i=0;
  pid_t   pid;
  FILE    *fp;
  uid_t   uid;
#ifdef USE_THREAD
  pthread_t tid;
  pthread_attr_t attr;
  struct rlimit rl;
  rlim_t max_fd = (rlim_t)MAX_FD;
  rlim_t save_fd = 0;
#endif

#ifdef USE_THREAD
  threading = 1;
  max_thread = MAX_THREAD;
#endif

  max_child = MAX_CHILD;
  cur_child = 0;

  /* create service socket table (malloc) */
  if (serv_init(NULL) < 0) {
    msg_out(crit, "cannot malloc: %m");
    exit(-1);
  }

  proxy_tbl = NULL;
  proxy_tbl_ind = 0;

  method_num = 0;

  uid = getuid();

  openlog(ident, LOG_PID | LOG_NDELAY, SYSLOGFAC);

  while((ch = getopt(ac, av, "a:c:i:x:J:m:o:p:u:frstbwgIqvh?")) != -1)
    switch (ch) {
    case 'a':
      if (optarg != NULL) {
	for (i=0; i<sizeof method_tab; optarg++) {
	  if (*optarg == '\0')
	    break;
	  switch (*optarg) {
	  case 'p':
	    if ( uid != 0 ) {
	      /* process does not started by root */
	      msg_out(warn, "uid == %d (!=0),"
		      "user/pass auth will not work, ignored.",
		      uid);
	      break;
	    }
	    method_tab[i++] = S5AUSRPAS;
	    method_num++;
	    break;
	  case 'n':
	    method_tab[i++] = S5ANOAUTH;
	    method_num++;
	    break;
	  default:
	    break;
	  }
	}
      }
      break;

    case 'b':
      bind_restrict = 0;
      break;

    case 'c':
      if (optarg != NULL) {
        config = strdup(optarg);
      }
      break;

    case 'u':
      if (optarg != NULL) {
        pwdfile = strdup(optarg);
      }
      break;

    case 'i':
      if (optarg != NULL) {
	if (serv_init(optarg) < 0) {
	  msg_out(warn, "cannot init server socket(-i %s): %m", optarg);
	  break;
	}
      }
      break;

#ifdef SO_BINDTODEVICE
    case 'J':
      if (optarg != NULL) {
	bindtodevice = strdup(optarg);
      }
      break;
#endif

    case 'x':
      if (optarg != NULL) {
	bindout = strdup(optarg);
      }
      break;

    case 'o':
      if (optarg != NULL) {
	idle_timeout = atol(optarg);
      }
      break;

    case 'p':
      if (optarg != NULL) {
	pidfile = strdup(optarg);
      }
      break;

    case 'm':
      if (optarg != NULL) {
#ifdef USE_THREAD
	max_thread = atoi(optarg);
#endif
	max_child = atoi(optarg);
      }
      break;

    case 't':
#ifdef USE_THREAD
      threading = 0;    /* threading disabled. */
#endif
      break;

    case 'g':
      same_interface = 1;
      break;

    case 'f':
      fg = 1;
      break;

    case 'r':
      resolv_client = 1;
      break;

    case 's':
      forcesyslog = 1;
      break;

    case 'w':
#ifdef HAVE_LIBWRAP
      use_tcpwrap = 1;
#endif /* HAVE_LIBWRAP */
      break;

    case 'I':
      inetd_mode = 1;
      break;

    case 'q':
      be_quiet = 1;
      break;

    case 'v':
      show_version();
      exit(1);

    case 'h':
    case '?':
    default:
      usage();
    }

  ac -= optind;
  av += optind;

  if (fg && !forcesyslog && isatty(fileno(stderr)))
    setvbuf(stderr, NULL, _IOLBF, 0);

  if ((fp = fopen(config, "r")) != NULL) {
    if (readconf(fp) != 0) {
      /* readconf error */
      exit(1);
    }
    fclose(fp);
  }

  if (inetd_mode) {
    /* close all server socket if opened */
    close_all_serv();
    /* assuming that STDIN_FILENO handles bi-directional
     */
    exit(inetd_service(STDIN_FILENO));
    /* not reached */
  }

  if (serv_sock_ind == 0) {   /* no valid ifs yet */
    if (serv_init(":") < 0) { /* use default */
      /* fatal */
      msg_out(crit, "cannot open server socket");
      exit(1);
    }
  }

#ifdef USE_THREAD
  if ( ! threading ) {
#endif
    if (queue_init() != 0) {
      msg_out(crit, "cannot init signal queue");
      exit(1);
    }
#ifdef USE_THREAD
  }
#endif

  /* try changing working directory */
  if ( chdir(WORKDIR0) != 0 )
    if ( chdir(WORKDIR1) != 0 )
      msg_out(norm, "giving up chdir to workdir");

  if (!fg) {
    /* force stdin/out/err allocate to /dev/null */
    fclose(stdin);
    fp = fopen("/dev/null", "w+");
    if (fileno(fp) != STDIN_FILENO) {
      msg_out(crit, "fopen: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1) {
      msg_out(crit, "dup2-1: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
      msg_out(crit, "dup2-2: %m");
      exit(1);
    }

    switch(fork()) {
    case -1:
      msg_out(crit, "fork: %m");
      exit(1);
    case 0:
      /* child */
      pid = setsid();
      if (pid == -1) {
	msg_out(crit, "setsid: %m");
	exit(1);
      }
      break;
    default:
      /* parent */
      exit(0);
    }
  }

  master_pid = getpid();
  umask(S_IWGRP|S_IWOTH);
  if ((fp = fopen(pidfile, "w")) != NULL) {
    fprintf(fp, "%u\n", (unsigned)master_pid);
    fchown(fileno(fp), PROCUID, PROCGID);
    fclose(fp);
  } else {
    msg_out(warn, "cannot open pidfile %s", pidfile);
  }

  setsignal(SIGHUP, reload);
  if (fg)
    setsignal(SIGINT, cleanup);
  else
    setsignal(SIGINT, SIG_IGN);
  setsignal(SIGQUIT, SIG_IGN);
  setsignal(SIGILL, SIG_IGN);
  setsignal(SIGTRAP, SIG_IGN);
  setsignal(SIGABRT, SIG_IGN);
#ifdef SIGEMT
  setsignal(SIGEMT, SIG_IGN);
#endif
  setsignal(SIGSYS, SIG_IGN);
  setsignal(SIGPIPE, SIG_IGN);
  setsignal(SIGALRM, SIG_IGN);
  setsignal(SIGTERM, cleanup);
  setsignal(SIGUSR1, SIG_IGN);
  setsignal(SIGUSR2, SIG_IGN);
#ifdef SIGPOLL
  setsignal(SIGPOLL, SIG_IGN);
#endif
  setsignal(SIGVTALRM, SIG_IGN);
  setsignal(SIGPROF, SIG_IGN);
  setsignal(SIGXCPU, SIG_IGN);
  setsignal(SIGXFSZ, SIG_IGN);

#ifdef USE_THREAD
  if ( threading ) {
    if (max_thread <= 0 || max_thread > THREAD_LIMIT) {
      max_thread = THREAD_LIMIT;
    }
    /* resource limit is problem in threadig (e.g. Solaris:=64)*/
    memset((caddr_t)&rl, 0, sizeof rl);
    if (getrlimit(RLIMIT_NOFILE, &rl) != 0)
      msg_out(warn, "getrlimit: %m");
    else
      save_fd = rl.rlim_cur;
    if (rl.rlim_cur < (rlim_t)max_fd)
      rl.rlim_cur = max_fd;        /* willing to fix to max_fd */
    if ( rl.rlim_cur != save_fd )  /* if rlim_cur is changed   */
      if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
        msg_out(warn, "cannot set rlimit(max_fd)");

    setregid(0, PROCGID);
    setreuid(0, PROCUID);

    pthread_mutex_init(&mutex_select, NULL);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    msg_out(norm, "Starting: MAX_TH(%d)", max_thread);
    for (i=0; i<max_thread; i++) {
      if (pthread_create(&tid, &attr,
			 (void *)&serv_loop, (void *)NULL) != 0)
        exit(1);
    }
    main_thread = pthread_self();   /* store main thread ID */
    for (;;) {
      pause();
    }
  } else {
#endif
    setsignal(SIGCHLD, reapchild);
    setregid(0, PROCGID);
    setreuid(0, PROCUID);
    msg_out(norm, "Starting: MAX_CH(%d)", max_child);
    serv_loop();
#ifdef USE_THREAD
  }
#endif
  return(0);
}
Exemple #4
0
void sfSound_pause(sfSound* sound)
{
    CSFML_CALL(sound, pause());
}
Exemple #5
0
void AVDemuxThread::run()
{
    m_buffering = false;
    end = false;
    if (audio_thread && !audio_thread->isRunning())
        audio_thread->start(QThread::HighPriority);
    if (video_thread && !video_thread->isRunning())
        video_thread->start();

    int index = 0;
    Packet pkt;
    pause(false);
    qDebug("get av queue a/v thread = %p %p", audio_thread, video_thread);
    PacketBuffer *aqueue = audio_thread ? audio_thread->packetQueue() : 0;
    PacketBuffer *vqueue = video_thread ? video_thread->packetQueue() : 0;
    // aqueue as a primary buffer: music with/without cover
    AVThread* thread = !video_thread || (audio_thread && demuxer->hasAttacedPicture()) ? audio_thread : video_thread;
    m_buffer = thread->packetQueue();
    const qint64 buf2 = aqueue ? aqueue->bufferValue() : 1; // TODO: may be changed by user. Deal with audio track change
    if (aqueue) {
        aqueue->clear();
        aqueue->setBlocking(true);
    }
    if (vqueue) {
        vqueue->clear();
        vqueue->setBlocking(true);
    }
    connect(thread, SIGNAL(seekFinished(qint64)), this, SIGNAL(seekFinished(qint64)), Qt::DirectConnection);
    seek_tasks.clear();
    bool was_end = false;
    if (ademuxer) {
        ademuxer->seek(0LL);
    }
    while (!end) {
        processNextSeekTask();
        if (demuxer->atEnd()) {
            if (!was_end) {
                if (aqueue) {
                    aqueue->put(Packet::createEOF());
                    aqueue->blockEmpty(false); // do not block if buffer is not enough. block again on seek
                }
                if (vqueue) {
                    vqueue->put(Packet::createEOF());
                    vqueue->blockEmpty(false);
                }
            }
            m_buffering = false;
            Q_EMIT mediaStatusChanged(QtAV::BufferedMedia);
            was_end = true;
            // wait for a/v thread finished
            msleep(100);
            continue;
        }
        was_end = false;
        if (tryPause()) {
            continue; //the queue is empty and will block
        }
        updateBufferState();
        if (!demuxer->readFrame()) {
            continue;
        }
        index = demuxer->stream();
        pkt = demuxer->packet();
        Packet apkt;
        bool audio_has_pic = demuxer->hasAttacedPicture();
        int a_ext = 0;
        if (ademuxer) {
            QMutexLocker locker(&buffer_mutex);
            Q_UNUSED(locker);
            if (ademuxer) {
                a_ext = -1;
                audio_has_pic = ademuxer->hasAttacedPicture();
                // FIXME: buffer full but buffering!!!
                // avoid read external track everytime. aqueue may not block full
                // vqueue will not block if aqueue is not enough
                if (!aqueue->isFull() || aqueue->isBuffering()) {
                    if (ademuxer->readFrame()) {
                        if (ademuxer->stream() == ademuxer->audioStream()) {
                            a_ext = 1;
                            apkt = ademuxer->packet();
                        }
                    }
                    // no continue otherwise. ademuxer finished earlier than demuxer
                }
            }
        }
        //qDebug("vqueue: %d, aqueue: %d/isbuffering %d isfull: %d, buffer: %d/%d", vqueue->size(), aqueue->size(), aqueue->isBuffering(), aqueue->isFull(), aqueue->buffered(), aqueue->bufferValue());

        //QMutexLocker locker(&buffer_mutex); //TODO: seems we do not need to lock
        //Q_UNUSED(locker);
        /*1 is empty but another is enough, then do not block to
          ensure the empty one can put packets immediatly.
          But usually it will not happen, why?
        */
        /* demux thread will be blocked only when 1 queue is full and still put
         * if vqueue is full and aqueue becomes empty, then demux thread
         * will be blocked. so we should wake up another queue when empty(or threshold?).
         * TODO: the video stream and audio stream may be group by group. provide it
         * stream data: aaaaaaavvvvvvvaaaaaaaavvvvvvvvvaaaaaa, it happens
         * stream data: aavavvavvavavavavavavavavvvaavavavava, it's ok
         */
        //TODO: use cache queue, take from cache queue if not empty?
        const bool a_internal = index == demuxer->audioStream();
        if (a_internal || a_ext > 0) {//apkt.isValid()) {
            if (a_internal && !a_ext) // internal is always read even if external audio used
                apkt = demuxer->packet();
            /* if vqueue if not blocked and full, and aqueue is empty, then put to
             * vqueue will block demuex thread
             */
            if (aqueue) {
                if (!audio_thread || !audio_thread->isRunning()) {
                    aqueue->clear();
                    continue;
                }
                // must ensure bufferValue set correctly before continue
                if (m_buffer != aqueue)
                    aqueue->setBufferValue(m_buffer->isBuffering() ? std::numeric_limits<qint64>::max() : buf2);
                // always block full if no vqueue because empty callback may set false
                // attached picture is cover for song, 1 frame
                aqueue->blockFull(!video_thread || !video_thread->isRunning() || !vqueue || audio_has_pic);
                // external audio: a_ext < 0, index = audio_idx=>put invalid packet
                if (a_ext >= 0)
                    aqueue->put(apkt); //affect video_thread
            }
        }
        // always check video stream if use external audio
        if (index == demuxer->videoStream()) {
            if (vqueue) {
                if (!video_thread || !video_thread->isRunning()) {
                    vqueue->clear();
                    continue;
                }
                vqueue->blockFull(!audio_thread || !audio_thread->isRunning() || !aqueue || aqueue->isEnough());
                vqueue->put(pkt); //affect audio_thread
            }
        } else { //subtitle
            continue;
        }
    }
    m_buffering = false;
    m_buffer = 0;
    while (audio_thread && audio_thread->isRunning()) {
        qDebug("waiting audio thread.......");
        aqueue->blockEmpty(false); //FIXME: why need this
        audio_thread->wait(500);
    }
    while (video_thread && video_thread->isRunning()) {
        qDebug("waiting video thread.......");
        vqueue->blockEmpty(false);
        video_thread->wait(500);
    }
    thread->disconnect(this, SIGNAL(seekFinished(qint64)));
    qDebug("Demux thread stops running....");
    emit mediaStatusChanged(QtAV::EndOfMedia);
}
Exemple #6
0
int
main(int argc, char *argv[])
{
	int r;

#ifdef ENABLE_NLS
	/* Init locale */
	setlocale(LC_CTYPE, "");
	setlocale(LC_MESSAGES, "");

	/* Internationalisation */
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
#endif

	/* Initialize settings to NULL values. */
	char *config_filepath = NULL;

	/* Settings for day, night and transition.
	   Initialized to indicate that the values are not set yet. */
	transition_scheme_t scheme =
		{ TRANSITION_HIGH, TRANSITION_LOW };

	scheme.day.temperature = -1;
	scheme.day.gamma[0] = NAN;
	scheme.day.brightness = NAN;

	scheme.night.temperature = -1;
	scheme.night.gamma[0] = NAN;
	scheme.night.brightness = NAN;

	/* Temperature for manual mode */
	int temp_set = -1;

	const gamma_method_t *method = NULL;
	char *method_args = NULL;

	const location_provider_t *provider = NULL;
	char *provider_args = NULL;

	int transition = -1;
	program_mode_t mode = PROGRAM_MODE_CONTINUAL;
	int verbose = 0;
	char *s;

	/* Flush messages consistently even if redirected to a pipe or
	   file.  Change the flush behaviour to line-buffered, without
	   changing the actual buffers being used. */
	setvbuf(stdout, NULL, _IOLBF, 0);
	setvbuf(stderr, NULL, _IOLBF, 0);

	/* Parse command line arguments. */
	int opt;
	while ((opt = getopt(argc, argv, "b:c:g:hl:m:oO:prt:vVx")) != -1) {
		switch (opt) {
		case 'b':
			parse_brightness_string(optarg,
						&scheme.day.brightness,
						&scheme.night.brightness);
			break;
		case 'c':
			free(config_filepath);
			config_filepath = strdup(optarg);
			break;
		case 'g':
			r = parse_gamma_string(optarg, scheme.day.gamma);
			if (r < 0) {
				fputs(_("Malformed gamma argument.\n"),
				      stderr);
				fputs(_("Try `-h' for more"
					" information.\n"), stderr);
				exit(EXIT_FAILURE);
			}

			/* Set night gamma to the same value as day gamma.
			   To set these to distinct values use the config
			   file. */
			memcpy(scheme.night.gamma, scheme.day.gamma,
			       sizeof(scheme.night.gamma));
			break;
		case 'h':
			print_help(argv[0]);
			exit(EXIT_SUCCESS);
			break;
		case 'l':
			/* Print list of providers if argument is `list' */
			if (strcasecmp(optarg, "list") == 0) {
				print_provider_list();
				exit(EXIT_SUCCESS);
			}

			char *provider_name = NULL;

			/* Don't save the result of strtof(); we simply want
			   to know if optarg can be parsed as a float. */
			errno = 0;
			char *end;
			strtof(optarg, &end);
			if (errno == 0 && *end == ':') {
				/* Use instead as arguments to `manual'. */
				provider_name = "manual";
				provider_args = optarg;
			} else {
				/* Split off provider arguments. */
				s = strchr(optarg, ':');
				if (s != NULL) {
					*(s++) = '\0';
					provider_args = s;
				}

				provider_name = optarg;
			}

			/* Lookup provider from name. */
			provider = find_location_provider(provider_name);
			if (provider == NULL) {
				fprintf(stderr, _("Unknown location provider"
						  " `%s'.\n"), provider_name);
				exit(EXIT_FAILURE);
			}

			/* Print provider help if arg is `help'. */
			if (provider_args != NULL &&
			    strcasecmp(provider_args, "help") == 0) {
				provider->print_help(stdout);
				exit(EXIT_SUCCESS);
			}
			break;
		case 'm':
			/* Print list of methods if argument is `list' */
			if (strcasecmp(optarg, "list") == 0) {
				print_method_list();
				exit(EXIT_SUCCESS);
			}

			/* Split off method arguments. */
			s = strchr(optarg, ':');
			if (s != NULL) {
				*(s++) = '\0';
				method_args = s;
			}

			/* Find adjustment method by name. */
			method = find_gamma_method(optarg);
			if (method == NULL) {
				/* TRANSLATORS: This refers to the method
				   used to adjust colors e.g VidMode */
				fprintf(stderr, _("Unknown adjustment method"
						  " `%s'.\n"), optarg);
				exit(EXIT_FAILURE);
			}

			/* Print method help if arg is `help'. */
			if (method_args != NULL &&
			    strcasecmp(method_args, "help") == 0) {
				method->print_help(stdout);
				exit(EXIT_SUCCESS);
			}
			break;
		case 'o':
			mode = PROGRAM_MODE_ONE_SHOT;
			break;
		case 'O':
			mode = PROGRAM_MODE_MANUAL;
			temp_set = atoi(optarg);
			break;
		case 'p':
			mode = PROGRAM_MODE_PRINT;
			break;
		case 'r':
			transition = 0;
			break;
		case 't':
			s = strchr(optarg, ':');
			if (s == NULL) {
				fputs(_("Malformed temperature argument.\n"),
				      stderr);
				fputs(_("Try `-h' for more information.\n"),
				      stderr);
				exit(EXIT_FAILURE);
			}
			*(s++) = '\0';
			scheme.day.temperature = atoi(optarg);
			scheme.night.temperature = atoi(s);
			break;
		case 'v':
			verbose = 1;
			break;
                case 'V':
                        printf("%s\n", PACKAGE_STRING);
                        exit(EXIT_SUCCESS);
                        break;
		case 'x':
			mode = PROGRAM_MODE_RESET;
			break;
		case '?':
			fputs(_("Try `-h' for more information.\n"), stderr);
			exit(EXIT_FAILURE);
			break;
		}
	}

	/* Load settings from config file. */
	config_ini_state_t config_state;
	r = config_ini_init(&config_state, config_filepath);
	if (r < 0) {
		fputs("Unable to load config file.\n", stderr);
		exit(EXIT_FAILURE);
	}

	free(config_filepath);

	/* Read global config settings. */
	config_ini_section_t *section = config_ini_get_section(&config_state,
							       "redshift");
	if (section != NULL) {
		config_ini_setting_t *setting = section->settings;
		while (setting != NULL) {
			if (strcasecmp(setting->name, "temp-day") == 0) {
				if (scheme.day.temperature < 0) {
					scheme.day.temperature =
						atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "temp-night") == 0) {
				if (scheme.night.temperature < 0) {
					scheme.night.temperature =
						atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "transition") == 0) {
				if (transition < 0) {
					transition = !!atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness") == 0) {
				if (isnan(scheme.day.brightness)) {
					scheme.day.brightness =
						atof(setting->value);
				}
				if (isnan(scheme.night.brightness)) {
					scheme.night.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness-day") == 0) {
				if (isnan(scheme.day.brightness)) {
					scheme.day.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness-night") == 0) {
				if (isnan(scheme.night.brightness)) {
					scheme.night.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "elevation-high") == 0) {
				scheme.high = atof(setting->value);
			} else if (strcasecmp(setting->name,
					      "elevation-low") == 0) {
				scheme.low = atof(setting->value);
			} else if (strcasecmp(setting->name, "gamma") == 0) {
				if (isnan(scheme.day.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.day.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
					memcpy(scheme.night.gamma, scheme.day.gamma,
					       sizeof(scheme.night.gamma));
				}
			} else if (strcasecmp(setting->name, "gamma-day") == 0) {
				if (isnan(scheme.day.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.day.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name, "gamma-night") == 0) {
				if (isnan(scheme.night.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.night.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name,
					      "adjustment-method") == 0) {
				if (method == NULL) {
					method = find_gamma_method(
						setting->value);
					if (method == NULL) {
						fprintf(stderr, _("Unknown"
								  " adjustment"
								  " method"
								  " `%s'.\n"),
							setting->value);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name,
					      "location-provider") == 0) {
				if (provider == NULL) {
					provider = find_location_provider(
						setting->value);
					if (provider == NULL) {
						fprintf(stderr, _("Unknown"
								  " location"
								  " provider"
								  " `%s'.\n"),
							setting->value);
						exit(EXIT_FAILURE);
					}
				}
			} else {
				fprintf(stderr, _("Unknown configuration"
						  " setting `%s'.\n"),
					setting->name);
			}
			setting = setting->next;
		}
	}

	/* Use default values for settings that were neither defined in
	   the config file nor on the command line. */
	if (scheme.day.temperature < 0) {
		scheme.day.temperature = DEFAULT_DAY_TEMP;
	}
	if (scheme.night.temperature < 0) {
		scheme.night.temperature = DEFAULT_NIGHT_TEMP;
	}

	if (isnan(scheme.day.brightness)) {
		scheme.day.brightness = DEFAULT_BRIGHTNESS;
	}
	if (isnan(scheme.night.brightness)) {
		scheme.night.brightness = DEFAULT_BRIGHTNESS;
	}

	if (isnan(scheme.day.gamma[0])) {
		scheme.day.gamma[0] = DEFAULT_GAMMA;
		scheme.day.gamma[1] = DEFAULT_GAMMA;
		scheme.day.gamma[2] = DEFAULT_GAMMA;
	}
	if (isnan(scheme.night.gamma[0])) {
		scheme.night.gamma[0] = DEFAULT_GAMMA;
		scheme.night.gamma[1] = DEFAULT_GAMMA;
		scheme.night.gamma[2] = DEFAULT_GAMMA;
	}

	if (transition < 0) transition = 1;

	location_t loc = { NAN, NAN };

	/* Initialize location provider. If provider is NULL
	   try all providers until one that works is found. */
	location_state_t location_state;

	/* Location is not needed for reset mode and manual mode. */
	if (mode != PROGRAM_MODE_RESET &&
	    mode != PROGRAM_MODE_MANUAL) {
		if (provider != NULL) {
			/* Use provider specified on command line. */
			r = provider_try_start(provider, &location_state,
					       &config_state, provider_args);
			if (r < 0) exit(EXIT_FAILURE);
		} else {
			/* Try all providers, use the first that works. */
			for (int i = 0;
			     location_providers[i].name != NULL; i++) {
				const location_provider_t *p =
					&location_providers[i];
				fprintf(stderr,
					_("Trying location provider `%s'...\n"),
					p->name);
				r = provider_try_start(p, &location_state,
						       &config_state, NULL);
				if (r < 0) {
					fputs(_("Trying next provider...\n"),
					      stderr);
					continue;
				}

				/* Found provider that works. */
				printf(_("Using provider `%s'.\n"), p->name);
				provider = p;
				break;
			}

			/* Failure if no providers were successful at this
			   point. */
			if (provider == NULL) {
				fputs(_("No more location providers"
					" to try.\n"), stderr);
				exit(EXIT_FAILURE);
			}
		}

		/* Get current location. */
		r = provider->get_location(&location_state, &loc);
		if (r < 0) {
		        fputs(_("Unable to get location from provider.\n"),
		              stderr);
		        exit(EXIT_FAILURE);
		}
	
		provider->free(&location_state);
	
		if (verbose) {
			print_location(&loc);

			printf(_("Temperatures: %dK at day, %dK at night\n"),
			       scheme.day.temperature,
			       scheme.night.temperature);

		        /* TRANSLATORS: Append degree symbols if possible. */
			printf(_("Solar elevations: day above %.1f, night below %.1f\n"),
			       scheme.high, scheme.low);
		}

		/* Latitude */
		if (loc.lat < MIN_LAT || loc.lat > MAX_LAT) {
		        /* TRANSLATORS: Append degree symbols if possible. */
		        fprintf(stderr,
		                _("Latitude must be between %.1f and %.1f.\n"),
		                MIN_LAT, MAX_LAT);
		        exit(EXIT_FAILURE);
		}
	
		/* Longitude */
		if (loc.lon < MIN_LON || loc.lon > MAX_LON) {
		        /* TRANSLATORS: Append degree symbols if possible. */
		        fprintf(stderr,
		                _("Longitude must be between"
		                  " %.1f and %.1f.\n"), MIN_LON, MAX_LON);
		        exit(EXIT_FAILURE);
		}

		/* Color temperature */
		if (scheme.day.temperature < MIN_TEMP ||
		    scheme.day.temperature > MAX_TEMP ||
		    scheme.night.temperature < MIN_TEMP ||
		    scheme.night.temperature > MAX_TEMP) {
			fprintf(stderr,
				_("Temperature must be between %uK and %uK.\n"),
				MIN_TEMP, MAX_TEMP);
			exit(EXIT_FAILURE);
		}

		/* Solar elevations */
		if (scheme.high < scheme.low) {
		        fprintf(stderr,
		                _("High transition elevation cannot be lower than"
				  " the low transition elevation.\n"));
		        exit(EXIT_FAILURE);
		}
	}

	if (mode == PROGRAM_MODE_MANUAL) {
		/* Check color temperature to be set */
		if (temp_set < MIN_TEMP || temp_set > MAX_TEMP) {
			fprintf(stderr,
				_("Temperature must be between %uK and %uK.\n"),
				MIN_TEMP, MAX_TEMP);
			exit(EXIT_FAILURE);
		}
	}

	/* Brightness */
	if (scheme.day.brightness < MIN_BRIGHTNESS ||
	    scheme.day.brightness > MAX_BRIGHTNESS ||
	    scheme.night.brightness < MIN_BRIGHTNESS ||
	    scheme.night.brightness > MAX_BRIGHTNESS) {
		fprintf(stderr,
			_("Brightness values must be between %.1f and %.1f.\n"),
			MIN_BRIGHTNESS, MAX_BRIGHTNESS);
		exit(EXIT_FAILURE);
	}

	if (verbose) {
		printf(_("Brightness: %.2f:%.2f\n"),
		       scheme.day.brightness, scheme.night.brightness);
	}

	/* Gamma */
	if (!gamma_is_valid(scheme.day.gamma) ||
	    !gamma_is_valid(scheme.night.gamma)) {
		fprintf(stderr,
			_("Gamma value must be between %.1f and %.1f.\n"),
			MIN_GAMMA, MAX_GAMMA);
		exit(EXIT_FAILURE);
	}

	if (verbose) {
		/* TRANSLATORS: The string in parenthesis is either
		   Daytime or Night (translated). */
		printf(_("Gamma (%s): %.3f, %.3f, %.3f\n"),
		       _("Daytime"), scheme.day.gamma[0],
		       scheme.day.gamma[1], scheme.day.gamma[2]);
		printf(_("Gamma (%s): %.3f, %.3f, %.3f\n"),
		       _("Night"), scheme.night.gamma[0],
		       scheme.night.gamma[1], scheme.night.gamma[2]);
	}

	/* Initialize gamma adjustment method. If method is NULL
	   try all methods until one that works is found. */
	gamma_state_t state;

	/* Gamma adjustment not needed for print mode */
	if (mode != PROGRAM_MODE_PRINT) {
		if (method != NULL) {
			/* Use method specified on command line. */
			r = method_try_start(method, &state, &config_state,
					     method_args);
			if (r < 0) exit(EXIT_FAILURE);
		} else {
			/* Try all methods, use the first that works. */
			for (int i = 0; gamma_methods[i].name != NULL; i++) {
				const gamma_method_t *m = &gamma_methods[i];
				if (!m->autostart) continue;

				r = method_try_start(m, &state, &config_state, NULL);
				if (r < 0) {
					fputs(_("Trying next method...\n"), stderr);
					continue;
				}

				/* Found method that works. */
				printf(_("Using method `%s'.\n"), m->name);
				method = m;
				break;
			}

			/* Failure if no methods were successful at this point. */
			if (method == NULL) {
				fputs(_("No more methods to try.\n"), stderr);
				exit(EXIT_FAILURE);
			}
		}
	}

	config_ini_free(&config_state);

	switch (mode) {
	case PROGRAM_MODE_ONE_SHOT:
	case PROGRAM_MODE_PRINT:
	{
		/* Current angular elevation of the sun */
		double now;
		r = systemtime_get_time(&now);
		if (r < 0) {
			fputs(_("Unable to read system time.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		double elevation = solar_elevation(now, loc.lat, loc.lon);

		if (verbose) {
			/* TRANSLATORS: Append degree symbol if possible. */
			printf(_("Solar elevation: %f\n"), elevation);
		}

		/* Use elevation of sun to set color temperature */
		color_setting_t interp;
		interpolate_color_settings(&scheme, elevation, &interp);

		if (verbose || mode == PROGRAM_MODE_PRINT) {
			period_t period = get_period(&scheme,
						     elevation);
			double transition =
				get_transition_progress(&scheme,
							elevation);
			print_period(period, transition);
			printf(_("Color temperature: %uK\n"),
			       interp.temperature);
			printf(_("Brightness: %.2f\n"),
			       interp.brightness);
		}

		if (mode == PROGRAM_MODE_PRINT) {
			exit(EXIT_SUCCESS);
		}

		/* Adjust temperature */
		r = method->set_temperature(&state, &interp);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_MANUAL:
	{
		if (verbose) printf(_("Color temperature: %uK\n"), temp_set);

		/* Adjust temperature */
		color_setting_t manual;
		memcpy(&manual, &scheme.day, sizeof(color_setting_t));
		manual.temperature = temp_set;
		r = method->set_temperature(&state, &manual);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_RESET:
	{
		/* Reset screen */
		color_setting_t reset = { NEUTRAL_TEMP, { 1.0, 1.0, 1.0 }, 1.0 };
		r = method->set_temperature(&state, &reset);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_CONTINUAL:
	{
		r = run_continual_mode(&loc, &scheme,
				       method, &state,
				       transition, verbose);
		if (r < 0) exit(EXIT_FAILURE);
	}
	break;
	}

	/* Clean up gamma adjustment state */
	method->free(&state);

	return EXIT_SUCCESS;
}
Exemple #7
0
int main( int argc, char *argv[] )
{
  int i, k, t_num, arg_offset, c;
  long j;
  float f;
  pthread_t *t;
  thread_arg *thd_arg;
  timer_t timer;
  struct itimerval itval;
  struct sigaction  sigact;
  int port= 3306;
  int fd, seed;

  printf("***************************************\n");
  printf("*** ###easy### TPC-C Load Generator ***\n");
  printf("***************************************\n");

  /* initialize */
  hist_init();
  activate_transaction = 1;
  counting_on = 0;

  for ( i=0; i<5; i++ ){
    success[i]=0;
    late[i]=0;
    retry[i]=0;
    failure[i]=0;

    prev_s[i]=0;
    prev_l[i]=0;

    max_rt[i]=0.0;
  }

  /* dummy initialize*/
  num_ware = 1;
  num_conn = 10;
  lampup_time = 10;
  measure_time = 20;
  strcpy( db_string, "tpcc" );

  /* number of node (default 0) */
  num_node = 0;
  arg_offset = 0;


  clk_tck = sysconf(_SC_CLK_TCK);

  /* Parse args */

    while ( (c = getopt(argc, argv, "h:P:d:u:p:w:c:r:l:i:f:")) != -1) {
        switch (c) {
        case 'h':
            printf ("option h with value '%s'\n", optarg);
            strncpy(connect_string, optarg, DB_STRING_MAX);
            break;
        case 'd':
            printf ("option d with value '%s'\n", optarg);
            strncpy(db_string, optarg, DB_STRING_MAX);
            break;
        case 'u':
            printf ("option u with value '%s'\n", optarg);
            strncpy(db_user, optarg, DB_STRING_MAX);
            break;
        case 'p':
            printf ("option p with value '%s'\n", optarg);
            strncpy(db_password, optarg, DB_STRING_MAX);
            break;
        case 'f':
            printf ("option f with value '%s'\n", optarg);
            strncpy(report_file, optarg, DB_STRING_MAX);
            break;
        case 'w':
            printf ("option w with value '%s'\n", optarg);
            num_ware = atoi(optarg);
            break;
        case 'c':
            printf ("option c with value '%s'\n", optarg);
            num_conn = atoi(optarg);
            break;
        case 'r':
            printf ("option r with value '%s'\n", optarg);
            lampup_time = atoi(optarg);
            break;
        case 'l':
            printf ("option l with value '%s'\n", optarg);
            measure_time = atoi(optarg);
            break;
        case 'i':
            printf ("option i with value '%s'\n", optarg);
            PRINT_INTERVAL = atoi(optarg);
            break;
        case 'P':
            printf ("option P with value '%s'\n", optarg);
            port = atoi(optarg);
            break;
        case '?':
    	    printf("Usage: tpcc_start -h server_host -P port -d database_name -u mysql_user -p mysql_password -w warehouses -c connections -r warmup_time -l running_time -i report_interval -f report_file\n");
            exit(0);
        default:
            printf ("?? getopt returned character code 0%o ??\n", c);
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }

/*
  if ((num_node == 0)&&(argc == 14)) { 
    valuable_flg = 1;
  }

  if ((num_node == 0)&&(valuable_flg == 0)&&(argc != 9)) {
    fprintf(stderr, "\n usage: tpcc_start [server] [DB] [user] [pass] [warehouse] [connection] [rampup] [measure]\n");
    exit(1);
  }

  if ( strlen(argv[1]) >= DB_STRING_MAX ) {
    fprintf(stderr, "\n server phrase is too long\n");
    exit(1);
  }
  if ( strlen(argv[2]) >= DB_STRING_MAX ) {
    fprintf(stderr, "\n DBname phrase is too long\n");
    exit(1);
  }
  if ( strlen(argv[3]) >= DB_STRING_MAX ) {
    fprintf(stderr, "\n user phrase is too long\n");
    exit(1);
  }
  if ( strlen(argv[4]) >= DB_STRING_MAX ) {
    fprintf(stderr, "\n pass phrase is too long\n");
    exit(1);
  }
  if ((num_ware = atoi(argv[5 + arg_offset])) <= 0) {
    fprintf(stderr, "\n expecting positive number of warehouses\n");
    exit(1);
  }
  if ((num_conn = atoi(argv[6 + arg_offset])) <= 0) {
    fprintf(stderr, "\n expecting positive number of connections\n");
    exit(1);
  }
  if ((lampup_time = atoi(argv[7 + arg_offset])) < 0) {
    fprintf(stderr, "\n expecting positive number of lampup_time [sec]\n");
    exit(1);
  }
  if ((measure_time = atoi(argv[8 + arg_offset])) < 0) {
    fprintf(stderr, "\n expecting positive number of measure_time [sec]\n");
    exit(1);
  }

  if (parse_host_get_port(&port, argv[1]) < 0) {
      fprintf(stderr, "cannot prase the host: %s\n", argv[1]);
      exit(1);
  }
  strcpy( db_string, argv[2] );
  strcpy( db_user, argv[3] );
  strcpy( db_password, argv[4] );
*/

  if(strcmp(db_string,"l")==0){
    is_local = 1;
  }else{
    is_local = 0;
  }

  if(valuable_flg==1){
    if( (atoi(argv[9 + arg_offset]) < 0)||(atoi(argv[10 + arg_offset]) < 0)||(atoi(argv[11 + arg_offset]) < 0)
	||(atoi(argv[12 + arg_offset]) < 0)||(atoi(argv[13 + arg_offset]) < 0) ) {
      fprintf(stderr, "\n expecting positive number of ratio parameters\n");
      exit(1);
    }
  }

  if( num_node > 0 ){
    if( num_ware % num_node != 0 ){
      fprintf(stderr, "\n [warehouse] value must be devided by [num_node].\n");
      exit(1);
    }
    if( num_conn % num_node != 0 ){
      fprintf(stderr, "\n [connection] value must be devided by [num_node].\n");
      exit(1);
    }
  }

  if ( strlen(report_file) > 0 ) {
    freport_file=fopen(report_file,"w+");
  }


  printf("<Parameters>\n");
  if(is_local==0) {
    printf("     [server]: ");
      printf("%s",  connect_string);
    printf("\n");
  }
  if(is_local==0)printf("     [port]: %d\n", port);
  printf("     [DBname]: %s\n", db_string);
  printf("       [user]: %s\n", db_user);
  printf("       [pass]: %s\n", db_password);

  printf("  [warehouse]: %d\n", num_ware);
  printf(" [connection]: %d\n", num_conn);
  printf("     [rampup]: %d (sec.)\n", lampup_time);
  printf("    [measure]: %d (sec.)\n", measure_time);

  if(valuable_flg==1){
    printf("      [ratio]: %d:%d:%d:%d:%d\n", atoi(argv[9 + arg_offset]), atoi(argv[10 + arg_offset]),
	   atoi(argv[11 + arg_offset]), atoi(argv[12 + arg_offset]), atoi(argv[13 + arg_offset]) );
  }

  /* alarm initialize */
  time_count = 0;
  itval.it_interval.tv_sec = PRINT_INTERVAL;
  itval.it_interval.tv_usec = 0;
  itval.it_value.tv_sec = PRINT_INTERVAL;
  itval.it_value.tv_usec = 0;
  sigact.sa_handler = alarm_handler;
  sigact.sa_flags = 0;
  sigemptyset(&sigact.sa_mask);

  /* setup handler&timer */
  if( sigaction( SIGALRM, &sigact, NULL ) == -1 ) {
    fprintf(stderr, "error in sigaction()\n");
    exit(1);
  }

  fd = open("/dev/urandom", O_RDONLY);
  if (fd == -1) {
    fd = open("/dev/random", O_RDONLY);
    if (fd == -1) {
      struct timeval  tv;
      gettimeofday(&tv, NULL);
      seed = (tv.tv_sec ^ tv.tv_usec) * tv.tv_sec * tv.tv_usec ^ tv.tv_sec;
    }else{
      read(fd, &seed, sizeof(seed));
      close(fd);
    }
  }else{
    read(fd, &seed, sizeof(seed));
    close(fd);
  }
  SetSeed(seed);

  if(valuable_flg==0){
    seq_init(10,10,1,1,1); /* normal ratio */
  }else{
    seq_init( atoi(argv[9 + arg_offset]), atoi(argv[10 + arg_offset]), atoi(argv[11 + arg_offset]),
	      atoi(argv[12 + arg_offset]), atoi(argv[13 + arg_offset]) );
  }

  /* set up each counter */
  for ( i=0; i<5; i++ ){
      success2[i] = malloc( sizeof(int) * num_conn );
      late2[i] = malloc( sizeof(int) * num_conn );
      retry2[i] = malloc( sizeof(int) * num_conn );
      failure2[i] = malloc( sizeof(int) * num_conn );
      for ( k=0; k<num_conn; k++ ){
	  success2[i][k] = 0;
	  late2[i][k] = 0;
	  retry2[i][k] = 0;
	  failure2[i][k] = 0;
      }
  }

  /* set up threads */

  t = malloc( sizeof(pthread_t) * num_conn );
  if ( t == NULL ){
    fprintf(stderr, "error at malloc(pthread_t)\n");
    exit(1);
  }
  thd_arg = malloc( sizeof(thread_arg) * num_conn );
  if( thd_arg == NULL ){
    fprintf(stderr, "error at malloc(thread_arg)\n");
    exit(1);
  }

  ctx = malloc( sizeof(MYSQL *) * num_conn );
  stmt = malloc( sizeof(MYSQL_STMT **) * num_conn );
  for( i=0; i < num_conn; i++ ){
      stmt[i] = malloc( sizeof(MYSQL_STMT *) * 40 );
  }

  if ( ctx == NULL ){
    fprintf(stderr, "error at malloc(sql_context)\n");
    exit(1);
  }

  /* EXEC SQL WHENEVER SQLERROR GOTO sqlerr; */

  for( i=0; i < num_conn; i++ ){
    ctx[i] = mysql_init(NULL);
    if(!ctx[i]) goto sqlerr;
  }

  for( t_num=0; t_num < num_conn; t_num++ ){
    thd_arg[t_num].port= port;
    thd_arg[t_num].number= t_num;
    pthread_create( &t[t_num], NULL, (void *)thread_main, (void *)&(thd_arg[t_num]) );
  }


  printf("\nRAMP-UP TIME.(%d sec.)\n",lampup_time);
  fflush(stdout);
  sleep(lampup_time);
  printf("\nMEASURING START.\n\n");
  fflush(stdout);

  /* sleep(measure_time); */
  /* start timer */

#ifndef _SLEEP_ONLY_
  if( setitimer(ITIMER_REAL, &itval, NULL) == -1 ) {
    fprintf(stderr, "error in setitimer()\n");
  }
#endif

  counting_on = 1;
  /* wait signal */
  for(i = 0; i < (measure_time / PRINT_INTERVAL); i++ ) {
#ifndef _SLEEP_ONLY_
    pause();
#else
    sleep(PRINT_INTERVAL);
    alarm_dummy();
#endif
  }
  counting_on = 0;

#ifndef _SLEEP_ONLY_
  /* stop timer */
  itval.it_interval.tv_sec = 0;
  itval.it_interval.tv_usec = 0;
  itval.it_value.tv_sec = 0;
  itval.it_value.tv_usec = 0;
  if( setitimer(ITIMER_REAL, &itval, NULL) == -1 ) {
    fprintf(stderr, "error in setitimer()\n");
  }
#endif

  printf("\nSTOPPING THREADS");
  activate_transaction = 0;

  /* wait threads' ending and close connections*/
  for( i=0; i < num_conn; i++ ){
    pthread_join( t[i], NULL );
  }

  printf("\n");

  free(ctx);
  for( i=0; i < num_conn; i++ ){
      free(stmt[i]);
  }
  free(stmt);

  free(t);
  free(thd_arg);

  //hist_report();
  if (freport_file != NULL)
	  fclose(freport_file);

  printf("\n<Raw Results>\n");
  for ( i=0; i<5; i++ ){
    printf("  [%d] sc:%d  lt:%d  rt:%d  fl:%d \n", i, success[i], late[i], retry[i], failure[i]);
  }
  printf(" in %d sec.\n", (measure_time / PRINT_INTERVAL) * PRINT_INTERVAL);

  printf("\n<Raw Results2(sum ver.)>\n");
  for( i=0; i<5; i++ ){
      success2_sum[i] = 0;
      late2_sum[i] = 0;
      retry2_sum[i] = 0;
      failure2_sum[i] = 0;
      for( k=0; k<num_conn; k++ ){
	  success2_sum[i] += success2[i][k];
	  late2_sum[i] += late2[i][k];
	  retry2_sum[i] += retry2[i][k];
	  failure2_sum[i] += failure2[i][k];
      }
  }
  for ( i=0; i<5; i++ ){
      printf("  [%d] sc:%d  lt:%d  rt:%d  fl:%d \n", i, success2_sum[i], late2_sum[i], retry2_sum[i], failure2_sum[i]);
  }

  printf("\n<Constraint Check> (all must be [OK])\n [transaction percentage]\n");
  for ( i=0, j=0; i<5; i++ ){
    j += (success[i] + late[i]);
  }

  f = 100.0 * (float)(success[1] + late[1])/(float)j;
  printf("        Payment: %3.2f%% (>=43.0%%)",f);
  if ( f >= 43.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)(success[2] + late[2])/(float)j;
  printf("   Order-Status: %3.2f%% (>= 4.0%%)",f);
  if ( f >= 4.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)(success[3] + late[3])/(float)j;
  printf("       Delivery: %3.2f%% (>= 4.0%%)",f);
  if ( f >= 4.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)(success[4] + late[4])/(float)j;
  printf("    Stock-Level: %3.2f%% (>= 4.0%%)",f);
  if ( f >= 4.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }

  printf(" [response time (at least 90%% passed)]\n");
  f = 100.0 * (float)success[0]/(float)(success[0] + late[0]);
  printf("      New-Order: %3.2f%% ",f);
  if ( f >= 90.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)success[1]/(float)(success[1] + late[1]);
  printf("        Payment: %3.2f%% ",f);
  if ( f >= 90.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)success[2]/(float)(success[2] + late[2]);
  printf("   Order-Status: %3.2f%% ",f);
  if ( f >= 90.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)success[3]/(float)(success[3] + late[3]);
  printf("       Delivery: %3.2f%% ",f);
  if ( f >= 90.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }
  f = 100.0 * (float)success[4]/(float)(success[4] + late[4]);
  printf("    Stock-Level: %3.2f%% ",f);
  if ( f >= 90.0 ){
    printf(" [OK]\n");
  }else{
    printf(" [NG] *\n");
  }

  printf("\n<TpmC>\n");
  f = (float)(success[0] + late[0]) * 60.0
    / (float)((measure_time / PRINT_INTERVAL) * PRINT_INTERVAL);
  printf("                 %.3f TpmC\n",f);
  exit(0);

 sqlerr:
  fprintf(stdout, "error at main\n");
  error(ctx[i],0);
  exit(1);

}
void login(LinkedList<Item> *listOfItems, LinkedList<Club> *listOfClubs, LinkedList<User> *listOfUsers)
{
	string password, username;
	Node<User> *tmp;
	
	cout << "Input username: "******"Input password: "******"Input password" << endl;

				temp = _getch();
				if (temp == '\r')
					break;
				std::cout << "*";
				password += temp;
			}
	#elif __APPLE__
		//password = getpass("Input password");
	#elif __linux__
		//password = getpass("Input password");
	#elif __unix__
		//password = getpass("Input password");
	#endif
	*/

	tmp = listOfUsers->mHead;

	while (tmp != NULL)
	{
		if ((tmp->mData.getUserName() == username) && (tmp->mData.getPassword() == password))
		{
			clearScreen();
			cout << "You logged in!" << endl;
			pause();
			bool logout = false;
			do {
				logout = displayAdminMenu(listOfItems, listOfClubs, listOfUsers);
			} while (!logout);
			return;
		}

		tmp = tmp->mNext;
	}

	cout << "This is not a valid login." << endl;
	login(listOfItems, listOfClubs, listOfUsers);

	//if (checkWords(username, password, listOfItems, listOfClubs, listOfUsers) == true)
	//{
	//	clearScreen();
	//	cout << "You logged in!" << endl;
	//	displayAdminMenu(listOfItems, listOfClubs, listOfUsers);
	//	system("pause");
	//}

	//else
	//{
	//	cout << "This is not a valid login." << endl;
	//	login(listOfItems, listOfClubs, listOfUsers);
	//	return;
	//}
}
Exemple #9
0
val_t eic_pause(void)
{
    val_t v;
    v.ival = pause();
    return v;
}
Exemple #10
0
void Pause() 
{
    (void)pause();
    return;
}
Exemple #11
0
 void game::handelevents()
    {
     SDL_Event event;
     while (SDL_PollEvent(&event))
     {
      switch (event.type)
      {
      case SDL_QUIT:
      running=false;
      return;
      case SDL_KEYDOWN:
      switch(event.key.keysym.sym)
      {
      case SDLK_LEFT :
          direction[0]=1;
          player1->setMoving(1);
          //player1->setJump(0);
          break;
      case SDLK_RIGHT:
          direction[1]=1;
          player1->setMoving(1);
         // player1->setJump(0);
          break;
      case SDLK_SPACE:
          player1->setJump();
          player1->setMoving(0);
          break;
       case SDLK_c:
           if(player1->getDirection()=='r' && player1->getpower()==1)
           {
          bullets.push_back(new bullet(bull,player1->getRect()->x+player1->getRect()->w-8,player1->getRect()->y-5,5,0,10));
          break;
           }
           if(player1->getDirection()=='l' && player1->getpower()==1)
           {
          bullets.push_back(new bullet(bull,player1->getRect()->x-player1->getRect()->w+10,player1->getRect()->y-5,-5,0,10));
          break;
       case SDLK_ESCAPE :
          int h=pause(screen);
          if (h==1)
              running=false;
              break;
           }
      }
      break;
      case SDL_KEYUP:
      switch(event.key.keysym.sym)
      {
      case SDLK_LEFT :
          direction[0]=0;
          player1->setMoving(0);
          break;
      case SDLK_RIGHT:
          direction[1]=0;
          player1->setMoving(0);
          break;
      }
      break;
     }
    }
    }
Exemple #12
0
int
main(int argc, char ** argv)
{
	int			did;
	int			opt;
	int			errflg = 0;
	int			showstats = 0;
	int			doset = 0;
	int			dofg = 0;
	struct stat		buf;
	sigset_t		myset;
	struct sigaction	sighupaction;
	static void		client_killserver();
	int			debug_level = 0;

	/* setup for localization */
	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	openlog("ldap_cachemgr", LOG_PID, LOG_DAEMON);

	if (chdir(NSLDAPDIRECTORY) < 0) {
		(void) fprintf(stderr, gettext("chdir(\"%s\") failed: %s\n"),
		    NSLDAPDIRECTORY, strerror(errno));
		exit(1);
	}

	/*
	 * Correctly set file mode creation mask, so to make the new files
	 * created for door calls being readable by all.
	 */
	(void) umask(0);

	/*
	 *  Special case non-root user here -	he/she/they/it can just print
	 *					stats
	 */

	if (geteuid()) {
		if (argc != 2 || strcmp(argv[1], "-g")) {
			(void) fprintf(stderr,
			    gettext("Must be root to use any option "
			    "other than -g.\n\n"));
			usage(argv[0]);
		}

		if ((__ns_ldap_cache_ping() != SUCCESS) ||
		    (client_getadmin(&current_admin) != 0)) {
			(void) fprintf(stderr,
			    gettext("%s doesn't appear to be running.\n"),
			    argv[0]);
			exit(1);
		}
		(void) client_showstats(&current_admin);
		exit(0);
	}



	/*
	 *  Determine if there is already a daemon running
	 */

	will_become_server = (__ns_ldap_cache_ping() != SUCCESS);

	/*
	 *  load normal config file
	 */

	if (will_become_server) {
		static const ldap_stat_t defaults = {
			0,		/* stat */
			DEFAULTTTL};	/* ttl */

		current_admin.ldap_stat = defaults;
		(void) strcpy(current_admin.logfile, LOGFILE);
	} else {
		if (client_getadmin(&current_admin)) {
			(void) fprintf(stderr, gettext("Cannot contact %s "
			    "properly(?)\n"), argv[0]);
			exit(1);
		}
	}

#ifndef SLP
	while ((opt = getopt(argc, argv, "fKgl:r:d:")) != EOF) {
#else
	while ((opt = getopt(argc, argv, "fKgs:l:r:d:")) != EOF) {
#endif /* SLP */
		ldap_stat_t	*cache;

		switch (opt) {
		case 'K':
			client_killserver();
			exit(0);
			break;
		case 'g':
			showstats++;
			break;
		case 'f':
			dofg++;
			break;
		case 'r':
			doset++;
			cache = getcacheptr("ldap");
			if (!optarg) {
				errflg++;
				break;
			}
			cache->ldap_ttl = atoi(optarg);
			break;
		case 'l':
			doset++;
			(void) strlcpy(current_admin.logfile,
			    optarg, sizeof (current_admin.logfile));
			break;
		case 'd':
			doset++;
			debug_level = atoi(optarg);
			break;
#ifdef SLP
		case 's':	/* undocumented: use dynamic (SLP) config */
			use_slp = 1;
			break;
#endif /* SLP */
		default:
			errflg++;
			break;
		}
	}

	if (errflg)
		usage(argv[0]);

	/*
	 * will not show statistics if no daemon running
	 */
	if (will_become_server && showstats) {
		(void) fprintf(stderr,
		    gettext("%s doesn't appear to be running.\n"),
		    argv[0]);
		exit(1);
	}

	if (!will_become_server) {
		if (showstats) {
			(void) client_showstats(&current_admin);
		}
		if (doset) {
			current_admin.debug_level = debug_level;
			if (client_setadmin(&current_admin) < 0) {
				(void) fprintf(stderr,
				    gettext("Error during admin call\n"));
				exit(1);
			}
		}
		if (!showstats && !doset) {
			(void) fprintf(stderr,
			gettext("%s already running....use '%s "
			    "-K' to stop\n"), argv[0], argv[0]);
		}
		exit(0);
	}

	/*
	 *   daemon from here on
	 */

	if (debug_level) {
		/*
		 * we're debugging...
		 */
		if (strlen(current_admin.logfile) == 0)
			/*
			 * no specified log file
			 */
			(void) strcpy(current_admin.logfile, LOGFILE);
		else
			(void) cachemgr_set_lf(&current_admin,
			    current_admin.logfile);
		/*
		 * validate the range of debug level number
		 * and set the number to current_admin.debug_level
		 */
		if (cachemgr_set_dl(&current_admin, debug_level) < 0) {
				/*
				 * print error messages to the screen
				 * cachemgr_set_dl prints msgs to cachemgr.log
				 * only
				 */
				(void) fprintf(stderr,
				gettext("Incorrect Debug Level: %d\n"
				"It should be between %d and %d\n"),
				    debug_level, DBG_OFF, MAXDEBUG);
			exit(-1);
		}
	} else {
		if (strlen(current_admin.logfile) == 0)
			(void) strcpy(current_admin.logfile, "/dev/null");
			(void) cachemgr_set_lf(&current_admin,
			    current_admin.logfile);
	}

	if (dofg == 0)
		detachfromtty(argv[0]);

	/*
	 * perform some initialization
	 */

	initialize_lookup_clearance();

	if (getldap_init() != 0)
		exit(-1);

	/*
	 * Establish our own server thread pool
	 */

	(void) door_server_create(server_create);
	if (thr_keycreate(&server_key, server_destroy) != 0) {
		logit("thr_keycreate() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: thr_keycreate() call failed"));
		perror("thr_keycreate");
		exit(-1);
	}

	/*
	 * Create a door
	 */

	if ((did = door_create(switcher, LDAP_CACHE_DOOR_COOKIE,
	    DOOR_UNREF | DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) < 0) {
		logit("door_create() call failed\n");
		syslog(LOG_ERR, gettext(
		    "ldap_cachemgr: door_create() call failed"));
		perror("door_create");
		exit(-1);
	}

	/*
	 * bind to file system
	 */

	if (stat(LDAP_CACHE_DOOR, &buf) < 0) {
		int	newfd;

		if ((newfd = creat(LDAP_CACHE_DOOR, 0444)) < 0) {
			logit("Cannot create %s:%s\n",
			    LDAP_CACHE_DOOR,
			    strerror(errno));
			exit(1);
		}
		(void) close(newfd);
	}

	if (fattach(did, LDAP_CACHE_DOOR) < 0) {
		if ((errno != EBUSY) ||
		    (fdetach(LDAP_CACHE_DOOR) <  0) ||
		    (fattach(did, LDAP_CACHE_DOOR) < 0)) {
			logit("fattach() call failed\n");
			syslog(LOG_ERR, gettext(
			    "ldap_cachemgr: fattach() call failed"));
			perror("fattach");
			exit(2);
		}
	}

	/* catch SIGHUP revalid signals */
	sighupaction.sa_handler = getldap_revalidate;
	sighupaction.sa_flags = 0;
	(void) sigemptyset(&sighupaction.sa_mask);
	(void) sigemptyset(&myset);
	(void) sigaddset(&myset, SIGHUP);

	if (sigaction(SIGHUP, &sighupaction, NULL) < 0) {
		logit("sigaction() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: sigaction() call failed"));
		perror("sigaction");
		exit(1);
	}

	if (thr_sigsetmask(SIG_BLOCK, &myset, NULL) < 0) {
		logit("thr_sigsetmask() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: thr_sigsetmask() call failed"));
		perror("thr_sigsetmask");
		exit(1);
	}

	/*
	 *  kick off revalidate threads only if ttl != 0
	 */

	if (thr_create(NULL, NULL, (void *(*)(void*))getldap_refresh,
	    0, 0, NULL) != 0) {
		logit("thr_create() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: thr_create() call failed"));
		perror("thr_create");
		exit(1);
	}

	/*
	 *  kick off the thread which refreshes the server info
	 */

	if (thr_create(NULL, NULL, (void *(*)(void*))getldap_serverInfo_refresh,
	    0, 0, NULL) != 0) {
		logit("thr_create() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: thr_create() call failed"));
		perror("thr_create");
		exit(1);
	}

#ifdef SLP
	if (use_slp) {
		/* kick off SLP discovery thread */
		if (thr_create(NULL, NULL, (void *(*)(void *))discover,
		    (void *)&refresh, 0, NULL) != 0) {
			logit("thr_create() call failed\n");
			syslog(LOG_ERR, gettext("ldap_cachemgr: thr_create() "
			    "call failed"));
			perror("thr_create");
			exit(1);
		}
	}
#endif /* SLP */

	if (thr_sigsetmask(SIG_UNBLOCK, &myset, NULL) < 0) {
		logit("thr_sigsetmask() call failed\n");
		syslog(LOG_ERR,
		    gettext("ldap_cachemgr: the_sigsetmask() call failed"));
		perror("thr_sigsetmask");
		exit(1);
	}

	/*CONSTCOND*/
	while (1) {
		(void) pause();
	}
	/* NOTREACHED */
	/*LINTED E_FUNC_HAS_NO_RETURN_STMT*/
}


/*
 * Before calling the alloca() function we have to be sure that we won't get
 * beyond the stack. Since we don't know the precise layout of the stack,
 * the address of an automatic of the function gives us a rough idea, plus/minus
 * a bit. We also need a bit more of stackspace after the call to be able
 * to call further functions. Even something as simple as making a system call
 * from within this function can take ~100 Bytes of stackspace.
 */
#define	SAFETY_BUFFER 32 * 1024 /* 32KB */

static
size_t
get_data_size(LineBuf *config_info, int *err_code)
{
	size_t		configSize = sizeof (ldap_return_t);
	dataunion	*buf = NULL; /* For the 'sizeof' purpose */

	if (config_info->str != NULL &&
	    config_info->len >= sizeof (buf->data.ldap_ret.ldap_u.config)) {
		configSize = sizeof (buf->space) +
		    config_info->len -
		    sizeof (buf->data.ldap_ret.ldap_u.config);

		if (!stack_inbounds((char *)&buf -
		    (configSize + SAFETY_BUFFER))) {
			/*
			 * We do not have enough space on the stack
			 * to accomodate the whole DUAProfile
			 */
			logit("The DUAProfile is too big. There is not enough "
			    "space to process it. Ignoring it.\n");
			syslog(LOG_ERR, gettext("ldap_cachemgr: The DUAProfile "
			    "is too big. There is not enough space "
			    "to process it. Ignoring it."));

			*err_code = SERVERERROR;

			free(config_info->str);
			config_info->str = NULL;
			config_info->len = 0;
			configSize = sizeof (ldap_return_t);
		}
	}

	return (configSize);
}
Exemple #13
0
Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
#ifndef PLAYER_NO_COLOROPTIONS
    , colorDialog(0)
#endif
{
//! [create-objs]
    player = new QMediaPlayer(this);
    // owned by PlaylistModel
    playlist = new QMediaPlaylist();
    player->setPlaylist(playlist);
//! [create-objs]

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
    connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
    connect(player, SIGNAL(videoAvailableChanged(bool)), this, SLOT(videoAvailableChanged(bool)));
    connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));

//! [2]
    videoWidget = new VideoWidget(this);
    player->setVideoOutput(videoWidget);

    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(playlist);
//! [2]

    playlistView = new QListView(this);
    playlistView->setModel(playlistModel);
    playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));

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

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

    labelDuration = new QLabel(this);
    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
    

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

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

    PlayerControls *controls = new PlayerControls(this, player);
    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()), playlist, SLOT(next()));
    connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
    connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));

    connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));

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

    fullScreenButton = new QPushButton(tr("FullScreen"), this);
    fullScreenButton->setCheckable(true);

#ifndef PLAYER_NO_COLOROPTIONS
    colorButton = new QPushButton(tr("Color Options..."), this);
    colorButton->setEnabled(false);
    connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
#endif

    QBoxLayout *displayLayout = new QHBoxLayout;
    displayLayout->addWidget(videoWidget, 2);
    displayLayout->addWidget(playlistView);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(fullScreenButton);
#ifndef PLAYER_NO_COLOROPTIONS
    controlLayout->addWidget(colorButton);
#endif

    QBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(displayLayout);
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(slider);
    hLayout->addWidget(labelDuration);
    layout->addLayout(hLayout);
    layout->addLayout(controlLayout);

    setLayout(layout);

    if (!player->isAvailable()) {
        QMessageBox::warning(this, tr("Service not available"),
                             tr("The QMediaPlayer object does not have a valid service.\n"\
                                "Please check the media service plugins are installed."));

        controls->setEnabled(false);
        playlistView->setEnabled(false);
        openButton->setEnabled(false);
#ifndef PLAYER_NO_COLOROPTIONS
        colorButton->setEnabled(false);
#endif
        fullScreenButton->setEnabled(false);
    }

    metaDataChanged();

    QStringList arguments = qApp->arguments();
    arguments.removeAt(0);
    addToPlaylist(arguments);
}
Exemple #14
0
int
main(int ac, char **av)
{
	int lc;                         /* loop counter */
	const char *msg;		/* message returned from parse_opts */
	pid_t pid, fake_pid;
	int exno, status, fake_status, nsig;

	/* parse standard options */
	if ((msg = parse_opts(ac, av, (option_t *)NULL, NULL)) != (char *)NULL){
		tst_brkm(TBROK, cleanup, "OPTION PARSING ERROR - %s", msg);
	}

	setup();                        /* global setup */

	TEST_EXP_ENOS(exp_enos);

	/* The following loop checks looping state if -i option given */
	for (lc = 0; TEST_LOOPING(lc); lc++) {

		/* reset Tst_count in case we are looping */
		Tst_count = 0;
		status = 1;
		exno = 1;
		pid = fork();
		if (pid < 0) {
			tst_brkm(TBROK, cleanup, "Fork failed");
		} else if (pid == 0) {
			pause();
			/*NOTREACHED*/
			exit(exno);
		} else {
			fake_pid = fork();
			if (fake_pid < 0) {
				tst_brkm(TBROK, cleanup, "Second fork failed");
			} else if (fake_pid == 0) {
				pause();
				/*NOTREACHED*/
				exit(exno);
			}
			kill(fake_pid, TEST_SIG);
			waitpid(fake_pid, &fake_status, 0);
			TEST(kill(fake_pid, TEST_SIG));
			kill(pid, TEST_SIG);
			waitpid(pid, &status, 0);
		}

		if (TEST_RETURN != -1) {
			tst_brkm(TFAIL, cleanup, "%s failed - errno = %d : %s "
				"Expected a return value of -1 got %d",
				TCID, TEST_ERRNO, strerror(TEST_ERRNO)),
				TEST_RETURN;
			/*NOTREACHED*/
		}

		if (STD_FUNCTIONAL_TEST) {
			/*
			 * Check to see if the errno was set to the expected
			 * value of 3 : ESRCH
			 */
			nsig = WTERMSIG(status);
			TEST_ERROR_LOG(TEST_ERRNO);
			if (TEST_ERRNO == ESRCH) {
				tst_resm(TPASS, "errno set to %d : %s, as "
					"expected", TEST_ERRNO,
					strerror(TEST_ERRNO));
			} else {
				tst_resm(TFAIL, "errno set to %d : %s expected "
					"%d : %s", TEST_ERRNO,
					strerror(TEST_ERRNO), 3, strerror(3));
			}
		}
	}
	cleanup();

	/*NOTREACHED*/
}
Exemple #15
0
void Controller::addFilter(std::string fltName, std::vector<std::string> args) {
    Filter *flt;
    std::string name;
    bool resume = false;

    if((flt = pipeline->addFilter2(fltName.c_str()))) {
        if((resume = player.isRunning())) {
            pause();
        }

        try {
        if (fltName == "grayscale")
        {
          name = "Grayscale";
        }
        else if (fltName ==  "sepia")
        {
          name = "Sepia";
        }
        else if (fltName == "colorinvert")
        {
          name = "Color inversion";
        }
        else if (fltName == "transform")
        {
          name = "Transformation";
          //set arguments
          std::string::size_type sz;
          TransformFilter *filter = dynamic_cast<TransformFilter*>(flt);
          float m[args.size()];
          for(int i = 0; i < args.size(); i++) {
              if(!args[i].empty())
                m[i] = stof(args[i], &sz);
              else m[i] = 0;
          }
          filter->setMatrix(m);
#ifdef DEBUG
          for(int i = 0; i < args.size(); i++) {
              std::cout << m[i] << std::endl;
          }
#endif
        }
        else if (fltName == "conv2d")
        {
            name = "Convolution 2D";
            //set arguments
            //stored row by row
            std::string::size_type sz;
            Conv2DFilter *filter = dynamic_cast<Conv2DFilter*>(flt);
            float kernel[args.size()];
            //try {
            for(int i = 0; i < args.size(); i++) {
                if(!args[i].empty())
                  kernel[i] = stof(args[i], &sz);
                else kernel[i] = 0;
            }
//            } catch (const std::invalid_argument& ia) {
//                Controller::ctrlInst()->writeMsg(ia.w);
//            }

            for(int i = 0; i < args.size(); i++) {
                std::cout << kernel[i] << std::endl;
            }

            filter->setFilterKernel(kernel, sqrt(args.size()));
        }
        else if (fltName == "separableconv2d")
        {
            name = "Separable Convolution 2D";
            //set arguments
            std::string::size_type sz;
            SeparableConv2DFilter *filter = dynamic_cast<SeparableConv2DFilter*>(flt);
            int size = args.size() / 2;
            float horizKernel[size];
            float verticKernel[size];

            for(int i = 0; i < size; i++) {
                if(!args[i].empty()) {
                  horizKernel[i] = stof(args[i], &sz);
                  verticKernel[i] = stof(args[i + size], &sz);
                } else {
                    horizKernel[i] = 0;
                    verticKernel[i] = 0;
                }
            }
#ifdef DEBUG
            for(int i = 0; i < size; i++) {
                std::cout << horizKernel[i] << ":vert=" << verticKernel[i] << std::endl;
            }
#endif
            filter->setHorizontalFilterKernel(horizKernel, size);
            filter->setVerticalFilterKernel(verticKernel, size);
        }
        else if (fltName == "sobel")
        {
            name = "Sobel Operator";


        }
        else if (fltName == "emboss")
        {
            name = "Embossing";

            //set arguments
            std::string::size_type sz;
            EmbossFilter *filter = dynamic_cast<EmbossFilter*>(flt);

#ifdef DEBUG
            for(int i = 0; i < args.size(); i++) {
                std::cout << args[i] << std::endl;
            }
#endif

            //first gray level
            float grayLevel = stof(args[0], &sz);
            filter->setGrayLevel(grayLevel);

            //second size
            //0 = EmbossFilter::NORMAL
            //1 = EmbossFilter::LARGE
            switch(stoi(args[1], &sz)) {
            case 0: {
                filter->setSize(EmbossFilter::NORMAL);
            }break;
            case 1: {
                filter->setSize(EmbossFilter::LARGE);
            }break;
            }
        }
        else if (fltName == "dog")
        {
            name = "Difference of Gaussians";
            //set arguments
            std::string::size_type sz;
            DoGFilter *filter = dynamic_cast<DoGFilter*>(flt);
            //first factor
            float factor = stof(args[0], &sz);
            filter->setFactor(factor);

            //second bias
            float bias = stof(args[1], &sz);
            filter->setBias(bias);

            if (args[2] == "true")
              filter->setInverted(true);

#ifdef DEBUG
           // for(int i = 0; i < args.size(); i++) {
                std::cout << factor << std::endl;
                std::cout << bias << std::endl;
            //}
#endif
        }
        else if (fltName == "gaussianblur")
        {
            name = "Gaussian Blur";
            //set arguments
            std::string::size_type sz;
            GaussianBlurFilter *filter = dynamic_cast<GaussianBlurFilter*>(flt);
            //first sigma
            double sigma = stod(args[0], &sz);
            filter->setSigma(sigma);

            //second variance
            double variance = stod(args[1], &sz);
            filter->setVariance(variance);

            //third size
            int size = stoi(args[2], &sz);
            filter->setSize(size);

#ifdef DEBUG
            for(int i = 0; i < args.size(); i++) {
                std::cout << sigma << std::endl;
                std::cout << variance << std::endl;
                std::cout << size << std::endl;
            }
#endif
        }
        else if (fltName == "oilify")
        {
          name = "Oilify";
          //set arguments
          OilifyFilter *filter = dynamic_cast<OilifyFilter*>(flt);
          filter->setRadius(atoi(args[0].c_str()));
          filter->setLevels(atoi(args[1].c_str()));
        }
        else if (fltName == "shake")
        {
          name = "Shake";
          //set arguments
          ShakeFilter *filter = dynamic_cast<ShakeFilter*>(flt);
          filter->setIntensity(double(atoi(args[0].c_str()) / 100.0f));
        }
        else {
            std::cerr << "Controller: Invalid filter name!" << std::endl;
        }


        filterVec.push_back(std::pair<std::string, Filter*>(name, flt));

        if(resume)
            play();

        Controller::ctrlInst()->writeMsg("Filter successfully added.");
        } catch (const std::invalid_argument) {
            Controller::ctrlInst()->writeMsg("Invalid filter argument (i.e. not a number)");
        }
    }else {
        std::cerr << "Controller: Error adding filter" << std::endl;
    }
}
void
hpet_fasync(int argc, const char **argv)
{
	unsigned long		freq;
	int			iterations, i, fd, value;
	sig_t			oldsig;
	struct hpet_info	info;

	hpet_sigio_count = 0;
	fd = -1;

	if ((oldsig = signal(SIGIO, hpet_sigio)) == SIG_ERR) {
		fprintf(stderr, "hpet_fasync: failed to set signal handler\n");
		return;
	}

	if (argc != 3) {
		fprintf(stderr, "hpet_fasync: device-name freq iterations\n");
		goto out;
	}

	fd = open(argv[0], O_RDONLY);

	if (fd < 0) {
		fprintf(stderr, "hpet_fasync: failed to open %s\n", argv[0]);
		return;
	}


	if ((fcntl(fd, F_SETOWN, getpid()) == 1) ||
		((value = fcntl(fd, F_GETFL)) == 1) ||
		(fcntl(fd, F_SETFL, value | O_ASYNC) == 1)) {
		fprintf(stderr, "hpet_fasync: fcntl failed\n");
		goto out;
	}

	freq = atoi(argv[1]);
	iterations = atoi(argv[2]);

	if (ioctl(fd, HPET_IRQFREQ, freq) < 0) {
		fprintf(stderr, "hpet_fasync: HPET_IRQFREQ failed\n");
		goto out;
	}

	if (ioctl(fd, HPET_INFO, &info) < 0) {
		fprintf(stderr, "hpet_fasync: failed to get info\n");
		goto out;
	}

	fprintf(stderr, "hpet_fasync: info.hi_flags 0x%lx\n", info.hi_flags);

	if (info.hi_flags && (ioctl(fd, HPET_EPI, 0) < 0)) {
		fprintf(stderr, "hpet_fasync: HPET_EPI failed\n");
		goto out;
	}

	if (ioctl(fd, HPET_IE_ON, 0) < 0) {
		fprintf(stderr, "hpet_fasync, HPET_IE_ON failed\n");
		goto out;
	}

	for (i = 0; i < iterations; i++) {
		(void) pause();
		fprintf(stderr, "hpet_fasync: count = %d\n", hpet_sigio_count);
	}

out:
	signal(SIGIO, oldsig);

	if (fd >= 0)
		close(fd);

	return;
}
Exemple #17
0
//Start program
int main (int argc, char ** argv) {
	//define buffers for input
	//user input
	char line[MAX_LENGTH];
	//the command the user wanted
	char *cmd;
	//current working directory
	char cwd[1024];
	//the argument needed for two part commands
	char *arg;
	//true false to determine if using a file or not
	char fn = '1';
	//the batch file to be read
	FILE *batch;
	//a duplicate of the original path needed when executing readme
	char cwd_dup[1024];
	//getting the original path for readme
	getcwd(cwd_dup, sizeof(cwd_dup));
	//define pointers
	//Set environment variable "shell"
	if (setenv("SHELL",cwd_dup,1)){
		printf("Failed to set environment!\n");
	}
	//If the argument ocunter is 2 when the program starts
	//open the file
	if (argc == 2)
	{
		//determines if the file can be opened
		//if it can, run the program from the file
		//file path is argv[1]
		batch = fopen(argv[1], "r");
		if (batch == NULL){
			printf("Error opening file!\n");
		}else{
			fn = '0';
		}
	}
		

	//print working directory
	//read command input from console in a loop
   
	//Keep reading input line until "quit" command, or eof of redirect input like "Ctrl+C", or eof of the file
	while(1){
		//get the current directory
	    getcwd(cwd, sizeof(cwd));
	    //if it is from console, fn is 1
	    //otherwise 0 is fro file
	    //if it is form console, display the current directory and gets the line from the user
	    if(fn == '1'){
	    	printf("%s: ", cwd);
	    	fgets(line, MAX_LENGTH, stdin);
	    }else if(fn == '0'){
	    	if(feof(batch) == 0)
	    	{
	    		fgets(line, MAX_LENGTH, batch);
	    	}else{
	    		fn = '1';
	    		fclose(batch);
	    		continue;
	    		//exit(0);
	    	}
	    }
		//Tokenize the input args array
		cmd = strtok(line, DELIMS);
		//Check for supported internal commands
		if (!cmd){
			//Do nothing with no command
		}else if (strcmp(cmd, "cd") == 0) {
			//store the command name and any arguments
			//pass command to OS through calling "system()", or call related functions
			//change environment variables if need it
			//display result if need it
			arg = strtok(0, DELIMS);
			//cd must have an argument to attempt path change
	        if (!arg) {
	        	fprintf(stderr, "cd missing argument.\n");
	        }
	        else {
	        	//If the path change fails, tell the user
	        	if(chdir(arg) == -1){
	        		printf("Directory change failed!\n");
	        	}
	        	
	        }
	    //clears the screen
		}else if(strcmp(cmd, "clr") == 0) {
			clr();
		//look at the specified directory by the user
		}else if(strcmp(cmd, "dir") == 0) {
			pid_t pid;
			pid = fork();
			if(pid == -1)
		        	printf("Error Creating child\n");
			else if ( pid == 0)
			{

				//if no argument after dir is put, it shows the current Directory
				DIR *dp;
				struct dirent *ep;  
				arg = strtok(0, DELIMS);  
				if(arg == NULL){
					dp = opendir (cwd);
				}else{
					dp = opendir (arg);
				}
				//if it cannot open the directory to show, tell the user
				if (dp != NULL)
				{
					//otherwise it reads each object in the directory
					while (ep = readdir (dp))
					{
						puts (ep->d_name);
					}
					//closes the directory read when it is done
				    (void) closedir (dp);
				}else{
				    perror ("Couldn't open the directory\n");
				}
				exit(0);
			}else if ( pid != 0)
			{
		        wait(NULL);
			}
		//displays the enviroment and all its variables
		}else if(strcmp(cmd, "environ") == 0) {
			pid_t pid;
			pid = fork();
			if(pid == -1)
		        	printf("Error Creating child\n");
			else if ( pid == 0)
			{
				//creates an external pointer to the enviroment
				extern char **environ;
				//finds the amount in environment and display it
				char **current;
				for(current = environ; *current; current++)
				{
					//new line for each element in environment
					printf("%s\n",*current);
				}
				exit(0);
			}else if ( pid != 0)
			{
		        wait(NULL);
			}
		//redisplay what the user wrote after echo
		}else if(strcmp(cmd, "echo") == 0) {
			pid_t pid;
			pid = fork();
			if(pid == -1)
		        	printf("Error Creating child\n");
			else if ( pid == 0)
			{
				//take out the command and display the rest as original text
				arg = strtok(0,"");
				printf("%s", arg);
				exit(0);
			}else if ( pid != 0)
			{
		        wait(NULL);
			}
		//show help
		}else if(strcmp(cmd, "help") == 0) {
			help(cwd_dup);
		//pauses the program
		}else if(strcmp(cmd, "pause") == 0) {
			pause();
		//quits the program
		//tells the user the program has terminated and then quits
		}else if(strcmp(cmd, "quit") == 0) {
			printf("Terminated\n");
			exit(0);
		//otherwise it tries to run an external
		}else{
			externPro(cmd, cwd);
		}
	}
}
//////////////////////////////////////////////////////////////////////////////////////////
// static
void LLViewerParcelMedia::processParcelMediaCommandMessage( LLMessageSystem *msg, void ** )
{
	// extract the agent id
	//	LLUUID agent_id;
	//	msg->getUUID( agent_id );

	U32 flags;
	U32 command;
	F32 time;
	msg->getU32( "CommandBlock", "Flags", flags );
	msg->getU32( "CommandBlock", "Command", command);
	msg->getF32( "CommandBlock", "Time", time );

	if (flags &( (1<<PARCEL_MEDIA_COMMAND_STOP)
				| (1<<PARCEL_MEDIA_COMMAND_PAUSE)
				| (1<<PARCEL_MEDIA_COMMAND_PLAY)
				| (1<<PARCEL_MEDIA_COMMAND_LOOP)
				| (1<<PARCEL_MEDIA_COMMAND_UNLOAD) ))
	{
		// stop
		if( command == PARCEL_MEDIA_COMMAND_STOP )
		{
			stop();
		}
		else
		// pause
		if( command == PARCEL_MEDIA_COMMAND_PAUSE )
		{
			pause();
		}
		else
		// play
		if(( command == PARCEL_MEDIA_COMMAND_PLAY ) ||
		   ( command == PARCEL_MEDIA_COMMAND_LOOP ))
		{
			if (LLViewerMedia::isMediaPaused())
			{
				start();
			}
			else
			{
				LLParcel *parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
				play(parcel);
			}
		}
		else
		// unload
		if( command == PARCEL_MEDIA_COMMAND_UNLOAD )
		{
			stop();
		}
	}

	if (flags & (1<<PARCEL_MEDIA_COMMAND_TIME))
	{
		if(! LLViewerMedia::hasMedia())
		{
			LLParcel *parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
			play(parcel);
		}
		seek(time);
	}
}
Exemple #19
0
static int 
acd_geom_ioctl(struct g_provider *pp, u_long cmd, void *addr, int fflag, struct thread *td)
{
    device_t dev = pp->geom->softc;
    struct ata_device *atadev = device_get_softc(dev);
    struct acd_softc *cdp = device_get_ivars(dev);
    int error = 0, nocopyout = 0;

    if (!cdp)
	return ENXIO;

    if (atadev->flags & ATA_D_MEDIA_CHANGED) {
	switch (cmd) {
	case CDIOCRESET:
	    acd_test_ready(dev);
	    break;
	   
	default:
	    acd_read_toc(dev);
	    acd_prevent_allow(dev, 1);
	    cdp->flags |= F_LOCKED;
	    break;
	}
    }

    switch (cmd) {

    case CDIOCRESUME:
	error = acd_pause_resume(dev, 1);
	break;

    case CDIOCPAUSE:
	error = acd_pause_resume(dev, 0);
	break;

    case CDIOCSTART:
	error = acd_start_stop(dev, 1);
	break;

    case CDIOCSTOP:
	error = acd_start_stop(dev, 0);
	break;

    case CDIOCALLOW:
	error = acd_prevent_allow(dev, 0);
	cdp->flags &= ~F_LOCKED;
	break;

    case CDIOCPREVENT:
	error = acd_prevent_allow(dev, 1);
	cdp->flags |= F_LOCKED;
	break;

    /*
     * XXXRW: Why does this require privilege?
     */
    case CDIOCRESET:
	error = priv_check(td, PRIV_DRIVER);
	if (error)
	    break;
	error = acd_test_ready(dev);
	break;

    case CDIOCEJECT:
	if (pp->acr != 1) {
	    error = EBUSY;
	    break;
	}
	error = acd_tray(dev, 0);
	break;

    case CDIOCCLOSE:
	if (pp->acr != 1)
	    break;
	error = acd_tray(dev, 1);
	break;

    case CDIOREADTOCHEADER:
	if (!cdp->toc.hdr.ending_track) {
	    error = EIO;
	    break;
	}
	bcopy(&cdp->toc.hdr, addr, sizeof(cdp->toc.hdr));
	break;

    case CDIOREADTOCENTRYS:
	{
	    struct ioc_read_toc_entry *te = (struct ioc_read_toc_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    int starting_track = te->starting_track;
	    int len;

	    if (!toc->hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->data_len < sizeof(toc->tab[0]) || 
		(te->data_len % sizeof(toc->tab[0])) != 0 || 
		(te->address_format != CD_MSF_FORMAT &&
		te->address_format != CD_LBA_FORMAT)) {
		error = EINVAL;
		break;
	    }

	    if (!starting_track)
		starting_track = toc->hdr.starting_track;
	    else if (starting_track == 170) 
		starting_track = toc->hdr.ending_track + 1;
	    else if (starting_track < toc->hdr.starting_track ||
		     starting_track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    len = ((toc->hdr.ending_track + 1 - starting_track) + 1) *
		  sizeof(toc->tab[0]);
	    if (te->data_len < len)
		len = te->data_len;
	    if (len > sizeof(toc->tab)) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		if (!(toc = malloc(sizeof(struct toc), M_ACD, M_NOWAIT))) {
		    error = ENOMEM;
		    break;
		}
		bcopy(&cdp->toc, toc, sizeof(struct toc));
		entry = toc->tab + (toc->hdr.ending_track + 1 -
			toc->hdr.starting_track) + 1;
		while (--entry >= toc->tab) {
		    lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			    &entry->addr.msf.second, &entry->addr.msf.frame);
		    entry->addr_type = CD_MSF_FORMAT;
		}
	    }
	    error = copyout(toc->tab + starting_track - toc->hdr.starting_track,
			    te->data, len);
	    if (te->address_format == CD_MSF_FORMAT)
		free(toc, M_ACD);
	}
	break;

    case CDIOREADTOCENTRY:
	{
	    struct ioc_read_toc_single_entry *te =
		(struct ioc_read_toc_single_entry *)addr;
	    struct toc *toc = &cdp->toc;
	    u_char track = te->track;

	    if (!toc->hdr.ending_track) {
		error = EIO;
		break;
	    }

	    if (te->address_format != CD_MSF_FORMAT && 
		te->address_format != CD_LBA_FORMAT) {
		error = EINVAL;
		break;
	    }

	    if (!track)
		track = toc->hdr.starting_track;
	    else if (track == 170)
		track = toc->hdr.ending_track + 1;
	    else if (track < toc->hdr.starting_track ||
		     track > toc->hdr.ending_track + 1) {
		error = EINVAL;
		break;
	    }

	    if (te->address_format == CD_MSF_FORMAT) {
		struct cd_toc_entry *entry;

		if (!(toc = malloc(sizeof(struct toc), M_ACD, M_NOWAIT))) {
		    error = ENOMEM;
		    break;
		}
		bcopy(&cdp->toc, toc, sizeof(struct toc));
		entry = toc->tab + (track - toc->hdr.starting_track);
		lba2msf(ntohl(entry->addr.lba), &entry->addr.msf.minute,
			&entry->addr.msf.second, &entry->addr.msf.frame);
	    }
	    bcopy(toc->tab + track - toc->hdr.starting_track,
		  &te->entry, sizeof(struct cd_toc_entry));
	    if (te->address_format == CD_MSF_FORMAT)
		free(toc, M_ACD);
	}
	break;

#if __FreeBSD_version > 600008
    case CDIOCREADSUBCHANNEL_SYSSPACE:
	nocopyout = 1;
	/* FALLTHROUGH */

#endif
    case CDIOCREADSUBCHANNEL:
	{
	    struct ioc_read_subchannel *args =
		(struct ioc_read_subchannel *)addr;
	    u_int8_t format;
	    int8_t ccb[16] = { ATAPI_READ_SUBCHANNEL, 0, 0x40, 1, 0, 0, 0,
			       sizeof(cdp->subchan)>>8, sizeof(cdp->subchan),
			       0, 0, 0, 0, 0, 0, 0 };

	    if (args->data_len > sizeof(struct cd_sub_channel_info) ||
		args->data_len < sizeof(struct cd_sub_channel_header)) {
		error = EINVAL;
		break;
	    }

	    format = args->data_format;
	    if ((format != CD_CURRENT_POSITION) &&
		(format != CD_MEDIA_CATALOG) && (format != CD_TRACK_INFO)) {
		error = EINVAL;
		break;
	    }

	    ccb[1] = args->address_format & CD_MSF_FORMAT;

	    if ((error = ata_atapicmd(dev, ccb, (caddr_t)&cdp->subchan,
				      sizeof(cdp->subchan), ATA_R_READ, 10)))
		break;

	    if ((format == CD_MEDIA_CATALOG) || (format == CD_TRACK_INFO)) {
		if (cdp->subchan.header.audio_status == 0x11) {
		    error = EINVAL;
		    break;
		}

		ccb[3] = format;
		if (format == CD_TRACK_INFO)
		    ccb[6] = args->track;

		if ((error = ata_atapicmd(dev, ccb, (caddr_t)&cdp->subchan, 
					  sizeof(cdp->subchan),ATA_R_READ,10))){
		    break;
		}
	    }
	    if (nocopyout == 0) {
		error = copyout(&cdp->subchan, args->data, args->data_len);
	    } else {
		error = 0;
		bcopy(&cdp->subchan, args->data, args->data_len);
	    }
	}
	break;

    case CDIOCPLAYMSF:
	{
	    struct ioc_play_msf *args = (struct ioc_play_msf *)addr;

	    error = 
		acd_play(dev, 
			 msf2lba(args->start_m, args->start_s, args->start_f),
			 msf2lba(args->end_m, args->end_s, args->end_f));
	}
	break;

    case CDIOCPLAYBLOCKS:
	{
	    struct ioc_play_blocks *args = (struct ioc_play_blocks *)addr;

	    error = acd_play(dev, args->blk, args->blk + args->len);
	}
	break;

    case CDIOCPLAYTRACKS:
	{
	    struct ioc_play_track *args = (struct ioc_play_track *)addr;
	    int t1, t2;

	    if (!cdp->toc.hdr.ending_track) {
		error = EIO;
		break;
	    }
	    if (args->end_track < cdp->toc.hdr.ending_track + 1)
		++args->end_track;
	    if (args->end_track > cdp->toc.hdr.ending_track + 1)
		args->end_track = cdp->toc.hdr.ending_track + 1;
	    t1 = args->start_track - cdp->toc.hdr.starting_track;
	    t2 = args->end_track - cdp->toc.hdr.starting_track;
	    if (t1 < 0 || t2 < 0 ||
		t1 > (cdp->toc.hdr.ending_track-cdp->toc.hdr.starting_track)) {
		error = EINVAL;
		break;
	    }
	    error = acd_play(dev, ntohl(cdp->toc.tab[t1].addr.lba),
			     ntohl(cdp->toc.tab[t2].addr.lba));
	}
	break;

    case CDIOCGETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(dev, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;

	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    arg->vol[0] = cdp->au.port[0].volume;
	    arg->vol[1] = cdp->au.port[1].volume;
	    arg->vol[2] = cdp->au.port[2].volume;
	    arg->vol[3] = cdp->au.port[3].volume;
	}
	break;

    case CDIOCSETVOL:
	{
	    struct ioc_vol *arg = (struct ioc_vol *)addr;

	    if ((error = acd_mode_sense(dev, ATAPI_CDROM_AUDIO_PAGE,
					(caddr_t)&cdp->au, sizeof(cdp->au))))
		break;
	    if (cdp->au.page_code != ATAPI_CDROM_AUDIO_PAGE) {
		error = EIO;
		break;
	    }
	    if ((error = acd_mode_sense(dev, ATAPI_CDROM_AUDIO_PAGE_MASK,
					(caddr_t)&cdp->aumask,
					sizeof(cdp->aumask))))
		break;
	    cdp->au.data_length = 0;
	    cdp->au.port[0].channels = CHANNEL_0;
	    cdp->au.port[1].channels = CHANNEL_1;
	    cdp->au.port[0].volume = arg->vol[0] & cdp->aumask.port[0].volume;
	    cdp->au.port[1].volume = arg->vol[1] & cdp->aumask.port[1].volume;
	    cdp->au.port[2].volume = arg->vol[2] & cdp->aumask.port[2].volume;
	    cdp->au.port[3].volume = arg->vol[3] & cdp->aumask.port[3].volume;
	    error =  acd_mode_select(dev, (caddr_t)&cdp->au, sizeof(cdp->au));
	}
	break;

    case CDIOCSETPATCH:
	{
	    struct ioc_patch *arg = (struct ioc_patch *)addr;

	    error = acd_setchan(dev, arg->patch[0], arg->patch[1],
				arg->patch[2], arg->patch[3]);
	}
	break;

    case CDIOCSETMONO:
	error = acd_setchan(dev, CHANNEL_0|CHANNEL_1, CHANNEL_0|CHANNEL_1, 0,0);
	break;

    case CDIOCSETSTEREO:
	error = acd_setchan(dev, CHANNEL_0, CHANNEL_1, 0, 0);
	break;

    case CDIOCSETMUTE:
	error = acd_setchan(dev, 0, 0, 0, 0);
	break;

    case CDIOCSETLEFT:
	error = acd_setchan(dev, CHANNEL_0, CHANNEL_0, 0, 0);
	break;

    case CDIOCSETRIGHT:
	error = acd_setchan(dev, CHANNEL_1, CHANNEL_1, 0, 0);
	break;

    case CDRIOCBLANK:
	error = acd_blank(dev, (*(int *)addr));
	break;

    case CDRIOCNEXTWRITEABLEADDR:
	{
	    struct acd_track_info track_info;

	    if ((error = acd_read_track_info(dev, 0xff, &track_info)))
		break;

	    if (!track_info.nwa_valid) {
		error = EINVAL;
		break;
	    }
	    *(int*)addr = track_info.next_writeable_addr;
	}
	break;
 
    case CDRIOCINITWRITER:
	error = acd_init_writer(dev, (*(int *)addr));
	break;

    case CDRIOCINITTRACK:
	error = acd_init_track(dev, (struct cdr_track *)addr);
	break;

    case CDRIOCFLUSH:
	error = acd_flush(dev);
	break;

    case CDRIOCFIXATE:
	error = acd_fixate(dev, (*(int *)addr));
	break;

    case CDRIOCREADSPEED:
	{
	    int speed = *(int *)addr;

	    /* Preserve old behavior: units in multiples of CDROM speed */
	    if (speed < 177)
		speed *= 177;
	    error = acd_set_speed(dev, speed, CDR_MAX_SPEED);
	}
	break;

    case CDRIOCWRITESPEED:
	{
	    int speed = *(int *)addr;

	    if (speed < 177)
		speed *= 177;
	    error = acd_set_speed(dev, CDR_MAX_SPEED, speed);
	}
	break;

    case CDRIOCGETBLOCKSIZE:
	*(int *)addr = cdp->block_size;
	break;

    case CDRIOCSETBLOCKSIZE:
	cdp->block_size = *(int *)addr;
	pp->sectorsize = cdp->block_size;       /* hack for GEOM SOS */
	acd_set_ioparm(dev);
	break;

    case CDRIOCGETPROGRESS:
	error = acd_get_progress(dev, (int *)addr);
	break;

    case CDRIOCSENDCUE:
	error = acd_send_cue(dev, (struct cdr_cuesheet *)addr);
	break;

    case CDRIOCREADFORMATCAPS:
	error = acd_read_format_caps(dev, (struct cdr_format_capacities *)addr);
	break;

    case CDRIOCFORMAT:
	error = acd_format(dev, (struct cdr_format_params *)addr);
	break;

    case DVDIOCREPORTKEY:
	if (cdp->cap.media & MST_READ_DVDROM)
	    error = acd_report_key(dev, (struct dvd_authinfo *)addr);
	else
	    error = EINVAL;
	break;

    case DVDIOCSENDKEY:
	if (cdp->cap.media & MST_READ_DVDROM)
	    error = acd_send_key(dev, (struct dvd_authinfo *)addr);
	else
	    error = EINVAL;
	break;

    case DVDIOCREADSTRUCTURE:
	if (cdp->cap.media & MST_READ_DVDROM)
	    error = acd_read_structure(dev, (struct dvd_struct *)addr);
	else
	    error = EINVAL;
	break;

    default:
	error = ata_device_ioctl(dev, cmd, addr);
    }
    return error;
}

static int
acd_geom_access(struct g_provider *pp, int dr, int dw, int de)
{
    device_t dev = pp->geom->softc;
    struct acd_softc *cdp = device_get_ivars(dev);
    struct ata_request *request;
    int8_t ccb[16] = { ATAPI_TEST_UNIT_READY, 0, 0, 0, 0,
		       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int timeout = 60, track;

    if (!(request = ata_alloc_request()))
	return ENOMEM;

    /* wait if drive is not finished loading the medium */
    while (timeout--) {
	request->dev = dev;
	bcopy(ccb, request->u.atapi.ccb, 16);
	request->flags = ATA_R_ATAPI;
	request->timeout = ATA_REQUEST_TIMEOUT;
	ata_queue_request(request);
	if (!request->error &&
	    (request->u.atapi.sense.key == 2 ||
	     request->u.atapi.sense.key == 7) &&
	    request->u.atapi.sense.asc == 4 &&
	    request->u.atapi.sense.ascq == 1)
	    pause("acdld", hz / 2);
	else
	    break;
    }
    ata_free_request(request);

    if (pp->acr == 0) {
	acd_prevent_allow(dev, 1);
	cdp->flags |= F_LOCKED;
	acd_read_toc(dev);
    }

    if (dr + pp->acr == 0) {
	acd_prevent_allow(dev, 0);
	cdp->flags &= ~F_LOCKED;
    }

    if ((track = pp->index)) {
	pp->sectorsize = (cdp->toc.tab[track - 1].control & 4) ? 2048 : 2352;
	pp->mediasize = ntohl(cdp->toc.tab[track].addr.lba) -
			ntohl(cdp->toc.tab[track - 1].addr.lba);
    }
    else {
	pp->sectorsize = cdp->block_size;
	pp->mediasize = cdp->disk_size;
    }
    pp->mediasize *= pp->sectorsize;

    return 0;
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::slotPause()
{
    pause();
}
Exemple #21
0
int main(void)
{
    // seed pseudorandom number generator
    srand48(time(NULL));

    // instantiate window
    GWindow window = newGWindow(WIDTH, HEIGHT);

    // instantiate bricks
    initBricks(window);

    // instantiate ball, centered in middle of window
    GOval ball = initBall(window);

    // instantiate paddle, centered at bottom of window
    GRect paddle = initPaddle(window);

    // instantiate scoreboard, centered in middle of window, just above ball
    GLabel label = initScoreboard(window);

    // number of bricks initially
    int bricks = COLS * ROWS;

    // number of lives initially
    int lives = LIVES;

    // number of points initially
    int points = 0;
    // velocity of ball
    double vX = drand48();
    double vY = 2;
    // keep playing until game over
    while (lives > 0 && points<50)
    {
        move(ball,vX,vY);
        GEvent mouse = getNextEvent(MOUSE_EVENT);
        if(mouse!=NULL) {
            if(getEventType(mouse) == MOUSE_MOVED) {
            int y = 500;
            double x = getX(mouse) - getWidth(paddle)/2;
            setLocation(paddle,x,y);
            }
        }
      if(getX(ball) + getWidth(ball) >= getWidth(window)) {
        vX = -vX;
    } else if(getY(ball) <=0) {
        vY = -vY;
    } else if(getX(ball)<=0) {
        vX = -vX;
    } else if(getY(ball) + getHeight(ball) >= getHeight(window)) {
    lives--;
    waitForClick();
    setLocation(ball, 190, 290);
    setLocation(paddle, 150, 480);
    }
    
    GObject obj = detectCollision(window,ball);
    if(obj!=NULL) {
        if(obj == paddle) {
            vY = -vY;
    }   else if (strcmp(getType(obj),"GRect")==0) {
            removeGWindow(window,obj);
            points++;
            vY = -vY;
            updateScoreboard(window, label, points);
    
    }  

    }
    pause(10);
}
    // wait for click before exiting
    waitForClick();
    // game over
    closeGWindow(window);
    return 0;
}
Exemple #22
0
int
main (int   argc,
      char *argv[])
{
  jack_client_t *client = jack_client_open (CLIENT_NAME,
                                            JackNullOption,
                                            NULL);

  state data;

  char *end = argv[1];

  if (argc > 1)
    data.frequency = strtod (argv[1], &end);

  if (end == argv[1])
    data.frequency = MIDDLE_C;

  data.sample_rate = jack_get_sample_rate (client);

  if (data.sample_rate < 1)
    data.sample_rate = SAMPLE_RATE;

  data.input_port = jack_port_register (client,
                                        INPUT_NAME,
                                        JACK_DEFAULT_AUDIO_TYPE,
                                        JackPortIsInput,
                                        0);

  data.output_port = jack_port_register (client,
                                         OUTPUT_NAME,
                                         JACK_DEFAULT_AUDIO_TYPE,
                                         JackPortIsOutput,
                                         0);

  data.sine_port = jack_port_register (client,
                                       SINE_NAME,
                                       JACK_DEFAULT_AUDIO_TYPE,
                                       JackPortIsOutput,
                                       0);

  data.square_port = jack_port_register (client,
                                         SQUARE_NAME,
                                         JACK_DEFAULT_AUDIO_TYPE,
                                         JackPortIsOutput,
                                         0);

  data.block_size  = jack_get_buffer_size (client);
  data.block_count = BUFFER_SIZE / data.block_size;

  int buffer_size = data.block_count * data.block_size;

  data.sample_data = calloc (2 * buffer_size - data.block_size, sizeof (jack_sample_t));
  data.window_data = malloc (buffer_size * sizeof (double));
  data.input_data  = fftw_malloc (buffer_size * sizeof (double));
  data.output_data = fftw_malloc ((buffer_size / 2 + 1) * sizeof (fftw_complex));

  data.fft_routine = fftw_plan_dft_r2c_1d (buffer_size,
                                           data.input_data,
                                           data.output_data,
                                           FFTW_MEASURE | FFTW_DESTROY_INPUT);

  data.indexed_train = calloc (buffer_size / 2 + 1, sizeof (pulse));
  data.sorted_train  = malloc ((buffer_size / 2 + 1) * sizeof (pulse));

  data.current_block = 0;

  int sample;

  for (sample = 0; sample < buffer_size; sample++)
    data.window_data[sample] = window (buffer_size, sample);

  for (sample = 0; sample < buffer_size / 2 + 1; sample++)
    data.indexed_train[sample].index = sample;

  jack_set_process_callback (client, process, &data);

  jack_activate (client);

  while (pause ());

  return 0;
}
Exemple #23
0
int main(int argc, char** argv)
{
    (void)(argc);
    (void)(argv);
    
    test_fsm fsm;

    std::cout << std::endl << "Test fsm" << std::endl;

    std::cout << "sizeof(test_fsm): " << sizeof(test_fsm) << std::endl;

    struct ev_1 ev1;
    struct ev_2 ev2;
    struct ev_3 ev3;
    struct ev_4 ev4;
    struct ev_5 ev5;
    struct ev_6 ev6;

    st s;

    std::cout << "TEST 1" << std::endl;
    std::cout << "initial state: ";
    out_state(fsm.state());

    // 1 -> 2 -> 3 -> 4 -> 5 -> 1
    s = fsm.process_event(ev1);
    out_state(s);
    s = fsm.process_event(ev2);
    out_state(s);
    s = fsm.process_event(ev3);
    out_state(s);
    s = fsm.process_event(ev4);
    out_state(s);
    s = fsm.process_event(ev5);
    out_state(s);

    std::cout << std::endl << "TEST 2" << std::endl;
    std::cout << "initial state: ";
    out_state(fsm.state());

    // 1 -> 2 -> 4 -> 5 -> 5
    s = fsm.process_event(ev1);
    out_state(s);
    s = fsm.process_event(ev6);
    out_state(s);
    s = fsm.process_event(ev4);
    out_state(s);
    s = fsm.process_event(ev6);
    out_state(s);

    fsm.reset();
    std::cout << std::endl << "TEST 3" << std::endl;
    std::cout << "initial state: ";
    out_state(fsm.state());

    // 1 -> 2 -> 3
    s = fsm.process_event(ev1);
    out_state(s);
    s = fsm.process_event(ev2);
    out_state(s);
    s = fsm.process_event(ev6);
    out_state(s);

    std::cout << std::endl << "Player fsm" << std::endl;

    player p;
    std::cout << "sizeof(player): " << sizeof(player) << std::endl;

    p.process_event(open_close()); // user opens CD player
    p.process_event(open_close()); // inserts CD and closes
    std::vector<float> tracks(7);
    tracks[0] = 3.08;
    tracks[1] = 4.34;
    tracks[2] = 2.58;
    tracks[3] = 5.01;
    tracks[4] = 4.12;
    tracks[5] = 3.24;
    tracks[6] = 1.23;

    p.process_event(               // CD is detected
        cd_detected(
             "CD disk"
           , tracks
        )
    );
    p.process_event(play());       // etc.
    p.process_event(pause());
    p.process_event(play());
    p.process_event(stop());
}
Exemple #24
0
int
main(int argc, char *argv[])
{
    struct sigaction sa;
    int fd, events, fnum;
    const int NOTIFY_SIG = SIGRTMIN;
    char *p;

    if (argc < 2 || strcmp(argv[1], "--help") == 0)
        usageError(argv[0], NULL);

    /* Establish handler for notification signal */

    sa.sa_sigaction = handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;           /* So handler gets siginfo_t arg. */
    if (sigaction(NOTIFY_SIG, &sa, NULL) == -1)
        errExit("sigaction");

    for (fnum = 1; fnum < argc; fnum++) {
        p = strchr(argv[fnum], ':');    /* Look for optional ':' */

        if (p == NULL) {                /* Default is all events + multishot */
            events = DN_ACCESS | DN_ATTRIB | DN_CREATE | DN_DELETE |
                     DN_MODIFY | DN_RENAME | DN_MULTISHOT;
        } else {                        /* ':' present, parse event chars */
            *p = '\0';                  /* Terminates directory component */
            events = 0;
            for (p++; *p != '\0'; p++) {
                switch (*p) {
                case 'a': events |= DN_ACCESS;          break;
                case 'A': events |= DN_ATTRIB;          break;
                case 'c': events |= DN_CREATE;          break;
                case 'd': events |= DN_DELETE;          break;
                case 'm': events |= DN_MODIFY;          break;
                case 'r': events |= DN_RENAME;          break;
                case 'M': events |= DN_MULTISHOT;       break;
                default:  usageError(argv[0], "Bad event character\n");
                }
            }
        }

        /* Obtain a file descriptor for the directory to be monitored */

        fd = open(argv[fnum], O_RDONLY);
        if (fd == -1)
            errExit("open");
        printf("opened '%s' as file descriptor %d\n", argv[fnum], fd);

        /* Use alternate signal instead of SIGIO for dnotify events */

        if (fcntl(fd, F_SETSIG, NOTIFY_SIG) == -1)
            errExit("fcntl - F_SETSIG");

        /* Enable directory change notifications */

        if (fcntl(fd, F_NOTIFY, events) == -1)
            errExit("fcntl-F_NOTIFY");
        printf("events: %o\n", (unsigned int) events);
    }

    for (;;)
        pause();                        /* Wait for events */
}
int main(int argc, char* argv[])
{
	int semDonnee;
	int semObs;
    int mutDonnee;
	int mutObs;
	/*initialize random seed*/
	srand(time(NULL));
	
    mutDonnee = rt_mutex_create(&mutex_donnee,"mutexDonnee");
	mutObs = rt_mutex_create(&mutex_obs,"mutexObstacle");
    semDonnee = rt_sem_create(&sem_donnee,"Semaphore Donnee",SEM_INIT,SEM_MODE);
    semObs = rt_sem_create(&sem_obs,"Semaphore Obstacle",SEM_INIT,SEM_MODE);
	
	/* Avoids memory swapping for this program */
    mlockall(MCL_CURRENT|MCL_FUTURE);
    
	
	
	gettimeofday(&tim, NULL);
	start = tim.tv_sec+(tim.tv_usec/1000000.0);
	/*
	 * Arguments: &task,
	 * name,
	 * stack size (0=default),
	 * priority,
	 * mode (FPU, start suspended, ...)
	 */
    rt_task_create(&sensorTaskt, "sensor", 0, 99, 0);
    rt_task_create(&computationTaskt, "computation", 0, 99, 0);
	rt_task_create(&printTaskt, "print", 0, 99, 0);
	
	/*
	 * Arguments: &task,
	 * task function,
	 * function argument
	 */	
    rt_task_start(&sensorTaskt, &sensorTask, NULL);
	rt_task_start(&computationTaskt, &computationTask, NULL);
	rt_task_start(&printTaskt, &printTask, NULL);

    pause();
	
    rt_task_delete(&sensorTask);
    rt_task_delete(&computationTask);
    rt_task_delete(&printTask);
	
    rt_sem_delete(&sem_donnee);
    rt_sem_delete(&sem_obs);
	
	rt_mutex_delete(&mutex_donnee);
	rt_mutex_delete(&mutex_obs);
	
	obstacle* temp1 = obstacleList;
		obstacle* temp2;
		while(temp1->nxt != NULL){
			temp2 = temp1->nxt;
			free(temp1);
			temp1=temp2;
		} 
		free(temp1);

}
bool QSpotifySession::event(QEvent *e)
{
    if (e->type() == NotifyMainThreadEventType) {
      //  qDebug() << "Process spotify event";
        processSpotifyEvents();
        e->accept();
        return true;
    } else if (e->type() == QEvent::Timer) {
       // qDebug() << "Timer, start spotify events";
        QTimerEvent *te = static_cast<QTimerEvent *>(e);
        if (te->timerId() == m_timerID) {
            processSpotifyEvents();
            e->accept();
            return true;
        }
    } else if (e->type() == ConnectionErrorEventType) {
        qDebug() << "Connection error";
        QSpotifyConnectionErrorEvent *ev = static_cast<QSpotifyConnectionErrorEvent *>(e);
        setConnectionError(ConnectionError(ev->error()), QString::fromUtf8(sp_error_message(ev->error())));
        e->accept();
        return true;
    } else if (e->type() == MetaDataEventType) {
     //   qDebug() << "Meta data";
        emit metadataUpdated();
        e->accept();
        return true;
    } else if (e->type() == EndOfTrackEventType) {
     //   qDebug() << "End track";
        m_trackChangedAutomatically = true;
        emit trackFinished();
       // playNext();
        e->accept();
        return true;
    } else if (e->type() == StopEventType) {
      //  qDebug() << "Stop";
        stop();
        e->accept();
        return true;
    } else if (e->type() == TrackProgressEventType) {
      //  qDebug() << "Track progress";
        if(!m_isPlaying) {
            e->accept();
            return true;
        }
        // Track progressed
        QSpotifyTrackProgressEvent *ev = static_cast<QSpotifyTrackProgressEvent *>(e);
        int currentTrackPositionDelta = ev->delta();
        if (m_previousTrackRemaining > 0) {
            // We're still playing the previous back from our buffer
            int fromPreviousTrack = qMin(currentTrackPositionDelta, m_previousTrackRemaining);
            currentTrackPositionDelta -= fromPreviousTrack;
            m_previousTrackRemaining -= fromPreviousTrack;
        }

        m_currentTrackPosition += currentTrackPositionDelta;
        m_currentTrackPlayedDuration += currentTrackPositionDelta;
        emit currentTrackPositionChanged();
        e->accept();
        return true;
    } else if (e->type() == SendImageRequestEventType) {
        QSpotifyRequestImageEvent *ev = static_cast<QSpotifyRequestImageEvent *>(e);
        sendImageRequest(ev->imageId());
        e->accept();
        return true;
    } else if (e->type() == ReceiveImageRequestEventType) {
        QSpotifyReceiveImageEvent *ev = static_cast<QSpotifyReceiveImageEvent *>(e);
        receiveImageResponse(ev->image());
        e->accept();
        return true;
    } else if (e->type() == PlayTokenLostEventType) {
     //   qDebug() << "Play token lost";
        emit playTokenLost();
        pause();
        e->accept();
        return true;
    } else if (e->type() == LoggedInEventType) {
        qDebug() << "Logged in 1";
        onLoggedIn();
        e->accept();
        return true;
    } else if (e->type() == LoggedOutEventType) {
        qDebug() << "Logged out";
        onLoggedOut();
        e->accept();
        return true;
    } else if (e->type() == OfflineErrorEventType) {
        qDebug() << "Offline error";
        QSpotifyOfflineErrorEvent *ev = static_cast<QSpotifyOfflineErrorEvent *>(e);
        m_offlineErrorMessage = QString::fromUtf8(sp_error_message(ev->error()));
        emit offlineErrorMessageChanged();
        e->accept();
        return true;
    } else if (e->type() == ScrobbleLoginErrorEventType) {
        qDebug() << "Scrobble login error";
        m_lfmLoggedIn = false;
        emit lfmLoggedInChanged();
        emit lfmLoginError();
        e->accept();
        return true;
    } else if (e->type() == ConnectionStateUpdateEventType) {
        qDebug() << "Connectionstate update event";
        setConnectionStatus(ConnectionStatus(sp_session_connectionstate(m_sp_session)));
        if (m_offlineMode && m_connectionStatus == LoggedIn) {
            setConnectionRules(m_connectionRules | AllowNetwork);
            setConnectionRules(m_connectionRules & ~AllowNetwork);
        }
        e->accept();
        return true;
    }
    return QObject::event(e);
}
Exemple #27
0
static int
oce_be3_flashdata(POCE_SOFTC sc, const struct firmware *fw, int num_imgs)
{
	char cookie[2][16] =    {"*** SE FLAS", "H DIRECTORY *** "};
	const char *p = (const char *)fw->data;
	const struct flash_sec_info *fsec = NULL;
	struct mbx_common_read_write_flashrom *req;
	int rc = 0, i, img_type, bin_offset = 0;
	boolean_t skip_image;
	uint32_t optype = 0, size = 0, start = 0, num_bytes = 0;
	uint32_t opcode = 0;
	OCE_DMA_MEM dma_mem;

	/* Validate Cookie */
	bin_offset = (sizeof(struct flash_file_hdr) +
		(num_imgs * sizeof(struct image_hdr)));
	p += bin_offset;
	while (p < ((const char *)fw->data + fw->datasize)) {
		fsec = (const struct flash_sec_info *)p;
		if (!memcmp(cookie, fsec->cookie, sizeof(cookie)))
			break;
		fsec = NULL;
		p += 32;
	}

	if (!fsec) {
		device_printf(sc->dev,
			"Invalid Cookie. Firmware image corrupted ?\n");
		return EINVAL;
	}

	rc = oce_dma_alloc(sc, sizeof(struct mbx_common_read_write_flashrom)
			+ 32*1024, &dma_mem, 0);
	if (rc) {
		device_printf(sc->dev,
			"Memory allocation failure while flashing\n");
		return ENOMEM;
	}
	req = OCE_DMAPTR(&dma_mem, struct mbx_common_read_write_flashrom);

	for (i = 0; i < MAX_FLASH_COMP; i++) {

		img_type = fsec->fsec_entry[i].type;
		skip_image = FALSE;
		switch (img_type) {
		case IMG_ISCSI:
			optype = 0;
			size = 2097152;
			start = 2097152;
			break;
		case IMG_REDBOOT:
			optype = 1;
			size = 1048576;
			start = 262144;
			if (!oce_img_flashing_required(sc, fw->data,
				optype, start, size, bin_offset))
				skip_image = TRUE;
			break;
		case IMG_BIOS:
			optype = 2;
			size = 524288;
			start = 12582912;
			break;
		case IMG_PXEBIOS:
			optype = 3;
			size = 524288;
			start = 13107200;
			break;
		case IMG_FCOEBIOS:
			optype = 8;
			size = 524288;
			start = 13631488;
			break;
		case IMG_ISCSI_BAK:
			optype = 9;
			size = 2097152;
			start = 4194304;
			break;
		case IMG_FCOE:
			optype = 10;
			size = 2097152;
			start = 6291456;
			break;
		case IMG_FCOE_BAK:
			optype = 11;
			size = 2097152;
			start = 8388608;
			break;
		case IMG_NCSI:
			optype = 13;
			size = 262144;
			start = 15990784;
			break;
		case IMG_PHY:
			optype = 99;
			size = 262144;
			start = 1310720;
			if (!oce_phy_flashing_required(sc))
				skip_image = TRUE;
			break;
		default:
			skip_image = TRUE;
			break;
		}
		if (skip_image)
			continue;

		p = fw->data;
		p = p + bin_offset + start;
		if ((p + size) > ((const char *)fw->data + fw->datasize)) {
			rc = 1;
			goto ret;
		}

		while (size) {

			if (size > 32*1024)
				num_bytes = 32*1024;
			else
				num_bytes = size;
			size -= num_bytes;

			if (!size)
				opcode = FLASHROM_OPER_FLASH;
			else
				opcode = FLASHROM_OPER_SAVE;

			memcpy(req->data_buffer, p, num_bytes);
			p += num_bytes;

			rc = oce_mbox_write_flashrom(sc, optype, opcode,
						&dma_mem, num_bytes);
			if (rc) {
				device_printf(sc->dev,
					"cmd to write to flash rom failed.\n");
				rc = EIO;
				goto ret;
			}
			/* Leave the CPU for others for some time */
			pause("yield", 10);

		}
	}
ret:
	oce_dma_free(sc, &dma_mem);
	return rc;

}
Exemple #28
0
int
parent(char **arg)
{
	perf_event_desc_t *fds = NULL;
	int status, ret, i, num_fds = 0, grp, group_fd;
	int ready[2], go[2];
	char buf;
	pid_t pid;

	if (pfm_initialize() != PFM_SUCCESS)
		errx(1, "libpfm initialization failed");

	for (grp = 0; grp < options.num_groups; grp++) {
		int ret;
		ret = perf_setup_list_events(options.events[grp], &fds, &num_fds);
		if (ret || !num_fds)
			exit(1);
	}

	pid = options.pid;
	if (!pid) {
		ret = pipe(ready);
		if (ret)
			err(1, "cannot create pipe ready");

		ret = pipe(go);
		if (ret)
			err(1, "cannot create pipe go");


		/*
		 * Create the child task
		 */
		if ((pid=fork()) == -1)
			err(1, "Cannot fork process");

		/*
		 * and launch the child code
		 *
		 * The pipe is used to avoid a race condition
		 * between for() and exec(). We need the pid
		 * of the new tak but we want to start measuring
		 * at the first user level instruction. Thus we
		 * need to prevent exec until we have attached
		 * the events.
		 */
		if (pid == 0) {
			close(ready[0]);
			close(go[1]);

			/*
			 * let the parent know we exist
			 */
			close(ready[1]);
			if (read(go[0], &buf, 1) == -1)
				err(1, "unable to read go_pipe");


			exit(child(arg));
		}

		close(ready[1]);
		close(go[0]);

		if (read(ready[0], &buf, 1) == -1)
			err(1, "unable to read child_ready_pipe");

		close(ready[0]);
	}

	for(i=0; i < num_fds; i++) {
		int is_group_leader; /* boolean */

		is_group_leader = perf_is_group_leader(fds, i);
		if (is_group_leader) {
			/* this is the group leader */
			group_fd = -1;
		} else {
			group_fd = fds[fds[i].group_leader].fd;
		}

		/*
		 * create leader disabled with enable_on-exec
		 */
		if (!options.pid) {
			fds[i].hw.disabled = is_group_leader;
			fds[i].hw.enable_on_exec = is_group_leader;
		}

		fds[i].hw.read_format = PERF_FORMAT_SCALE;
		/* request timing information necessary for scaling counts */
		if (is_group_leader && options.format_group)
			fds[i].hw.read_format |= PERF_FORMAT_GROUP;

		if (options.inherit)
			fds[i].hw.inherit = 1;

		if (options.pin && is_group_leader)
			fds[i].hw.pinned = 1;
		fds[i].fd = perf_event_open(&fds[i].hw, pid, -1, group_fd, 0);
		if (fds[i].fd == -1) {
			warn("cannot attach event%d %s", i, fds[i].name);
			goto error;
		}
	}

	if (!options.pid)
		close(go[1]);

	if (options.print) {
		if (!options.pid) {
			while(waitpid(pid, &status, WNOHANG) == 0) {
				usleep(1000000);
        //sleep(1);
				print_counts(fds, num_fds);
			}
		} else {
			while(quit == 0) {
				usleep(1000000);
        
        //sleep(1);
				print_counts(fds, num_fds);
			}
		}
	} else {
		if (!options.pid)
			waitpid(pid, &status, 0);
		else
			pause();
		print_counts(fds, num_fds);
	}

	for(i=0; i < num_fds; i++)
		close(fds[i].fd);

	free(fds);

	/* free libpfm resources cleanly */
	pfm_terminate();

	return 0;
error:
	free(fds);
	if (!options.pid)
		kill(SIGKILL, pid);

	/* free libpfm resources cleanly */
	pfm_terminate();

	return -1;
}
Exemple #29
0
void *thr_fn(void *arg)
{
    printf("thread started ... \n");
    pause();
    return 0;
}
Exemple #30
0
int main(void)
{
    // seed pseudorandom number generator
    srand48(time(NULL));

    // instantiate window
    GWindow window = newGWindow(WIDTH, HEIGHT);

    // instantiate bricks
    initBricks(window);
    
    // instantiate ball, centered in middle of window
    GOval ball = initBall(window);

    // instantiate paddle, centered at bottom of window
    GRect paddle = initPaddle(window);

    // instantiate scoreboard, centered in middle of window, just above ball
    GLabel label = initScoreboard(window);

    // number of bricks initially
    int bricks = COLS * ROWS;

    // number of lives initially
    int lives = LIVES;

    // number of points initially
    int points = 0;

    // keep playing until game over
     double velocity= 2.0 + drand48() ;
     double vely = 2.0;
     updateScoreboard(window, label, points);
     waitForClick();
    while (lives > 0 && bricks > 0)
    {
        
        updateScoreboard(window, label, points);
        GEvent event = getNextEvent(MOUSE_EVENT);
        if (event != NULL)
            {
            
                
                if (getEventType(event) == MOUSE_MOVED)
                {
                    double x = getX(event) - getWidth(paddle) / 2;
                    setLocation(paddle, x, getY(paddle));                                              
                }
            }
                 
        move(ball, velocity, vely);
        
        if (getX(ball) + getWidth(ball) >= getWidth(window))
        {
            velocity = -velocity;
        }
        else if (getX(ball) <= 0)
        {
            velocity = -velocity;
          
        }
        if( getY(ball) <= 0)
        {
            vely = -vely;
        }
        else if (getY(ball)+getWidth(ball) >= HEIGHT)
        {      
           
            lives--;
            setLocation(ball, (WIDTH/2)-10, HEIGHT/2);
            waitForClick();
           
            
        }   
        
        GObject obj = detectCollision(window, ball);
        if(obj != NULL)
        {
            if(strcmp(getType(obj), "GRect")==0)
            {
                vely = -vely;
                if(obj != paddle)
                {
                    removeGWindow(window, obj);
                    bricks--;
                    points++;
                    
                    
                }
            }
        }
        pause(10);   
    }
         
    

    // wait for click before exiting
    waitForClick();

    // game over
    closeGWindow(window);
    return 0;
}