bool Eyelink::startDeviceIO(){
    boost::mutex::scoped_lock lock(EyelinkDriverLock);
	
	if(eyelink_is_connected() && stopped) {
		//Eyelink to offline mode
		set_offline_mode();
		// Eyelink to record mode
		if( start_recording(0,1,1,0) ) {
			merror(M_IODEVICE_MESSAGE_DOMAIN, "Eyelink does not start!");
		}
		
        
		shared_ptr<Scheduler> scheduler = Scheduler::instance();
		shared_ptr<Eyelink> this_one = component_shared_from_this<Eyelink>();
		schedule_node = scheduler->scheduleUS(std::string(FILELINE ": ") + getTag(),
											  update_period, //defer first start one period 
											  update_period, //repeat interval
											  M_REPEAT_INDEFINITELY, 
											  boost::bind(update_, this_one),
											  M_DEFAULT_IODEVICE_PRIORITY,
											  M_DEFAULT_IODEVICE_WARN_SLOP_US,
											  M_DEFAULT_IODEVICE_FAIL_SLOP_US,
											  M_MISSED_EXECUTION_DROP);
		
		stopped = false;
		mprintf(M_IODEVICE_MESSAGE_DOMAIN, "Eyelink successfully started.");
	}
	else {
		mwarning(M_IODEVICE_MESSAGE_DOMAIN, "Warning! Could not start EyeLink! (StartIO)");
	}
    
	return !stopped;
}
Esempio n. 2
0
int rzx_start_recording( const char *filename, int embed_snapshot )
{
  int error;

  if( rzx_playback ) return 1;

  rzx = libspectrum_rzx_alloc();

  /* Store the filename */
  rzx_filename = utils_safe_strdup( filename );

  /* If we're embedding a snapshot, create it now */
  if( embed_snapshot ) {
    error = rzx_add_snap( rzx, 0 );

    if( error ) {
      libspectrum_free( rzx_filename );
      libspectrum_rzx_free( rzx );
      return error;
    }
  }

  start_recording( rzx, settings_current.competition_mode );

  return 0;
}
Esempio n. 3
0
// ######################################################################
void EyeTrackerEyeLink::startTracking()
{
#ifndef HAVE_EYELINK
  LFATAL("Proprietary EyeLink developer API not installed");
#else
  // Show message at bottom of tracker display:
  eyecmd_printf(const_cast<char*>("record_status_message 'Recording [%d]...' "), getSession());

	// set FIXUPDATE event property
  eyecmd_printf(const_cast<char*>("fixation_update_interval = 50"));
  eyecmd_printf(const_cast<char*>("fixation_update_accumulate = 50"));

  // Always send a TRIALID message before starting to record.  It
  // should contain trial condition data required for analysis:
  eyemsg_printf(const_cast<char*>("TRIALID EYETRACK"));

  // TRIAL_VAR_DATA message is recorded for EyeLink Data Viewer
  // analysis It specifies the list of trial variables value for the
  // trial This must be specified within the scope of an individual
  // trial (i.e., after "TRIALID" and before "TRIAL_RESULT"):
  eyemsg_printf(const_cast<char*>("!V TRIAL_VAR_DATA EYETRACKING"));

  // Log eye tracker time at onset of clip:
  if (itsEventLog.isValid())
    itsEventLog->pushEvent(sformat("Eye Tracker Time = %d", int(current_msec())));

  // Actually start the recording:
  if (start_recording(1, 1, 1, 1))
    LFATAL("Error trying to start recording");
#endif
}
Esempio n. 4
0
int main(int argc, char*argv[])
{
    char *filename = argc == 1 ? "/tmp/noapp.raw" : argv[1];
    recorder_context_t *rctx;
    rctx = init_recorder_context(filename);
    init_recorder_handles(rctx);
    return start_recording(rctx);
}
Esempio n. 5
0
void start_game_check_replay()
{
    write_log_debug("Checking replay status");

    if (play.recording) {
        start_recording();
    }
    else if (play.playback) {
        start_playback();
    }
}
Esempio n. 6
0
static void
on_record_toggled (GtkToggleToolButton *tb, void *user_data)
{
    Viewer *self = (Viewer*) user_data;
    int record = gtk_toggle_tool_button_get_active (tb);

    if (record && ! self->is_recording) {
        start_recording (self);
    } else {
        stop_recording (self);
    }
}
Esempio n. 7
0
int demo_manager::set_state(demo_state new_state, char *filename)
{
  if (new_state==state) return 1;

  switch (state)
  {
    case RECORDING :
    { delete record_file; } break;
    case PLAYING :
    {
/*
      fade_in(cache.img(cache.reg("art/help.spe","sell6",SPEC_IMAGE,1)),8);
      Timer now; now.WaitMs(2000);
      fade_out(8);
*/
      delete record_file;
      l_difficulty = initial_difficulty;
      the_game->set_state(MENU_STATE);
      wm->Push(new Event(ID_NULL,NULL));

      view *v=player_list;
      for (; v; v=v->next)  // reset all the players
      { if (v->m_focus) { v->reset_player(); v->m_focus->set_aistate(0); } }
      delete current_level;
      current_level=NULL;
      the_game->reset_keymap();
      base->input_state=INPUT_PROCESSING;


    } break;
    default :
      break;
  }

  switch (new_state)
  {
    case RECORDING :
    { return start_recording(filename); } break;
    case PLAYING :
    { return start_playing(filename); } break;
    case NORMAL :
    { state=NORMAL; } break;
  }

  return 1;
}
Esempio n. 8
0
int
rzx_continue_recording( const char *filename )
{
  utils_file file;
  libspectrum_error libspec_error; int error;
  libspectrum_snap* snap = NULL;
  libspectrum_rzx_iterator last_it = NULL;

  if( rzx_recording || rzx_playback ) return 1;

  /* Store the filename */
  rzx_filename = utils_safe_strdup( filename );

  error = utils_read_file( filename, &file );
  if( error ) return error;

  rzx = libspectrum_rzx_alloc();

  libspec_error = libspectrum_rzx_read( rzx, file.buffer, file.length );
  if( libspec_error != LIBSPECTRUM_ERROR_NONE ) {
    utils_close_file( &file );
    return libspec_error;
  }

  utils_close_file( &file );

  /* Get final snapshot */
  last_it = libspectrum_rzx_iterator_last( rzx );
  if( last_it ) snap = libspectrum_rzx_iterator_get_snap( last_it );

  if( snap ) {
    error = snapshot_copy_from( snap );
    if( error ) return error;
  } else {
    ui_error( UI_ERROR_WARNING, "RZX file cannot be continued" );
    libspectrum_free( rzx_filename );
    libspectrum_rzx_free( rzx );
    return 1;
  }

  start_recording( rzx, 0 );

  return 0;
}
Esempio n. 9
0
int     taping_pression (int evtype, int voice, int data)
{
    if (istaping)
    {
#ifdef DEBSEQU
	fprintf (stderr, "entering recording mode\n");
#endif
	t = 0;			/* JDJDJD c'est violent ca */
	if (start_recording ())
	    return -1;
	if (initcurEVplay == NULL)
	    generate_freeze ();
	else
	    start_playing ();
    }
    else
    {
#ifdef DEBSEQU
	fprintf (stderr, "quiting recording mode\n");
#endif
	addevent (&curEVreg, &event_end);
	if (initcurEVplay != NULL)
	{
	    EventBuf *temp = evbuf_fusion (initcurEVplay, initcurEVreg);

	    evbuf_remove (initcurEVplay);
	    evbuf_remove (initcurEVreg);
	    initcurEVplay = temp;
	    initcurEVreg = NULL;
	}
	else
	{
	    initcurEVplay = initcurEVreg;
	    initcurEVreg = NULL;
	}
#ifdef DEBSEQU
	fprintf (stderr, "quiting recording mode...done\n");
#endif
    }
    return 0;
}
Esempio n. 10
0
/**
 * main replayer method
 */
