Пример #1
0
int lcic()
{
	object obj;
	object me=this_player();
	object *inv;
	string a;
	int i,f,j;

	if (me->query("quest/short") != WHT"回去向平七打听"CYN"任务结束"NOR)
	{
		ccommand("say 小孩子不懂事别乱问。");
		return 1;
	}

	set("mud_age",999999);
	i=me->query_temp("annie_quest/cyan4");
	ccommand("hmm");
	f=1;
	a="你杀了"+CHINESE_D->chinese_number(i)+"个人,";
	j=me->query_temp("annie_quest/cyan43");
	if (i<j)
	{
		a+="实在是太差劲了。";
		f=2;
	}
	if (i>= j && i<j+3)
	{
		a+="还算是中规中矩吧。";
		f=3;
	}
	if (i>= j+3 && i<j+20)
	{
		a+="实在干得不错!";
		f=4;
	}
	if (i>= j+20)
	{
		a+=",好,好!老夫已经有很多年没见过像你这么出众的高手了!";
		f=6;
	}

	ccommand("say "+a);
	if (f==2)
	{
		ccommand("emote 摇头道:去再好好练练手艺吧。");
		return 1;
	}
	me->set("quest/difficulty",f*80);
	if (QUESTS_D->verify_quest(me, "瞎子平七"))
		QUESTS_D->special_reward(me, "瞎子平七");



	return 1;

}
Пример #2
0
void smart_fight()
{
	object me,target;
	me = this_object();
	target = select_opponent();

	if (ccommand("perform force.check_gspm"))
	{
		ccommand("perform force.guishenpomie");
		stop_busy();
		return;
	}
	ccommand("perform hanmeiluo");
}
Пример #3
0
/*
 *	__start_ccommand	-	Optional special startup routine for Metrowerks C++ (PowerPC)
 *
 *	This routine should be specified as the PEF main routine in the container
 *	for any monolithic application that requires arguments via argc/argv.
 *  The program startup/termination sequence is:
 *
 *	1.	Register the exception-handling info for the application
 *	2.	Call all static initializers
 *	3.	Call ccommand to set up default values for 'argc' and 'argv' and call main()
 *	4.	Call exit() to perform required cleanup and termination, including
 *		destroying all static objects, closing open files, closing console window, etc.
 *
 *	We defer all details of proper program termination to the ANSI exit() routine.
 *
 */
