Exemplo n.º 1
0
int
PL_w32_wrap_ansi_console(void)
{ HANDLE hIn    = GetStdHandle(STD_INPUT_HANDLE);
  HANDLE hOut   = GetStdHandle(STD_OUTPUT_HANDLE);
  HANDLE hError = GetStdHandle(STD_ERROR_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO info;

  if ( hIn    == INVALID_HANDLE_VALUE ||
       hOut   == INVALID_HANDLE_VALUE ||
       hError == INVALID_HANDLE_VALUE ||
       !GetConsoleScreenBufferInfo(hOut, &info) )
    return FALSE;

  saved_functions       = Sinput->functions;
  con_functions	        = *Sinput->functions;
  con_functions.read    = Sread_win32_console;
  con_functions.write   = write_ansi;
  con_functions.close   = close_ansi;
  con_functions.control = control_ansi;
  con_functions.seek    = NULL;

  wrap_console(hIn,    Sinput,  &con_functions);
  wrap_console(hOut,   Soutput, &con_functions);
  wrap_console(hError, Serror,  &con_functions);

  init_output(Soutput->handle, &info);
  init_output(Serror->handle, &info);

  PL_set_prolog_flag("tty_control", PL_BOOL, TRUE);
  return TRUE;
}
Exemplo n.º 2
0
int main(void)
{	
  SysTick_Config(SystemCoreClock/1000);
	STM_EVAL_LEDInit(LED3); // Oranzova
	STM_EVAL_LEDInit(LED4); // Zelena
	STM_EVAL_LEDInit(LED5); // Cervena
	STM_EVAL_LEDInit(LED6); // Modra
	
	STM_EVAL_LEDOn(LEDG);
	Delay(1000);
	STM_EVAL_LEDOff(LEDG);
	
	Init_Measure();
	Init_Comunication();
	init_output();
	timer_init();
	
	STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI);
	
	USART_SendString(USART6, "\nSwitching Power Source Welcome\n");
  while(1)
  {
		if((Time-Last_Blink > 75) && output){
			STM_EVAL_LEDToggle(LEDB);
			Last_Blink=Time;
		}else if(Time-Last_Blink > 75){
			STM_EVAL_LEDOn(LEDB);
		}

		loop++;
		f = loop/(Time/1000);
  }
}
Exemplo n.º 3
0
int video_combine(char* filelist[],int fileCnt)
{
	char* outfilename=filelist[fileCnt-1];
	videoFile outVideo;
	videoFile inVideo;
	open_video(filelist[1],&inVideo);
	avformat_alloc_output_context2(&(outVideo.pFormatCtx), NULL, NULL, outfilename);
	AVFormatContext* pFormatCtx=outVideo.pFormatCtx;
	init_output(&inVideo,outfilename,&outVideo);
	av_dump_format(outVideo.pFormatCtx,0,outfilename,1);
    if (avio_open(&(pFormatCtx->pb),outfilename, AVIO_FLAG_READ_WRITE) < 0)  
    {  
        printf("输出文件打开失败");
        return -1; 
    }
	
	if(avformat_write_header(pFormatCtx,NULL)<0){fprintf(stderr,"写入文件头失败\n");return -1;}
	
	int i=0;
	for(i=1;i<fileCnt-1;i++)
	{	
		open_video(filelist[i],&inVideo);
		write_video2(&inVideo,&outVideo);
	}
	
	if(av_write_trailer(pFormatCtx)!=0){ERROR("写入文件尾失败\n");}
	avio_close(pFormatCtx->pb);
	avformat_free_context(pFormatCtx);
	return 0;
}
Exemplo n.º 4
0
static void
raw_callback(unsigned num, rgba *pixels) {
  if( libpng == NULL ) {
    init_output() ;
  }
  png_write_row(libpng,(png_bytep)pixels);
  xcffree(pixels);
}
Exemplo n.º 5
0
static int ca0110_init(struct hda_codec *codec)
{
	struct ca0110_spec *spec = codec->spec;
	struct auto_pin_cfg *cfg = &spec->autocfg;
	int i;

	for (i = 0; i < spec->multiout.num_dacs; i++)
		init_output(codec, spec->out_pins[i],
			    spec->multiout.dac_nids[i]);
	init_output(codec, cfg->hp_pins[0], spec->hp_dac);
	init_output(codec, cfg->dig_out_pins[0], spec->dig_out);

	for (i = 0; i < spec->num_inputs; i++)
		init_input(codec, spec->input_pins[i], spec->adcs[i]);
	init_input(codec, cfg->dig_in_pin, spec->dig_in);
	return 0;
}
Exemplo n.º 6
0
void column::start()
{
    assert(out == 0);
    if (!the_output)
        init_output();
    assert(the_output != 0);
    out = the_output;
    the_output = this;
}
Exemplo n.º 7
0
int main(int argc, char **argv)
{
  int g,rep;
  int i=0;
  int repCount = 10;
  double dutyCycle = 0.50;
  time_t waitTime = 1000000*30; // Default 30ms per blink

  // Wait time in ms
  if (argc > 1) waitTime=atoi( argv[1] )*1000;
  // number of reps
  if (argc > 2) repCount=atoi( argv[2] );
  // pulse width duty cycle
  if (argc > 3) dutyCycle=(double)(atoi(argv[3])/100.0);

  if (dutyCycle > 1.0) dutyCycle = 1.0;
  if (dutyCycle < 0.0) dutyCycle = 0.0;

  // Set up gpi pointer for direct register access
  setup_io();

  struct timespec waitStruct;
  waitStruct.tv_sec = 0;
  waitStruct.tv_nsec = (time_t)(waitTime*dutyCycle);

  struct timespec waitStructLo;
  waitStructLo.tv_sec = 0;
  waitStructLo.tv_nsec = (time_t)(waitTime*(1.0-dutyCycle));

  for (i=0;i<nPins;i++)
  {
    //INP_GPIO( pins[i] ); // must use INP_GPIO before we can use OUT_GPIO
    //OUT_GPIO( pins[i] );
    init_output( pins[i] );
  }

  for (rep=0; rep<repCount; rep++)
  {
    for (i = 0; i < nPins; i++)
    {
        SET_PIN( pins[i] );
    }
    nanosleep(&waitStruct, NULL);
    for (i = 0; i < nPins; i++)
    {
        CLR_PIN( pins[i] );
    }
    nanosleep(&waitStructLo,NULL);
  }

  GPIO_CLR = 1<<pins[0] | 1<<pins[1] | 1<<pins[2];

  return 0;

} // main
Exemplo n.º 8
0
int main(int argc, const char *argv[]) {

    if (argc != 3) {
        fprintf(stderr, "Usage: %s source_file_name reserved_word_file_name\n", argv[0]);
        exit(1);
    }

    /* argv[1] is filename, argv[2] is reserved_word_file */
    init_lexer(argv[1]);
    init_reserved_words(argv[2]);
    init_output(argv[1]);

    DEBUG_PRINT(("PARSING\n"));
    return parse();
}
Exemplo n.º 9
0
void		THIS::sendServer(std::shared_ptr<neb::fnd::net::msg::Base> m)
{
	assert(m);

	/** @todo wtf */
	gal::stl::wrapper<T> wrapper(std::move(m));
	
	auto buffer = S_MSG(new gal::net::message);
	buffer->init_output();

	/** @todo boost serial warning */
	*buffer->get_oar() << wrapper;

	sendServer(buffer);
}
Exemplo n.º 10
0
// Returns non-zero if it sprung a top-of-page trap.
// The optional parameter is for the .trunc register.
int top_level_diversion::begin_page(vunits n)
{
  if (exit_started) {
    if (page_count == last_page_count
	? curenv->is_empty()
	: (done_end_macro && (seen_last_page_ejector || began_page_in_end_macro)))
      cleanup_and_exit(0);
    if (!done_end_macro)
      began_page_in_end_macro = 1;
  }
  if (last_page_number > 0 && page_number == last_page_number)
    cleanup_and_exit(0);
  if (!the_output)
    init_output();
  ++page_count;
  if (have_next_page_number) {
    page_number = next_page_number;
    have_next_page_number = 0;
  }
  else if (before_first_page == 1)
    page_number = 1;
  else
    page_number++;
  // spring the top of page trap if there is one
  vunits next_trap_pos;
  vertical_position = -vresolution;
  trap *next_trap = find_next_trap(&next_trap_pos);
  vertical_position = V0;
  high_water_mark = V0;
  ejecting_page = 0;
  // If before_first_page was 2, then the top of page transition was undone
  // using eg .nr nl 0-1.  See nl_reg::set_value.
  if (before_first_page != 2)
    the_output->begin_page(page_number, page_length);
  before_first_page = 0;
  nl_reg_contents = vertical_position.to_units();
  if (vertical_position_traps_flag && next_trap != 0 && next_trap_pos == V0) {
    truncated_space = n;
    spring_trap(next_trap->nm);
    return 1;
  }
  else
    return 0;
}
Exemplo n.º 11
0
/**
 *
 * @brief Perform all selected benchmarks
 *
 * @return N/A
 */
void main(void)
{
	int	    continuously = 0;
	int	    test_result;

	init_output(&continuously);
	bench_test_init();

	do {
		fprintf(output_file, sz_module_title_fmt,
			"Nanokernel API test");
		fprintf(output_file, sz_kernel_ver_fmt,
			sys_kernel_version_get());
		fprintf(output_file,
			"\n\nEach test below is repeated %d times;\n"
			"average time for one iteration is displayed.",
			NUMBER_OF_LOOPS);

		test_result = 0;

		test_result += sema_test();
		test_result += lifo_test();
		test_result += fifo_test();
		test_result += stack_test();

		if (test_result) {
			/* sema/lifo/fifo/stack account for 12 tests in total */
			if (test_result == 12) {
				fprintf(output_file, sz_module_result_fmt,
					sz_success);
			} else {
				fprintf(output_file, sz_module_result_fmt,
					sz_partial);
			}
		} else {
			fprintf(output_file, sz_module_result_fmt, sz_fail);
		}
		TC_PRINT_RUNID;

	} while (continuously && !kbhit());

	output_close();
}
Exemplo n.º 12
0
void x86_kernel_main(struct multiboot *multiboot)
{
	init_output();
	init_paging(multiboot);
	init_acpi();
	init_descriptor_tables();

	kprint("Stack pointer: ");
	kprint_hexnl(read_esp());
	kprint("Mod count: ");
	kprint_hexnl(multiboot->mods_count);
	kprint("Kernel phys end : ");
	kprint_hexnl((u32)&__phys_end);
	kprint("Mod addr start : ");
	kprint_hexnl(*(u32*)(phys_to_virt(multiboot->mods_addr)));
	kprint("Mod addr end : ");
	kprint_hexnl(*(u32*)(phys_to_virt(multiboot->mods_addr) + 4));

	//init_tasking();

	kernel_main();

	if (multiboot->mods_count == 13) {
		kprint("Executing module..\n");

		typedef void (*module_fun)(void);

		u32 modaddr = phys_to_virt(multiboot->mods_addr);
		modaddr = phys_to_virt(*(u32*)modaddr);

		//kprint_hexnl(modaddr);
		//kprint_hexnl(*(u32*)modaddr);

		module_fun module = (module_fun)modaddr;

		module();
		kprint("Modadr is ");

	}
}
Exemplo n.º 13
0
/**
 *
 * @brief Perform all selected benchmarks
 * see config.h to select or to unselect
 *
 * @return N/A
 */