static void start(int option, int argc, char* argv[], char** envp)
{
	pid_t pid;
	int status, fake_argc;

	if (option == RECORD) {
		copy_executable(argv[2]);
		if (access(__executable, X_OK)) {
			printf("The specified file '%s' does not exist or is not executable\n", __executable);
			return;
		}

		/* create directory for trace files */
		setup_trace_dir(0);

		/* initialize trace files */
		open_trace_files();
		init_trace_files();
		copy_argv(argc, argv);
		copy_envp(envp);
		record_argv_envp(argc, __argv, __envp);
		close_trace_files();

		pid = sys_fork();
		/* child process */
		if (pid == 0) {
			sys_start_trace(__executable, __argv, __envp);
			/* parent process */
		} else {
			child = pid;

			/* make sure that the child process dies when the master process gets interrupted */
			install_signal_handler();

			/* sync with the child process */
			sys_waitpid(pid, &status);

			/* configure the child process to get a message upon a thread start, fork(), etc. */
			sys_ptrace_setup(pid);

			/* initialize stuff */
			init_libpfm();
			/* initialize the trace file here -- we need to record argc and envp */
			open_trace_files();

			/* register thread at the scheduler and start the HPC */
			rec_sched_register_thread(0, pid);

			/* perform the action recording */
			fprintf(stderr, "start recording...\n");
			start_recording();
			fprintf(stderr, "done recording -- cleaning up\n");
			/* cleanup all initialized data-structures */
			close_trace_files();
			close_libpfm();
		}

		/* replayer code comes here */
	} else if (option == REPLAY) {
		init_environment(argv[2], &fake_argc, __argv, __envp);

		copy_executable(__argv[0]);
		if (access(__executable, X_OK)) {
			printf("The specified file '%s' does not exist or is not executable\n", __executable);
			return;
		}

		pid = sys_fork();
		//child process
		if (pid == 0) {
			sys_start_trace(__executable, __argv, __envp);
			/* parent process */
		} else {
			child = pid;
			/* make sure that the child process dies when the master process gets interrupted */
			install_signal_handler();

			sys_waitpid(pid, &status);
			sys_ptrace_setup(pid);


			/* initialize stuff */
			init_libpfm();
			rep_sched_init();
			/* sets the file pointer to the first trace entry */

			read_trace_init(argv[2]);

			pid_t rec_main_thread = get_recorded_main_thread();
			rep_sched_register_thread(pid, rec_main_thread);

			/* main loop */
			replay();
			/* thread wants to exit*/
			close_libpfm();
			read_trace_close();
			rep_sched_close();
		}
	}
}
Esempio n. 11
0
int gaze_control_trial(UINT32 time_limit)
{
	UINT32 trial_start;		/* trial start time (for timeout) */
	UINT32 drawing_time;	/* retrace-to-draw delay*/
	int button;				/* the button pressed (0 if timeout) */
	int error;				/* trial result code*/

	ALLF_DATA evt;			/* buffer to hold sample and event data*/
	int eye_used = -1;		/* indicates which eye's data to display*/
	int i;

	SDL_Surface *gbm;			/* The bitmap containing the stimulus display*/

	   /* This supplies the title at the bottom of the eyetracker display */
	eyecmd_printf("record_status_message 'GAZE CONTROL TRIAL' ");

	/*	
	Always send a TRIALID message before starting to record. 
	It should contain trial condition data required for analysis.
	*/
	eyemsg_printf("TRIALID CONTROL");

  /* TRIAL_VAR_DATA message is recorded for EyeLink Data Viewer analysis
	It specifies the list of trial variables value for the trial 
	This must be specified within the scope of an individual trial (i.e., after 
	"TRIALID" and before "TRIAL_RESULT") 
	*/
	eyemsg_printf("!V TRIAL_VAR_DATA GAZECTRL");
	/* 
	IMGLOAD command is recorded for EyeLink Data Viewer analysis
	It displays a default image on the overlay mode of the trial viewer screen. 
	Writes the image filename + path info
     */
	eyemsg_printf("!V IMGLOAD FILL images/grid.png");	

	/* 
	IAREA command is recorded for EyeLink Data Viewer analysis
	It creates a set of interest areas by reading the segment files
	Writes segmentation filename + path info
	*/
	eyemsg_printf("!V IAREA FILE segments/grid.ias"); 

	/* Before recording, we place reference graphics on the EyeLink display*/
	set_offline_mode();			/* Must be offline to draw to EyeLink screen*/
	gbm = draw_grid_to_bitmap_segment("grid.ias", "segments", 1);;/* Draw bitmap and EyeLink reference graphics*/
	segment_source = gbm;

	/* 
		Save bitmap and transfer to the tracker pc.
		Since it takes a long to save the bitmap to the file, the 
		value of sv_options should be set as SV_NOREPLACE to save time
	*/

	bitmap_save_and_backdrop(gbm, 0, 0, 0, 0, "grid.png", "images", SV_NOREPLACE,
				  0, 0, (UINT16)(BX_MAXCONTRAST|((eyelink_get_tracker_version(NULL)>=2)?0:BX_GRAYSCALE)));

	   /* DO PRE-TRIAL DRIFT CORRECTION */
	   /* We repeat if ESC key pressed to do setup. */
	while(1)
	{              /* Check link often so we can exit if tracker stopped*/
	  if(!eyelink_is_connected()) return ABORT_EXPT;
	   /* We let do_drift_correct() draw target in this example*/
	   /* 3rd argument would be 0 if we already drew the display*/
	  error = do_drift_correct((INT16)(SCRWIDTH/2), (INT16)(SCRHEIGHT/2), 1, 1);
		   /* repeat if ESC was pressed to access Setup menu */
	  if(error!=27) break;
	}

	clear_full_screen_window(target_background_color);  /* make sure display is blank*/

		/* Configure EyeLink to send fixation updates every 50 msec*/
	eyecmd_printf("link_event_filter = LEFT,RIGHT,FIXUPDATE");
	eyecmd_printf("fixation_update_interval = 50");
	eyecmd_printf("fixation_update_accumulate = 50");

	init_regions();	/* Initialize regions for this display*/

	/* 
		Start data recording to EDF file, BEFORE DISPLAYING STIMULUS 
		You should always start recording 50-100 msec before required
		otherwise you may lose a few msec of data 
	*/
	error = start_recording(1,1,0,1);   /* send events only through link*/
	if(error != 0)           /* ERROR: couldn't start recording*/
	{
	  SDL_FreeSurface(gbm);   /* Be sure to delete bitmap before exiting!*/
	  return error;        /* Return the error code*/
	}
							  /* record for 100 msec before displaying stimulus */
	begin_realtime_mode(100);   /* Windows 2000/XP: no interruptions from now on*/

	/* 
		DISPLAY OUR IMAGE TO SUBJECT  by copying bitmap to display
		Because of faster drawing speeds and good refresh locking,
		we now place the stimulus onset message just after display refresh 
		and before drawing the stimulus.  This is accurate and will allow 
		drawing a new stimulus each display refresh.
	 
		However, we do NOT send the message after the retrace--this may take too long
		instead, we add a number to the message that represents the delay 
		from the event to the message in msec
	*/


	/* COPY BITMAP to display*/
	SDL_BlitSurface(gbm, NULL, window,NULL);
	Flip(window);
	drawing_time = current_msec();                   /* time of retrace*/
	trial_start = drawing_time;
	SDL_BlitSurface(gbm, NULL, window,NULL);
	



	/* delay from retrace (time to draw)*/
	drawing_time = current_msec()-drawing_time;    
	/* message for RT recording in analysis */
	eyemsg_printf("%d DISPLAY ON", drawing_time);
	/* message marks zero-plot time for EDFVIEW */
	eyemsg_printf("SYNCTIME %d", drawing_time);	 

	

	/* Print a title for the trial (for demo only)*/
	get_new_font("Times Roman", 24, 1);     
	graphic_printf(window,target_foreground_color, NONE, SCRWIDTH/2, 24, "Gaze Control Trial");
	

	if(!eyelink_wait_for_block_start(100, 0, 1))  /* wait for link event data*/
	{
	  end_trial();
	  alert_printf("ERROR: No link events received!");
	  return TRIAL_ERROR;
	}
	eye_used = eyelink_eye_available(); /* determine which eye(s) are available*/ 
	switch(eye_used)		      /* select eye, add annotation to EDF file	*/
	{			
	  case RIGHT_EYE:
		eyemsg_printf("EYE_USED 1 RIGHT");
		break;
	  case BINOCULAR:           /* both eye's data present: use left eye only*/
		eye_used = LEFT_EYE;
	  case LEFT_EYE:
		eyemsg_printf("EYE_USED 0 LEFT");
		break;
	}
								 
	/* Now get ready for trial loop*/
	eyelink_flush_keybuttons(0);   /* reset keys and buttons from tracker */

	/* 
		we don't use getkey() especially in a time-critical trial
		as Windows may interrupt us and cause an unpredicatable delay
		so we would use buttons or tracker keys only  
		Trial loop: till timeout or response -- added code for processing
		FIXUPDATE events
	*/
	while(1) 
	{ 
		/* First, check if recording aborted */
	  if((error=check_recording())!=0) return error;  
								 
	  /* Check if trial time limit expired*/
	  if(current_time() > trial_start+time_limit)
		{
			eyemsg_printf("TIMEOUT");    /* message to log the timeout */
			end_trial();                 /* local function to stop recording*/
			button = 0;                  /* trial result message is 0 if timeout */
			break;                       /* exit trial loop*/
		}

	  if(break_pressed())     /* check for program termination or ALT-F4 or CTRL-C keys*/
		{
			end_trial();         /* local function to stop recording*/
			return ABORT_EXPT;   /* return this code to terminate experiment*/
		}

	  /* check for local ESC key to abort trial (useful in debugging)   */
	  if(escape_pressed())    
		 {
			end_trial();         /* local function to stop recording*/
			return SKIP_TRIAL;   /* return this code if trial terminated*/
		 }

		/* BUTTON RESPONSE TEST */
		/* Check for eye-tracker buttons pressed
		/* This is the preferred way to get response data or end trials	*/
	  button = eyelink_last_button_press(NULL);
	  if(button!=0)       /* button number, or 0 if none pressed*/
		{
		  /* message to log the button press*/
			eyemsg_printf("ENDBUTTON %d", button);  
			/* local function to stop recording*/
			end_trial();                            
			break; /* exit trial loop*/
		}

		/* GET FIXUPDATE EVENTS, PROCESS*/

		i = eyelink_get_next_data(NULL);    /* Check for data from link*/
		if(i == FIXUPDATE)	  /* only process FIXUPDATE events*/
		{
			/* get a copy of the FIXUPDATE event */
			eyelink_get_float_data(&evt);  
			/* only process if it's from the desired eye?*/
			if(evt.fe.eye == eye_used)	   
			{   
				/* get average position and duration of the update */
				process_fixupdate((int)(evt.fe.gavx), (int)(evt.fe.gavy),/* Process event */
	       			 evt.fe.entime-evt.fe.sttime);
			}
		}
	}/* end of loop*/
	/* report response result: 0=timeout, else button number*/
	eyemsg_printf("TRIAL_RESULT %d", button);
		/* Call this at the end of the trial, to handle special conditions*/
	SDL_FreeSurface(gbm);
	segment_source = NULL;
	return check_record_exit();
}
/**
 * @name best_first_search
 *
 * Find the best segmentation by doing a best first search of the
 * solution space.
 */