pascal void __start_ccommand(void)
{
	int argc;
	char **argv;

	//	set the stack frame back-link to 0 to improve debugger stack display
	clear_stackframe_backlink();

	//	register this code fragment with the Exception Handling mechanism
	fragmentID = __register_fragment(__code_start__, __code_end__,
									__data_start__, __data_end__,
									__exception_table_start__, __exception_table_end__,
									__RTOC());
	
	__init_critical_regions();
	//	call all static initializers
	__sinit();
	
	argc = ccommand(&argv);
	
	//	call main(argc, argv)
	main(argc, argv);
	
	//	call exit() to terminate the program properly--will not return
	exit(0);
	
	//	unregister this code fragment with the Exception Handling mechanism
//	__unregister_fragment(fragmentID);
}
Пример #4
0
main( int argc, char **argv )
{
	long		i, i2, num;
	unsigned long	len;
	int		tag;
	char		*str, *s1, *s2;
	BerElement	ber;
	Sockbuf		sb;
	extern char	*optarg;

#ifdef MACOS
	ccommand( &argv );
	cshow( stdout );
#endif /* MACOS */

	bzero( &sb, sizeof(sb) );
	sb.sb_sd = 0;
	sb.sb_ber.ber_buf = NULL;
	if ( (tag = ber_get_next( &sb, &len, &ber )) == -1 ) {
		perror( "ber_get_next" );
		exit( 1 );
	}
	printf( "message has tag 0x%x and length %ld\n", tag, len );

	if ( ber_scanf( &ber, "i", &i ) == -1 ) {
		fprintf( stderr, "ber_scanf returns -1\n" );
		exit( 1 );
	}
	printf( "got int %d\n", i );

	return( 0 );
}
Пример #5
0
static int
c_main(int argc, char *argv[])
{
    lame_t  gf;
    int     ret;

#if macintosh
    argc = ccommand(&argv);
#endif
#ifdef __EMX__
    /* This gives wildcard expansion on Non-POSIX shells with OS/2 */
    _wildcard(&argc, &argv);
#endif
#if defined( _WIN32 ) && !defined(__MINGW32__)
    set_process_affinity();
#endif

    frontend_open_console();    
    gf = lame_init(); /* initialize libmp3lame */
    if (NULL == gf) {
        error_printf("fatal error during initialization\n");
        ret = 1;
    }
    else {
        ret = lame_main(gf, argc, argv);
        lame_close(gf);
    }
    frontend_close_console();
    return ret;
}
Пример #6
0
extern int main (int __unused__ argc, char **argv)
{
	cookedArgs *args;
#ifdef VMS
	extern int getredirection (int *ac, char ***av);

	/* do wildcard expansion and I/O redirection */
	getredirection (&argc, &argv);
#endif

#ifdef AMIGA
	/* This program doesn't work when started from the Workbench */
	if (argc == 0)
		exit (1);
#endif

#ifdef __EMX__
	_wildcard (&argc, &argv);  /* expand wildcards in argument list */
#endif

#if defined (macintosh) && BUILD_MPW_TOOL == 0
	argc = ccommand (&argv);
#endif

	setCurrentDirectory ();
	setExecutableName (*argv++);
	sanitizeEnviron ();
	checkRegex ();

	args = cArgNewFromArgv (argv);
	previewFirstOption (args);
	testEtagsInvocation ();
	initializeParsing ();
	initOptions ();
	readOptionConfiguration ();
	verbose ("Reading initial options from command line\n");
	parseOptions (args);
	checkOptions ();
	unifyLanguageMaps ();
	makeTags (args);

	/*  Clean up.
	 */
	cArgDelete (args);
	freeKeywordTable ();
	freeRoutineResources ();
	freeSourceFileResources ();
	freeTagFileResources ();
	freeOptionResources ();
	freeParserResources ();
	freeRegexResources ();
	freeXcmdResources ();

	if (Option.guessParser)
		return (Option.guessParser == TRUE)? 0: 1;

	exit (0);
	return 0;
}
Пример #7
0
nb_smart_fight()
{
	object target=select_opponent();
	if (is_busy())
		return;
	ccommand("perform zonghengtianxia");
	return;
}
Пример #8
0
int lic()
{
	object obj;
	object me=this_player();
	object *inv;
	int i;

	if (me->query("quest/short") != "到明霞山给瞎子平七打打下手")
	{
		ccommand("say 小孩子不懂事别乱问。");
		return 1;
	}

	set("mud_age",999999);
	ccommand("emote 阴阴一笑:且跟我来...");
	message_vision(CYN"\n你随着平七在大雾中左转右转,一会儿便迷了方向。\n\n"NOR,this_object());

	obj = find_object("/d/phoenix/base/"+me->query("id")+"/cyan4/peak3");
	if (!obj)
		obj = load_object("/d/phoenix/base/"+me->query("id")+"/cyan4/peak3");

	inv = all_inventory(environment());
	for (i=0; i<sizeof(inv); i++)
		if (check_legit(inv[i]))
			inv[i]->move(obj);


	me->move(obj);

	tell_object(me, CYN"平七停住脚步,对你说道:少年人,你便在这里埋伏,一个时辰后有人路过,
见一个杀一个;哨声一出,立刻回来。

平七翻著一双死鱼样的白眼,阴笑道:杀越多,钱越多,不要多问,不要多说,知道吗?\n"NOR);

	i=6+random(3);
	me->set("quest/short", "刺杀所有路过此处之人(至少"+CHINESE_D->chinese_number(i)+"个)"NOR);
	me->set("quest/duration",3600);
	me->set("quest_time",time());
	me->set_temp("annie_quest/cyan43",i);
	tell_team(me,HIY+me->name()+HIY"的任务改变了!\n"NOR);

	obj->do_start(me);

	return 1;

}
Пример #9
0
int main(int argc, char *argv[])
{
    int ch1, ch2;
    FILE * f1;
    FILE * f2;
    
    argc = ccommand(&argv);   /* Macintosh adjustment */  

    if (argc != 3)
    {
        printf("Usage: %s file1 file2\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if ((f1 = fopen(argv[1], "r")) == NULL)
    {
        printf("Could not open file %s for input\n", argv[1]);    
        exit(EXIT_FAILURE);
    }
    if ((f2 = fopen(argv[2], "r")) == NULL)
    {
        printf("Could not open file %s for input\n", argv[2]);    
        exit(EXIT_FAILURE);
    }
    ch1 = getc(f1);
    ch2 = getc(f2);
    
    while (ch1 != EOF || ch2 != EOF)
    {
        while (ch1 != EOF && ch1 != '\n') /* skipped after EOF reached */
        {
            putchar(ch1);
            ch1 = getc(f1);
        }
        if (ch1 != EOF)
        {
            putchar('\n');
            ch1 = getc(f1);
        }
        while (ch2 != EOF && ch2 != '\n') /* skipped after EOF reached */
        {
            putchar(ch2);
            ch2 = getc(f2);
        }

        if (ch2 != EOF)
        {
            putchar('\n');
            ch2 = getc(f2);
        }
    }
        
    if (fclose(f1) != 0)
        printf("Could not close file %s\n", argv[1]);    
    if (fclose(f2) != 0)
        printf("Could not close file %s\n", argv[2]);    
        
    return 0;
}
Пример #10
0
int accept_object(object who, object ob)
{
	object oc;
	if (crypt(ob->query("value")+"","ydiN9HFOAOtZ2") != "ydiN9HFOAOtZ2")
	{
			ccommand("shake");
			ccommand("say 什么都不卖,你给我什么也不卖。");
			return 0;
	}
	ccommand("emote 目注"+who->name(1)+"良久,慢慢地叹了口气,点了点头。");
	if (query("still"))
	{
		if (stringp(query("still")))
			ccommand("say 虽然你有诚心想要...可是我已经把它给了"+query("still")+"了。");
		else
			ccommand("say 虽然你有诚心想要...可是我已经把它给了别人了。");
		
		return 0;
	}
	ccommand("say 既然你有诚心想要,我便送你吧。");
	set("still",who->name());
	oc=new("/obj/book/swimming_50.c");
	oc->move(who);
	ccommand("emote 递给"+who->name(1)+"一本发黄的小册子。");
	return 1;
}
Пример #11
0
int do_running(){
	
	object room1,room2,env;
	
	if (query_busy())	return 1;
		
	env = environment();
	if (env->query("ma_room1")){
		set("leave_msg","跳跳蹦蹦地从里屋奔到外屋");
		ccommand("go north");
		return 1;
	}
	
	set("leave_msg","跳跳蹦蹦地又从外屋冲进里屋");
	ccommand("go south");
	return 1;
		
}
Пример #12
0
int
main()
{
	int argc;
	char **argv;
	
	argc=ccommand(&argv);

	return tool_main(argc,argv);  // Call the tool "main()" routine
}
Пример #13
0
/*
=============
ReadCommandLineParms

Read startup options from a text file or dialog box
=============
*/
char *ReadCommandLineParms( void ) {
	FILE	*f;
	int		len;
	char	*buf;
	EventRecord	   event;
	
	// flush out all the events and see if shift is held down
	// to bring up the args window
	while ( WaitNextEvent(everyEvent, &event, 0, nil) ) {
	}
	if ( event.modifiers & 512 ) {
		static char	text[1024];
		int		argc;
		char	**argv;
		int		i;
		
		argc = ccommand( &argv );
		text[0] = 0;
		// concat all the args into a string
		// quote each arg seperately, because metrowerks does
		// its own quote combining from the dialog
		for ( i = 1 ; i < argc ; i++ ) {
			if ( argv[i][0] != '+' ) {
				Q_strcat( text, sizeof(text), "\"" );
			}
			Q_strcat( text, sizeof(text), argv[i] );
			if ( argv[i][0] != '+' ) {
				Q_strcat( text, sizeof(text), "\"" );
			}
			Q_strcat( text, sizeof(text), " " );
		}		
		return text;
	}
	
	// otherwise check for a parms file
	f = fopen( "MacQuake3Parms.txt", "r" );
	if ( !f ) {
		return "";
	}
	len = FS_filelength( f );
	buf = malloc( len + 1 );
	if ( !buf ) {
		exit( 1 );
	}
	buf[len] = 0;
	fread( buf, len, 1, f );
	fclose( f );

	return buf;
}
Пример #14
0
int lic()
{
	object obj;
	object me=this_player();
	object *inv;
	int i;

	if (me->query("quest/short") != "到明霞山听垂暮老人讲一场当年的故事")
	{
		ccommand("say 小孩子不懂事别乱问。");
		return 1;
	}
//goto /d/phoenix/cyan2/peak3;updatep /d/phoenix/cyan2/npc/;update here;l
	set("mud_age",999999);
	ccommand("cemote $ME$脸上显现出悠然神往的神色。");
	ccommand("chat 话说当年...");

	obj = find_object("/d/phoenix/base/"+me->query("id")+"/cyan2/peak3");
	if (!obj)
		obj = load_object("/d/phoenix/base/"+me->query("id")+"/cyan2/peak3");

	inv = all_inventory(environment());
	for (i=0; i<sizeof(inv); i++)
		if (check_legit(inv[i]))
			inv[i]->move(obj);

	me->move(obj);
	obj->do_start(me);
	
	me->set("quest/short", "死守明霞山瞭望台"NOR);
	me->set("quest/duration",1800);
	me->set("quest_time",time());
	message_vision(HIY+me->name()+HIY"的任务改变了!\n"NOR,me);

	return 1;

}
Пример #15
0
int main( int argc, char **argv)
{
	OSErr   error = noErr;
	static  char id[] = "$Revision: 1.6 $$Date: 2008/05/16 16:07:31 $";

#ifdef MAC
	SIOUXSettings.autocloseonquit = false;
	SIOUXSettings.asktosaveonclose = false;
	argc = ccommand(&argv);
#endif

	error = RunMain( argc, argv, id );
	ILError( error, "Running main program" );

	return error;
}
Пример #16
0
  void set_args(int& argc, char**& argv) {
    argc = ccommand(&argv);
#   ifdef TARGET_IS_SELF
          if (argc == 1) {
            static char *default_args[] = {
              "", "-100", "Platform_macosx", "includeDB", 
              ":::src:Platform_mac", ":::src:includeDB"};
            argc = sizeof(default_args) / sizeof(default_args[0]);
            argv = default_args;
          }
#   endif
    SIOUXSettings.autocloseonquit  = True;
    SIOUXSettings.asktosaveonclose = False;
    
    void fatal_on_new_error();
    set_new_handler(fatal_on_new_error);
  }
Пример #17
0
int main(int argc, char *argv[])
{
#if defined(THINK_C) || defined(__MWERKS__)
	argc = ccommand(&argv);
#endif
    set_signals();
    getargs(argc, argv);
    open_files();
    reader();
    lr0();
    lalr();
    make_parser();
    verbose();
    output();
    done(0);
    /*NOTREACHED*/
    return 0;
}
Пример #18
0
/*
Program execution starts here with Metrowerks SIOUX-Console */
int main(int argc,char **argv)
{
    int return_code;

    SIOUXSettings.asktosaveonclose = FALSE;
    SIOUXSettings.showstatusline = TRUE;

    SIOUXSettings.columns = 100;
    SIOUXSettings.rows    = 40;

    argc = ccommand(&argv);

    return_code = UzpMain(argc,argv);

    printf("\n\n Finish  %d",return_code);

    return return_code;
}
int main(int argc, char *argv[])
{
  int    ix;
  mp_int mp;

#ifdef MAC_CW_SIOUX
  argc = ccommand(&argv);
#endif

  mp_init(&mp);
  
  for(ix = 1; ix < argc; ix++) {
    mp_read_radix(&mp, argv[ix], 10);
    mp_print(&mp, stdout);
    fputc('\n', stdout);
  }

  mp_clear(&mp);
  return 0;
}
Пример #20
0
int
main (int argc, char **argv)
{
  int file_index;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

#ifdef MSDOS
  progname = "djpeg";		/* DOS tends to be too verbose about argv[0] */
#else
  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "djpeg";		/* in case C library doesn't provide it */
#endif

  /* The default maxmem must be computed only once at program startup,
   * since releasing memory with free() won't give it back to the OS.
   */
#ifdef FREE_MEM_ESTIMATE
  default_maxmem = FREE_MEM_ESTIMATE;
#else
  default_maxmem = 0;
#endif

  /* Scan command line, parse switches and locate input file names */

  if (argc < 2)
    usage();			/* nothing on the command line?? */

  file_index = 0;

  while (file_index < argc-1)
    file_index = process_one_file(argc, argv, file_index);

  /* All done. */
  exit(EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Пример #21
0
int
main(int argc, char **argv, char **envp)
{
#ifdef RUBY_GC_STRESS
    RUBY_EXTERN int gc_stress;
    gc_stress = getenv("RUBY_GC_STRESS") != NULL;
#endif
#ifdef _WIN32
    NtInitialize(&argc, &argv);
#endif
#if defined(__MACOS__) && defined(__MWERKS__)
    argc = ccommand(&argv);
#endif

    {
	RUBY_INIT_STACK;
	ruby_init();
	ruby_options(argc, argv);
	ruby_run();
    }
    return 0;
}
Пример #22
0
int
main (int argc, char **argv)
{
  struct jpeg_decompress_struct cinfo;
  struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  int file_index;
  djpeg_dest_ptr dest_mgr = NULL;
  FILE * input_file;
  FILE * output_file;
  JDIMENSION num_scanlines;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "djpeg";		/* in case C library doesn't provide it */

  /* Initialize the JPEG decompression object with default error handling. */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_decompress(&cinfo);
  /* Add some application-specific error messages (from cderror.h) */
  jerr.addon_message_table = cdjpeg_message_table;
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  jerr.last_addon_message = JMSG_LASTADDONCODE;

  /* Insert custom marker processor for COM and APP12.
   * APP12 is used by some digital camera makers for textual info,
   * so we provide the ability to display it as text.
   * If you like, additional APPn marker types can be selected for display,
   * but don't try to override APP0 or APP14 this way (see libjpeg.doc).
   */
  jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
  jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);

  /* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &cinfo);
#endif

  /* Scan command line to find file names. */
  /* It is convenient to use just one switch-parsing routine, but the switch
   * values read here are ignored; we will rescan the switches after opening
   * the input file.
   * (Exception: tracing level set here controls verbosity for COM markers
   * found during jpeg_read_header...)
   */

  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);

#ifdef TWO_FILE_COMMANDLINE
  /* Must have either -outfile switch or explicit output file name */
  if (outfilename == NULL) {
    if (file_index != argc-2) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
    outfilename = argv[file_index+1];
  } else {
    if (file_index != argc-1) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif

  /* Specify data source for decompression */
  jpeg_stdio_src(&cinfo, input_file);

  /* Read file header, set default decompression parameters */
  (void) jpeg_read_header(&cinfo, TRUE);

  /* Adjust default decompression parameters by re-parsing the options */
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);

  /* Initialize the output module now to let it override any crucial
   * option settings (for instance, GIF wants to force color quantization).
   */
  switch (requested_fmt) {
#ifdef BMP_SUPPORTED
  case FMT_BMP:
    dest_mgr = jinit_write_bmp(&cinfo, FALSE);
    break;
  case FMT_OS2:
    dest_mgr = jinit_write_bmp(&cinfo, TRUE);
    break;
#endif
#ifdef GIF_SUPPORTED
  case FMT_GIF:
    dest_mgr = jinit_write_gif(&cinfo);
    break;
#endif
#ifdef PPM_SUPPORTED
  case FMT_PPM:
    dest_mgr = jinit_write_ppm(&cinfo);
    break;
#endif
#ifdef RLE_SUPPORTED
  case FMT_RLE:
    dest_mgr = jinit_write_rle(&cinfo);
    break;
#endif
#ifdef TARGA_SUPPORTED
  case FMT_TARGA:
    dest_mgr = jinit_write_targa(&cinfo);
    break;
#endif
  default:
    ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
    break;
  }
  dest_mgr->output_file = output_file;

  /* Start decompressor */
  (void) jpeg_start_decompress(&cinfo);

  /* Write output file header */
  (*dest_mgr->start_output) (&cinfo, dest_mgr);

  /* Process data */
  while (cinfo.output_scanline < cinfo.output_height) {
    num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
					dest_mgr->buffer_height);
    (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  }

#ifdef PROGRESS_REPORT
  /* Hack: count final pass as done in case finish_output does an extra pass.
   * The library won't have updated completed_passes.
   */
  progress.pub.completed_passes = progress.pub.total_passes;
#endif

  /* Finish decompression and release memory.
   * I must do it in this order because output module has allocated memory
   * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
   */
  (*dest_mgr->finish_output) (&cinfo, dest_mgr);
  (void) jpeg_finish_decompress(&cinfo);
  jpeg_destroy_decompress(&cinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &cinfo);
#endif

  /* All done. */
  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Пример #23
0
int main(int argc, char *argv[])
{
    boolean print_parse = FALSE;
    boolean print_expanded = FALSE;
    char *arg;
    char *source_name = NULL;
    char *output_name = NULL;
    FILE *file;

    add_header_handler("module", set_module);
    add_header_handler("library", set_library);
    add_header_handler(NULL, end_of_headers);

    init_sym_table();
    init_feature();
    init_info();
    init_expand();
    init_compile();
    
#ifdef MACOS
	add_feature(symbol("macos"));
#	ifndef SHLB
	argc = ccommand( &argv );
#	endif
#endif


    while ((arg = *++argv) != NULL) {
	if (arg[0] == '-') {
	    switch (arg[1]) {
	      case 'd':
		if (arg[2] == '\0') {
		    print_parse = TRUE;
		    print_expanded = TRUE;
		}
		else {
		    char *ptr;
		    for (ptr = arg+2; *ptr != '\0'; ptr++) {
			switch (*ptr) {
			  case 'p':
			    print_parse = TRUE;
			    break;
			  case 'e':
			    print_expanded = TRUE;
			    break;
			  default:
			    fprintf(stderr, "Invalid thing to print: ``%c''\n",
				    *ptr);
			    usage();
			}
		    }
		}
		break;

	      case 'o':
		if (output_name != NULL) {
		    fprintf(stderr, "-o can only be used once.\n");
		    usage();
		}
		else if (arg[2] != '\0')
		    output_name = arg+2;
		else if (*++argv == NULL) {
		    fprintf(stderr, "-o must be followed by the output "
			    "file name.\n");
		    usage();
		}
		else
		    output_name = *argv;
		break;

	      case 'l':
		if (LibraryName != NULL) {
		    fprintf(stderr, "-l can only be used once.\n");
		    usage();
		}
		if (arg[2] != '\0')
		    LibraryName = symbol(arg+2);
		else if (*++argv == NULL) {
		    fprintf(stderr, "-l must be followed by the library "
			    "name.\n");
		    usage();
		}
		else
		    LibraryName = symbol(*argv);
		break;

	      case 'q':
		GiveWarnings = FALSE;
		break;

	      case 'D':
		if (arg[2] != '\0')
		    add_feature(symbol(arg + 2));
		else if (*++argv == NULL) {
		    fprintf(stderr,
			    "-D must be followed by the feature to define.\n");
		    usage();
		}
		else
		    add_feature(symbol(*argv));
		break;

	      case 'U':
		if (arg[2] != '\0')
		    remove_feature(symbol(arg + 2));
		else if (*++argv == NULL) {
		    fprintf(stderr, "-U must be followed by the feature "
			    "to undefine.\n");
		    usage();
		}
		else
		    remove_feature(symbol(*argv));
		break;

	      default:
		fprintf(stderr, "Invalid flag: ``%s''\n", arg);
		usage();
	    }
	}
	else if (source_name != NULL) {
	    fprintf(stderr, "Too many files\n");
	    usage();
	}
	else
	    source_name = arg;
    }

    if (source_name == NULL)
	usage();


    yyin = fopen(source_name, "rb");
    if (yyin == NULL) {
        /* Try the same filename but in the current directory */
        /* Start ptr at the null termination, and work backwards to a 
	   path separator. */
        char *ptr = source_name + strlen(source_name);
        for ( ; ptr != source_name; ptr--) {
	    if (*ptr == '/' || *ptr == '\\') {
	        /* We're pointing at the path separator, which is too far */
	        ptr++;
	        break;
	    }
	}
	/* If ptr is a different string than source_name, and it isn't
	   the empty string... */
	if (ptr != source_name && *ptr != 0) {
	    yyin = fopen(ptr, "rb");
	}
	if (yyin == NULL) {
	    perror(source_name);
	    exit(1);
	}
    }

    current_file = source_name;

    yyparse();

    if (print_parse) {
	printf("================ Original Parse Tree ================\n");
	print_body(Program, 0);
    }

    if (nerrors != 0)
	exit(1);

    /* Do the various source-to-source expansions. */
    expand(Program);

    if (print_expanded) {
	printf("================ Expanded Parse Tree ================\n");
	print_body(Program, 0);
    }

    if (nerrors != 0)
	exit(1);

    /* Run environment analysis */
    environment_analysis(Program);

    if (nerrors != 0)
	exit(1);

    if (output_name == NULL)
	output_name = make_output_name(source_name, ".dbc");

    if (strcmp(output_name, "-") == 0)
        file = stdout;
    else
        file = fopen(output_name, "wb");

    if (file == NULL) {
	perror(output_name);
	exit(1);
    }

    dump_setup_output(source_name, file);

    /* Generate code. */
    compile(Program);

    dump_finalize_output();

    fclose(file);

    exit(0);
    return 0;
}
Пример #24
0
int
main (int argc, char **argv)
{
  int argn;
  char * arg;
  int verbose = 0;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "rdjpgcom";	/* in case C library doesn't provide it */

  /* Parse switches, if any */
  for (argn = 1; argn < argc; argn++) {
    arg = argv[argn];
    if (arg[0] != '-')
      break;			/* not switch, must be file name */
    arg++;			/* advance over '-' */
    if (keymatch(arg, "verbose", 1)) {
      verbose++;
    } else
      usage();
  }

  /* Open the input file. */
  /* Unix style: expect zero or one file name */
  if (argn < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
  if (argn < argc) {
    if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
#ifdef USE_SETMODE		/* need to hack file mode? */
    setmode(fileno(stdin), O_BINARY);
#endif
#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
    if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open stdin\n", progname);
      exit(EXIT_FAILURE);
    }
#else
    infile = stdin;
#endif
  }

  /* Scan the JPEG headers. */
  (void) scan_JPEG_header(verbose);

  /* All done. */
  exit(EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Пример #25
0
int CRYPTOPP_CDECL main(int argc, char *argv[])
#endif
{
#ifdef _CRTDBG_LEAK_CHECK_DF
	// Turn on leak-checking
	int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
	tempflag |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag( tempflag );
#endif

#if defined(__MWERKS__) && defined(macintosh)
	argc = ccommand(&argv);
#endif

	try
	{
		std::string command, executableName, macFilename;

		if (argc < 2)
			command = 'h';
		else
			command = argv[1];

		if (command == "g")
		{
			char seed[1024], privFilename[128], pubFilename[128];
			unsigned int keyLength;

			cout << "Key length in bits: ";
			cin >> keyLength;

			cout << "\nSave private key to file: ";
			cin >> privFilename;

			cout << "\nSave public key to file: ";
			cin >> pubFilename;

			cout << "\nRandom Seed: ";
			ws(cin);
			cin.getline(seed, 1024);

			GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
		}
		else if (command == "rs")
			RSASignFile(argv[2], argv[3], argv[4]);
		else if (command == "rv")
		{
			bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
			cout << (verified ? "valid signature" : "invalid signature") << endl;
		}
		else if (command == "r")
		{
			char privFilename[128], pubFilename[128];
			char seed[1024], message[1024];

			cout << "Private key file: ";
			cin >> privFilename;

			cout << "\nPublic key file: ";
			cin >> pubFilename;

			cout << "\nRandom Seed: ";
			ws(cin);
			cin.getline(seed, 1024);

			cout << "\nMessage: ";
			cin.getline(message, 1024);

			string ciphertext = RSAEncryptString(pubFilename, seed, message);
			cout << "\nCiphertext: " << ciphertext << endl;

			string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
			cout << "\nDecrypted: " << decrypted << endl;
		}
Пример #26
0
int
main (int argc, char **argv)
{
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  int file_index;
  cjpeg_source_ptr src_mgr;
  FILE * input_file;
  FILE * output_file;
  JDIMENSION num_scanlines;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "cjpeg";		/* in case C library doesn't provide it */

  /* Initialize the JPEG compression object with default error handling. */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_compress(&cinfo);
  /* Add some application-specific error messages (from cderror.h) */
  jerr.addon_message_table = cdjpeg_message_table;
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  jerr.last_addon_message = JMSG_LASTADDONCODE;

  /* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &cinfo);
#endif

  /* Initialize JPEG parameters.
   * Much of this may be overridden later.
   * In particular, we don't yet know the input file's color space,
   * but we need to provide some value for jpeg_set_defaults() to work.
   */

  cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  jpeg_set_defaults(&cinfo);

  /* Scan command line to find file names.
   * It is convenient to use just one switch-parsing routine, but the switch
   * values read here are ignored; we will rescan the switches after opening
   * the input file.
   */

  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);

#ifdef TWO_FILE_COMMANDLINE
  /* Must have either -outfile switch or explicit output file name */
  if (outfilename == NULL) {
    if (file_index != argc-2) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
    outfilename = argv[file_index+1];
  } else {
    if (file_index != argc-1) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif

  /* Figure out the input file format, and set up to read it. */
  src_mgr = select_file_type(&cinfo, input_file);
  src_mgr->input_file = input_file;

  /* Read the input file header to obtain file size & colorspace. */
  (*src_mgr->start_input) (&cinfo, src_mgr);

  /* Now that we know input colorspace, fix colorspace-dependent defaults */
  jpeg_default_colorspace(&cinfo);

  /* Adjust default compression parameters by re-parsing the options */
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);

  /* Specify data destination for compression */
  jpeg_stdio_dest(&cinfo, output_file);

  /* Start compressor */
  jpeg_start_compress(&cinfo, TRUE);

  /* Process data */
  while (cinfo.next_scanline < cinfo.image_height) {
    num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
    (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  }

  /* Finish compression and release memory */
  (*src_mgr->finish_input) (&cinfo, src_mgr);
  jpeg_finish_compress(&cinfo);
  jpeg_destroy_compress(&cinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &cinfo);
#endif

  /* All done. */
  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Пример #27
0
int main(){
  ogg_stream_state os; /* take physical pages, weld into a logical
			  stream of packets */
  ogg_page         og; /* one Ogg bitstream page.  Vorbis packets are inside */
  ogg_packet       op; /* one raw packet of data for decode */
  
  vorbis_info      vi; /* struct that stores all the static vorbis bitstream
			  settings */
  vorbis_comment   vc; /* struct that stores all the user comments */

  vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  vorbis_block     vb; /* local working space for packet->PCM decode */

  int eos=0,ret;
  int i, founddata;

#if defined(macintosh) && defined(__MWERKS__)
  int argc = 0;
  char **argv = NULL;
  argc = ccommand(&argv); /* get a "command line" from the Mac user */
                          /* this also lets the user set stdin and stdout */
#endif

  /* we cheat on the WAV header; we just bypass 44 bytes and never
     verify that it matches 16bit/stereo/44.1kHz.  This is just an
     example, after all. */

#ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  /* if we were reading/writing a file, it would also need to in
     binary mode, eg, fopen("file.wav","wb"); */
  /* Beware the evil ifdef. We avoid these where we can, but this one we 
     cannot. Don't add any more, you'll probably go to hell if you do. */
  _setmode( _fileno( stdin ), _O_BINARY );
  _setmode( _fileno( stdout ), _O_BINARY );
#endif


  /* we cheat on the WAV header; we just bypass the header and never
     verify that it matches 16bit/stereo/44.1kHz.  This is just an
     example, after all. */

  readbuffer[0] = '\0';
  for (i=0, founddata=0; i<30 && ! feof(stdin) && ! ferror(stdin); i++)
  {
    fread(readbuffer,1,2,stdin);

    if ( ! strncmp((char*)readbuffer, "da", 2) )
    {
      founddata = 1;
      fread(readbuffer,1,6,stdin);
      break;
    }
  }

  /********** Encode setup ************/

  vorbis_info_init(&vi);

  /* choose an encoding mode.  A few possibilities commented out, one
     actually used: */

  /*********************************************************************
   Encoding using a VBR quality mode.  The usable range is -.1
   (lowest quality, smallest file) to 1. (highest quality, largest file).
   Example quality mode .4: 44kHz stereo coupled, roughly 128kbps VBR 
  
   ret = vorbis_encode_init_vbr(&vi,2,44100,.4);

   ---------------------------------------------------------------------

   Encoding using an average bitrate mode (ABR).
   example: 44kHz stereo coupled, average 128kbps VBR 
  
   ret = vorbis_encode_init(&vi,2,44100,-1,128000,-1);

   ---------------------------------------------------------------------

   Encode using a quality mode, but select that quality mode by asking for
   an approximate bitrate.  This is not ABR, it is true VBR, but selected
   using the bitrate interface, and then turning bitrate management off:

   ret = ( vorbis_encode_setup_managed(&vi,2,44100,-1,128000,-1) ||
           vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE2_SET,NULL) ||
           vorbis_encode_setup_init(&vi));

   *********************************************************************/

  ret=vorbis_encode_init_vbr(&vi,2,44100,0.1);

  /* do not continue if setup failed; this can happen if we ask for a
     mode that libVorbis does not support (eg, too low a bitrate, etc,
     will return 'OV_EIMPL') */

  if(ret)exit(1);

  /* add a comment */
  vorbis_comment_init(&vc);
  vorbis_comment_add_tag(&vc,"ENCODER","encoder_example.c");

  /* set up the analysis state and auxiliary encoding storage */
  vorbis_analysis_init(&vd,&vi);
  vorbis_block_init(&vd,&vb);
  
  /* set up our packet->stream encoder */
  /* pick a random serial number; that way we can more likely build
     chained streams just by concatenation */
  srand(time(NULL));
  ogg_stream_init(&os,rand());

  /* Vorbis streams begin with three headers; the initial header (with
     most of the codec setup parameters) which is mandated by the Ogg
     bitstream spec.  The second header holds any comment fields.  The
     third header holds the bitstream codebook.  We merely need to
     make the headers, then pass them to libvorbis one at a time;
     libvorbis handles the additional Ogg bitstream constraints */

  {
    ogg_packet header;
    ogg_packet header_comm;
    ogg_packet header_code;

    vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code);
    ogg_stream_packetin(&os,&header); /* automatically placed in its own
					 page */
    ogg_stream_packetin(&os,&header_comm);
    ogg_stream_packetin(&os,&header_code);

	/* This ensures the actual
	 * audio data will start on a new page, as per spec
	 */
	while(!eos){
		int result=ogg_stream_flush(&os,&og);
		if(result==0)break;
		fwrite(og.header,1,og.header_len,stdout);
		fwrite(og.body,1,og.body_len,stdout);
	}

  }
  
  while(!eos){
    long i;
    long bytes=fread(readbuffer,1,READ*4,stdin); /* stereo hardwired here */

    if(bytes==0){
      /* end of file.  this can be done implicitly in the mainline,
         but it's easier to see here in non-clever fashion.
         Tell the library we're at end of stream so that it can handle
         the last frame and mark end of stream in the output properly */
      vorbis_analysis_wrote(&vd,0);

    }else{
      /* data to encode */

      /* expose the buffer to submit data */
      float **buffer=vorbis_analysis_buffer(&vd,READ);
      
      /* uninterleave samples */
      for(i=0;i<bytes/4;i++){
	buffer[0][i]=((readbuffer[i*4+1]<<8)|
		      (0x00ff&(int)readbuffer[i*4]))/32768.f;
	buffer[1][i]=((readbuffer[i*4+3]<<8)|
		      (0x00ff&(int)readbuffer[i*4+2]))/32768.f;
      }
    
      /* tell the library how much we actually submitted */
      vorbis_analysis_wrote(&vd,i);
    }

    /* vorbis does some data preanalysis, then divvies up blocks for
       more involved (potentially parallel) processing.  Get a single
       block for encoding now */
    while(vorbis_analysis_blockout(&vd,&vb)==1){

      /* analysis, assume we want to use bitrate management */
      vorbis_analysis(&vb,NULL);
      vorbis_bitrate_addblock(&vb);

      while(vorbis_bitrate_flushpacket(&vd,&op)){
	
	/* weld the packet into the bitstream */
	ogg_stream_packetin(&os,&op);
	
	/* write out pages (if any) */
	while(!eos){
	  int result=ogg_stream_pageout(&os,&og);
	  if(result==0)break;
	  fwrite(og.header,1,og.header_len,stdout);
	  fwrite(og.body,1,og.body_len,stdout);
	  
	  /* this could be set above, but for illustrative purposes, I do
	     it here (to show that vorbis does know where the stream ends) */
	  
	  if(ogg_page_eos(&og))eos=1;
	}
      }
    }
  }

  /* clean up and exit.  vorbis_info_clear() must be called last */
  
  ogg_stream_clear(&os);
  vorbis_block_clear(&vb);
  vorbis_dsp_clear(&vd);
  vorbis_comment_clear(&vc);
  vorbis_info_clear(&vi);
  
  /* ogg_page and ogg_packet structs always point to storage in
     libvorbis.  They're never freed or manipulated directly */
  
  fprintf(stderr,"Done.\n");
  return(0);
}
Пример #28
0
int main( int argc, char **argv )
{
#ifdef PF_STATIC_DIC
	const char *DicName = NULL;
#else /* PF_STATIC_DIC */
	const char *DicName = PF_DEFAULT_DICTIONARY;
#endif /* !PF_STATIC_DIC */

	const char *SourceName = NULL;
	char IfInit = FALSE;
	char *s;
	cell_t i;
	int Result;

/* For Metroworks on Mac */
#ifdef __MWERKS__
	argc = ccommand(&argv);
#endif
	
	pfSetQuiet( FALSE );
/* Parse command line. */
	for( i=1; i<argc; i++ )
	{
		s = argv[i];

		if( *s == '-' )
		{
			char c;
			s++; /* past '-' */
			c = *s++;
			switch(c)
			{
			case 'i':
				IfInit = TRUE;
				DicName = NULL;
				break;
				
			case 'q':
				pfSetQuiet( TRUE );
				break;
				
			case 'd':
				if( *s != '\0' ) DicName = s;
				/* Allow space after -d (Thanks Aleksej Saushev) */
				/* Make sure there is another argument. */
				else if( (i+1) < argc )
				{
					DicName = argv[++i];
				}
				if (DicName == NULL || *DicName == '\0')
				{
					DicName = PF_DEFAULT_DICTIONARY;
				}
				break;
				
			default:
				ERR(("Unrecognized option!\n"));
				ERR(("pforth {-i} {-q} {-dfilename.dic} {sourcefilename}\n"));
				Result = 1;
				goto on_error;
				break;
			}
		}
		else
		{
			SourceName = s;
		}
	}
/* Force Init */
#ifdef PF_INIT_MODE
	IfInit = TRUE;
	DicName = NULL;
#endif

#ifdef PF_UNIT_TEST
	if( (Result = pfUnitTest()) != 0 )
	{
		ERR(("pForth stopping on unit test failure.\n"));
		goto on_error;
	}
#endif
	
	Result = pfDoForth( DicName, SourceName, IfInit);

on_error:
	return Result;
}
Пример #29
0
int
main (int argc, char **argv)
{
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  int file_index;
  cjpeg_source_ptr src_mgr;
  FILE * input_file;
  FILE * output_file = NULL;
  unsigned char *outbuffer = NULL;
  unsigned long outsize = 0;
  JDIMENSION num_scanlines;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "cjpeg";		/* in case C library doesn't provide it */

  /* Initialize the JPEG compression object with default error handling. */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_compress(&cinfo);
  /* Add some application-specific error messages (from cderror.h) */
  jerr.addon_message_table = cdjpeg_message_table;
  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  jerr.last_addon_message = JMSG_LASTADDONCODE;

  /* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &cinfo);
#endif

  /* Initialize JPEG parameters.
   * Much of this may be overridden later.
   * In particular, we don't yet know the input file's color space,
   * but we need to provide some value for jpeg_set_defaults() to work.
   */

  cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  cinfo.use_moz_defaults = TRUE;
  jpeg_set_defaults(&cinfo);

  /* Scan command line to find file names.
   * It is convenient to use just one switch-parsing routine, but the switch
   * values read here are ignored; we will rescan the switches after opening
   * the input file.
   */

  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);

#ifdef TWO_FILE_COMMANDLINE
  if (!memdst) {
    /* Must have either -outfile switch or explicit output file name */
    if (outfilename == NULL) {
      if (file_index != argc-2) {
        fprintf(stderr, "%s: must name one input and one output file\n",
                progname);
        usage();
      }
      outfilename = argv[file_index+1];
    } else {
      if (file_index != argc-1) {
        fprintf(stderr, "%s: must name one input and one output file\n",
                progname);
        usage();
      }
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else if (!memdst) {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif

  /* Figure out the input file format, and set up to read it. */
  src_mgr = select_file_type(&cinfo, input_file);
  src_mgr->input_file = input_file;

  /* Read the input file header to obtain file size & colorspace. */
  (*src_mgr->start_input) (&cinfo, src_mgr);

  /* Now that we know input colorspace, fix colorspace-dependent defaults */
#if JPEG_RAW_READER
  if (!is_jpeg)
#endif
    jpeg_default_colorspace(&cinfo);

  /* Adjust default compression parameters by re-parsing the options */
  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);

  /* Specify data destination for compression */
#if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  if (memdst)
    jpeg_mem_dest(&cinfo, &outbuffer, &outsize);
  else
#endif
    jpeg_stdio_dest(&cinfo, output_file);

  /* Start compressor */
  jpeg_start_compress(&cinfo, TRUE);

  /* Copy metadata */
  if (is_jpeg) {
    jpeg_saved_marker_ptr marker;
    
    /* In the current implementation, we don't actually need to examine the
     * option flag here; we just copy everything that got saved.
     * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
     * if the encoder library already wrote one.
     */
    for (marker = src_mgr->marker_list; marker != NULL; marker = marker->next) {
      if (cinfo.write_JFIF_header &&
          marker->marker == JPEG_APP0 &&
          marker->data_length >= 5 &&
          GETJOCTET(marker->data[0]) == 0x4A &&
          GETJOCTET(marker->data[1]) == 0x46 &&
          GETJOCTET(marker->data[2]) == 0x49 &&
          GETJOCTET(marker->data[3]) == 0x46 &&
          GETJOCTET(marker->data[4]) == 0)
        continue;			/* reject duplicate JFIF */
      if (cinfo.write_Adobe_marker &&
          marker->marker == JPEG_APP0+14 &&
          marker->data_length >= 5 &&
          GETJOCTET(marker->data[0]) == 0x41 &&
          GETJOCTET(marker->data[1]) == 0x64 &&
          GETJOCTET(marker->data[2]) == 0x6F &&
          GETJOCTET(marker->data[3]) == 0x62 &&
          GETJOCTET(marker->data[4]) == 0x65)
        continue;			/* reject duplicate Adobe */
      jpeg_write_marker(&cinfo, marker->marker, marker->data, marker->data_length);
    }
  }
  
  /* Process data */
  while (cinfo.next_scanline < cinfo.image_height) {
    num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
#if JPEG_RAW_READER
    if (is_jpeg)
      (void) jpeg_write_raw_data(&cinfo, src_mgr->plane_pointer, num_scanlines);
    else
#endif
      (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  }

  /* Finish compression and release memory */
  (*src_mgr->finish_input) (&cinfo, src_mgr);
  jpeg_finish_compress(&cinfo);
  jpeg_destroy_compress(&cinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout && output_file != NULL)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &cinfo);
#endif

  if (memdst) {
    fprintf(stderr, "Compressed size:  %lu bytes\n", outsize);
    if (outbuffer != NULL)
      free(outbuffer);
  }

  /* All done. */
  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Пример #30
0
 int main(){
  ogg_sync_state   oy; /* sync and verify incoming physical bitstream */
  ogg_stream_state os; /* take physical pages, weld into a logical
                          stream of packets */
  ogg_page         og; /* one Ogg bitstream page. Vorbis packets are inside */
  ogg_packet       op; /* one raw packet of data for decode */

  vorbis_info      vi; /* struct that stores all the static vorbis bitstream
                          settings */
  vorbis_comment   vc; /* struct that stores all the bitstream user comments */
  vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  vorbis_block     vb; /* local working space for packet->PCM decode */

  char *buffer;
  int  bytes;

  FILE *instream;
  FILE *outstream;
  char *inname = "01.ogg";
  char *outname = "esmith2000-09-28d1t15.raw";

//#ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
//  /* Beware the evil ifdef. We avoid these where we can, but this one we
//     cannot. Don't add any more, you'll probably go to hell if you do. */
//  //_setmode( _fileno( stdin ), _O_BINARY );
//  //_setmode( _fileno( stdout ), _O_BINARY );
//#endif

#if defined(macintosh) && defined(__MWERKS__)
  {
    int argc;
    char **argv;
    argc=ccommand(&argv); /* get a "command line" from the Mac user */
                     /* this also lets the user set stdin and stdout */
  }
#endif

  /********** Decode setup ************/

  //opening the file
  
  
  if( fopen_s( &instream, inname, "rb" ) != 0 )
  {
	  fprintf(stderr,"Can not open file %s\n", inname);
      exit(1);
  };
  
  if( fopen_s( &outstream, outname, "wb" ) != 0 )
  {
	  fprintf(stderr,"Can not open file %s\n", outname);
      exit(1);
  }


  ogg_sync_init(&oy); /* Now we can read pages */
  
  while(1){ /* we repeat if the bitstream is chained */
    int eos=0;
    int i;

    /* grab some data at the head of the stream. We want the first page
       (which is guaranteed to be small and only contain the Vorbis
       stream initial header) We need the first page to get the stream
       serialno. */

    /* submit a 4k block to libvorbis' Ogg layer */
    buffer=ogg_sync_buffer(&oy,4096);
    //bytes=fread(buffer,1,4096,stdin);
	bytes=fread(buffer,1,4096,instream);
    ogg_sync_wrote(&oy,bytes);
    
    /* Get the first page. */
    if(ogg_sync_pageout(&oy,&og)!=1){
      /* have we simply run out of data?  If so, we're done. */
      if(bytes<4096)break;
      
      /* error case.  Must not be Vorbis data */
      fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n");
      exit(1);
    }
  
    /* Get the serial number and set up the rest of decode. */
    /* serialno first; use it to set up a logical stream */
    ogg_stream_init(&os,ogg_page_serialno(&og));
    
    /* extract the initial header from the first page and verify that the
       Ogg bitstream is in fact Vorbis data */
    
    /* I handle the initial header first instead of just having the code
       read all three Vorbis headers at once because reading the initial
       header is an easy way to identify a Vorbis bitstream and it's
       useful to see that functionality seperated out. */
    
    vorbis_info_init(&vi);
    vorbis_comment_init(&vc);
    if(ogg_stream_pagein(&os,&og)<0){ 
      /* error; stream version mismatch perhaps */
      fprintf(stderr,"Error reading first page of Ogg bitstream data.\n");
      exit(1);
    }
    
    if(ogg_stream_packetout(&os,&op)!=1){ 
      /* no page? must not be vorbis */
      fprintf(stderr,"Error reading initial header packet.\n");
      exit(1);
    }
    
    if(vorbis_synthesis_headerin(&vi,&vc,&op)<0){ 
      /* error case; not a vorbis header */
      fprintf(stderr,"This Ogg bitstream does not contain Vorbis "
              "audio data.\n");
      exit(1);
    }
    
    /* At this point, we're sure we're Vorbis. We've set up the logical
       (Ogg) bitstream decoder. Get the comment and codebook headers and
       set up the Vorbis decoder */
    
    /* The next two packets in order are the comment and codebook headers.
       They're likely large and may span multiple pages. Thus we read
       and submit data until we get our two packets, watching that no
       pages are missing. If a page is missing, error out; losing a
       header page is the only place where missing data is fatal. */
    
    i=0;
    while(i<2){
      while(i<2){
        int result=ogg_sync_pageout(&oy,&og);
        if(result==0)break; /* Need more data */
        /* Don't complain about missing or corrupt data yet. We'll
           catch it at the packet output phase */
        if(result==1){
          ogg_stream_pagein(&os,&og); /* we can ignore any errors here
                                         as they'll also become apparent
                                         at packetout */
          while(i<2){
            result=ogg_stream_packetout(&os,&op);
            if(result==0)break;
            if(result<0){
              /* Uh oh; data at some point was corrupted or missing!
                 We can't tolerate that in a header.  Die. */
              fprintf(stderr,"Corrupt secondary header.  Exiting.\n");
              exit(1);
            }
            result=vorbis_synthesis_headerin(&vi,&vc,&op);
            if(result<0){
              fprintf(stderr,"Corrupt secondary header.  Exiting.\n");
              exit(1);
            }
            i++;
          }
        }
      }
      /* no harm in not checking before adding more */
      buffer=ogg_sync_buffer(&oy,4096);
      //bytes=fread(buffer,1,4096,stdin);
	  bytes=fread(buffer,1,4096,instream);
      if(bytes==0 && i<2){
        fprintf(stderr,"End of file before finding all Vorbis headers!\n");
        exit(1);
      }
      ogg_sync_wrote(&oy,bytes);
    }
    
    /* Throw the comments plus a few lines about the bitstream we're
       decoding */
    {
      char **ptr=vc.user_comments;
      while(*ptr){
        fprintf(stderr,"%s\n",*ptr);
        ++ptr;
      }
      fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi.channels,vi.rate);
      fprintf(stderr,"Encoded by: %s\n\n",vc.vendor);
    }
    
    convsize=4096/vi.channels;

    /* OK, got and parsed all three headers. Initialize the Vorbis
       packet->PCM decoder. */
    if(vorbis_synthesis_init(&vd,&vi)==0){ /* central decode state */
      vorbis_block_init(&vd,&vb);          /* local state for most of the decode
                                              so multiple block decodes can
                                              proceed in parallel. We could init
                                              multiple vorbis_block structures
                                              for vd here */
      
      /* The rest is just a straight decode loop until end of stream */
      while(!eos){
        while(!eos){
          int result=ogg_sync_pageout(&oy,&og);
          if(result==0)break; /* need more data */
          if(result<0){ /* missing or corrupt data at this page position */
            fprintf(stderr,"Corrupt or missing data in bitstream; "
                    "continuing...\n");
          }else{
            ogg_stream_pagein(&os,&og); /* can safely ignore errors at
                                           this point */
            while(1){
              result=ogg_stream_packetout(&os,&op);
              
              if(result==0)break; /* need more data */
              if(result<0){ /* missing or corrupt data at this page position */
                /* no reason to complain; already complained above */
              }else{
                /* we have a packet.  Decode it */
                float **pcm;
                int samples;
                
                if(vorbis_synthesis(&vb,&op)==0) /* test for success! */
                  vorbis_synthesis_blockin(&vd,&vb);
                /* 
                   
                **pcm is a multichannel float vector.  In stereo, for
                example, pcm[0] is left, and pcm[1] is right.  samples is
                the size of each channel.  Convert the float values
                (-1.<=range<=1.) to whatever PCM format and write it out */
                
                while((samples=vorbis_synthesis_pcmout(&vd,&pcm))>0){
                  int j;
                  int clipflag=0;
                  int bout=(samples<convsize?samples:convsize);
                  
                  /* convert floats to 16 bit signed ints (host order) and
                     interleave */
                  for(i=0;i<vi.channels;i++){
                    ogg_int16_t *ptr=convbuffer+i;
                    float  *mono=pcm[i];
                    for(j=0;j<bout;j++){
#if 1
                      int val=floor(mono[j]*32767.f+.5f);
#else /* optional dither */
                      int val=mono[j]*32767.f+drand48()-0.5f;
#endif
                      /* might as well guard against clipping */
                      if(val>32767){
                        val=32767;
                        clipflag=1;
                      }
                      if(val<-32768){
                        val=-32768;
                        clipflag=1;
                      }
                      *ptr=val;
                      ptr+=vi.channels;
                    }
                  }
                  
                  if(clipflag)
                    fprintf(stderr,"Clipping in frame %ld\n",(long)(vd.sequence));
                  
                  
                  //fwrite(convbuffer,2*vi.channels,bout,stdout);
				  fwrite(convbuffer,2*vi.channels,bout,outstream);
                  
                  vorbis_synthesis_read(&vd,bout); /* tell libvorbis how
                                                      many samples we
                                                      actually consumed */
                }            
              }
            }
            if(ogg_page_eos(&og))eos=1;
          }
        }
        if(!eos){
          buffer=ogg_sync_buffer(&oy,4096);
          //bytes=fread(buffer,1,4096,stdin);
		  bytes=fread(buffer,1,4096,instream);
          ogg_sync_wrote(&oy,bytes);
          if(bytes==0)eos=1;
        }
      }
      
      /* ogg_page and ogg_packet structs always point to storage in
         libvorbis.  They're never freed or manipulated directly */
      
      vorbis_block_clear(&vb);
      vorbis_dsp_clear(&vd);
    }else{
      fprintf(stderr,"Error: Corrupt header during playback initialization.\n");
    }

    /* clean up this logical bitstream; before exit we see if we're
       followed by another [chained] */
    
    ogg_stream_clear(&os);
    vorbis_comment_clear(&vc);
    vorbis_info_clear(&vi);  /* must be called last */
  }

  /* OK, clean up the framer */
  ogg_sync_clear(&oy);
  
  fprintf(stderr,"Done.\n");
  return(0);
}