void BenchTask(void)
{
	int autorun = 0, continuously = 0;

	init_output(&continuously, &autorun);
	bench_test_init();

	PRINT_STRING(newline, output_file);
	do {
		PRINT_STRING(dashline, output_file);
		PRINT_STRING("|          S I M P L E   S E R V I C E    "
					 "M E A S U R E M E N T S  |  nsec    |\n",
					 output_file);
		PRINT_STRING(dashline, output_file);
		task_start(RECVTASK);
		call_test();
		queue_test();
		sema_test();
		mutex_test();
		memorymap_test();
		mempool_test();
		event_test();
		mailbox_test();
		pipe_test();
		PRINT_STRING("|         END OF TESTS                     "
					 "                                   |\n",
					 output_file);
		PRINT_STRING(dashline, output_file);
		PRINT_STRING("PROJECT EXECUTION SUCCESSFUL\n",output_file);
	} while (continuously && !kbhit());

	WAIT_FOR_USER();

	if (autorun) {
		task_sleep(SECONDS(2));
	}

	output_close();
}
Exemplo n.º 14
0
/*视频合成主调用*/
int video_combine2(char* filelist[],int fileCnt)
{
	char* outfilename=filelist[fileCnt-1];
	videoFile outVideo;
	videoFile inVideo;
	open_video(filelist[1],&inVideo);
	avformat_alloc_output_context2(&(outVideo.pFormatCtx), NULL, NULL, outfilename);
	AVFormatContext* pFormatCtx=outVideo.pFormatCtx;
	init_output(&inVideo,outfilename,&outVideo);
	av_dump_format(outVideo.pFormatCtx,0,outfilename,1);
    if (avio_open(&(pFormatCtx->pb),outfilename, AVIO_FLAG_READ_WRITE) < 0)  
    {  
        printf("输出文件打开失败");
        return -1; 
    }
	
	if(avformat_write_header(pFormatCtx,NULL)<0){ERROR("写入文件尾失败");}
	AVFrame* frameArr[10000];
	int index[10]={0};
	int i=0;
	for(i=1;i<fileCnt-1;i++)
	{	
		open_video(filelist[i],&inVideo);
		//printf("%d\n",read_video(&inVideo,frameArr,index[i-1]));
		if(i==1){index[i]=read_video(&inVideo,frameArr,0)-1;}
		else{index[i]=read_video(&inVideo,frameArr,index[i-1]+1)+index[i-1];}
	}
	//STOP;
	//printf("%d %d %d %d\n",index[0],index[1],index[2],index[3]);
	
	write_video3(&outVideo,&inVideo,frameArr,index,fileCnt-2);
	
	if(av_write_trailer(pFormatCtx)!=0){ERROR("写入文件尾失败");}
	avio_close(pFormatCtx->pb);
	avformat_free_context(pFormatCtx);
}
Exemplo n.º 15
0
int main(void)
{
    /* Voyant ON */
    DDRD |= (1<<DDD7);
    PORTD |= (1<<PD7);

    /* Voyant POWER */
    DDRB |= (1<<DDB3);
    PORTB |= (1<<PB3);
    TCCR2 = (0<<FOC2)|(1<<WGM20)|(1<<COM21)|(0<<COM20)|(1<<WGM21)|(0<<CS22)|(0<<CS21)|(1<<CS20);
    OCR2=0;


    init_uart();
    init_output();

    a2dInit(); // init analog to digital converter

//	pos=0x00; // MIN
    pos=0x7F; // MED
//	pos=0xFF; // MAX

    while (1)
    {
        //pos=a2dConvert8bit(0);
        //pos=a2dConvert8bit(0);
        pos=a2dConvert10bit(0);
        //OCR1A=(pos<<2) + MIN_WIDTH; // 1000 approx 1024
        //OCR1A=((((double) pos)*1000.0)/255.0) + MIN_WIDTH;
        OCR1A=((((double) pos)*1000.0)/1023.0) + MIN_WIDTH;
        OCR2=pos>>2; /* voyant POWER */
        rprintf("Testeur de servo en cours...Sebastien CELLES... %d\r\n",OCR2);
    };

    return 0;
}
Exemplo n.º 16
0
int main(int sys_argc, char ** sys_argv)
{
	int result;
	char end_of_files = FALSE;
	long parr;
	char *fname;
	int libpar = 0;
	mpg123_pars *mp;
#if !defined(WIN32) && !defined(GENERIC)
	struct timeval start_time;
#endif
	aux_out = stdout; /* Need to initialize here because stdout is not a constant?! */
#if defined (WANT_WIN32_UNICODE)
	if(win32_cmdline_utf8(&argc, &argv) != 0)
	{
		error("Cannot convert command line to UTF8!");
		safe_exit(76);
	}
#else
	argv = sys_argv;
	argc = sys_argc;
#endif
#if defined (WANT_WIN32_SOCKETS)
	win32_net_init();
#endif

	/* Extract binary and path, take stuff before/after last / or \ . */
	if((prgName = strrchr(argv[0], '/')) || (prgName = strrchr(argv[0], '\\')))
	{
		/* There is some explicit path. */
		prgName[0] = 0; /* End byte for path. */
		prgName++;
		binpath = argv[0];
	}
	else
	{
		prgName = argv[0]; /* No path separators there. */
		binpath = NULL; /* No path at all. */
	}

	/* Need to initialize mpg123 lib here for default parameter values. */

	result = mpg123_init();
	if(result != MPG123_OK)
	{
		error1("Cannot initialize mpg123 library: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	cleanup_mpg123 = TRUE;

	mp = mpg123_new_pars(&result); /* This may get leaked on premature exit(), which is mainly a cosmetic issue... */
	if(mp == NULL)
	{
		error1("Crap! Cannot get mpg123 parameters: %s", mpg123_plain_strerror(result));
		safe_exit(78);
	}

	/* get default values */
	mpg123_getpar(mp, MPG123_DOWN_SAMPLE, &parr, NULL);
	param.down_sample = (int) parr;
	mpg123_getpar(mp, MPG123_RVA, &param.rva, NULL);
	mpg123_getpar(mp, MPG123_DOWNSPEED, &param.halfspeed, NULL);
	mpg123_getpar(mp, MPG123_UPSPEED, &param.doublespeed, NULL);
	mpg123_getpar(mp, MPG123_OUTSCALE, &param.outscale, NULL);
	mpg123_getpar(mp, MPG123_FLAGS, &parr, NULL);
	mpg123_getpar(mp, MPG123_INDEX_SIZE, &param.index_size, NULL);
	param.flags = (int) parr;
	param.flags |= MPG123_SEEKBUFFER; /* Default on, for HTTP streams. */
	mpg123_getpar(mp, MPG123_RESYNC_LIMIT, &param.resync_limit, NULL);
	mpg123_getpar(mp, MPG123_PREFRAMES, &param.preframes, NULL);

#ifdef OS2
        _wildcard(&argc,&argv);
#endif

	while ((result = getlopt(argc, argv, opts)))
	switch (result) {
		case GLO_UNKNOWN:
			fprintf (stderr, "%s: Unknown option \"%s\".\n", 
				prgName, loptarg);
			usage(1);
		case GLO_NOARG:
			fprintf (stderr, "%s: Missing argument for option \"%s\".\n",
				prgName, loptarg);
			usage(1);
	}
	/* Do this _after_ parameter parsing. */
	check_locale(); /* Check/set locale; store if it uses UTF-8. */

	if(param.list_cpu)
	{
		const char **all_dec = mpg123_decoders();
		printf("Builtin decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.test_cpu)
	{
		const char **all_dec = mpg123_supported_decoders();
		printf("Supported decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.gain != -1)
	{
	    warning("The parameter -g is deprecated and may be removed in the future.");
	}

	if (loptind >= argc && !param.listname && !param.remote) usage(1);
	/* Init audio as early as possible.
	   If there is the buffer process to be spawned, it shouldn't carry the mpg123_handle with it. */
	bufferblock = mpg123_safe_buffer(); /* Can call that before mpg123_init(), it's stateless. */
	if(init_output(&ao) < 0)
	{
		error("Failed to initialize output, goodbye.");
		mpg123_delete_pars(mp);
		return 99; /* It's safe here... nothing nasty happened yet. */
	}
	have_output = TRUE;

	/* ========================================================================================================= */
	/* Enterning the leaking zone... we start messing with stuff here that should be taken care of when leaving. */
	/* Don't just exit() or return out...                                                                        */
	/* ========================================================================================================= */

	httpdata_init(&htd);

#if !defined(WIN32) && !defined(GENERIC)
	if (param.remote)
	{
		param.verbose = 0;
		param.quiet = 1;
		param.flags |= MPG123_QUIET;
	}
#endif

	/* Set the frame parameters from command line options */
	if(param.quiet) param.flags |= MPG123_QUIET;

#ifdef OPT_3DNOW
	if(dnow != 0) param.cpu = (dnow == SET_3DNOW) ? "3dnow" : "i586";
#endif
	if(param.cpu != NULL && (!strcmp(param.cpu, "auto") || !strcmp(param.cpu, ""))) param.cpu = NULL;
	if(!(  MPG123_OK == (result = mpg123_par(mp, MPG123_VERBOSE, param.verbose, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FLAGS, param.flags, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWN_SAMPLE, param.down_sample, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RVA, param.rva, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FORCE_RATE, param.force_rate, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWNSPEED, param.halfspeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_UPSPEED, param.doublespeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_ICY_INTERVAL, 0, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RESYNC_LIMIT, param.resync_limit, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_TIMEOUT, param.timeout, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_OUTSCALE, param.outscale, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_PREFRAMES, param.preframes, 0))
			))
	{
		error2("Cannot set library parameter %i: %s", libpar, mpg123_plain_strerror(result));
		safe_exit(45);
	}
	if (!(param.listentry < 0) && !param.quiet) print_title(stderr); /* do not pollute stdout! */

	{
		long default_index;
		mpg123_getpar(mp, MPG123_INDEX_SIZE, &default_index, NULL);
		if( param.index_size != default_index && (result = mpg123_par(mp, MPG123_INDEX_SIZE, param.index_size, 0.)) != MPG123_OK )
		error1("Setting of frame index size failed: %s", mpg123_plain_strerror(result));
	}

	if(param.force_rate && param.down_sample)
	{
		error("Down sampling and fixed rate options not allowed together!");
		safe_exit(1);
	}

	/* Now actually get an mpg123_handle. */
	mh = mpg123_parnew(mp, param.cpu, &result);
	if(mh == NULL)
	{
		error1("Crap! Cannot get a mpg123 handle: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	mpg123_delete_pars(mp); /* Don't need the parameters anymore ,they're in the handle now. */

	/* Prepare stream dumping, possibly replacing mpg123 reader. */
	if(dump_open(mh) != 0) safe_exit(78);

	/* Now either check caps myself or query buffer for that. */
	audio_capabilities(ao, mh);

	load_equalizer(mh);

#ifdef HAVE_SETPRIORITY
	if(param.aggressive) { /* tst */
		int mypid = getpid();
		setpriority(PRIO_PROCESS,mypid,-20);
	}
#endif

#if defined (HAVE_SCHED_SETSCHEDULER) && !defined (__CYGWIN__) && !defined (HAVE_WINDOWS_H)
/* Cygwin --realtime seems to fail when accessing network, using win32 set priority instead */
/* MinGW may have pthread installed, we prefer win32API */
	if (param.realtime) {  /* Get real-time priority */
	  struct sched_param sp;
	  fprintf(stderr,"Getting real-time priority\n");
	  memset(&sp, 0, sizeof(struct sched_param));
	  sp.sched_priority = sched_get_priority_min(SCHED_FIFO);
	  if (sched_setscheduler(0, SCHED_RR, &sp) == -1)
	    fprintf(stderr,"Can't get real-time priority\n");
	}
#endif

#ifdef HAVE_WINDOWS_H
	/* argument "3" is equivalent to realtime priority class */
	win32_set_priority( param.realtime ? 3 : param.w32_priority);
#endif

	if(!param.remote) prepare_playlist(argc, argv);

#if !defined(WIN32) && !defined(GENERIC)
	/* Remote mode is special... but normal console and terminal-controlled operation needs to catch the SIGINT.
	   For one it serves for track skip when not in terminal control mode.
	   The more important use being a graceful exit, including telling the buffer process what's going on. */
	if(!param.remote) catchsignal (SIGINT, catch_interrupt);
#endif

	if(param.remote) {
		int ret;
		ret = control_generic(mh);
		safe_exit(ret);
	}
#ifdef HAVE_TERMIOS
		debug1("param.term_ctrl: %i", param.term_ctrl);
		if(param.term_ctrl)
			term_init();
#endif
	if(APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

	while ((fname = get_next_file()))
	{
		char *dirname, *filename;
		int newdir;
		/* skip_tracks includes the previous one. */
		if(skip_tracks) --skip_tracks;
		if(skip_tracks)
		{
			debug("Skipping this track.");
			continue;
		}
		if(param.delay > 0)
		{
			/* One should enable terminal control during that sleeping phase! */
			if(param.verbose > 2) fprintf(stderr, "Note: pausing %i seconds before next track.\n", param.delay);
			output_pause(ao);
#ifdef WIN32
			Sleep(param.delay*1000);
#else
			sleep(param.delay);
#endif
			output_unpause(ao);
		}
		if(!APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

		debug1("Going to play %s", strcmp(fname, "-") ? fname : "standard input");

		if(intflag || !open_track(fname))
		{
#ifdef HAVE_TERMIOS
			/* We need the opportunity to cancel in case of --loop -1 . */
			if(param.term_ctrl) term_control(mh, ao);
#endif
			/* No wait for a second interrupt before we started playing. */
			if(intflag) break;

			continue;
		}

		if(!param.quiet) fprintf(stderr, "\n");
		if(param.index)
		{
			if(param.verbose) fprintf(stderr, "indexing...\r");
			mpg123_scan(mh);
		}
		/*
			Only trigger a seek if we do not want to start with the first frame.
			Rationale: Because of libmpg123 sample accuracy, this could cause an unnecessary backwards seek, that even may fail on non-seekable streams.
			For start frame of 0, we are already at the correct position!
		*/
		framenum = 0;
		if(param.start_frame > 0)
		framenum = mpg123_seek_frame(mh, param.start_frame, SEEK_SET);

		if(APPFLAG(MPG123APP_CONTINUE)) param.start_frame = 0;

		if(framenum < 0)
		{
			error1("Initial seek failed: %s", mpg123_strerror(mh));
			if(mpg123_errcode(mh) == MPG123_BAD_OUTFORMAT)
			{
				fprintf(stderr, "%s", "So, you have trouble getting an output format... this is the matrix of currently possible formats:\n");
				print_capabilities(ao, mh);
				fprintf(stderr, "%s", "Somehow the input data and your choices don't allow one of these.\n");
			}
			mpg123_close(mh);
			continue;
		}

		/* Prinout and xterm title need this, possibly independently. */
		newdir = split_dir_file(fname ? fname : "standard input", &dirname, &filename);

		if (!param.quiet)
		{
			if(newdir) fprintf(stderr, "Directory: %s\n", dirname);

#ifdef HAVE_TERMIOS
		/* Reminder about terminal usage. */
		if(param.term_ctrl) term_hint();
#endif


			fprintf(stderr, "Playing MPEG stream %lu of %lu: %s ...\n", (unsigned long)pl.pos, (unsigned long)pl.fill, filename);
			if(htd.icy_name.fill) fprintf(stderr, "ICY-NAME: %s\n", htd.icy_name.p);
			if(htd.icy_url.fill)  fprintf(stderr, "ICY-URL: %s\n",  htd.icy_url.p);
		}
#if !defined(GENERIC)
{
	const char *term_type;
	term_type = getenv("TERM");
	if(term_type && param.xterm_title)
	{
		if(!strncmp(term_type,"xterm",5) || !strncmp(term_type,"rxvt",4))
		fprintf(stderr, "\033]0;%s\007", filename);
		else if(!strncmp(term_type,"screen",6))
		fprintf(stderr, "\033k%s\033\\", filename);
		else if(!strncmp(term_type,"iris-ansi",9))
		fprintf(stderr, "\033P1.y %s\033\\\033P3.y%s\033\\", filename, filename);

		fflush(stderr); /* Paranoia: will the buffer buffer the escapes? */
	}
}
#endif

/* Rethink that SIGINT logic... */
#if !defined(WIN32) && !defined(GENERIC)
#ifdef HAVE_TERMIOS
		if(!param.term_ctrl)
#endif
			gettimeofday (&start_time, NULL);
#endif

		while(!intflag)
		{
			int meta;
			if(param.frame_number > -1)
			{
				debug1("frames left: %li", (long) frames_left);
				if(!frames_left)
				{
					if(APPFLAG(MPG123APP_CONTINUE)) end_of_files = TRUE;

					break;
				}
			}
			if(!play_frame()) break;
			if(!param.quiet)
			{
				meta = mpg123_meta_check(mh);
				if(meta & (MPG123_NEW_ID3|MPG123_NEW_ICY))
				{
					if(meta & MPG123_NEW_ID3) print_id3_tag(mh, param.long_id3, stderr);
					if(meta & MPG123_NEW_ICY) print_icy(mh, stderr);

					mpg123_meta_free(mh); /* Do not waste memory after delivering. */
				}
			}
			if(!fresh && param.verbose)
			{
#ifndef NOXFERMEM
				if (param.verbose > 1 || !(framenum & 0x7))
					print_stat(mh,0,xfermem_get_usedspace(buffermem)); 
#else
				if(param.verbose > 1 || !(framenum & 0x7))	print_stat(mh,0,0);
#endif
			}
#ifdef HAVE_TERMIOS
			if(!param.term_ctrl) continue;
			else term_control(mh, ao);
#endif
		}

	if(!param.smooth && param.usebuffer) buffer_drain();
	if(param.verbose) print_stat(mh,0,xfermem_get_usedspace(buffermem)); 

	if(!param.quiet)
	{
		double secs;
		long frank;
		fprintf(stderr, "\n");
		if(mpg123_getstate(mh, MPG123_FRANKENSTEIN, &frank, NULL) == MPG123_OK && frank)
		fprintf(stderr, "This was a Frankenstein track.\n");

		mpg123_position(mh, 0, 0, NULL, NULL, &secs, NULL);
		fprintf(stderr,"[%d:%02d] Decoding of %s finished.\n", (int)(secs / 60), ((int)secs) % 60, filename);
	}
	else if(param.verbose) fprintf(stderr, "\n");

	mpg123_close(mh);

	if (intflag)
	{
		if(!skip_or_die(&start_time)) break;

        intflag = FALSE;

#ifndef NOXFERMEM
        if(!param.smooth && param.usebuffer) buffer_resync();
#endif
	}

		if(end_of_files) break;
	} /* end of loop over input files */

	/* Ensure we played everything. */
	if(param.smooth && param.usebuffer)
	{
		buffer_drain();
		buffer_resync();
	}

	if(APPFLAG(MPG123APP_CONTINUE))
	{
		continue_msg("CONTINUE");
	}

	/* Free up memory used by playlist */    
	if(!param.remote) free_playlist();

	safe_exit(0); /* That closes output and restores terminal, too. */
	return 0;
}
Exemplo n.º 17
0
/** main function
 */
int main(void) {
    init_output();
    init_pwm();

#if SERIAL_UART
    init_uart();
#endif

#if RC5_DECODER
    init_rc5();
#endif

#if I2C
    init_i2c();
#endif

    global_pwm.channels[0].brightness = 50;
    global_pwm.channels[0].target_brightness = 50;

#if STATIC_SCRIPTS
    init_script_threads();

    #if RS485_CTRL == 0
    /* start the example scripts */
    script_threads[0].handler.execute = &memory_handler_flash;
    script_threads[0].handler.position = (uint16_t) &colorchange_red;
    script_threads[0].flags.disabled = 0;

    //script_threads[1].handler.execute = &memory_handler_flash;
    //script_threads[1].handler.position = (uint16_t) &testscript_flash2;
    //script_threads[1].flags.disabled = 0;
    //
    //script_threads[2].handler.execute = &memory_handler_eeprom;
    //script_threads[2].handler.position = (uint16_t) &testscript_eeprom;
    //script_threads[2].flags.disabled = 0;

    //script_threads[0].handler.execute = &memory_handler_flash;
    //script_threads[0].handler.position = (uint16_t) &blinken;
    //script_threads[0].flags.disabled = 0;
    #endif

#endif

#if I2C_MASTER
    i2c_global.send_messages[0].command.size = 4;
    i2c_global.send_messages[0].command.code = COMMAND_SET_COLOR;
    i2c_global.send_messages[0].command.set_color_parameters.colors[0] = 0x10;
    i2c_global.send_messages[0].command.set_color_parameters.colors[1] = 0x10;
    i2c_global.send_messages[0].command.set_color_parameters.colors[2] = 0x10;

    i2c_global.send_messages_count = 1;
#endif

#if RS485_CTRL
    /* init command bus */
    UCSR0A = _BV(MPCM0); /* enable multi-processor communication mode */
    UCSR0C = _BV(UCSZ00) | _BV(UCSZ01); /* 9 bit frame size */

    #define UART_UBRR 8 /* 115200 baud at 16mhz */
    UBRR0H = HIGH(UART_UBRR);
    UBRR0L = LOW(UART_UBRR);

    UCSR0B = _BV(RXEN0) | _BV(TXEN0) | _BV(UCSZ02); /* enable receiver and transmitter */
#endif

    /* enable interrupts globally */
    sei();

    while (1) {
        /* after the last pwm timeslot, rebuild the timeslot table */
        if (global.flags.last_pulse) {
            global.flags.last_pulse = 0;

            update_pwm_timeslots();
        }

        /* at the beginning of each pwm cycle, call the fading engine and
         * execute all script threads */
        if (global.flags.new_cycle) {
            global.flags.new_cycle = 0;

            update_brightness();
#if STATIC_SCRIPTS
            execute_script_threads();
#endif

            continue;
        }


#if SERIAL_UART
        /* check if we received something via uart */
        if (fifo_fill(&global_uart.rx_fifo) > 0) {
            check_serial_input(fifo_load(&global_uart.rx_fifo));
            continue;
        }
#endif


#if RC5_DECODER
        /* check if we received something via ir */
        if (global_rc5.new_data) {
            static uint8_t toggle_bit = 2;

            /* if key has been pressed again */
            if (global_rc5.received_command.toggle_bit != toggle_bit) {

                /* if code is 0x01 (key '1' on a default remote) */
                if (global_rc5.received_command.code == 0x01) {

                    /* install script into thread 1 */
                    script_threads[1].handler.execute = &memory_handler_flash;
                    script_threads[1].handler.position = (uint16_t) &green_flash;
                    script_threads[1].flags.disabled = 0;
                    script_threads[1].handler_stack_offset = 0;

                }

                /* store new toggle bit state */
                toggle_bit = global_rc5.received_command.toggle_bit;

            }

            /* reset the new_data flag, so that new commands can be received */
            global_rc5.new_data = 0;

            continue;
        }
#endif

#if RS485_CTRL
        if (UCSR0A & _BV(RXC0)) {

            uint8_t address = UCSR0B & _BV(RXB80); /* read nineth bit, zero if data, one if address */
            uint8_t data = UDR0;
            static uint8_t buffer[8];
            static uint8_t fill = 0;

            if (UCSR0A & _BV(MPCM0) || address) { /* if MPCM mode is still active, or ninth bit set, this is an address packet */

                /* check if we are ment */
                if (data == 0 || data == RS485_ADDRESS) {

                    /* remove MPCM flag and reset buffer fill counter */
                    UCSR0A &= ~_BV(MPCM0);
                    fill = 0;

                    continue;

                } else {/* turn on MPCM */

                    UCSR0A |= _BV(MPCM0);
                    continue;

                }
            }

            /* else this is a data packet, put data into buffer */
            buffer[fill++] = data;

            if (buffer[0] == 0x01) {  /* soft reset */

                jump_to_bootloader();

            } else if (buffer[0] == 0x02 && fill == 4) { /* set color */

                for (uint8_t pos = 0; pos < 3; pos++) {
                    global_pwm.channels[pos].target_brightness = buffer[pos + 1];
                    global_pwm.channels[pos].brightness = buffer[pos + 1];
                }

                UCSR0A |= _BV(MPCM0); /* return to MPCM mode */

            } else if (buffer[0] == 0x03 && fill == 6) { /* fade to color */

                for (uint8_t pos = 0; pos < 3; pos++) {
                    global_pwm.channels[pos].speed_h = buffer[1];
                    global_pwm.channels[pos].speed_l = buffer[2];
                    global_pwm.channels[pos].target_brightness = buffer[pos + 3];
                }

                UCSR0A |= _BV(MPCM0); /* return to MPCM mode */
            }

        }
#endif

#if I2C_MASTER
        i2c_master_check_queue();
#endif
    }
}
Exemplo n.º 18
0
int main(int argc, char **argv) {
    char *hexaeskey = 0, *hexaesiv = 0;
    char *fmtpstr = 0;
    char *arg;
    int i;
    assert(RAND_MAX >= 0x10000);    // XXX move this to compile time
    while ( (arg = *++argv) ) {
        if (!strcasecmp(arg, "iv")) {
            hexaesiv = *++argv;
            argc--;
        } else
        if (!strcasecmp(arg, "key")) {
            hexaeskey = *++argv;
            argc--;
        } else
        if (!strcasecmp(arg, "fmtp")) {
            fmtpstr = *++argv;
        } else
        if (!strcasecmp(arg, "cport")) {
            controlport = atoi(*++argv);
        } else
        if (!strcasecmp(arg, "tport")) {
            timingport = atoi(*++argv);
        } else
        if (!strcasecmp(arg, "dport")) {
            dataport = atoi(*++argv);
        } else
        if (!strcasecmp(arg, "host")) {
            rtphost = *++argv;
        } else
        if (!strcasecmp(arg, "pipe")) {
            if (libao_driver || libao_devicename || libao_deviceid ) {
                die("Option 'pipe' may not be combined with 'ao_driver', 'ao_devicename' or 'ao_deviceid'");
            }

            pipename = *++argv;
        } else
        if (!strcasecmp(arg, "ao_driver")) {
            if (pipename) {
                die("Option 'ao_driver' may not be combined with 'pipe'");
            }

            libao_driver = *++argv;
        } else
        if (!strcasecmp(arg, "ao_devicename")) {
            if (pipename || libao_deviceid ) {
                die("Option 'ao_devicename' may not be combined with 'pipe' or 'ao_deviceid'");
            }

            libao_devicename = *++argv;
        } else
        if (!strcasecmp(arg, "ao_deviceid")) {
            if (pipename || libao_devicename) {
                die("Option 'ao_deviceid' may not be combined with 'pipe' or 'ao_devicename'");
            }

            libao_deviceid = *++argv;
        }
#ifdef FANCY_RESAMPLING
        else
        if (!strcasecmp(arg, "resamp")) {
            fancy_resampling = atoi(*++argv);
        }
#endif
    }

    if (!hexaeskey || !hexaesiv)
        die("Must supply AES key and IV!");

    if (hex2bin(aesiv, hexaesiv))
        die("can't understand IV");
    if (hex2bin(aeskey, hexaeskey))
        die("can't understand key");
    AES_set_decrypt_key(aeskey, 128, &aes);

    memset(fmtp, 0, sizeof(fmtp));
    i = 0;
    while ( (arg = strsep(&fmtpstr, " \t")) )
        fmtp[i++] = atoi(arg);

    init_decoder();
    init_buffer();
    init_rtp();      // open a UDP listen port and start a listener; decode into ring buffer
    fflush(stdout);
    init_output();              // resample and output from ring buffer

    char line[128];
    int in_line = 0;
    int n;
    double f;
    while (fgets(line + in_line, sizeof(line) - in_line, stdin)) {
        n = strlen(line);
        if (line[n-1] != '\n') {
            in_line = strlen(line) - 1;
            if (n == sizeof(line)-1)
                in_line = 0;
            continue;
        }
        if (sscanf(line, "vol: %lf\n", &f)) {
            assert(f<=0);
            if (debug)
                fprintf(stderr, "VOL: %lf\n", f);
            volume = pow(10.0,0.05*f);
            fix_volume = 65536.0 * volume;
            continue;
        }
        if (!strcmp(line, "exit\n")) {
            exit(0);
        }
        if (!strcmp(line, "flush\n")) {
            pthread_mutex_lock(&ab_mutex);
            ab_resync();
            pthread_mutex_unlock(&ab_mutex);
            if (debug)
                fprintf(stderr, "FLUSH\n");
        }
    }
    fprintf(stderr, "bye!\n");
    fflush(stderr);

    return EXIT_SUCCESS;
}
Exemplo n.º 19
0
int hairtunes_init(char *pAeskey, char *pAesiv, char *fmtpstr, int pCtrlPort, int pTimingPort,
         int pDataPort, char *pRtpHost, char*pPipeName, char *pLibaoDriver, char *pLibaoDeviceName, char *pLibaoDeviceId)
{
    if(pAeskey != NULL)    
        memcpy(aeskey, pAeskey, sizeof(aeskey));
    if(pAesiv != NULL)
        memcpy(aesiv, pAesiv, sizeof(aesiv));
    if(pRtpHost != NULL)
        rtphost = pRtpHost;
    if(pPipeName != NULL)
        pipename = pPipeName;
    if(pLibaoDriver != NULL)
        libao_driver = pLibaoDriver;
    if(pLibaoDeviceName != NULL)
        libao_devicename = pLibaoDeviceName;
    if(pLibaoDeviceId != NULL)
        libao_deviceid = pLibaoDeviceId;
    
    controlport = pCtrlPort;
    timingport = pTimingPort;
    dataport = pDataPort;

    AES_set_decrypt_key(aeskey, 128, &aes);

    memset(fmtp, 0, sizeof(fmtp));
    int i = 0;
    char *arg;
    while ( (arg = strsep(&fmtpstr, " \t")) )
        fmtp[i++] = atoi(arg);

    init_decoder();
    init_buffer();
    init_rtp();      // open a UDP listen port and start a listener; decode into ring buffer
    fflush(stdout);
    init_output();              // resample and output from ring buffer

    char line[128];
    int in_line = 0;
    int n;
    double f;
    while (fgets(line + in_line, sizeof(line) - in_line, stdin)) {
        n = strlen(line);
        if (line[n-1] != '\n') {
            in_line = strlen(line) - 1;
            if (n == sizeof(line)-1)
                in_line = 0;
            continue;
        }
        if (sscanf(line, "vol: %lf\n", &f)) {
            assert(f<=0);
            if (debug)
                fprintf(stderr, "VOL: %lf\n", f);
            volume = pow(10.0,0.05*f);
            fix_volume = 65536.0 * volume;
            continue;
        }
        if (!strcmp(line, "exit\n")) {
            exit(0);
        }
        if (!strcmp(line, "flush\n")) {
            pthread_mutex_lock(&ab_mutex);
            ab_resync();
            pthread_mutex_unlock(&ab_mutex);
            if (debug)
                fprintf(stderr, "FLUSH\n");
        }
    }
    fprintf(stderr, "bye!\n");
    fflush(stderr);

    return EXIT_SUCCESS;
}
Exemplo n.º 20
0
static void sharp_execute_job_mpi (sharp_job *job, MPI_Comm comm)
  {
  int ntasks;
  MPI_Comm_size(comm, &ntasks);
  if (ntasks==1) /* fall back to scalar implementation */
    { sharp_execute_job (job); return; }

  MPI_Barrier(comm);
  double timer=wallTime();
  job->opcnt=0;
  sharp_mpi_info minfo;
  sharp_make_mpi_info(comm, job, &minfo);

  if (minfo.npairtotal>minfo.ntasks*300)
    {
    int nsub=(minfo.npairtotal+minfo.ntasks*200-1)/(minfo.ntasks*200);
    for (int isub=0; isub<nsub; ++isub)
      {
      sharp_job ljob=*job;
      // When creating a_lm, every sub-job produces a complete set of
      // coefficients; they need to be added up.
      if ((isub>0)&&(job->type==SHARP_MAP2ALM)) ljob.flags|=SHARP_ADD;
      sharp_geom_info lginfo;
      lginfo.pair=RALLOC(sharp_ringpair,(job->ginfo->npairs/nsub)+1);
      lginfo.npairs=0;
      lginfo.nphmax = job->ginfo->nphmax;
      while (lginfo.npairs*nsub+isub<job->ginfo->npairs)
        {
        lginfo.pair[lginfo.npairs]=job->ginfo->pair[lginfo.npairs*nsub+isub];
        ++lginfo.npairs;
        }
      ljob.ginfo=&lginfo;
      sharp_execute_job_mpi (&ljob,comm);
      job->opcnt+=ljob.opcnt;
      DEALLOC(lginfo.pair);
      }
    }
  else
    {
    int lmax = job->ainfo->lmax;
    job->norm_l = sharp_Ylmgen_get_norm (lmax, job->spin);

    /* clear output arrays if requested */
    init_output (job);

    alloc_phase_mpi (job,job->ainfo->nm,job->ginfo->npairs,minfo.mmax+1,
      minfo.npairtotal);

    double *cth = RALLOC(double,minfo.npairtotal),
          *sth = RALLOC(double,minfo.npairtotal);
    int *mlim = RALLOC(int,minfo.npairtotal);
    for (int i=0; i<minfo.npairtotal; ++i)
      {
      cth[i] = cos(minfo.theta[i]);
      sth[i] = sin(minfo.theta[i]);
      mlim[i] = sharp_get_mlim(lmax, job->spin, sth[i], cth[i]);
      }

    /* map->phase where necessary */
    map2phase (job, minfo.mmax, 0, job->ginfo->npairs);

    map2alm_comm (job, &minfo);

#pragma omp parallel if ((job->flags&SHARP_NO_OPENMP)==0)
{
    sharp_job ljob = *job;
    sharp_Ylmgen_C generator;
    sharp_Ylmgen_init (&generator,lmax,minfo.mmax,ljob.spin);
    alloc_almtmp(&ljob,lmax);

#pragma omp for schedule(dynamic,1)
    for (int mi=0; mi<job->ainfo->nm; ++mi)
      {
  /* alm->alm_tmp where necessary */
      alm2almtmp (&ljob, lmax, mi);

  /* inner conversion loop */
      inner_loop (&ljob, minfo.ispair, cth, sth, 0, minfo.npairtotal,
        &generator, mi, mlim);

  /* alm_tmp->alm where necessary */
      almtmp2alm (&ljob, lmax, mi);
      }

    sharp_Ylmgen_destroy(&generator);
    dealloc_almtmp(&ljob);

#pragma omp critical
    job->opcnt+=ljob.opcnt;
} /* end of parallel region */

    alm2map_comm (job, &minfo);

  /* phase->map where necessary */
    phase2map (job, minfo.mmax, 0, job->ginfo->npairs);

    DEALLOC(mlim);
    DEALLOC(cth);
    DEALLOC(sth);
    DEALLOC(job->norm_l);
    dealloc_phase (job);
    }
  sharp_destroy_mpi_info(&minfo);
  job->time=wallTime()-timer;
  }
Exemplo n.º 21
0
int main(int argc ,char *argv[]){

	/*first ,open input file ,and obtain input file information*/
	INPUT_CONTEXT *ptr_input_ctx;

	if( (ptr_input_ctx = malloc (sizeof(INPUT_CONTEXT))) == NULL){
		printf("ptr_input_ctx malloc failed .\n");
		exit(MEMORY_MALLOC_FAIL);
	}

	/*second ,open output file ,and set output file information*/
	OUTPUT_CONTEXT *ptr_output_ctx;
	if( (ptr_output_ctx = malloc (sizeof(OUTPUT_CONTEXT))) == NULL){
		printf("ptr_output_ctx malloc failed .\n");
		exit(MEMORY_MALLOC_FAIL);
	}

	//init inputfile ,and get input file information
	init_input(ptr_input_ctx ,argv[1]);


	//init oputfile ,and set output file information
	init_output(ptr_output_ctx ,argv[2] ,ptr_input_ctx);

	//open video and audio ,set video_out_buf and audio_out_buf
	open_stream_codec(ptr_output_ctx);


    // open the output file, if needed
    if (!(ptr_output_ctx->fmt->flags & AVFMT_NOFILE)) {		//for mp4 or mpegts ,this must be performed
        if (avio_open(&ptr_output_ctx->ptr_format_ctx->pb, argv[2], AVIO_FLAG_WRITE) < 0) {
            fprintf(stderr, "Could not open '%s'\n", argv[2]);
            exit(OPEN_MUX_FILE_FAIL);
        }
    }

    // write the stream header, if any
    avformat_write_header(ptr_output_ctx->ptr_format_ctx ,NULL);

    printf("ptr_output_ctx->ptr_format_ctx->nb_streams = %d \n\n" ,ptr_output_ctx->ptr_format_ctx->nb_streams);  //streams number in output file

    ptr_output_ctx->img_convert_ctx = sws_getContext(
    		ptr_input_ctx->video_codec_ctx->width ,ptr_input_ctx->video_codec_ctx->height ,PIX_FMT_YUV420P,
    		 ptr_output_ctx->video_stream->codec->width ,ptr_output_ctx->video_stream->codec->height ,PIX_FMT_YUV420P ,
    		 SWS_BICUBIC ,NULL ,NULL ,NULL);


    printf("src_width = %d ,src_height = %d \n" ,ptr_input_ctx->video_codec_ctx->width ,ptr_input_ctx->video_codec_ctx->height);
    printf("dts_width = %d ,dts_height = %d \n" ,ptr_output_ctx->video_stream->codec->width ,
    		ptr_output_ctx->video_stream->codec->height);

//    while(1);

	printf("before av_read_frame ...\n");
	/*************************************************************************************/
	/*decoder loop*/
	//
	//
	//***********************************************************************************/
	while(av_read_frame(ptr_input_ctx->ptr_format_ctx ,&ptr_input_ctx->pkt) >= 0){

		if (ptr_input_ctx->pkt.stream_index == ptr_input_ctx->video_index) {

			#if 1

			//decode video packet
			int got_picture = 0;
			ptr_input_ctx->mark_have_frame = 0;
			avcodec_decode_video2(ptr_input_ctx->video_codec_ctx,
					ptr_input_ctx->yuv_frame, &got_picture, &ptr_input_ctx->pkt);

			if (got_picture) {
				//encode video
				ptr_output_ctx->sync_ipts = av_q2d(ptr_input_ctx->ptr_format_ctx->streams[ptr_input_ctx->video_index]->time_base) *
						(ptr_input_ctx->yuv_frame->best_effort_timestamp  )
						- (double)ptr_input_ctx->ptr_format_ctx->start_time / AV_TIME_BASE;

				//first swscale
				sws_scale(ptr_output_ctx->img_convert_ctx ,
						(const uint8_t* const*)ptr_input_ctx->yuv_frame->data ,ptr_input_ctx->yuv_frame->linesize ,
						0 ,
						ptr_input_ctx->video_codec_ctx->height ,
						ptr_output_ctx->encoded_yuv_pict->data ,ptr_output_ctx->encoded_yuv_pict->linesize);

				//second swscale
				encode_video_frame(ptr_output_ctx , ptr_output_ctx->encoded_yuv_pict ,ptr_input_ctx);
			}
			#endif

		} else if (ptr_input_ctx->pkt.stream_index == ptr_input_ctx->audio_index) {
			#if 1
			//decode audio packet
			while (ptr_input_ctx->pkt.size > 0) {
				int got_frame = 0;
				int len = avcodec_decode_audio4(ptr_input_ctx->audio_codec_ctx,
						ptr_input_ctx->audio_decode_frame, &got_frame,
						&ptr_input_ctx->pkt);

				if (len < 0) { //decode failed ,skip frame
					fprintf(stderr, "Error while decoding audio frame\n");
					break;
				}

				if (got_frame) {
					//acquire the large of the decoded audio info...
					int data_size = av_samples_get_buffer_size(NULL,
							ptr_input_ctx->audio_codec_ctx->channels,
							ptr_input_ctx->audio_decode_frame->nb_samples,
							ptr_input_ctx->audio_codec_ctx->sample_fmt, 1);
					ptr_input_ctx->audio_size = data_size; //audio data size

					//encode audio
					int frame_bytes = ptr_output_ctx->audio_stream->codec->frame_size
										* av_get_bytes_per_sample(ptr_output_ctx->audio_stream->codec->sample_fmt)
										* ptr_output_ctx->audio_stream->codec->channels;
					uint8_t * audio_buf = ptr_input_ctx->audio_decode_frame->data[0];

					while (data_size >= frame_bytes) {

						encode_audio_frame(ptr_output_ctx ,audio_buf ,frame_bytes /*data_size*/);  //
						data_size -= frame_bytes;
						audio_buf += frame_bytes;
					}

				} else { //no data
					printf("======>avcodec_decode_audio4 ,no data ..\n");
					continue;
				}

				ptr_input_ctx->pkt.size -= len;
				ptr_input_ctx->pkt.data += len;
			}
			#endif
		}

	}//endwhile


	printf("before flush ,ptr_output_ctx->ptr_format_ctx->nb_streams = %d \n\n" ,ptr_output_ctx->ptr_format_ctx->nb_streams);
	encode_flush(ptr_output_ctx ,ptr_output_ctx->ptr_format_ctx->nb_streams);

	printf("before wirite tailer ...\n\n");

	av_write_trailer(ptr_output_ctx->ptr_format_ctx );

	/*free memory*/
}
Exemplo n.º 22
0
int main (int argc, char **argv) {
    /////////////////////
    // Parse Arguments //
    /////////////////////
    params *pars = new params;
    init_pars(pars);
    parse_cmd_args(argc, argv, pars);
    if( pars->version ) {
        printf("ngsF v%s\nCompiled on %s @ %s", version, __DATE__, __TIME__);
#ifdef _USE_BGZF
        printf(" (BGZF library)\n");
#else
        printf(" (STD library)\n");
#endif

        exit(0);
    }
    if( pars->verbose >= 1 ) {
        printf("==> Input Arguments:\n");
        printf("\tglf file: %s\n\tinit_values: %s\n\tfreq_fixed: %s\n\tout file: %s\n\tn_ind: %d\n\tn_sites: %lu\n\tchunk_size: %lu\n\tfast_lkl: %s\n\tapprox_EM: %s\n\tcall_geno: %s\n\tmax_iters: %d\n\tmin_epsilon: %.10f\n\tn_threads: %d\n\tseed: %lu\n\tquick: %s\n\tversion: %s\n\tverbose: %d\n\n",
               pars->in_glf, pars->init_values, pars->freq_fixed ? "true":"false", pars->out_file, pars->n_ind, pars->n_sites, pars->max_chunk_size, pars->fast_lkl ? "true":"false", pars->approx_EM ? "true":"false", pars->call_geno ? "true":"false", pars->max_iters, pars->min_epsilon, pars->n_threads, pars->seed, pars->quick ? "true":"false", version, pars->verbose);
    }
    if( pars->verbose > 4 ) printf("==> Verbose values greater than 4 for debugging purpose only. Expect large amounts of info on screen\n");



    /////////////////////
    // Check Arguments //
    /////////////////////
    if(pars->in_glf == NULL)
        error(__FUNCTION__,"GL input file (-glf) missing!");
    else if( strcmp(pars->in_glf, "-") == 0 ) {
        pars->in_glf_type = new char[6];
        pars->in_glf_type = strcat(pars->in_glf_type, "STDIN");
    } else {
        pars->in_glf_type = strrchr(pars->in_glf, '.');
        if(pars->in_glf_type == NULL)
            error(__FUNCTION__,"invalid file type!");
    }
    if(pars->out_file == NULL)
        error(__FUNCTION__,"output file (-out) missing!");
    if(pars->n_ind == 0)
        error(__FUNCTION__,"number of individuals (-n_ind) missing!");
    if(pars->n_sites == 0)
        error(__FUNCTION__,"number of sites (-n_sites) missing!");



    ///////////////////////
    // Check input files //
    ///////////////////////
    // Get file total size
    struct stat st;
    stat(pars->in_glf, &st);
    if( strcmp(pars->in_glf_type, "STDIN") != 0 ) {
        if( pars->n_sites == st.st_size/sizeof(double)/pars->n_ind/3 && strcmp(pars->in_glf_type, ".glf") == 0 ) {
            if(pars->verbose >= 1)
                printf("==> UNCOMP input file (\"%s\"): number of sites (%lu) match expected file size\n", pars->in_glf_type, pars->n_sites);
        } else if( strcmp(pars->in_glf_type, ".glf") != 0 ) {
            if( pars->verbose >= 1)
                printf("==> COMPRESSED input file (\"%s\"): number of sites (%lu) do NOT match expected file size\n", pars->in_glf_type, pars->n_sites);
        } else
            error(__FUNCTION__,"wrong number of sites or invalid/corrupt file!");
    }


    // Adjust max_chunk_size in case of fewer sites
    if(pars->max_chunk_size > pars->n_sites) {
        if( pars->verbose >= 1 ) printf("==> Fewer sites (%lu) than chunk_size (%lu). Reducing chunk size to match number of sites\n", pars->n_sites, pars->max_chunk_size);
        pars->max_chunk_size = pars->n_sites;
    }
    // Calculate total number of chunks
    pars->n_chunks = ceil( (double) pars->n_sites/ (double) pars->max_chunk_size );
    if( pars->verbose >= 1 ) printf("==> Analysis will be run in %ld chunk(s)\n", pars->n_chunks);
    // Alocate memory for the chunk index
    pars->chunks_voffset = new int64_t[pars->n_chunks];
    memset(pars->chunks_voffset, 0, pars->n_chunks*sizeof(int64_t));
    // Adjust thread number to chunks
    if(pars->n_chunks < pars->n_threads) {
        if( pars->verbose >= 1 ) printf("==> Fewer chunks (%ld) than threads (%d). Reducing the number of threads to match number of chunks\n", pars->n_chunks, pars->n_threads);
        pars->n_threads = pars->n_chunks;
    }


    // Open input file
#ifdef _USE_BGZF
    if( pars->verbose >= 1 ) printf("==> Using BGZF I/O library\n");
    // Open BGZIP file
    if( strcmp(pars->in_glf_type, ".bgz") == 0 ) {
        if( (pars->in_glf_fh = bgzf_open(pars->in_glf, "rb")) < 0 )
            error(__FUNCTION__,"Cannot open BGZIP file!");
    } else
        error(__FUNCTION__,"BGZF library only supports BGZIP files!");

    bgzf_set_cache_size(pars->in_glf_fh, CACHE_SIZE * 1024uL * 1024uL * 1024uL);
#else

    if( pars->verbose >= 1 ) printf("==> Using native I/O library\n");
    // Open GLF file
    if( strcmp(pars->in_glf_type, "STDIN") == 0 )
        pars->in_glf_fh = stdin;
    else if( strcmp(pars->in_glf_type, ".glf") == 0 ) {
        if( (pars->in_glf_fh = fopen(pars->in_glf, "rb")) == NULL )
            error(__FUNCTION__,"Cannot open GLF file!");
    } else
        error(__FUNCTION__,"Standard library only supports UNCOMPRESSED GLF files!");

    // Allocate memory and read from the file
    pars->data = new double* [pars->n_sites];
    for(uint64_t s = 0; s < pars->n_sites; s++) {
        pars->data[s] = new double[pars->n_ind * 3];
        if( fread (pars->data[s], sizeof(double), pars->n_ind * 3, pars->in_glf_fh) != pars->n_ind * 3)
            error(__FUNCTION__,"cannot read GLF file!");
        if(pars->call_geno)
            call_geno(pars->data[s], pars->n_ind, 3);
    }
#endif
    if( pars->in_glf_fh == NULL )
        error(__FUNCTION__,"cannot open GLF file!");



    ///////////////////////////////////
    // Declare variables for results //
    ///////////////////////////////////
    out_data *output = new out_data;
    output->site_freq = new double[pars->n_sites];
    output->site_freq_num = new double[pars->n_sites];
    output->site_freq_den = new double[pars->n_sites];
    output->site_prob_var = new double[pars->n_sites];
    output->site_tmpprob_var = new double[pars->n_sites];
    output->indF = new double[pars->n_ind];
    output->indF_num = new double[pars->n_ind];
    output->indF_den = new double[pars->n_ind];
    output->ind_lkl = new double[pars->n_ind];
    // Initialize output
    init_output(pars, output);



    //////////////////
    // Analyze Data //
    //////////////////
    if( pars->verbose >= 1 && !pars->fast_lkl && strcmp("e", pars->init_values) != 0 ) {
        printf("==> Initial LogLkl: %.15f\n", full_HWE_like(pars, output->site_freq, output->indF, 0, pars->n_ind));
        fflush(stdout);
    }
    do_EM(pars, output);
    if( pars->verbose >= 1 ) printf("\nFinal logLkl: %f\n", output->global_lkl);



    //////////////////
    // Print Output //
    //////////////////
    FILE *out_file;
    if( pars->verbose >= 1 ) printf("Printing Output...\n");

    out_file = fopen(pars->out_file, "w");
    if(out_file == NULL)
        error(__FUNCTION__,"Cannot open OUTPUT file!");
    for(uint16_t i = 0; i < pars->n_ind; i++)
        fprintf(out_file,"%f\n", output->indF[i]);
    fclose(out_file);



    //////////////////////
    // Close Input File //
    //////////////////////
    if( pars->verbose >= 1 ) printf("Exiting...\n");
#ifdef _USE_BGZF
    bgzf_close(pars->in_glf_fh);
#else
    for(uint64_t s = 0; s < pars->n_sites; s++)
        delete [] pars->data[s];
    delete [] pars->data;
    fclose(pars->in_glf_fh);
#endif



    /////////////////
    // Free Memory //
    /////////////////
    delete [] output->site_freq;
    delete [] output->site_freq_num;
    delete [] output->site_freq_den;
    delete [] output->site_prob_var;
    delete [] output->indF;
    delete [] output->indF_num;
    delete [] output->indF_den;
    delete [] output->ind_lkl;
    delete output;
    //if( strcmp("e", pars->init_values) == 0 )
    //delete [] pars->init_values;
    delete [] pars->chunks_voffset;
    delete pars;

    return 0;
}
Exemplo n.º 23
0
bool CabDiag::tick(Packet* packet)
{
    // Initialize State
    if (!init)
    {
        init = true;
        press_start_to_exit = true;
        reset();

        switch (state)
        {
            case STATE_INTERFACE:
                init_interface();
                break;

            case STATE_OUTPUT:
                init_output();
                break;

            case STATE_INPUT:
                init_input();
                break;

            case STATE_CRT:
                init_crt();
                break;

            case STATE_MOTORT:
                init_motor_test();
                press_start_to_exit = false; // Not skippable
                break;
        }
    }

    if (counter == 60)
        ohud.blit_text_new(7, 23, "PRESS START BUTTON TO EXIT", 0x84);

    if (press_start_to_exit && counter >= 60 && input.is_pressed(Input::START))
    {
        done = true;
    }

    // Tick State
    switch (state)
    {
        case STATE_INTERFACE:
            tick_interface(packet);
            break;

        case STATE_OUTPUT:
            tick_output();
            break;

        case STATE_INPUT:
            tick_input(packet);
            break;

        case STATE_CRT:
            break;

        case STATE_MOTORT:
            press_start_to_exit = outrun.outputs->diag_motor(packet->ai1, packet->mci, 0);
            break;
    }
    osprites.sprite_copy();
    osprites.update_sprites();
    otiles.write_tilemap_hw();
    oroad.tick();
    
    if (press_start_to_exit)
        counter++;

    return done;
}
Exemplo n.º 24
0
int main(int argc ,char *argv[]){

	/*first ,open input file ,and obtain input file information*/
	INPUT_CONTEXT *ptr_input_ctx;

	if( (ptr_input_ctx = malloc (sizeof(INPUT_CONTEXT))) == NULL){
		printf("ptr_input_ctx malloc failed .\n");
		exit(MEMORY_MALLOC_FAIL);
	}

	/*second ,open output file ,and set output file information*/
	OUTPUT_CONTEXT *ptr_output_ctx;
	if( (ptr_output_ctx = malloc (sizeof(OUTPUT_CONTEXT))) == NULL){
		printf("ptr_output_ctx malloc failed .\n");
		exit(MEMORY_MALLOC_FAIL);
	}

	//init inputfile ,and get input file information
	init_input(ptr_input_ctx ,argv[1]);


	//init oputfile ,and set output file information
	init_output(ptr_output_ctx ,argv[2] ,ptr_input_ctx);

	ptr_output_ctx->fifo = av_fifo_alloc(1024);
	                if (!ptr_output_ctx->fifo) {
	                    exit (1);
	                }
	                av_log(NULL, AV_LOG_WARNING ,"--av_fifo_size(ost->fifo) = %d \n" ,av_fifo_size(ptr_output_ctx->fifo));  //输出是0?!
	//open video and audio ,set video_out_buf and audio_out_buf
	open_stream_codec(ptr_output_ctx);


    // open the output file, if needed
    if (!(ptr_output_ctx->fmt->flags & AVFMT_NOFILE)) {		//for mp4 or mpegts ,this must be performed
        if (avio_open(&ptr_output_ctx->ptr_format_ctx->pb, argv[2], AVIO_FLAG_WRITE) < 0) {
            fprintf(stderr, "Could not open '%s'\n", argv[2]);
            exit(OPEN_MUX_FILE_FAIL);
        }
    }

    // write the stream header, if any
    avformat_write_header(ptr_output_ctx->ptr_format_ctx ,NULL);

    printf("ptr_output_ctx->ptr_format_ctx->nb_streams = %d \n\n" ,ptr_output_ctx->ptr_format_ctx->nb_streams);  //streams number in output file

//    while(1);

	printf("before av_read_frame ...\n");
	/*************************************************************************************/
	/*decoder loop*/
	//
	//
	//***********************************************************************************/
	while(av_read_frame(ptr_input_ctx->ptr_format_ctx ,&ptr_input_ctx->pkt) >= 0){

		 if (ptr_input_ctx->pkt.stream_index == ptr_input_ctx->audio_index) {

//			printf("HAHA.................\n");
			#if 1
			//decode audio packet
			while (ptr_input_ctx->pkt.size > 0) {
				int got_frame = 0;
				int len = avcodec_decode_audio4(ptr_input_ctx->audio_codec_ctx,
						ptr_input_ctx->audio_decode_frame, &got_frame,
						&ptr_input_ctx->pkt);

				if (len < 0) { //decode failed ,skip frame
					fprintf(stderr, "Error while decoding audio frame\n");
					break;
				}

				if (got_frame) {
					//encode the audio data ,and write the data into the output
					do_audio_out(ptr_output_ctx ,ptr_input_ctx ,ptr_input_ctx->audio_decode_frame);

				} else { //no data
					printf("======>avcodec_decode_audio4 ,no data ..\n");
					continue;
				}

				ptr_input_ctx->pkt.size -= len;
				ptr_input_ctx->pkt.data += len;

			}
			#endif
		}

	}//endwhile


	printf("before flush ,ptr_output_ctx->ptr_format_ctx->nb_streams = %d \n\n" ,ptr_output_ctx->ptr_format_ctx->nb_streams);
	encode_flush(ptr_output_ctx ,ptr_output_ctx->ptr_format_ctx->nb_streams);

	printf("before wirite tailer ...\n\n");

	av_write_trailer(ptr_output_ctx->ptr_format_ctx );

	/*free memory*/
}
Exemplo n.º 25
0
int main(int argc, char *argv[])
{
  Parameters *parameters; // user defined parameters
  Geometry *geometry; // homogenous cube geometry
  Material *material; // problem material
  Bank *source_bank; // array for particle source sites
  Tally *tally; // scalar flux tally
  double *keff; // effective multiplication factor
  double t1, t2; // timers

  #ifdef _OPENMP
    unsigned long counter = 0; //counter to decide the start pos of master bank copy from sub banks
    Bank *g_fission_bank; //global fission bank
  #endif

  // Get inputs: set parameters to default values, parse parameter file,
  // override with any command line inputs, and print parameters
  parameters = init_parameters();
  parse_parameters(parameters);
  read_CLI(argc, argv, parameters);
  print_parameters(parameters);


  // Set initial RNG seed
  set_initial_seed(parameters->seed);
  set_stream(STREAM_INIT);

  // Create files for writing results to
  init_output(parameters);

  // Set up geometry
  geometry = init_geometry(parameters);

  // Set up material
  material = init_material(parameters);

  // Set up tallies
  tally = init_tally(parameters);

  // Create source bank and initial source distribution
  source_bank = init_source_bank(parameters, geometry);

  // Create fission bank
  #ifdef _OPENMP
    omp_set_num_threads(parameters->n_threads); // Set number of openmp threads
    printf("threads num: %d\n", parameters->n_threads);
    // Allocate one master fission bank
    g_fission_bank = init_bank(2*parameters->n_particles);
  #endif

  // Set up array for k effective
  keff = calloc(parameters->n_active, sizeof(double));

  center_print("SIMULATION", 79);
  border_print();
  printf("%-15s %-15s %-15s\n", "BATCH", "KEFF", "MEAN KEFF");

  #ifdef _OPENMP
    // Start time
    t1 = omp_get_wtime();

    run_eigenvalue(counter, g_fission_bank, parameters, geometry, material, source_bank, fission_bank, tally, keff);

    // Stop time
    t2 = omp_get_wtime();
  #endif

  printf("Simulation time: %f secs\n", t2-t1);

  // Free memory
  #ifdef _OPENMP
    free_bank(g_fission_bank);
  #endif

  free(keff);
  free_tally(tally);
  free_bank(source_bank);
  free_material(material);
  free(geometry);
  free(parameters);

  return 0;
}
Exemplo n.º 26
0
int main (int argc, char * argv[]) {
    MOATypeDimn seqNum;
    MOATypeShape * seqLen = NULL;
    char * * sequences = NULL,  * * seqName = NULL, msg[MID_MESSAGE_SIZE];
    long partitionSize;
    long ID1;
    int stype, MPI_return;
    /*char ufilename[SHORT_MESSAGE_SIZE];*/
    int ret;
    ProcessData * pData;
    ScoringData * sData;
    WavesData * wData;
	
    TBFlag = 1;
    prevNow = NULL;
    prevNow = mmalloc ((MOATypeInd) sizeof *prevNow);
    currNow = NULL;
    //currNow = mmalloc ((MOATypeInd) sizeof *currNow);
    currNow = getTime();
    if (currNow == NULL) {
        printf ("Could not read current time. Exiting.\n");
        return -1;
    }
    ID1 = getpid();

    printf("[%d]>PID = %ld Started at time (%d, %d, %d, %d)\n", myProcid, ID1, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
    /* 1. Process Arguments*/
    processArguments(argc, argv, &seqNum, &sequences, &seqName, &seqLen, &stype, &partitionSize);
    /*strcpy (ufilename, outputfilename);*/
    strcpy (outPrefix, "b");
    /*sprintf (outputfilename, "mmtb%s", ufilename);*/
    init_output();
    sprintf (msg, "Program Arguments: debuglevel = %d maxAlignmentsNumber = %d Epsilons= %ld Alignment Type = %d stype %d outputfilename = %s partitionSize = %ld\n", pdebug, maxAlignmentsNumber, Epsilons, AlignmentType, stype, outputfilename, partitionSize);
    mprintf (1, msg, 1);
  
    /*2. Do the Master Tasks: Synchronize with Slaves to trace back*/
    /* one path for now*/
  
    ret = initProcessMemory(&pData, &sData, &wData, seqNum, seqLen, sequences, seqName, stype, partitionSize);  
    if (ret != 0) { 
        mprintf (1, " Could not initialize process memory\n", 1);
        freeProcessMemory (&pData, &sData, &wData);
        return -1;
    }
    /*3. Load Tensor Partitions Computed*/
    ret = restoreCheckPoint (pData, wData);
    if (ret != 0) {
        printf (" Could not read Slave data from checkpoint file\n");
        freeProcessMemory (&pData, &sData, &wData);
        return -1;
    }
    if (pData->computedPartitions <= 0) {
        mprintf (1, " No Partitions read in this process\n", 1);
        /*ExitProcess (pData);*/
        /*return -1;*/
    }
    else {
        sprintf (msg, "read Slave data from checkpoint file partitions %ld last score in last partition is %ld sqm %ld sqlen0 %ld %ld %ld\n", pData->partitionsCount, pData->msaAlgn->elements[pData->msaAlgn->elements_ub - 1].val, pData->seqNum, pData->seqLen[0], pData->seqLen[1], pData->seqLen[2]);
        mprintf(3, msg, 1);
    }

    tbMaster(pData, wData);
        /* Getting Process Resources Usage ===================== */
        struct rusage usageRec;
        double utime, stime;

        ret = getrusage(RUSAGE_SELF, &usageRec);
        if (ret == 0) {
            //printf ("[%d]Resources Usage: UTime %ld, STime %ld, Mem %ld, Virt %ld\n", myProcid, usageRec.ru_utime.tv_sec, usageRec.ru_stime.tv_sec, usageRec.ru_maxrss, usageRec.ru_ixrss);
            utime = (double) usageRec.ru_utime.tv_sec + 1.e-6 * (double) usageRec.ru_utime.tv_usec;
            stime = (double) usageRec.ru_stime.tv_sec + 1.e-6 * (double) usageRec.ru_stime.tv_usec;	
            //printf ("[%d]Resources Usage: UTime %f, STime %f\n", myProcid, utime, stime);
        }
        else
            printf ("Failed to retrieve Process Resources Usage, errno %d\n", errno);

        //struct mallinfo info;
        //info = mallinfo();

        //printf("[%d] STime\tUTime\theap\tMemory\t\n",myProcid);
        //printf("[%d] %f\t%f\t%d\t%d\n", myProcid, stime, utime, info.arena, info.usmblks + info.uordblks);

        printf("STime\tUTime\n");
        printf("%f\t%f\n", stime, utime);
        currNow = getTime();
        printf("Finalized at time (%d, %d, %d, %d)\n", currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec);
   freeProcessMemory (&pData, &sData, &wData);

    return 0;
}
int init_seg_union(Segment_U * segment_union ,int prog_no) {   //传递是指针变量的地址


	Segment_U * seg_union =segment_union;

	seg_union->segment_no = 0;
	seg_union->picture_capture = avcodec_alloc_frame();
	seg_union->picture_capture_no = 0;

	/*	-----------base seg_union do something---------------	*/
	//	create directory
	create_directory(seg_union->storage_dir);

	// create m3u8 file
	create_m3u8_name(seg_union);
	chris_printf("seg_union->full_m3u8_name = %s \n" ,seg_union->full_m3u8_name);

	/*----------following ,start to set  Output_Context information----- */
	//malloc Output_context
	if( (seg_union->output_ctx = malloc (sizeof(Output_Context))) == NULL){

		fprintf(stderr ,"ptr_output_ctx malloc failed .\n");
		exit(MEMORY_MALLOC_FAIL);
	}
	//segment element in output context
	seg_union->output_ctx->frame_rate				=		 seg_union->frame_rate;						 //frame rate
	seg_union->output_ctx->width					=		 seg_union->width;							//video width
	seg_union->output_ctx->height					=		 seg_union->height;							//video height
	seg_union->output_ctx->video_rate				=		 seg_union->video_rate;						//video bitrate
	seg_union->output_ctx->audio_rate				=		 seg_union->audio_rate;						//audio bitrate
	seg_union->output_ctx->sample					=		 seg_union->sample;							//audio sample
	seg_union->output_ctx->channel					=		 seg_union->channel;						//audio channels
	seg_union->output_ctx->num_in_dir				= seg_union->num_in_dir;
	seg_union->output_ctx->num_in_m3u8 				= seg_union->num_in_m3u8;
	seg_union->output_ctx->segment_duration 		=		 seg_union->segment_duration;
	seg_union->output_ctx->ts_prfix_name 			= 		 seg_union->ts_prfix_name;
	seg_union->output_ctx->mode_type				=		 seg_union->mode_type;
	//
	seg_union->output_ctx->segment_no				= 		 seg_union->segment_no;
	seg_union->output_ctx->full_m3u8_name			=		 seg_union->full_m3u8_name;
	seg_union->output_ctx->m3u8						= 		 seg_union->m3u8_name;
	//
	seg_union->output_ctx->frame_count 				= 0;			//this frame_count be used to generate video pts.


	chris_printf("num_in_m3u8 = %d ,num_in_dir = %d \n\n" ,seg_union->output_ctx->num_in_m3u8 ,seg_union->output_ctx->num_in_dir);

	/*-----------	following ,only do in the mode_type yy_live	--------------*/
	if(seg_union->mode_type == YY_LIVE){	// live mode

		/*	live something	*/
		//malloc live_buffer for m3u8 buffer  //the content of m3u8
		seg_union->output_ctx->live_write_buf = malloc(sizeof(char) * 1024 * 100);
		if (!seg_union->output_ctx->live_write_buf) {
			fprintf(stderr, "Could not allocate write buffer for live_write_buf\n");
			exit(ALLOCATE_M3U8_WRITE_BUFFER_LIVE);
		}
		memset(seg_union->output_ctx->live_write_buf ,0  ,1024*100);

		chris_printf("ptr_output_ctx->num_in_m3u8 = %d \n" ,seg_union->output_ctx->num_in_m3u8);
		seg_union->output_ctx->seg_duration_arr = malloc(sizeof(double) *  ( seg_union->output_ctx->num_in_m3u8 + 1) );  	//use to storage the every ts file length in the m3u8 ,the array[0] reserved
		if(seg_union->output_ctx->seg_duration_arr == NULL){
			fprintf(stderr ,"seg_duration_arr malloc failed .. ,%s ,line %d \n" ,__FILE__ ,__LINE__);
			exit(MEMORY_MALLOC_FAIL);
		}

		/*	judge for the log.info 	*/
		int ret =find_log_file(seg_union);
		if(ret){//find the log file ,and recover the scene ,recover the segment_no use to create the ts name
			recover_from_log(seg_union);
			chris_printf("......after recover from the log file ...\n\n\n");
		}
	}

	//splice the first ts name
	create_first_ts_name(seg_union ,seg_union->mode_type);

	//the followint ,dir_name_len and ts_name set must be set after the function create_first_ts_name!!!!
	seg_union->output_ctx->dir_name_len 		    = 		 seg_union->dir_name_len;   //
	seg_union->output_ctx->ts_name 					=		 seg_union->ts_name;		//
	chris_printf("--------------->before transcode init function  ,seg_union->ts_name = %s..\n" ,seg_union->ts_name);

	//add audio stream and video into the output_ctx ,of course ,set codec information also in the function init_output
//	init_output(seg_union->output_ctx ,seg_union->ts_name );  //add stream information in this function
	init_output(seg_union->output_ctx ,seg_union->ts_name , prog_no);  //add stream information in this function

	//open video and audio codecs ,set video_out_buf and audio_out_buf
	open_stream_codec(seg_union->output_ctx ,prog_no);
	chris_printf("--------------->after transcode init function ..\n");


	return 0;
}
Exemplo n.º 28
0
/** main function
 */
int main(void) { /* {{{ */
	reboot = 0;
	wdt_enable(WDTO_1S);

#if RANDOM
    unsigned long int cnt = 1000;
    unsigned char white, red, green, blue;
    unsigned char save = 0;
    srand(eeprom_read_word(&seed));
#endif

	init_output();

#if COLORFUL_INIT
	uint16_t j = 0;
	LED01_PORT |= _BV(LED_CHANNEL0);	//Switch On
	for (j = 0; j <= 10; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED01_PORT &= ~_BV(LED_CHANNEL0);	//Switch Off
	for (j = 0; j <= 17; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED01_PORT |= _BV(LED_CHANNEL1);	//Switch On
	for (j = 0; j <= 10; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED01_PORT &= ~_BV(LED_CHANNEL1);	//Switch Off
	for (j = 0; j <= 17; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED23_PORT |= _BV(LED_CHANNEL2);	//Switch On
	for (j = 0; j <= 10; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED23_PORT &= ~_BV(LED_CHANNEL2);	//Switch Off
	for (j = 0; j <= 17; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED23_PORT |= _BV(LED_CHANNEL3);	//Switch On
	for (j = 0; j <= 10; j ++) {
		wdt_reset();
		_delay_ms(10);
	}
	LED23_PORT &= ~_BV(LED_CHANNEL3);	//Switch Off
#endif

	init_pwm();

#if RC5_DECODER
	init_rc5();
#endif

#if STATIC_SCRIPTS
	init_script_threads();

	#if RS485_CTRL == 0
	/* start the example scripts */
	//script_threads[0].handler.execute = &memory_handler_flash;
	//script_threads[0].handler.position = (uint16_t) &blinken;
	//script_threads[0].flags.disabled = 0;
	
	script_threads[0].handler.execute = &memory_handler_flash;
	script_threads[0].handler.position = (uint16_t) &strobo_rgb;
	script_threads[0].flags.disabled = 0;
	#endif

#endif

#if RS485_CTRL
	/* init command bus */
	UCSR0A = _BV(MPCM0); /* enable multi-processor communication mode */
	UCSR0C = _BV(UCSZ00) | _BV(UCSZ01); /* 9 bit frame size */

	#define UART_UBRR 8 /* 115200 baud at 16mhz */
	UBRR0H = HIGH(UART_UBRR);
	UBRR0L = LOW(UART_UBRR);

	UCSR0B = _BV(RXEN0) | _BV(TXEN0) | _BV(UCSZ02); /* enable receiver and transmitter */
#endif

#if USB
	usbInit();
	usbDeviceDisconnect();	/* enforce re-enumeration, do this while interrupts are disabled! */
	uchar i = 0;
	while(--i){		/* fake USB disconnect for > 250 ms */
		_delay_ms(1);
	}
	usbDeviceConnect();
	//TCCR0 = 5;		/* set prescaler to 1/1024 */
#endif

	/* enable interrupts globally */
	sei();

	while (1) {
		wdt_reset();
#if USB
		usbPoll();
#endif
//		if (TIFR & (1 << TOV0)) {
//			TIFR |= 1 << TOV0;	/* clear pending flag */
//		}
		if (reboot) {
			soft_reset();
		}
		if (global.flags.new_cycle) {
			global.flags.new_cycle = 0;
			update_brightness();

#if RANDOM
            if (++cnt == 1200) {
               red   = pwmtable[rand() % 16];
               green = pwmtable[rand() % 16];
               blue  = pwmtable[rand() % 16];
               white = whitetable[rand() % 8];
               set_fade(1, blue, 800);
               set_fade(2, green, 800);
               set_fade(3, red, 800);
               if (blue + green + red <= 32)
                    set_fade(0, white, 800);
               else
                    set_fade(0, 0, 800);
               cnt = 0;

               if (++save == 100)
                    eeprom_write_word(&seed, rand());
            }
#endif

#if STATIC_SCRIPTS
			execute_script_threads();
#endif
			continue;
		}
	}


#if RC5_DECODER
	/* check if we received something via ir */
	if (global_rc5.new_data) {
		static uint8_t toggle_bit = 2;

		/* if key has been pressed again */
		if (global_rc5.received_command.toggle_bit != toggle_bit) {

			/* if code is 0x01 (key '1' on a default remote) */
			if (global_rc5.received_command.code == 0x01) {

				/* install script into thread 1 */
				script_threads[1].handler.execute = &memory_handler_flash;
				script_threads[1].handler.position = (uint16_t) &green_flash;
				script_threads[1].flags.disabled = 0;
				script_threads[1].handler_stack_offset = 0;

			}

			/* store new toggle bit state */
			toggle_bit = global_rc5.received_command.toggle_bit;

		}

		/* reset the new_data flag, so that new commands can be received */
		global_rc5.new_data = 0;

		continue;
	}
#endif

#if RS485_CTRL
	if (UCSR0A & _BV(RXC0)) {

		uint8_t address = UCSR0B & _BV(RXB80); /* read nineth bit, zero if data, one if address */
		uint8_t data = UDR0;
		static uint8_t buffer[8];
		static uint8_t fill = 0;

		if (UCSR0A & _BV(MPCM0) || address) { /* if MPCM mode is still active, or ninth bit set, this is an address packet */

			/* check if we are ment */
			if (data == 0 || data == RS485_ADDRESS) {

				/* remove MPCM flag and reset buffer fill counter */
				UCSR0A &= ~_BV(MPCM0);
				fill = 0;

				continue;

			} else {/* turn on MPCM */

				UCSR0A |= _BV(MPCM0);
				continue;

			}
		}

		/* else this is a data packet, put data into buffer */
		buffer[fill++] = data;

		if (buffer[0] == 0x01) {	/* soft reset */

			jump_to_bootloader();

		} else if (buffer[0] == 0x02 && fill == 4) { /* set color */

			CHANNEL0_PWM = buffer[1];
			CHANNEL1_PWM = buffer[2];
			CHANNEL2_PWM = buffer[3];
			CHANNEL3_PWM = buffer[4];
			for (uint8_t pos = 0; pos < PWM_CHANNELS; pos++) {
				global_pwm.channels[pos].target_brightness = buffer[pos + 1];
				global_pwm.channels[pos].brightness = buffer[pos + 1];
			}

			UCSR0A |= _BV(MPCM0); /* return to MPCM mode */

		} else if (buffer[0] == 0x03 && fill == 6) { /* fade to color */

			for (uint8_t pos = 0; pos < PWM_CHANNELS; pos++) {
				global_pwm.channels[pos].speed_h = buffer[1];
				global_pwm.channels[pos].speed_l = buffer[2];
				global_pwm.channels[pos].target_brightness = buffer[pos + 3];
			}

			UCSR0A |= _BV(MPCM0); /* return to MPCM mode */
		}

	}
#endif
}
Exemplo n.º 29
0
int main (int argc, char **argv){
    int ret = 0, got_frame;
    AVFormatContext *ofmt_ctx = NULL;
    AVOutputFormat *ofmt = NULL;
    


    uint8_t *sample_buf;
    
    
    if (argc != 4 && argc != 5) {
        fprintf(stderr, "input  1.source file:%s\n"
                "2.output_video\n"
                "3.output_audio\n"
                "4.mux video file(Optional)\n"
                "\n", argv[0]);
        exit(1);
    }
    
    src_filename = argv[1];
    video_dst_filename = argv[2];
    audio_dst_filename = argv[3];
    //optional mux to any type video
    if(argc == 5){
        out_filename = argv[4];
    }
    
    /* register all formats and codecs */
    av_register_all();
    //for network stream
    avformat_network_init();
    
    ret = init_input();
    if(ret){
        goto end;
    }


    ret = init_video_out_context();
    if(ret){
        goto end;
    }


    ret = init_audio_out_context(sample_buf);
    if(ret){
        goto end;
    }else{
        int aud_buffer_size;
        //alloc frame and packet
        AudFrame = av_frame_alloc();
        AudFrame->nb_samples     = AudCodecCtx->frame_size;
        AudFrame->format         = AudCodecCtx->sample_fmt;
        AudFrame->channel_layout = AudCodecCtx->channel_layout;
        
        aud_buffer_size = av_samples_get_buffer_size(NULL, AudCodecCtx->channels,AudCodecCtx->frame_size,AudCodecCtx->sample_fmt, 1);
        sample_buf = (uint8_t *)av_malloc(aud_buffer_size);
        avcodec_fill_audio_frame(AudFrame, AudCodecCtx->channels, AudCodecCtx->sample_fmt,(const uint8_t*)sample_buf, aud_buffer_size, 1);
        av_new_packet(&AudPkt,aud_buffer_size);
    }
    
    
    if(argc == 5){
        //alloc memory
        avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
        if (!ofmt_ctx) {
            printf( "Could not create output context\n");
            ret = AVERROR_UNKNOWN;
            return 1;
        }
        ofmt = ofmt_ctx->oformat;

        ret = init_output(ofmt_ctx);
        if(ret){
            printf("Init output ERROR\n");
            goto end;
        }
    }
    
    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            printf( "Could not open output file '%s'", out_filename);
            goto end;
        }
    }

    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
        printf( "Error occurred when opening output file\n");
        goto end;
    }
    
    //this will fill up by decoder(|read frame|->packet->|decoder|->frame)
    frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Could not allocate frame\n");
        ret = AVERROR(ENOMEM);
        goto end;
    }
    
    if (video_stream)
        printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
    if (audio_stream)
        printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
    
    
    //Write video Header
    avformat_write_header(pFormatCtx,NULL);
    //Write audio Header
    avformat_write_header(AudFormatCtx,NULL);
    
    //alloc packet to get copy from pkt
    av_new_packet(&epkt,picture_size);
    
    /*setup the convert parameter
     *due to input sample format AV_SAMPLE_FMT_FLTP
     *can't be converted to AV_SAMPLE_FMT_S16
     *which only accepted by the aac encoder
     */
    swr = swr_alloc();
    av_opt_set_int(swr, "in_channel_layout",  audio_dec_ctx->channel_layout, 0);
    av_opt_set_int(swr, "out_channel_layout", AudCodecCtx->channel_layout,  0);
    av_opt_set_int(swr, "in_sample_rate",     audio_dec_ctx->sample_rate, 0);
    av_opt_set_int(swr, "out_sample_rate",    AudCodecCtx->sample_rate, 0);
    av_opt_set_sample_fmt(swr, "in_sample_fmt",  AV_SAMPLE_FMT_FLTP, 0);
    av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16,  0);
    swr_init(swr);
    
    
    
    
    /*start read frames from the file */
    while (av_read_frame(fmt_ctx, &pkt) >= 0) {
        //do demux & decode -> encode -> output h264 & aac file
        ret = decode_packet();

        if (ret < 0)
            break;
        if(argc == 5){
            remux_packet(ofmt_ctx,&pkt);
        }
        
        av_free_packet(&pkt);
    }
    
    /* flush cached frames */
    pkt.data = NULL;
    pkt.size = 0;
    
    
    //Flush Encoder
    int retfe = flush_encoder(pFormatCtx,0);
    if (retfe < 0) {
        printf("Flushing encoder failed\n");
        return -1;
    }
    
    //Flush Encoder
    ret = flush_encoder(pFormatCtx,0);
    if (ret < 0) {
        printf("Flushing encoder failed\n");
        return -1;
    }
    
    //Write video trailer
    av_write_trailer(pFormatCtx);
    
    //Write audio Trailer
    av_write_trailer(AudFormatCtx);
    
    //Write remux Trailer
    if(argc == 5){
        av_write_trailer(ofmt_ctx);
    }
    
    
    printf("Output succeeded!!!!\n");
    
    
    
    
    
    
    
    
    
end:
    //free remux
    if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
        avio_close(ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);
    
    //free audio
    if (audio_st){
        avcodec_close(audio_st->codec);
        av_free(AudFrame);
        av_free(sample_buf);
    }
    avio_close(AudFormatCtx->pb);
    avformat_free_context(AudFormatCtx);
    
    //free video
    if (video_st){
        avcodec_close(video_st->codec);
        av_free(pFrame);
        av_free(picture_buf);
    }
    avio_close(pFormatCtx->pb);  
    avformat_free_context(pFormatCtx);
    
    //free decode
    avcodec_close(video_dec_ctx);
    avcodec_close(audio_dec_ctx);
    avformat_close_input(&fmt_ctx);
    if (video_dst_file)
        fclose(video_dst_file);
    if (audio_dst_file)
        fclose(audio_dst_file);    
    av_frame_free(&frame);
    return ret < 0;
}
Exemplo n.º 30
0
Arquivo: vasm.c Projeto: ezrec/vasm
int main(int argc,char **argv)
{
    int i;
    for(i=1; i<argc; i++) {
        if(argv[i][0]=='-'&&argv[i][1]=='F') {
            output_format=argv[i]+2;
            argv[i][0]=0;
        }
        if(!strcmp("-quiet",argv[i])) {
            verbose=0;
            argv[i][0]=0;
        }
    }
    if(!init_output(output_format))
        general_error(16,output_format);
    if(!init_main())
        general_error(10,"main");
    if(verbose)
        printf("%s\n%s\n%s\n%s\n",copyright,cpu_copyright,syntax_copyright,output_copyright);
    for(i=1; i<argc; i++) {
        if(argv[i][0]==0)
            continue;
        if(argv[i][0]!='-') {
            if(inname)
                general_error(11);
            inname=argv[i];
            continue;
        }
        if(!strcmp("-o",argv[i])&&i<argc-1) {
            if(outname)
                general_error(28,'o');
            outname=argv[++i];
            continue;
        }
        if(!strcmp("-L",argv[i])&&i<argc-1) {
            if(listname)
                general_error(28,'L');
            listname=argv[++i];
            produce_listing=1;
            continue;
        }
        if(!strcmp("-Lnf",argv[i])) {
            listformfeed=0;
            continue;
        }
        if(!strcmp("-Lns",argv[i])) {
            listnosyms=1;
            continue;
        }
        if(!strncmp("-Ll",argv[i],3)) {
            sscanf(argv[i]+3,"%i",&listlinesperpage);
            continue;
        }
        if(!strncmp("-D",argv[i],2)) {
            char *def=NULL;
            expr *val;
            if(argv[i][2])
                def=&argv[i][2];
            else if (i<argc-1)
                def=argv[++i];
            if(def) {
                char *s=def;
                if(ISIDSTART(*s)) {
                    s++;
                    while(ISIDCHAR(*s))
                        s++;
                    def=cnvstr(def,s-def);
                    if(*s=='=') {
                        s++;
                        val=parse_expr(&s);
                    }
                    else
                        val=number_expr(1);
                    if(*s)
                        general_error(23,'D');  /* trailing garbage after option */
                    new_abs(def,val);
                    myfree(def);
                    continue;
                }
            }
        }
        if(!strncmp("-I",argv[i],2)) {
            char *path=NULL;
            if(argv[i][2])
                path=&argv[i][2];
            else if (i<argc-1)
                path=argv[++i];
            if(path) {
                new_include_path(path);
                continue;
            }
        }
        if(!strcmp("-unnamed-sections",argv[i])) {
            unnamed_sections=1;
            continue;
        }
        if(!strcmp("-ignore-mult-inc",argv[i])) {
            ignore_multinc=1;
            continue;
        }
        if(!strcmp("-nocase",argv[i])) {
            nocase=1;
            continue;
        }
        if(!strcmp("-noesc",argv[i])) {
            esc_sequences=0;
            continue;
        }
        if(!strcmp("-nosym",argv[i])) {
            no_symbols=1;
            continue;
        }
        if(!strncmp("-nowarn=",argv[i],8)) {
            int wno;
            sscanf(argv[i]+8,"%i",&wno);
            disable_warning(wno);
            continue;
        }
        else if(!strcmp("-w",argv[i])) {
            no_warn=1;
            continue;
        }
        if(!strncmp("-maxerrors=",argv[i],11)) {
            sscanf(argv[i]+11,"%i",&max_errors);
            continue;
        }
        else if(!strcmp("-pic",argv[i])) {
            pic_check=1;
            continue;
        }
        if(cpu_args(argv[i]))
            continue;
        if(syntax_args(argv[i]))
            continue;
        if(output_args(argv[i]))
            continue;
        if (!strncmp("-x",argv[i],2)) {
            auto_import=0;
            continue;
        }
        general_error(14,argv[i]);
    }
    if(inname) {
        setfilename(inname);
        setdebugname(inname);
        include_source(inname);
    } else
        general_error(15);
    if(!init_parse())
        general_error(10,"parse");
    if(!init_syntax())
        general_error(10,"syntax");
    if(!init_cpu())
        general_error(10,"cpu");
    parse();
    if(errors==0||produce_listing)
        resolve();
    if(errors==0||produce_listing)
        assemble();
    if(errors==0&&!auto_import)
        undef_syms();
    if(!listname)
        listname="a.lst";
    if(produce_listing)
        write_listing(listname);
    if(!outname)
        outname="a.out";
    if(errors==0) {
        if(verbose)
            statistics();
        outfile=fopen(outname,"wb");
        if(!outfile)
            general_error(13,outname);
        write_object(outfile,first_section,first_symbol);
    }
    leave();
    return 0; /* not reached */
}