void Wordrec::best_first_search(CHUNKS_RECORD *chunks_record,
                                WERD_CHOICE *best_choice,
                                WERD_CHOICE *raw_choice,
                                STATE *state,
                                DANGERR *fixpt,
                                STATE *best_state) {
  SEARCH_RECORD *the_search;
  inT16 keep_going;
  STATE guided_state;   // not used

  num_joints = chunks_record->ratings->dimension() - 1;
  the_search = new_search(chunks_record, num_joints,
                          best_choice, raw_choice, state);

  // The default state is initialized as the best choice.  In order to apply
  // segmentation adjustment, or any other contextual processing in permute,
  // we give the best choice a poor rating to force the processed raw choice
  // to be promoted to best choice.
  the_search->best_choice->set_rating(100000.0);
  evaluate_state(chunks_record, the_search, fixpt);
  if (permute_debug) {
    tprintf("\n\n\n =========== BestFirstSearch ==============\n");
    best_choice->print("**Initial BestChoice**");
  }

#ifndef GRAPHICS_DISABLED
  save_best_state(chunks_record);
#endif
  start_recording();
  FLOAT32 worst_priority = 2.0f * prioritize_state(chunks_record, the_search);
  if (worst_priority < wordrec_worst_state)
    worst_priority = wordrec_worst_state;
  if (segment_debug) {
    print_state("BestFirstSearch", best_state, num_joints);
  }

  guided_state = *state;
  do {
                                 /* Look for answer */
    if (!hash_lookup (the_search->closed_states, the_search->this_state)) {

      if (tord_blob_skip) {
        free_state (the_search->this_state);
        break;
      }

      guided_state = *(the_search->this_state);
      keep_going = evaluate_state(chunks_record, the_search, fixpt);
      hash_add (the_search->closed_states, the_search->this_state);

      if (!keep_going ||
          (the_search->num_states > wordrec_num_seg_states) ||
          (tord_blob_skip)) {
        if (segment_debug)
          tprintf("Breaking best_first_search on keep_going %s numstates %d\n",
                  ((keep_going) ? "T" :"F"), the_search->num_states);
        free_state (the_search->this_state);
        break;
      }

      FLOAT32 new_worst_priority = 2.0f * prioritize_state(chunks_record,
                                                           the_search);
      if (new_worst_priority < worst_priority) {
        if (segment_debug)
          tprintf("Lowering WorstPriority %f --> %f\n",
                  worst_priority, new_worst_priority);
        // Tighten the threshold for admitting new paths as better search
        // candidates are found.  After lowering this threshold, we can safely
        // popout everything that is worse than this score also.
        worst_priority = new_worst_priority;
      }
      expand_node(worst_priority, chunks_record, the_search);
    }

    free_state (the_search->this_state);
    num_popped++;
    the_search->this_state = pop_queue (the_search->open_states);
    if (segment_debug && !the_search->this_state)
      tprintf("No more states to evalaute after %d evals", num_popped);
  }
  while (the_search->this_state);

  state->part1 = the_search->best_state->part1;
  state->part2 = the_search->best_state->part2;
  stop_recording();
  if (permute_debug) {
    tprintf("\n\n\n =========== BestFirstSearch ==============\n");
            // best_choice->debug_string(getDict().getUnicharset()).string());
    best_choice->print("**Final BestChoice**");
  }
  // save the best_state stats
  delete_search(the_search);
}
                // Trial using bitmap copying
                // Caller must create and destroy the bitmap
int bitmap_recording_trial(HBITMAP gbm, UINT32 time_limit)
{
  UINT32 trial_start;	// trial start time (for timeout) 
  UINT32 drawing_time;  // retrace-to-draw delay
  int button;		// the button pressed (0 if timeout) 
  int error;            // trial result code

    // NOTE: TRIALID AND TITLE MUST HAVE BEEN SET BEFORE DRIFT CORRECTION!
    // FAILURE TO INCLUDE THESE MAY CAUSE INCOMPATIBILITIES WITH ANALYSIS SOFTWARE!

	   // DO PRE-TRIAL DRIFT CORRECTION 
	   // We repeat if ESC key pressed to do setup. 
  while(1)
    {              // Check link often so we can exit if tracker stopped
      if(!eyelink_is_connected()) return ABORT_EXPT;
	   // We let do_drift_correct() draw target in this example
	   // 3rd argument would be 0 if we already drew the fixation target
      error = do_drift_correct((INT16)(SCRWIDTH/2), (INT16)(SCRHEIGHT/2), 1, 1);
           // repeat if ESC was pressed to access Setup menu 
      if(error!=27) break;
    }

  clear_full_screen_window(target_background_color);  // make sure display is blank
  
	// Start data recording to EDF file, BEFORE DISPLAYING STIMULUS 
	// You should always start recording 50-100 msec before required
	// otherwise you may lose a few msec of data 
  error = start_recording(1,1,0,0);   // record samples and events to EDF file only
  if(error != 0) return error;        // ERROR: couldn't start recording

                              // record for 100 msec before displaying stimulus 
  begin_realtime_mode(100);   // Windows 2000/XP: no interruptions till display start marked

    // DISPLAY OUR IMAGE TO SUBJECT  by copying bitmap to display
    // Because of faster drawing speeds and good refresh locking,
    // we now place the stimulus onset message just after display refresh 
    // and before drawing the stimulus.  This is accurate and will allow 
    // drawing a new stimulus each display refresh.
    // However, we do NOT send the message after the retrace--this may take too long
    // instead, we add a number to the message that represents the delay 
    // from the event to the message in msec
  wait_for_video_refresh();	// synchronize before drawing so all seen at once
  drawing_time = current_msec();                  // time of retrace
  trial_start = drawing_time;  // record the display onset time 
  
  display_bitmap(full_screen_window, gbm, 0, 0);  // COPY BITMAP to display
  wait_for_drawing(full_screen_window);    // wait till bitmap copy finished

  drawing_time = current_msec()-drawing_time;    // delay from retrace (time to draw)
  eyemsg_printf("%d DISPLAY ON", drawing_time);	 // message for RT recording in analysis 
  eyemsg_printf("SYNCTIME %d", drawing_time);	 // message marks zero-plot time for EDFVIEW 

                        // we would stay in realtime mode if timing is critical   
                        // for example, if a dynamic (changing) stimulus was used
                        // or if display duration accuracy of 1 video refresh. was needed
  end_realtime_mode();  // we don't care as much about time now, allow keyboard to work
     
                                 // Now get ready for trial loop
  eyelink_flush_keybuttons(0);   // reset keys and buttons from tracker 

                       // we don't use getkey() especially in a time-critical trial
                       // as Windows may interrupt us and cause an unpredicatable delay
                       // so we would use buttons or tracker keys only  

     // Trial loop: till timeout or response 
  while(1)   
    {                            // First, check if recording aborted 
      if((error=check_recording())!=0) return error;  
                                 // Check if trial time limit expired
      if(current_time() > trial_start+time_limit)
        {
          eyemsg_printf("TIMEOUT");    // message to log the timeout 
	  end_trial();                 // local function to stop recording
	  button = 0;                  // trial result message is 0 if timeout 
	  break;                       // exit trial loop
	}
      if(break_pressed())     // check for program termination or ALT-F4 or CTRL-C keys
	{
	   end_trial();         // local function to stop recording
	   return ABORT_EXPT;   // return this code to terminate experiment
	 }

      if(escape_pressed())    // check for local ESC key to abort trial (useful in debugging)   
         {
	   end_trial();         // local function to stop recording
	   return SKIP_TRIAL;   // return this code if trial terminated
         }

		/* BUTTON RESPONSE TEST */
		// Check for eye-tracker buttons pressed
		// This is the preferred way to get response data or end trials	
      button = eyelink_last_button_press(NULL);
      if(button!=0)       // button number, or 0 if none pressed
	{
	   eyemsg_printf("ENDBUTTON %d", button);  // message to log the button press
	   end_trial();                            // local function to stop recording
	   break;                                  // exit trial loop
	 }
    }                       // END OF RECORDING LOOP
  end_realtime_mode();      // safety cleanup code
  while(getkey());          // dump any accumulated key presses

			   // report response result: 0=timeout, else button number
  eyemsg_printf("TRIAL_RESULT %d", button);
			   // Call this at the end of the trial, to handle special conditions
  return check_record_exit();
}
      // Run gaze-contingent window trial
      // <fgbm> is bitmap to display within window
      // <bgbm> is bitmap to display outside window
      // <wwidth, wheight> is size of window in pixels
      // <mask> flags whether to treat window as a mask
      // <time_limit> is the maximum time the stimuli are displayed 
int gc_window_trial(HBITMAP fgbm, HBITMAP bgbm, 
                    int wwidth, int wheight, int mask, UINT32 time_limit)
{
  UINT32 trial_start=0;	// trial start time (for timeout) 
  UINT32 drawing_time;  // retrace-to-draw delay
  int button;		// the button pressed (0 if timeout) 
  int error;            // trial result code

  ALLF_DATA evt;         // buffer to hold sample and event data
  int first_display = 1; // used to determine first drawing of display  
  int eye_used = 0;      // indicates which eye's data to display
  float x, y;		 // gaze position 

    // NOTE: TRIALID AND TITLE MUST HAVE BEEN SET BEFORE DRIFT CORRECTION!
    // FAILURE TO INCLUDE THESE MAY CAUSE INCOMPATIBILITIES WITH ANALYSIS SOFTWARE!


       // Set size and type of gaze-contingent window 
  RECT display_rect;

  display_rect.top    = dispinfo.top;
  display_rect.bottom = dispinfo.bottom;
  display_rect.left   = dispinfo.left;
  display_rect.right  = dispinfo.right;
  initialize_gc_window(wwidth, wheight, fgbm, bgbm, 
                       full_screen_window, display_rect, 
                       mask, SCRWIDTH/300);  // sets 0.1 degree deadband

	   // DO PRE-TRIAL DRIFT CORRECTION 
	   // We repeat if ESC key pressed to do setup. 
  while(1)
    {              // Check link often so we can exit if tracker stopped
      if(!eyelink_is_connected()) return ABORT_EXPT;
	   // We let do_drift_correct() draw target in this example
	   // 3rd argument would be 0 if we already drew the display
      error = do_drift_correct((INT16)(SCRWIDTH/2), (INT16)(SCRHEIGHT/2), 1, 1);
           // repeat if ESC was pressed to access Setup menu 
      if(error!=27) break;
    }

  clear_full_screen_window(target_background_color);  // make sure display is blank
  
	// Start data recording to EDF file, BEFORE DISPLAYING STIMULUS 
	// You should always start recording 50-100 msec before required
	// otherwise you may lose a few msec of data 
  
	//  tell start_recording() to send link data
  error = start_recording(1,1,1,1);	// record with link data enabled
  if(error != 0) return error;          // ERROR: couldn't start recording
                              // record for 100 msec before displaying stimulus 
  begin_realtime_mode(100);   // Windows 2000/XP: no interruptions from now on

    // DONT DISPLAY OUR IMAGES TO SUBJECT until we have first gaze postion!
  
  if(!eyelink_wait_for_block_start(100, 1, 0))  // wait for link sample data
    {
      end_trial();
      alert_printf("ERROR: No link samples received!");
      return TRIAL_ERROR;
    }
  eye_used = eyelink_eye_available(); // determine which eye(s) are available 
  switch(eye_used)		      // select eye, add annotation to EDF file	
    {			
      case RIGHT_EYE:
        eyemsg_printf("EYE_USED 1 RIGHT");
        break;
      case BINOCULAR:           // both eye's data present: use left eye only
        eye_used = LEFT_EYE;
      case LEFT_EYE:
        eyemsg_printf("EYE_USED 0 LEFT");
        break;
    }
                                 // Now get ready for trial loop
  eyelink_flush_keybuttons(0);   // reset keys and buttons from tracker 
                       // we don't use getkey() especially in a time-critical trial
                       // as Windows may interrupt us and cause an unpredicatable delay
                       // so we would use buttons or tracker keys only  

     // Trial loop: till timeout or response -- added code for reading samples and moving cursor
  while(1) 
    {                            // First, check if recording aborted 
      if((error=check_recording())!=0) return error;  
                                 // Check if trial time limit expired
      if(current_time() > trial_start+time_limit && trial_start!=0)
        {
          eyemsg_printf("TIMEOUT");    // message to log the timeout 
	  end_trial();                 // local function to stop recording
	  button = 0;                  // trial result message is 0 if timeout 
	  break;                       // exit trial loop
	}

      if(break_pressed())     // check for program termination or ALT-F4 or CTRL-C keys
	{
	   end_trial();         // local function to stop recording
	   return ABORT_EXPT;   // return this code to terminate experiment
	 }

      if(escape_pressed())    // check for local ESC key to abort trial (useful in debugging)   
         {
	   end_trial();         // local function to stop recording
	   return SKIP_TRIAL;   // return this code if trial terminated
         }

		/* BUTTON RESPONSE TEST */
		// Check for eye-tracker buttons pressed
		// This is the preferred way to get response data or end trials	
      button = eyelink_last_button_press(NULL);
      if(button!=0)       // button number, or 0 if none pressed
	{
	   eyemsg_printf("ENDBUTTON %d", button);  // message to log the button press
	   end_trial();                            // local function to stop recording
	   break;                                  // exit trial loop
	 }
  
                // NEW CODE FOR GAZE CONTINGENT WINDOW 
  
      if(eyelink_newest_float_sample(NULL)>0)  // check for new sample update
	{
	  eyelink_newest_float_sample(&evt);   // get the sample 
          x = evt.fs.gx[eye_used];    // yes: get gaze position from sample 
	  y = evt.fs.gy[eye_used];
	  if(x!=MISSING_DATA && 
             y!=MISSING_DATA &&
	     evt.fs.pa[eye_used]>0)     // make sure pupil is present
            {
              if(first_display)  // mark display start AFTER first drawing of window
                {       
                  wait_for_video_refresh();	  // synchronize before drawing so all seen at once
                  drawing_time = current_msec();  // time of retrace
                  trial_start = drawing_time;   // record the display onset time 
                }
	      redraw_gc_window((int)x, (int)y);  // move window if visible
              if(first_display)  // mark display start AFTER first drawing of window
                {       
                  first_display = 0;      
                  drawing_time = current_msec() - drawing_time; // delay from retrace
                  eyemsg_printf("%d DISPLAY ON", drawing_time);	// message for RT recording in analysis 
                  eyemsg_printf("SYNCTIME %d", drawing_time);	// message marks zero-plot time for EDFVIEW 
                }
            }
	  else
            {
	        // Don't move window during blink
                // To hide window, use:   redraw_gc_window(MISSING, MISSING);
            }
        } 
    }                       // END OF RECORDING LOOP

  end_realtime_mode();      // safety cleanup code
  while(getkey());          // dump any accumulated key presses

			   // report response result: 0=timeout, else button number
  eyemsg_printf("TRIAL_RESULT %d", button);
			   // Call this at the end of the trial, to handle special conditions
  return check_record_exit();
}
Esempio n. 15
0
File: rec.c Progetto: oliv3/phaspa
int
main(int argc, char **argv) {
    char     *buf = NULL;
    uint32_t size = BUF_SIZE;
    char     command[MAXATOMLEN];
    int      index, version;

    if ((buf = (char *)calloc(size, sizeof(char))) == NULL)
        return -1;

    while (read_cmd(buf, &size) > 0) {
        /* Reset the index, so that ei functions can decode terms from the
         * beginning of the buffer */
        index = 0;

        // D("buf: %s", buf);

        /* Ensure that we are receiving the binary term by reading and
         * stripping the version byte */
        check(ei_decode_version(buf, &index, &version));

        /* Ici donc le code du recorder:
         *
         * if decode_atom => stop:
         *   arreter le thread -> ok, {error, not_started} sinon
         * else
         * if decode tuple de taille 2:
         *   starter le thread -> ok, {error, already_started} sinon
         */
        if (!ei_decode_atom(buf, &index, command)) {
            // D("Got atom: %s", command);
            if (!strcmp(command, "stop")) {
                if (recording)
                    stop_recording();
                else
                    ok();
            } else
                check(-1);
        } else {
            int arity;
            // long _span;

            check(ei_decode_tuple_header(buf, &index, &arity));
            // D("Arity: %d", arity);
            if (arity != 2) check(-1);

            check(ei_decode_atom(buf, &index, command));
            // D("Got atom: %s", command);
            if (strcmp(command, "record")) check(-1);

            check(ei_decode_long(buf, &index, &frequency));
            // D("Freq: %li", frequency);

            /* check(ei_decode_long(buf, &index, &_span)); */
            /* span = _span; */
            /* D("SPAN: %i", span); */

            if (!recording) {
                start_recording();
            } else
                error();
        }

        memset(buf, 0, size*sizeof(char));
    }

    free(buf);

    return 0;
}
Esempio n. 16
0
// seg000:04CD
int __pascal far process_key() {
	char sprintf_temp[80];
	int key;
	const char* answer_text;
	word need_show_text;
	need_show_text = 0;
	key = key_test_quit();

	if (start_level == 0) {
		if (key || control_shift) {
			#ifdef USE_QUICKSAVE
			if (key == SDL_SCANCODE_F9) need_quick_load = 1;
			#endif
			#ifdef USE_REPLAY
			if (key == SDL_SCANCODE_TAB) {
				start_replay();
			}
			else
			#endif
			if (key == (SDL_SCANCODE_L | WITH_CTRL)) { // ctrl-L
				if (!load_game()) return 0;
			} else {
				start_level = 1;
			}
			draw_rect(&screen_rect, 0);
#ifdef USE_FADE
			if (is_global_fading) {
				fade_palette_buffer->proc_restore_free(fade_palette_buffer);
				is_global_fading = 0;
			}
#endif
			start_game();
		}
	}
	// If the Kid died, enter or shift will restart the level.
	if (rem_min != 0 && Kid.alive > 6 && (control_shift || key == SDL_SCANCODE_RETURN)) {
		key = SDL_SCANCODE_A | WITH_CTRL; // ctrl-a
	}
#ifdef USE_REPLAY
	if (recording) key_press_while_recording(&key);
	else if (replaying) key_press_while_replaying(&key);
#endif
	if (key == 0) return 0;
	if (is_keyboard_mode) clear_kbd_buf();

	switch(key) {
		case SDL_SCANCODE_ESCAPE: // esc
		case SDL_SCANCODE_ESCAPE | WITH_SHIFT: // allow pause while grabbing
			is_paused = 1;
		break;
		case SDL_SCANCODE_SPACE: // space
			is_show_time = 1;
		break;
		case SDL_SCANCODE_A | WITH_CTRL: // ctrl-a
			if (current_level != 15) {
				stop_sounds();
				is_restart_level = 1;
			}
		break;
		case SDL_SCANCODE_G | WITH_CTRL: // ctrl-g
			// CusPoP: first and last level where saving is allowed
//			if (current_level > 2 && current_level < 14) { // original
			if (current_level >= saving_allowed_first_level && current_level <= saving_allowed_last_level) {
				save_game();
			}
		break;
		case SDL_SCANCODE_J | WITH_CTRL: // ctrl-j
			if ((sound_flags & sfDigi) && sound_mode == smTandy) {
				answer_text = "JOYSTICK UNAVAILABLE";
			} else {
				if (set_joy_mode()) {
					answer_text = "JOYSTICK MODE";
				} else {
					answer_text = "JOYSTICK NOT FOUND";
				}
			}
			need_show_text = 1;
		break;
		case SDL_SCANCODE_K | WITH_CTRL: // ctrl-k
			answer_text = "KEYBOARD MODE";
			is_joyst_mode = 0;
			is_keyboard_mode = 1;
			need_show_text = 1;
		break;
		case SDL_SCANCODE_R | WITH_CTRL: // ctrl-r
			start_level = 0;
			start_game();
		break;
		case SDL_SCANCODE_S | WITH_CTRL: // ctrl-s
			turn_sound_on_off((!is_sound_on) * 15);
			answer_text = "SOUND OFF";
			if (is_sound_on) {
				answer_text = "SOUND ON";
			}
			//
			need_show_text = 1;
		break;
		case SDL_SCANCODE_V | WITH_CTRL: // ctrl-v
			answer_text = "PRINCE OF PERSIA  V1.0";
			need_show_text = 1;
		break;
		case SDL_SCANCODE_L | WITH_SHIFT: // shift-l
			if (current_level <= 3 || cheats_enabled) {
				// if shift is not released within the delay, the cutscene is skipped
				Uint32 delay = 250;
				key_states[SDL_SCANCODE_LSHIFT] = 0;
				key_states[SDL_SCANCODE_RSHIFT] = 0;
				SDL_TimerID timer;
				timer = SDL_AddTimer(delay, temp_shift_release_callback, NULL);
				if (timer == 0) {
					sdlperror("SDL_AddTimer");
					quit(1);
				}
				if (current_level == 14) {
					next_level = 1;
				} else {
					if (current_level == 15 && cheats_enabled) {
#ifdef USE_COPYPROT
                        if (options.enable_copyprot) {
                        	next_level = copyprot_level;
                        	copyprot_level = -1;
                        }
#endif
					} else {
						next_level = current_level + 1;
						if (!cheats_enabled && rem_min > 15) {
							rem_min = 15;
							rem_tick = 719;
						}
					}
				}
				stop_sounds();
			}
		break;
#ifdef USE_QUICKSAVE
		case SDL_SCANCODE_F6:
		case SDL_SCANCODE_F6 | WITH_SHIFT:
			if (Kid.alive < 0) need_quick_save = 1;
		break;
		case SDL_SCANCODE_F9:
		case SDL_SCANCODE_F9 | WITH_SHIFT:
			need_quick_load = 1;
		break;
#ifdef USE_REPLAY
		case SDL_SCANCODE_TAB | WITH_CTRL:
		case SDL_SCANCODE_TAB | WITH_CTRL | WITH_SHIFT:
			if (recording) { // finished recording
				stop_recording();
			}
			else { // should start recording
				start_recording();
			}
			break;
#endif // USE_RECORD_REPLAY
#endif // USE_QUICKSAVE
	}
	if (cheats_enabled) {
		switch (key) {
			case SDL_SCANCODE_C: // c
				snprintf(sprintf_temp, sizeof(sprintf_temp), "S%d L%d R%d A%d B%d", drawn_room, room_L, room_R, room_A, room_B);
				answer_text = /*&*/sprintf_temp;
				need_show_text = 1;
			break;
			case SDL_SCANCODE_C | WITH_SHIFT: // shift-c
				snprintf(sprintf_temp, sizeof(sprintf_temp), "AL%d AR%d BL%d BR%d", room_AL, room_AR, room_BL, room_BR);
				answer_text = /*&*/sprintf_temp;
				need_show_text = 1;
			break;
			case SDL_SCANCODE_MINUS:
			case SDL_SCANCODE_KP_MINUS:		// '-' --> subtract time cheat
				if (rem_min > 1) --rem_min;
				text_time_total = 0;
				text_time_remaining = 0;
				is_show_time = 1;
			break;
			case SDL_SCANCODE_EQUALS | WITH_SHIFT: // '+'
			case SDL_SCANCODE_KP_PLUS:	   // '+' --> add time cheat
				++rem_min;
				text_time_total = 0;
				text_time_remaining = 0;
				is_show_time = 1;
			break;
			case SDL_SCANCODE_R: // R --> revive kid cheat
				if (Kid.alive > 0) {
					resurrect_time = 20;
					Kid.alive = -1;
					erase_bottom_text(1);
				}
			break;
			case SDL_SCANCODE_K: // K --> kill guard cheat
				guardhp_delta = -guardhp_curr;
				Guard.alive = 0;
			break;
			case SDL_SCANCODE_I | WITH_SHIFT: // shift+I --> invert cheat
				toggle_upside();
			break;
			case SDL_SCANCODE_W | WITH_SHIFT: // shift+W --> feather fall cheat
				feather_fall();
			break;
			case SDL_SCANCODE_H: // H --> view room to the left
				draw_guard_hp(0, 10);
				next_room = room_L;
			break;
			case SDL_SCANCODE_J: // J --> view room to the right
				draw_guard_hp(0, 10);
				next_room = room_R;
			break;
			case SDL_SCANCODE_U: // U --> view room above
				draw_guard_hp(0, 10);
				next_room = room_A;
			break;
			case SDL_SCANCODE_N: // N --> view room below
				draw_guard_hp(0, 10);
				next_room = room_B;
			break;
			case SDL_SCANCODE_B | WITH_SHIFT: // shift-b
				is_blind_mode = !is_blind_mode;
				if (is_blind_mode) {
					draw_rect(&rect_top, 0);
				} else {
					need_full_redraw = 1;
				}
			break;
			case SDL_SCANCODE_S | WITH_SHIFT: // shift-s
				if (hitp_curr != hitp_max) {
					play_sound(sound_33_small_potion); // small potion (cheat)
					hitp_delta = 1;
					flash_color = 4; // red
					flash_time = 2;
				}
			break;
			case SDL_SCANCODE_T | WITH_SHIFT: // shift-t
				play_sound(sound_30_big_potion); // big potion (cheat)
				flash_color = 4; // red
				flash_time = 4;
				add_life();
			break;
			#ifdef USE_DEBUG_CHEATS
			case SDL_SCANCODE_T:
				printf("Remaining minutes: %d\tticks:%d\n", rem_min, rem_tick);
				snprintf(sprintf_temp, sizeof(sprintf_temp), "M:%d S:%d T:%d", rem_min, rem_tick / 12, rem_tick);
				answer_text = sprintf_temp;
				need_show_text = 1;
			break;
			#endif
		}
	}

	if (need_show_text) {
		display_text_bottom(answer_text);
		text_time_total = 24;
		text_time_remaining = 24;
	}
	return 1;
}