Beispiel #1
0
int main(int argc, char *argv[])
{
    struct mhead mh;
    FILE *fp, *fo;
    long track1;
    int i, n, track1l;

    fp = stdin;
    fo = stdout;
    progname = argv[0];
    while ((n = getopt(argc, argv, "uv")) != -1) {
	switch (n) {
            case 'u':
                fprintf(stderr, "Usage: %s [ options ] [ midi_file ] [ csv_file ]\n", progname);
                fprintf(stderr, "       Options:\n");
                fprintf(stderr, "           -u            Print this message\n");
                fprintf(stderr, "           -v            Verbose: dump header and track information\n");
		fprintf(stderr, "Version %s\n", VERSION);
		return 0;

            case 'v':
		verbose = TRUE;
		break;

            case '?':
                fprintf(stderr, "%s: undefined option -%c specified.\n",
		    progname, n);
		return 2;
	}
    }

    i = 0;
    while (optind < argc) {
	switch (i++) {
	    case 0:
                if (strcmp(argv[optind], "-") != 0) {
                    fp = fopen(argv[optind], "rb");
		    if (fp == NULL) {
                        fprintf(stderr, "%s: Unable to to open MIDI input file %s\n",
				progname, argv[optind]);
			return 2;
		    }
		}
		break;

	    case 1:
                if (strcmp(argv[optind], "-") != 0) {
                    fo = fopen(argv[optind], "w");
		    if (fo == NULL) {
                        fprintf(stderr, "%s: Unable to to create CSV output file %s\n",
				progname, argv[optind]);
			return 2;
		    }
		}
		break;
	}
	optind++;
    }
#ifdef _WIN32

    /*  If input is from standard input, set the input file
    	mode to binary.  */

    if (fp == stdin) {
	_setmode(_fileno(fp), _O_BINARY);
    }
#endif

    /* Read and validate header */

    readMidiFileHeader(fp, &mh);
    if (memcmp(mh.chunktype, "MThd", sizeof mh.chunktype) != 0) {
        fprintf(stderr, "%s is not a Standard MIDI File.\n", argv[1]);
	return 2;
    }
    if (verbose) {
        fprintf(stderr, "Format %d MIDI file.  %d tracks, %d ticks per quarter note.\n",
	      mh.format, mh.ntrks, mh.division);
    }

    /*	Output header  */

    fprintf(fo, "0, 0, Header, %d, %d, %d\n", mh.format, mh.ntrks, mh.division);

    /*	Process tracks */

    for (i = 0; i < mh.ntrks; i++) {
	struct mtrack mt;
	byte *trk;

	if (i == 0) {
	    track1 = ftell(fp);
	}

	readMidiTrackHeader(fp, &mt);
        if (memcmp(mt.chunktype, "MTrk", sizeof mt.chunktype) != 0) {
            fprintf(stderr, "Track %d header is invalid.\n", i + 1);
	    return 2;
	}

	if (verbose) {
            fprintf(stderr, "Track %d: length %ld.\n", i + 1, mt.length);
	}
        fprintf(fo, "%d, 0, Start_track\n", i + 1);

	trk = (byte *) malloc(mt.length);
	if (trk == NULL) {
             fprintf(stderr, "%s: Cannot allocate %ld bytes for track.\n",
		progname, mt.length);
	     return 2;
	}

	fread((char *) trk, (int) mt.length, 1, fp);
	if (i == 0) {
	    track1l = (int) (ftell(fp) - track1);
	}

	trackcsv(fo, i + 1, trk, mt.length, mh.division);
	free(trk);
    }
    fprintf(fo, "0, 0, End_of_file\n");
    return 0;
}
Beispiel #2
0
Datei: main.c Projekt: abetusk/jq
int main(int argc, char* argv[]) {
  jq_state *jq = NULL;
  int ret = 0;
  int compiled = 0;
  int parser_flags = 0;
  int nfiles = 0;
  int badwrite;
  jv program_arguments = jv_array();

#ifdef WIN32
  SetConsoleOutputCP(CP_UTF8);
  fflush(stdout);
  fflush(stderr);
  _setmode(fileno(stdout), _O_TEXT | _O_U8TEXT);
  _setmode(fileno(stderr), _O_TEXT | _O_U8TEXT);
  int wargc;
  wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &wargc);
  assert(wargc == argc);
  size_t arg_sz;
  for (int i = 0; i < argc; i++) {
    argv[i] = alloca((arg_sz = WideCharToMultiByte(CP_UTF8,
                                                   0,
                                                   wargv[i],
                                                   -1, 0, 0, 0, 0)));
    WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], arg_sz, 0, 0);
  }
#endif

  if (argc) progname = argv[0];

  jq = jq_init();
  if (jq == NULL) {
    perror("malloc");
    ret = 2;
    goto out;
  }

  int dumpopts = JV_PRINT_INDENT_FLAGS(2);
  const char* program = 0;

  jv_extra_opt extra_opt;
  extra_opt.array_fold=0;
  extra_opt.array_fold_indent=1;

  jq_util_input_state *input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb

  int further_args_are_files = 0;
  int jq_flags = 0;
  size_t short_opts = 0;
  jv lib_search_paths = jv_null();
  for (int i=1; i<argc; i++, short_opts = 0) {
    if (further_args_are_files) {
      jq_util_input_add_input(input_state, argv[i]);
      nfiles++;
    } else if (!strcmp(argv[i], "--")) {
      if (!program) usage(2);
      further_args_are_files = 1;
    } else if (!isoptish(argv[i])) {
      if (program) {
        jq_util_input_add_input(input_state, argv[i]);
        nfiles++;
      } else {
        program = argv[i];
      }
    } else {
      if (argv[i][1] == 'L') {
        if (jv_get_kind(lib_search_paths) == JV_KIND_NULL)
          lib_search_paths = jv_array();
        if (argv[i][2] != 0) { // -Lname (faster check than strlen)
            lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i]+2)));
        } else if (i >= argc - 1) {
          fprintf(stderr, "-L takes a parameter: (e.g. -L /search/path or -L/search/path)\n");
          die();
        } else {
          lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i+1])));
          i++;
        }
        continue;
      }

      if (isoption(argv[i], 0, "fold", &short_opts)) {
        if (i >= argc - 1) {
          fprintf(stderr, "%s: --fold takes one parameter\n", progname);
          die();
        }
        extra_opt.array_fold = atoi(argv[i+1]);
        if (extra_opt.array_fold < 1 || extra_opt.array_fold > 255) {
          fprintf(stderr, "%s: --fold takes a number between 1 and 255\n", progname);
          die();
        }
        i++;
        if (!short_opts) continue;
      }


      if (isoption(argv[i], 's', "slurp", &short_opts)) {
        options |= SLURP;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'r', "raw-output", &short_opts)) {
        options |= RAW_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'c', "compact-output", &short_opts)) {
        dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'C', "color-output", &short_opts)) {
        options |= COLOR_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'M', "monochrome-output", &short_opts)) {
        options |= NO_COLOR_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'a', "ascii-output", &short_opts)) {
        options |= ASCII_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "unbuffered", &short_opts)) {
        options |= UNBUFFERED_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'S', "sort-keys", &short_opts)) {
        options |= SORTED_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'R', "raw-input", &short_opts)) {
        options |= RAW_INPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'n', "null-input", &short_opts)) {
        options |= PROVIDE_NULL;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'f', "from-file", &short_opts)) {
        options |= FROM_FILE;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'j', "join-output", &short_opts)) {
        options |= RAW_OUTPUT | RAW_NO_LF;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "tab", &short_opts)) {
        dumpopts &= ~JV_PRINT_INDENT_FLAGS(7);
        dumpopts |= JV_PRINT_TAB | JV_PRINT_PRETTY;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "indent", &short_opts)) {
        if (i >= argc - 1) {
          fprintf(stderr, "%s: --indent takes one parameter\n", progname);
          die();
        }
        dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));
        int indent = atoi(argv[i+1]);
        if (indent < -1 || indent > 7) {
          fprintf(stderr, "%s: --indent takes a number between -1 and 7\n", progname);
          die();
        }
        dumpopts |= JV_PRINT_INDENT_FLAGS(indent);
        i++;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "seq", &short_opts)) {
        options |= SEQ;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "stream", &short_opts)) {
        parser_flags |= JV_PARSE_STREAMING;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "stream-errors", &short_opts)) {
        parser_flags |= JV_PARSE_STREAM_ERRORS;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'e', "exit-status", &short_opts)) {
        options |= EXIT_STATUS;
        if (!short_opts) continue;
      }
      // FIXME: For --arg* we should check that the varname is acceptable
      if (isoption(argv[i], 0, "arg", &short_opts)) {
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --arg takes two parameters (e.g. --arg varname value)\n", progname);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        arg = jv_object_set(arg, jv_string("value"), jv_string(argv[i+2]));
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "argjson", &short_opts)) {
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --argjson takes two parameters (e.g. --argjson varname text)\n", progname);
          die();
        }
        jv v = jv_parse(argv[i+2]);
        if (!jv_is_valid(v)) {
          fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        arg = jv_object_set(arg, jv_string("value"), v);
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "argfile", &short_opts) ||
          isoption(argv[i], 0, "slurpfile", &short_opts)) {
        const char *which;
        if (isoption(argv[i], 0, "argfile", &short_opts))
          which = "argfile";
        else
          which = "slurpfile";
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --%s takes two parameters (e.g. --%s varname filename)\n", progname, which, which);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        jv data = jv_load_file(argv[i+2], 0);
        if (!jv_is_valid(data)) {
          data = jv_invalid_get_msg(data);
          fprintf(stderr, "%s: Bad JSON in --%s %s %s: %s\n", progname, which,
                  argv[i+1], argv[i+2], jv_string_value(data));
          jv_free(data);
          jv_free(arg);
          ret = 2;
          goto out;
        }
        if (isoption(argv[i], 0, "argfile", &short_opts) &&
            jv_get_kind(data) == JV_KIND_ARRAY && jv_array_length(jv_copy(data)) == 1)
            data = jv_array_get(data, 0);
        arg = jv_object_set(arg, jv_string("value"), data);
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i],  0,  "debug-dump-disasm", &short_opts)) {
        options |= DUMP_DISASM;
        if (!short_opts) continue;
      }
      if (isoption(argv[i],  0,  "debug-trace", &short_opts)) {
        jq_flags |= JQ_DEBUG_TRACE;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'h', "help", &short_opts)) {
        usage(0);
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'V', "version", &short_opts)) {
        printf("jq-%s\n", JQ_VERSION);
        ret = 0;
        goto out;
      }
      if (isoption(argv[i], 0, "run-tests", &short_opts)) {
        i++;
        // XXX Pass program_arguments, even a whole jq_state *, through;
        // could be useful for testing
        ret = jq_testsuite(lib_search_paths,
                           (options & DUMP_DISASM) || (jq_flags & JQ_DEBUG_TRACE),
                           argc - i, argv + i);
        goto out;
      }

      // check for unknown options... if this argument was a short option
      if (strlen(argv[i]) != short_opts + 1) {
        fprintf(stderr, "%s: Unknown option %s\n", progname, argv[i]);
        die();
      }
    }
  }

  if (isatty(fileno(stdout))) {
    dumpopts |= JV_PRINT_ISATTY;
#ifndef WIN32
  /* Disable color by default on Windows builds as Windows
     terminals tend not to display it correctly */
    dumpopts |= JV_PRINT_COLOR;
#endif
  }
  if (options & SORTED_OUTPUT) dumpopts |= JV_PRINT_SORTED;
  if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII;
  if (options & COLOR_OUTPUT) dumpopts |= JV_PRINT_COLOR;
  if (options & NO_COLOR_OUTPUT) dumpopts &= ~JV_PRINT_COLOR;

  if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {
    // Default search path list
    lib_search_paths = JV_ARRAY(jv_string("~/.jq"),
                                jv_string("$ORIGIN/../lib/jq"),
                                jv_string("$ORIGIN/lib"));
  }
  jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths);

  char *origin = strdup(argv[0]);
  if (origin == NULL) {
    fprintf(stderr, "Error: out of memory\n");
    exit(1);
  }
  jq_set_attr(jq, jv_string("JQ_ORIGIN"), jv_string(dirname(origin)));
  free(origin);

  if (strchr(JQ_VERSION, '-') == NULL)
    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string(JQ_VERSION));
  else
    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string_fmt("%.*s-master", (int)(strchr(JQ_VERSION, '-') - JQ_VERSION), JQ_VERSION));

#if (!defined(WIN32) && defined(HAVE_ISATTY)) || defined(HAVE__ISATTY)

#if defined(HAVE__ISATTY) && defined(isatty)
#undef isatty
#define isatty _isatty
#endif

  if (!program && isatty(STDOUT_FILENO) && !isatty(STDIN_FILENO))
    program = ".";
#endif

  if (!program) usage(2);

  if (options & FROM_FILE) {
    char *program_origin = strdup(program);
    if (program_origin == NULL) {
      perror("malloc");
      exit(2);
    }

    jv data = jv_load_file(program, 1);
    if (!jv_is_valid(data)) {
      data = jv_invalid_get_msg(data);
      fprintf(stderr, "%s: %s\n", progname, jv_string_value(data));
      jv_free(data);
      ret = 2;
      goto out;
    }
    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin))));
    compiled = jq_compile_args(jq, jv_string_value(data), jv_copy(program_arguments));
    free(program_origin);
    jv_free(data);
  } else {
    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good?
    compiled = jq_compile_args(jq, program, jv_copy(program_arguments));
  }
  if (!compiled){
    ret = 3;
    goto out;
  }

  if (options & DUMP_DISASM) {
    jq_dump_disassembly(jq, 0);
    printf("\n");
  }

  if ((options & SEQ))
    parser_flags |= JV_PARSE_SEQ;

  if ((options & RAW_INPUT))
    jq_util_input_set_parser(input_state, NULL, (options & SLURP) ? 1 : 0);
  else
    jq_util_input_set_parser(input_state, jv_parser_new(parser_flags), (options & SLURP) ? 1 : 0);

  // Let jq program read from inputs
  jq_set_input_cb(jq, jq_util_input_next_input_cb, input_state);

  // Let jq program call `debug` builtin and have that go somewhere
  jq_set_debug_cb(jq, debug_cb, &dumpopts);

  if (nfiles == 0)
    jq_util_input_add_input(input_state, "-");

  if (options & PROVIDE_NULL) {

    if (extra_opt.array_fold==0) {
      ret = process(jq, jv_null(), jq_flags, dumpopts);
    } else {
      ret = process_extra_opt(jq, jv_null(), jq_flags, dumpopts, &extra_opt);
    }
  } else {
    jv value;
    while (jq_util_input_errors(input_state) == 0 &&
           (jv_is_valid((value = jq_util_input_next_input(input_state))) || jv_invalid_has_msg(jv_copy(value)))) {
      if (jv_is_valid(value)) {
        if (extra_opt.array_fold==0) {
          ret = process(jq, value, jq_flags, dumpopts);
        } else {
          ret = process_extra_opt(jq, value, jq_flags, dumpopts, &extra_opt);
        }
        continue;
      }

      // Parse error
      jv msg = jv_invalid_get_msg(value);
      if (!(options & SEQ)) {
        // --seq -> errors are not fatal
        ret = 4;
        fprintf(stderr, "parse error: %s\n", jv_string_value(msg));
        jv_free(msg);
        break;
      }
      fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg));
      jv_free(msg);
    }
  }

  if (jq_util_input_errors(input_state) != 0)
    ret = 2;

out:
  badwrite = ferror(stdout);
  if (fclose(stdout)!=0 || badwrite) {
    fprintf(stderr,"Error: writing output failed: %s\n", strerror(errno));
    ret = 2;
  }

  jv_free(program_arguments);
  jq_util_input_free(&input_state);
  jq_teardown(&jq);
  if (ret >= 10 && (options & EXIT_STATUS))
    return ret - 10;
  if (ret >= 10)
    return 0;
  return ret;
}
Beispiel #3
0
void
__gnat_set_text_mode (int handle)
{
  _setmode (handle, O_TEXT);
}
Beispiel #4
0
int main(int argc, char **argv)
{
  int32 length;
  int c, block = 1, last_type = ASCII;

  ifp = stdin;
  ofp = stdout;
  print_banner();

  if (argc > 3)
    usage();

  /* possibly open input & output files */
  if (argc >= 2) {
    ifp = fopen(argv[1], "r");
    if (!ifp) {
      fprintf(stderr, "error: cannot open %s for reading\n", argv[1]);
      exit(1);
    }
  }
  if (argc == 3) {
    ofp = fopen(argv[2], "w");
    if (!ofp) {
      fprintf(stderr, "error: cannot open %s for writing\n", argv[2]);
      exit(1);
    }
  }

  #ifdef _MSDOS
    /* As we are processing a PFB (binary) input */
    /* file, we must set its file mode to binary. */
    _setmode(_fileno(ifp), _O_BINARY);
  #endif

  /* main loop through blocks */

  for (;;) {
    c = fgetc(ifp);
    if (c == EOF) {
      break;
    }
    if (c != MARKER) {
      fprintf(stderr,
              "error:  missing marker (128) at beginning of block %d",
              block);
      exit(1);
    }
    switch (c = fgetc(ifp)) {
    case ASCII:
      if (last_type != ASCII)
        fputc('\n', ofp);
      last_type = ASCII;
      for (length = read_length(); length > 0; length--)
        if ((c = fgetc(ifp)) == '\r')
          fputc('\n', ofp);
        else
          fputc(c, ofp);
      break;
    case BINARY:
      last_type = BINARY;
      for (length = read_length(); length > 0; length--)
        output_hex(fgetc(ifp));
      break;
    case DONE:
      /* nothing to be done --- will exit at top of loop with EOF */
      break;
    default:
      fprintf(stderr, "error: bad block type %d in block %d\n",
              c, block);
      break;
    }
    block++;
  }
  fclose(ifp);
  fclose(ofp);
  syncfs("/");
  return 0;
}
Beispiel #5
0
int
main(int argc, char *argv[])
{
  int c;
  FILE *ifp = 0, *ofp = 0;
  const char *ifp_filename = "<stdin>";
  struct font_reader fr;
  int max_blocklen = -1;

  Clp_Parser *clp =
    Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
  program_name = Clp_ProgramName(clp);

  /* interpret command line arguments using CLP */
  while (1) {
    int opt = Clp_Next(clp);
    switch (opt) {

     case BLOCK_LEN_OPT:
      max_blocklen = clp->val.i;
      if (max_blocklen <= 0) {
	max_blocklen = 1;
	error("warning: block length raised to %d", max_blocklen);
      }
      break;

     output_file:
     case OUTPUT_OPT:
      if (ofp)
	fatal_error("output file already specified");
      if (strcmp(clp->vstr, "-") == 0)
	ofp = stdout;
      else {
	ofp = fopen(clp->vstr, "wb");
	if (!ofp) fatal_error("%s: %s", clp->vstr, strerror(errno));
      }
      break;

     case HELP_OPT:
      usage();
      exit(0);
      break;

     case VERSION_OPT:
      printf("t1binary (LCDF t1utils) %s\n", VERSION);
      printf("Copyright (C) 1992-2010 I. Lee Hetherington, Eddie Kohler et al.\n\
This is free software; see the source for copying conditions.\n\
There is NO warranty, not even for merchantability or fitness for a\n\
particular purpose.\n");
      exit(0);
      break;

     case Clp_NotOption:
      if (ifp && ofp)
	fatal_error("too many arguments");
      else if (ifp)
	goto output_file;
      if (strcmp(clp->vstr, "-") == 0)
	ifp = stdin;
      else {
	ifp_filename = clp->vstr;
	ifp = fopen(clp->vstr, "r");
	if (!ifp) fatal_error("%s: %s", clp->vstr, strerror(errno));
      }
      break;

     case Clp_Done:
      goto done;

     case Clp_BadOption:
      short_usage();
      exit(1);
      break;

    }
  }

 done:
  if (!ifp) ifp = stdin;
  if (!ofp) ofp = stdout;

#if defined(_MSDOS) || defined(_WIN32)
  /* As we are processing a PFB (binary) output */
  /* file, we must set its file mode to binary. */
  _setmode(_fileno(ofp), _O_BINARY);
#endif

  /* prepare font reader and pfb writer */
  fr.output_ascii = pfb_output_ascii;
  fr.output_binary = pfb_output_binary;
  fr.output_end = pfb_output_end;
  init_pfb_writer(&w, max_blocklen, ofp);

  /* peek at first byte to see if it is the PFB marker 0x80 */
  c = getc(ifp);
  ungetc(c, ifp);

  /* do the file */
  if (c == PFB_MARKER)
    process_pfb(ifp, ifp_filename, &fr);
  else if (c == '%')
    process_pfa(ifp, ifp_filename, &fr);
  else
    fatal_error("%s does not start with font marker (`%%' or 0x80)", ifp_filename);

  fclose(ifp);
  fclose(ofp);

  if (!w.binary_blocks_written)
    fatal_error("no binary blocks written! Are you sure this was a font?");

  return 0;
}
Beispiel #6
0
int main( int argc, char * const argv[] )
#endif
{
#if defined( HAVE_GETRLIMIT )
	struct rlimit limit_data;
#endif
	system_character_t acquiry_operating_system[ 32 ];

	system_character_t * const *source_filenames   = NULL;
	libcerror_error_t *error                       = NULL;
	log_handle_t *log_handle                       = NULL;
	system_character_t *acquiry_software_version   = NULL;
	system_character_t *log_filename               = NULL;
	system_character_t *option_header_codepage     = NULL;
	system_character_t *option_process_buffer_size = NULL;
	system_character_t *option_target_path         = NULL;
	system_character_t *program                    = _SYSTEM_STRING( "ewfrecover" );
	system_integer_t option                        = 0;
	uint8_t calculate_md5                          = 1;
	uint8_t print_status_information               = 1;
	uint8_t use_chunk_data_functions               = 0;
	uint8_t verbose                                = 0;
	int number_of_filenames                        = 0;
	int result                                     = 1;

#if !defined( HAVE_GLOB_H )
	ewftools_glob_t *glob                        = NULL;
#endif

	libcnotify_stream_set(
	 stderr,
	 NULL );
	libcnotify_verbose_set(
	 1 );

	if( libclocale_initialize(
             "ewftools",
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to initialize locale values.\n" );

		goto on_error;
	}
	if( ewftools_output_initialize(
	     _IONBF,
	     &error ) != 1 )
	{
		ewftools_output_version_fprint(
		 stderr,
		 program );

		fprintf(
		 stderr,
		 "Unable to initialize output settings.\n" );

		goto on_error;
	}
#if defined( WINAPI ) && !defined( __CYGWIN__ )
#if defined( _MSC_VER )
	if( _setmode(
	     _fileno(
	      stdout ),
	     _O_BINARY ) == -1 )
#else
	if( setmode(
	     _fileno(
	      stdout ),
	     _O_BINARY ) == -1 )
#endif
	{
		ewftools_output_version_fprint(
		 stderr,
		 program );

		fprintf(
		 stderr,
		 "Unable to set stdout to binary mode.\n" );

		usage_fprint(
		 stdout );

		goto on_error;
	}
#endif
	while( ( option = ewftools_getopt(
	                   argc,
	                   argv,
	                   _SYSTEM_STRING( "A:f:hl:p:qt:vVx" ) ) ) != (system_integer_t) -1 )
	{
		switch( option )
		{
			case (system_integer_t) '?':
			default:
				ewftools_output_version_fprint(
				 stderr,
				 program );

				fprintf(
				 stderr,
				 "Invalid argument: %" PRIs_SYSTEM ".\n",
				 argv[ optind ] );

				usage_fprint(
				 stderr );

				goto on_error;

			case (system_integer_t) 'A':
				option_header_codepage = optarg;

				break;

			case (system_integer_t) 'h':
				ewftools_output_version_fprint(
				 stderr,
				 program );

				usage_fprint(
				 stderr );

				return( EXIT_SUCCESS );

			case (system_integer_t) 'l':
				log_filename = optarg;

				break;

			case (system_integer_t) 'p':
				option_process_buffer_size = optarg;

				break;

			case (system_integer_t) 'q':
				print_status_information = 0;

				break;

			case (system_integer_t) 't':
				option_target_path = optarg;

				break;

			case (system_integer_t) 'v':
				verbose = 1;

				break;

			case (system_integer_t) 'V':
				ewftools_output_version_fprint(
				 stderr,
				 program );

				ewftools_output_copyright_fprint(
				 stderr );

				return( EXIT_SUCCESS );

			case (system_integer_t) 'x':
				use_chunk_data_functions = 1;

				break;
		}
	}
	if( optind == argc )
	{
		ewftools_output_version_fprint(
		 stderr,
		 program );

		fprintf(
		 stderr,
		 "Missing EWF image file(s).\n" );

		usage_fprint(
		 stderr );

		goto on_error;
	}
	ewftools_output_version_fprint(
	 stderr,
	 program );

	libcnotify_verbose_set(
	 verbose );

#if !defined( HAVE_LOCAL_LIBEWF )
	libewf_notify_set_verbose(
	 verbose );
	libewf_notify_set_stream(
	 stderr,
	 NULL );
#endif

#if !defined( HAVE_GLOB_H )
	if( ewftools_glob_initialize(
	     &glob,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to initialize glob.\n" );

		goto on_error;
	}
	if( ewftools_glob_resolve(
	     glob,
	     &( argv[ optind ] ),
	     argc - optind,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to resolve glob.\n" );

		goto on_error;
	}
	if( ewftools_glob_get_results(
	     glob,
	     &number_of_filenames,
	     (system_character_t ***) &source_filenames,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to retrieve glob results.\n" );

		goto on_error;
	}
#else
	source_filenames    = &( argv[ optind ] );
	number_of_filenames = argc - optind;
#endif

	if( export_handle_initialize(
	     &ewfrecover_export_handle,
	     calculate_md5,
	     use_chunk_data_functions,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to create export handle.\n" );

		goto on_error;
	}
#if defined( HAVE_GETRLIMIT )
	if( getrlimit(
            RLIMIT_NOFILE,
            &limit_data ) != 0 )
	{
		fprintf(
		 stderr,
		 "Unable to determine limit: number of open file descriptors.\n" );
	}
	if( limit_data.rlim_max > (rlim_t) INT_MAX )
	{
		limit_data.rlim_max = (rlim_t) INT_MAX;
	}
	if( limit_data.rlim_max > 0 )
	{
		limit_data.rlim_max /= 2;
	}
	if( export_handle_set_maximum_number_of_open_handles(
	     ewfrecover_export_handle,
	     (int) limit_data.rlim_max,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to set maximum number of open file handles.\n" );

		goto on_error;
	}
#endif
	if( ewftools_signal_attach(
	     ewfrecover_signal_handler,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to attach signal handler.\n" );

		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );
	}
	result = export_handle_open_input(
	          ewfrecover_export_handle,
	          source_filenames,
	          number_of_filenames,
	          &error );

	if( ewfrecover_abort != 0 )
	{
		goto on_abort;
	}
	if( result != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to open EWF file(s).\n" );

		goto on_error;
	}
#if !defined( HAVE_GLOB_H )
	if( ewftools_glob_free(
	     &glob,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to free glob.\n" );

		goto on_error;
	}
#endif
	result = export_handle_input_is_corrupted(
	          ewfrecover_export_handle,
	          &error );

	if( result == -1 )
	{
		fprintf(
		 stderr,
		 "Unable to determine if EWF file(s) are corrupted.\n" );

		goto on_error;
	}
	else if( result == 0 )
	{
		fprintf(
		 stderr,
		 "EWF file(s) are not corrupted.\n" );

		goto on_error;
	}
	ewfrecover_export_handle->output_format = EXPORT_HANDLE_OUTPUT_FORMAT_EWF;
	ewfrecover_export_handle->export_size   = ewfrecover_export_handle->input_media_size;

	if( option_header_codepage != NULL )
	{
		result = export_handle_set_header_codepage(
			  ewfrecover_export_handle,
		          option_header_codepage,
			  &error );

		if( result == -1 )
		{
			fprintf(
			 stderr,
			 "Unable to set header codepage.\n" );

			goto on_error;
		}
		else if( result == 0 )
		{
			fprintf(
			 stderr,
			 "Unsupported header codepage defaulting to: ascii.\n" );
		}
	}
	if( option_target_path != NULL )
	{
		if( export_handle_set_string(
		     ewfrecover_export_handle,
		     option_target_path,
		     &( ewfrecover_export_handle->target_path ),
		     &( ewfrecover_export_handle->target_path_size ),
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to set target path.\n" );

			goto on_error;
		}
	}
	else
	{
		/* Make sure the target filename is set
		 */
		if( export_handle_set_string(
		     ewfrecover_export_handle,
		     _SYSTEM_STRING( "recover" ),
		     &( ewfrecover_export_handle->target_path ),
		     &( ewfrecover_export_handle->target_path_size ),
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to set target filename.\n" );

			goto on_error;
		}
	}
	/* Make sure we can write the target file
	 */
	if( export_handle_check_write_access(
	     ewfrecover_export_handle,
	     ewfrecover_export_handle->target_path,
	     &error ) != 1 )
	{
#if defined( HAVE_VERBOSE_OUTPUT )
		libcnotify_print_error_backtrace(
		 error );
#endif
		libcerror_error_free(
		 &error );

		fprintf(
		 stdout,
		 "Unable to write target file.\n" );

		goto on_error;
	}
	if( option_process_buffer_size != NULL )
	{
		result = export_handle_set_process_buffer_size(
			  ewfrecover_export_handle,
			  option_process_buffer_size,
			  &error );

		if( result == -1 )
		{
			fprintf(
			 stderr,
			 "Unable to set process buffer size.\n" );

			goto on_error;
		}
		else if( ( result == 0 )
		      || ( ewfrecover_export_handle->process_buffer_size > (size_t) SSIZE_MAX ) )
		{
			ewfrecover_export_handle->process_buffer_size = 0;

			fprintf(
			 stderr,
			 "Unsupported process buffer size defaulting to: chunk size.\n" );
		}
	}
	/* Initialize values
	 */
	if( log_filename != NULL )
	{
		if( log_handle_initialize(
		     &log_handle,
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to create log handle.\n" );

			goto on_error;
		}
		if( log_handle_open(
		     log_handle,
		     log_filename,
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to open log file: %" PRIs_SYSTEM ".\n",
			 log_filename );

			goto on_error;
		}
	}
	if( export_handle_open_output(
	     ewfrecover_export_handle,
	     ewfrecover_export_handle->target_path,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to open output.\n" );

		goto on_error;
	}
	if( platform_get_operating_system(
	     acquiry_operating_system,
	     32,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to determine operating system.\n" );

		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );

		acquiry_operating_system[ 0 ] = 0;
	}
	acquiry_software_version = _SYSTEM_STRING( LIBEWF_VERSION_STRING );

	if( export_handle_set_output_values(
	     ewfrecover_export_handle,
	     acquiry_operating_system,
	     program,
	     acquiry_software_version,
	     0,
	     1,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to set output values.\n" );

		goto on_error;
	}
	result = export_handle_export_input(
		  ewfrecover_export_handle,
		  0,
		  print_status_information,
		  log_handle,
		  &error );

	if( result != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to recover input.\n" );

		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );
	}
	if( log_handle != NULL )
	{
		if( log_handle_close(
		     log_handle,
		     &error ) != 0 )
		{
			fprintf(
			 stderr,
			 "Unable to close log file: %" PRIs_SYSTEM ".\n",
			 log_filename );

			goto on_error;
		}
		if( log_handle_free(
		     &log_handle,
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to free log handle.\n" );

			goto on_error;
		}
	}
on_abort:
	if( export_handle_close(
	     ewfrecover_export_handle,
	     &error ) != 0 )
	{
		fprintf(
		 stderr,
		 "Unable to close export handle.\n" );

		goto on_error;
	}
	if( ewftools_signal_detach(
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to detach signal handler.\n" );

		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );
	}
	if( export_handle_free(
	     &ewfrecover_export_handle,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to free export handle.\n" );

		goto on_error;
	}
	if( ewfrecover_abort != 0 )
	{
		fprintf(
		 stdout,
		 "%" PRIs_SYSTEM ": ABORTED\n",
		 program );

		return( EXIT_FAILURE );
	}
	if( result != 1 )
	{
		fprintf(
		 stdout,
		 "%" PRIs_SYSTEM ": FAILURE\n",
		 program );

		return( EXIT_FAILURE );
	}
	fprintf(
	 stdout,
	 "%" PRIs_SYSTEM ": SUCCESS\n",
	 program );

	return( EXIT_SUCCESS );

on_error:
	if( error != NULL )
	{
		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );
	}
	if( log_handle != NULL )
	{
		log_handle_close(
		 log_handle,
		 NULL );
		log_handle_free(
		 &log_handle,
		 NULL );
	}
	if( ewfrecover_export_handle != NULL )
	{
		export_handle_close(
		 ewfrecover_export_handle,
		 NULL );
		export_handle_free(
		 &ewfrecover_export_handle,
		 NULL );
	}
#if !defined( HAVE_GLOB_H )
	if( glob != NULL )
	{
		ewftools_glob_free(
		 &glob,
		 NULL );
	}
#endif
	return( EXIT_FAILURE );
}
int main_encoder(){
  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 (simplest WAV
     header is 44 bytes) and assume that the data is 44.1khz, stereo, 16 bit
     little endian pcm samples. 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);
}
Beispiel #8
0
/*!
* \return	Woolz error code.
* \ingroup	WlzExtFF
* \brief	Writes the given Woolz object to the given file(s)
*		using the ANALYZE 7.5 file format. The given file name is
*		used to generate the '.hdr' and '.img' filenames.
* \param	gvnFileName		Given file name with .hdr, .img or no
* 					extension.
* \param	obj			Given woolz object.
*/
WlzErrorNum	WlzEffWriteObjAnl(const char *gvnFileName, WlzObject *obj)
{
  int  		cnt = 0;
  double	dMin,
  		dMax;
  FILE		*fP = NULL;
  void	 	*data = NULL;
  WlzGreyP	dataP;
  WlzEffAnlDsr 	dsr;
  WlzGreyType	gType;
  WlzVertex	org,
  		sz;
  char		*fileName = NULL,
  		*hdrFileName = NULL,
		*imgFileName = NULL;
  WlzErrorNum	errNum = WLZ_ERR_NONE;

  dataP.v = NULL;
  if((gvnFileName == NULL) || (*gvnFileName == '\0'))
  {
    errNum = WLZ_ERR_PARAM_NULL;
  }
  else if(obj == NULL)
  {
    errNum = WLZ_ERR_OBJECT_NULL;
  }
  else if(obj->domain.core == NULL)
  {
    errNum = WLZ_ERR_DOMAIN_NULL;
  }
  else if(obj->values.core == NULL)
  {
    errNum = WLZ_ERR_VALUES_NULL;
  }
  else
  {
    errNum = WlzEffAnlFileNames(&fileName, &hdrFileName, &imgFileName,
				gvnFileName);
  }
  /* Fill in the ANALYZE file header data structures. */
  if(errNum == WLZ_ERR_NONE)
  {
    (void )memset(&dsr, 0, sizeof(WlzEffAnlDsr));
    switch(obj->type)
    {
      case WLZ_2D_DOMAINOBJ:
	org.i2.vtX = obj->domain.i->kol1;
	org.i2.vtY = obj->domain.i->line1;
	sz.i2.vtX = obj->domain.i->lastkl - org.i2.vtX + 1;
	sz.i2.vtY = obj->domain.i->lastln - org.i2.vtY + 1;
	if((sz.i2.vtX <= 0) || (sz.i2.vtY <= 0))
	{
	  errNum = WLZ_ERR_DOMAIN_DATA;
	}
	else
	{
	  dsr.dim.dim[0] = 2;
	  dsr.dim.dim[1] = sz.i2.vtX;
	  dsr.dim.dim[2] = sz.i2.vtY;
	  dsr.dim.pixdim[0] = 2;
	  dsr.dim.pixdim[1] = 1.0;
	  dsr.dim.pixdim[2] = 1.0;
	}
        break;
      case WLZ_3D_DOMAINOBJ:
	org.i3.vtX = obj->domain.p->kol1;
	org.i3.vtY = obj->domain.p->line1;
	org.i3.vtZ = obj->domain.p->plane1;
	sz.i3.vtX = obj->domain.p->lastkl - org.i3.vtX + 1;
	sz.i3.vtY = obj->domain.p->lastln - org.i3.vtY + 1;
	sz.i3.vtZ = obj->domain.p->lastpl - org.i3.vtZ + 1;
	if((sz.i3.vtX <= 0) || (sz.i3.vtY <= 0) || (sz.i3.vtZ <= 0))
	{
	  errNum = WLZ_ERR_DOMAIN_DATA;
	}
        else
	{
	  dsr.dim.dim[0] = 3;
	  dsr.dim.dim[1] = sz.i3.vtX;
	  dsr.dim.dim[2] = sz.i3.vtY;
	  dsr.dim.dim[3] = sz.i3.vtZ;
	  dsr.dim.pixdim[0] = 3;
	  dsr.dim.pixdim[1] = obj->domain.p->voxel_size[0];
	  dsr.dim.pixdim[2] = obj->domain.p->voxel_size[1];
	  dsr.dim.pixdim[3] = obj->domain.p->voxel_size[2];
	}
        break;
      default:
        errNum = WLZ_ERR_OBJECT_TYPE;
	break;
    }
  }
  if(errNum == WLZ_ERR_NONE)
  {
    (void )WlzGreyStats(obj, &gType, &dMin, &dMax, NULL, NULL, NULL, NULL,
    			&errNum);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    dsr.dim.glMax = (int )ceil(dMax);
    dsr.dim.glMin = (int )floor(dMin);
    switch(gType)
    {
      case WLZ_GREY_INT:
        dsr.dim.dataType = WLZEFF_ANL_DT_SIGNED_INT;
        dsr.dim.bitPix = 32;
        break;
      case WLZ_GREY_SHORT:
        dsr.dim.dataType = WLZEFF_ANL_DT_SIGNED_SHORT;
        dsr.dim.bitPix = 16;
	break;
      case WLZ_GREY_UBYTE:
        dsr.dim.dataType = WLZEFF_ANL_DT_UNSIGNED_CHAR;
        dsr.dim.bitPix = 8;
	break;
      case WLZ_GREY_FLOAT:
        dsr.dim.dataType = WLZEFF_ANL_DT_FLOAT;
        dsr.dim.bitPix = 32;
	break;
      case WLZ_GREY_DOUBLE:
        dsr.dim.dataType = WLZEFF_ANL_DT_DOUBLE;
        dsr.dim.bitPix = 64;
	break;
      default:
	errNum = WLZ_ERR_GREY_TYPE;
        break;
    }
  }
  if(errNum == WLZ_ERR_NONE)
  {
    dsr.hk.hdrSz = 348;
    dsr.hk.regular = 'r';
    dsr.hk.extents = 16384;
    (void )strcpy(dsr.hist.descrip, "Converted from Woolz");
    (void )strcpy(dsr.hist.originator, "Woolz");
    (void )strcpy(dsr.hist.generated, "Woolz");
  }
  /* Get Woolz object's values as an array. */
  if(WLZ_ERR_NONE == errNum)
  {
    switch(obj->type)
    {
      case WLZ_2D_DOMAINOBJ:
        cnt = sz.i2.vtX * sz.i2.vtY;
	errNum = WlzToArray2D((void ***)&data, obj, sz.i2, org.i2, 0, gType);
	if(errNum == WLZ_ERR_NONE)
	{
	  switch(gType)
	  {
	    case WLZ_GREY_INT:
	      dataP.inp = *(int **)data;
	      break;
	    case WLZ_GREY_SHORT:
	      dataP.shp = *(short **)data;
	      break;
	    case WLZ_GREY_UBYTE:
	      dataP.ubp = *(WlzUByte **)data;
	      break;
	    case WLZ_GREY_FLOAT:
	      dataP.flp = *(float **)data;
	      break;
	    case WLZ_GREY_DOUBLE:
	      dataP.dbp = *(double **)data;
	      break;
	    default:
	      errNum = WLZ_ERR_GREY_TYPE;
	      break;
	  }
	}
        break;
      case WLZ_3D_DOMAINOBJ:
        cnt = sz.i3.vtX * sz.i3.vtY * sz.i3.vtZ;
	errNum = WlzToArray3D((void ****)&data, obj, sz.i3, org.i3, 0, gType);
	if(errNum == WLZ_ERR_NONE)
	{
	  switch(gType)
	  {
	    case WLZ_GREY_INT:
	      dataP.inp = **(int ***)data;
	      break;
	    case WLZ_GREY_SHORT:
	      dataP.shp = **(short ***)data;
	      break;
	    case WLZ_GREY_UBYTE:
	      dataP.ubp = **(WlzUByte ***)data;
	      break;
	    case WLZ_GREY_FLOAT:
	      dataP.flp = **(float ***)data;
	      break;
	    case WLZ_GREY_DOUBLE:
	      dataP.dbp = **(double ***)data;
	      break;
	    default:
	      errNum = WLZ_ERR_GREY_TYPE;
	      break;
	  }
	}
        break;
      default:
	errNum = WLZ_ERR_OBJECT_TYPE;
        break;
    }
  }
  /* Open the ANALYZE .hdr file and write the header information. */
  if(errNum == WLZ_ERR_NONE)
  {
    if((fP = fopen(hdrFileName, "w")) == NULL)
    {
      errNum = WLZ_ERR_WRITE_EOF;
    }
#ifdef _WIN32
    else if(_setmode(_fileno(fP), 0x8000) == -1)
    {
	errNum = WLZ_ERR_READ_EOF;
    }
#endif
  }
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffWriteAnlHdrKey(fP, &dsr);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffWriteAnlHdrImageDim(fP, &dsr);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffWriteAnlHdrDataHistory(fP, &dsr);
  }
  if(fP)
  {
    (void )fclose(fP);
    fP = NULL;
  }
  /* Open the ANALYZE .img file and write the image data. */
  if(errNum == WLZ_ERR_NONE)
  {
    if((fP = fopen(imgFileName, "w")) == NULL)
    {
      errNum = WLZ_ERR_WRITE_EOF;
    }
#ifdef _WIN32
    else if(_setmode(_fileno(fP), 0x8000) == -1)
    {
	errNum = WLZ_ERR_READ_EOF;
    }
#endif
  }
  if(errNum == WLZ_ERR_NONE)
  {
    switch(gType)
    {
      case WLZ_GREY_INT:
	errNum = WlzEffWriteAnlInt(fP, cnt, dataP.inp);
        break;
      case WLZ_GREY_SHORT:
	errNum = WlzEffWriteAnlShort(fP, cnt, dataP.shp);
        break;
      case WLZ_GREY_UBYTE:
	errNum = WlzEffWriteAnlChar(fP, cnt, dataP.ubp);
        break;
      case WLZ_GREY_FLOAT:
	errNum = WlzEffWriteAnlFloat(fP, cnt, dataP.flp);
        break;
      case WLZ_GREY_DOUBLE:
	errNum = WlzEffWriteAnlDouble(fP, cnt, dataP.dbp);
	break;
      default:
        break;
    }
  }
  if(fP)
  {
    (void )fclose(fP);
  }
  if(data)
  {
    switch(obj->type)
    {
      case WLZ_2D_DOMAINOBJ:
	Alc2Free((void **)data);
	break;
      case WLZ_3D_DOMAINOBJ:
	Alc3Free((void ***)data);
	break;
      default:
	break;
    }
  }
  (void )AlcFree(fileName);
  (void )AlcFree(hdrFileName);
  (void )AlcFree(imgFileName);
  return(errNum);
}
Beispiel #9
0
int main(int argc, char *argv[])
{
   string     cfg_file;
   const char *parsed_file = NULL;
   const char *source_file = NULL;
   const char *output_file = NULL;
   const char *source_list = NULL;
   log_mask_t mask;
   int        idx;
   const char *p_arg;

   /* If ran without options... check keyword sort and show the usage info */
   if (argc == 1)
   {
      keywords_are_sorted();
      usage_exit(NULL, argv[0], EXIT_SUCCESS);
   }

   /* Build options map */
   register_options();

   Args arg(argc, argv);

   if (arg.Present("--version") || arg.Present("-v"))
   {
      version_exit();
   }
   if (arg.Present("--help") || arg.Present("-h") ||
       arg.Present("--usage") || arg.Present("-?"))
   {
      usage_exit(NULL, argv[0], EXIT_SUCCESS);
   }

   if (arg.Present("--show-config"))
   {
      print_options(stdout, true);
      return(0);
   }

#ifdef WIN32
   /* tell windoze not to change what I write to stdout */
   (void)_setmode(_fileno(stdout), _O_BINARY);
#endif

   /* Init logging */
   log_init(stderr);
   if (arg.Present("-q"))
   {
      logmask_from_string("", mask);
      log_set_mask(mask);
   }
   if (((p_arg = arg.Param("-L")) != NULL) ||
       ((p_arg = arg.Param("--log")) != NULL))
   {
      logmask_from_string(p_arg, mask);
      log_set_mask(mask);
   }
   cpd.frag = arg.Present("--frag");

   if ((p_arg = arg.Param("--decode")) != NULL)
   {
      log_pcf_flags(LSYS, strtoul(p_arg, NULL, 16));
      exit(EXIT_SUCCESS);
   }

   /* Get the config file name */
   if (((p_arg = arg.Param("--config")) != NULL) ||
       ((p_arg = arg.Param("-c")) != NULL))
   {
      cfg_file = p_arg;
   }

   /* Try to file a config at an alternate location */
   if (cfg_file.empty())
   {
      if (!unc_getenv("UNCRUSTIFY_CONFIG", cfg_file))
      {
         string home;

         if (unc_homedir(home))
         {
            struct stat tmp_stat;
            string      path;

            path = home + "/uncrustify.cfg";
            if (stat(path.c_str(), &tmp_stat) == 0)
            {
               cfg_file = path;
            }
            else
            {
               path = home + "/.uncrustify.cfg";
               if (stat(path.c_str(), &tmp_stat) == 0)
               {
                  cfg_file = path;
               }
            }
         }
      }
   }

   /* Get the parsed file name */
   if (((parsed_file = arg.Param("--parsed")) != NULL) ||
       ((parsed_file = arg.Param("-p")) != NULL))
   {
      LOG_FMT(LNOTE, "Will export parsed data to: %s\n", parsed_file);
   }

   /* Enable log sevs? */
   if (arg.Present("-s") || arg.Present("--show"))
   {
      log_show_sev(true);
   }

   /* Load the config file */
   set_option_defaults();

   /* Load type files */
   idx = 0;
   while ((p_arg = arg.Params("-t", idx)) != NULL)
   {
      load_keyword_file(p_arg);
   }

   /* add types */
   idx = 0;
   while ((p_arg = arg.Params("--type", idx)) != NULL)
   {
      add_keyword(p_arg, CT_TYPE);
   }

   /* Load define files */
   idx = 0;
   while ((p_arg = arg.Params("-d", idx)) != NULL)
   {
      load_define_file(p_arg);
   }

   /* add defines */
   idx = 0;
   while ((p_arg = arg.Params("--define", idx)) != NULL)
   {
      add_define(p_arg, NULL);
   }

   /* Check for a language override */
   if ((p_arg = arg.Param("-l")) != NULL)
   {
      cpd.lang_flags = language_from_tag(p_arg);
      if (cpd.lang_flags == 0)
      {
         LOG_FMT(LWARN, "Ignoring unknown language: %s\n", p_arg);
      }
      else
      {
         cpd.lang_forced = true;
      }
   }

   /* Get the source file name */
   if (((source_file = arg.Param("--file")) == NULL) &&
       ((source_file = arg.Param("-f")) == NULL))
   {
      // not using a single file, source_file is NULL
   }

   if (((source_list = arg.Param("--files")) == NULL) &&
       ((source_list = arg.Param("-F")) == NULL))
   {
      // not using a file list, source_list is NULL
   }

   const char *prefix = arg.Param("--prefix");
   const char *suffix = arg.Param("--suffix");

   bool no_backup        = arg.Present("--no-backup");
   bool replace          = arg.Present("--replace");
   bool keep_mtime       = arg.Present("--mtime");
   bool update_config    = arg.Present("--update-config");
   bool update_config_wd = arg.Present("--update-config-with-doc");
   bool detect           = arg.Present("--detect");

   /* Grab the output override */
   output_file = arg.Param("-o");

   LOG_FMT(LDATA, "config_file = %s\n", cfg_file.c_str());
   LOG_FMT(LDATA, "output_file = %s\n", (output_file != NULL) ? output_file : "null");
   LOG_FMT(LDATA, "source_file = %s\n", (source_file != NULL) ? source_file : "null");
   LOG_FMT(LDATA, "source_list = %s\n", (source_list != NULL) ? source_list : "null");
   LOG_FMT(LDATA, "prefix      = %s\n", (prefix != NULL) ? prefix : "null");
   LOG_FMT(LDATA, "suffix      = %s\n", (suffix != NULL) ? suffix : "null");
   LOG_FMT(LDATA, "replace     = %d\n", replace);
   LOG_FMT(LDATA, "no_backup   = %d\n", no_backup);
   LOG_FMT(LDATA, "detect      = %d\n", detect);

   if (replace || no_backup)
   {
      if ((prefix != NULL) || (suffix != NULL))
      {
         usage_exit("Cannot use --replace with --prefix or --suffix", argv[0], 66);
      }
      if ((source_file != NULL) || (output_file != NULL))
      {
         usage_exit("Cannot use --replace or --no-backup with -f or -o", argv[0], 66);
      }
   }
   else
   {
      if ((prefix == NULL) && (suffix == NULL))
      {
         suffix = ".uncrustify";
      }
   }

   /* Try to load the config file, if available.
    * It is optional for "--universalindent" and "--detect", but required for
    * everything else.
    */
   if (!cfg_file.empty())
   {
      cpd.filename = cfg_file.c_str();
      if (load_option_file(cpd.filename) < 0)
      {
         usage_exit("Unable to load the config file", argv[0], 56);
      }
   }

   if (arg.Present("--universalindent"))
   {
      FILE *pfile = stdout;

      if (output_file != NULL)
      {
         pfile = fopen(output_file, "w");
         if (pfile == NULL)
         {
            fprintf(stderr, "Unable to open %s for write: %s (%d)\n",
                    output_file, strerror(errno), errno);
            return(EXIT_FAILURE);
         }
      }

      print_universal_indent_cfg(pfile);

      return(EXIT_SUCCESS);
   }

   if (detect)
   {
      file_mem fm;

      if ((source_file == NULL) || (source_list != NULL))
      {
         fprintf(stderr, "The --detect option requires a single input file\n");
         return(EXIT_FAILURE);
      }

      /* Do some simple language detection based on the filename extension */
      if (!cpd.lang_forced || (cpd.lang_flags == 0))
      {
         cpd.lang_flags = language_from_filename(source_file);
      }

      /* Try to read in the source file */
      if (load_mem_file(source_file, fm) < 0)
      {
         LOG_FMT(LERR, "Failed to load (%s)\n", source_file);
         cpd.error_count++;
         return(EXIT_FAILURE);
      }

      uncrustify_start(fm.data);
      detect_options();
      uncrustify_end();

      redir_stdout(output_file);
      save_option_file(stdout, update_config_wd);
      return(EXIT_SUCCESS);
   }

   /* Everything beyond this point requires a config file, so complain and
    * bail if we don't have one.
    */
   if (cfg_file.empty())
   {
      usage_exit("Specify the config file with '-c file' or set UNCRUSTIFY_CONFIG",
                 argv[0], 58);
   }

   /*
    *  Done parsing args
    */

   if (update_config || update_config_wd)
   {
      redir_stdout(output_file);
      save_option_file(stdout, update_config_wd);
      return(0);
   }

   /* Check for unused args (ignore them) */
   idx   = 1;
   p_arg = arg.Unused(idx);

   /* Check args - for multifile options */
   if ((source_list != NULL) || (p_arg != NULL))
   {
      if (source_file != NULL)
      {
         usage_exit("Cannot specify both the single file option and a multi-file option.",
                    argv[0], 67);
      }

      if (output_file != NULL)
      {
         usage_exit("Cannot specify -o with a multi-file option.",
                    argv[0], 68);
      }
   }

   /* This relies on cpd.filename being the config file name */
   load_header_files();

   if ((source_file == NULL) && (source_list == NULL) && (p_arg == NULL))
   {
      /* no input specified, so use stdin */
      if (cpd.lang_flags == 0)
      {
         cpd.lang_flags = LANG_C;
      }

      redir_stdout(output_file);

      file_mem fm;
      if (!read_stdin(fm))
      {
         LOG_FMT(LERR, "Failed to read stdin\n");
         return(100);
      }

      cpd.filename = "stdin";

      /* Done reading from stdin */
      LOG_FMT(LSYS, "Parsing: %d bytes (%d chars) from stdin as language %s\n",
              (int)fm.raw.size(), (int)fm.data.size(),
              language_to_string(cpd.lang_flags));

      uncrustify_file(fm, stdout, parsed_file);
   }
   else if (source_file != NULL)
   {
      /* Doing a single file */
      do_source_file(source_file, output_file, parsed_file, no_backup, keep_mtime);
   }
   else
   {
      /* Doing multiple files */
      if (prefix != NULL)
      {
         LOG_FMT(LSYS, "Output prefix: %s/\n", prefix);
      }
      if (suffix != NULL)
      {
         LOG_FMT(LSYS, "Output suffix: %s\n", suffix);
      }

      /* Do the files on the command line first */
      idx = 1;
      while ((p_arg = arg.Unused(idx)) != NULL)
      {
         char outbuf[1024];
         do_source_file(p_arg,
                        make_output_filename(outbuf, sizeof(outbuf), p_arg, prefix, suffix),
                        NULL, no_backup, keep_mtime);
      }

      if (source_list != NULL)
      {
         process_source_list(source_list, prefix, suffix, no_backup, keep_mtime);
      }
   }

   clear_keyword_file();
   clear_defines();

   return((cpd.error_count != 0) ? 1 : 0);
}
Beispiel #10
0
/* convert file ipInFN to UNIX format text and write to file ipOutFN
 * RetVal: 0 if success
 *         -1 otherwise
 */
int ConvertDosToUnixNewFile(char *ipInFN, char *ipOutFN, CFlag *ipFlag)
{
  int RetVal = 0;
  FILE *InF = NULL;
  FILE *TempF = NULL;
  char *TempPath;
  struct stat StatBuf;
  struct utimbuf UTimeBuf;
#ifndef NO_FCHMOD
  mode_t mask;
#endif
#ifdef NO_MKSTEMP
  FILE* fd;
#else
  int fd;
#endif

  if ((ipFlag->Force == 0) && regfile(ipInFN))
  {
    ipFlag->status |= NO_REGFILE ;
    return -1;
  }
  else
    ipFlag->status = 0 ;

  /* retrieve ipInFN file date stamp */
  if (stat(ipInFN, &StatBuf))
    RetVal = -1;

#ifdef NO_MKSTEMP
  if((fd = MakeTempFileFrom(ipOutFN, &TempPath))==NULL) {
#else
  if((fd = MakeTempFileFrom (ipOutFN, &TempPath)) < 0) {
#endif
    perror(_("dos2unix: Failed to open temporary output file"));
    RetVal = -1;
  }

#ifdef DEBUG
  fprintf(stderr, _("dos2unix: using %s as temporary file\n"), TempPath);
#endif

  /* can open in file? */
  if ((!RetVal) && ((InF=OpenInFile(ipInFN)) == NULL))
    RetVal = -1;

  /* can open output file? */
#ifdef NO_MKSTEMP
  if ((!RetVal) && (InF) && ((TempF=fd) == NULL))
#else
  if ((!RetVal) && (InF) && ((TempF=OpenOutFile(fd)) == NULL))
#endif
  {
    fclose (InF);
    InF = NULL;
    RetVal = -1;
  }

#ifndef NO_FCHMOD
  /* preserve original mode as modified by umask */
  mask = umask(0);
  umask(mask);
  if (!RetVal && fchmod(fd, StatBuf.st_mode & ~mask))
    RetVal = -1;
#endif

  /* conversion sucessful? */
  if ((!RetVal) && (ConvertDosToUnix(InF, TempF, ipFlag)))
    RetVal = -1;

   /* can close in file? */
  if ((InF) && (fclose(InF) == EOF))
    RetVal = -1;

  /* can close output file? */
  if ((TempF) && (fclose(TempF) == EOF))
    RetVal = -1;

#ifdef NO_MKSTEMP
  if(fd!=NULL)
    fclose(fd);
#else
  if(fd>=0)
    close(fd);
#endif

  if ((!RetVal) && (ipFlag->KeepDate))
  {
    UTimeBuf.actime = StatBuf.st_atime;
    UTimeBuf.modtime = StatBuf.st_mtime;
    /* can change output file time to in file time? */
    if (utime(TempPath, &UTimeBuf) == -1)
      RetVal = -1;
  }

  /* any error? */
  if ((RetVal) && (remove(TempPath)))
    RetVal = -1;

  /* can rename temporary file to output file? */
  if (!RetVal)
  {
#ifdef NEED_REMOVE
    remove(ipOutFN);
#endif
    if ((rename(TempPath, ipOutFN) == -1) && (!ipFlag->Quiet))
    {
      fprintf(stderr, _("dos2unix: problems renaming '%s' to '%s'\n"), TempPath, ipOutFN);
      fprintf(stderr, _("          output file remains in '%s'\n"), TempPath);
      RetVal = -1;
    }
  }
  free(TempPath);
  return RetVal;
}


/* convert file ipInFN to UNIX format text
 * RetVal: 0 if success
 *         -1 otherwise
 */
int ConvertDosToUnixOldFile(char* ipInFN, CFlag *ipFlag)
{
  int RetVal = 0;
  FILE *InF = NULL;
  FILE *TempF = NULL;
  char *TempPath;
  struct stat StatBuf;
  struct utimbuf UTimeBuf;
#ifndef NO_FCHMOD
  mode_t mode = S_IRUSR | S_IWUSR;
#endif
#ifdef NO_MKSTEMP
  FILE* fd;
#else
  int fd;
#endif

  if ((ipFlag->Force == 0) && regfile(ipInFN))
  {
    ipFlag->status |= NO_REGFILE ;
    return -1;
  }
  else
    ipFlag->status = 0 ;

  /* retrieve ipInFN file date stamp */
  if (stat(ipInFN, &StatBuf))
    RetVal = -1;
#ifndef NO_FCHMOD
  else
    mode = StatBuf.st_mode;
#endif

#ifdef NO_MKSTEMP
  if((fd = MakeTempFileFrom(ipInFN, &TempPath))==NULL) {
#else
  if((fd = MakeTempFileFrom(ipInFN, &TempPath)) < 0) {
#endif
    perror(_("dos2unix: Failed to open temporary output file"));
    RetVal = -1;
  }

#ifndef NO_FCHMOD
  if (!RetVal && fchmod (fd, mode) && fchmod (fd, S_IRUSR | S_IWUSR))
    RetVal = -1;
#endif

#ifdef DEBUG
  fprintf(stderr, _("dos2unix: using %s as temporary file\n"), TempPath);
#endif

  /* can open in file? */
  if ((!RetVal) && ((InF=OpenInFile(ipInFN)) == NULL))
    RetVal = -1;

  /* can open output file? */
#ifdef NO_MKSTEMP
  if ((!RetVal) && (InF) && ((TempF=fd) == NULL))
#else
  if ((!RetVal) && (InF) && ((TempF=OpenOutFile(fd)) == NULL))
#endif
  {
    fclose (InF);
    InF = NULL;
    RetVal = -1;
  }

  /* conversion sucessful? */
  if ((!RetVal) && (ConvertDosToUnix(InF, TempF, ipFlag)))
    RetVal = -1;

   /* can close in file? */
  if ((InF) && (fclose(InF) == EOF))
    RetVal = -1;

  /* can close output file? */
  if ((TempF) && (fclose(TempF) == EOF))
    RetVal = -1;

#ifdef NO_MKSTEMP
  if(fd!=NULL)
    fclose(fd);
#else
  if(fd>=0)
    close(fd);
#endif

  if ((!RetVal) && (ipFlag->KeepDate))
  {
    UTimeBuf.actime = StatBuf.st_atime;
    UTimeBuf.modtime = StatBuf.st_mtime;
    /* can change output file time to in file time? */
    if (utime(TempPath, &UTimeBuf) == -1)
      RetVal = -1;
  }

  /* any error? */
  if ((RetVal) && (remove(TempPath)))
    RetVal = -1;

#ifdef NEED_REMOVE
  if (!RetVal)
    remove(ipInFN);
#endif
  /* can rename output file to in file? */
  if ((!RetVal) && (rename(TempPath, ipInFN) == -1))
  {
    if (!ipFlag->Quiet)
    {
      fprintf(stderr, _("dos2unix: problems renaming '%s' to '%s'\n"), TempPath, ipInFN);
      fprintf(stderr, _("          output file remains in '%s'\n"), TempPath);
    }
    RetVal = -1;
  }
  free(TempPath);
  return RetVal;
}


/* convert stdin to UNIX format text and write to stdout
 * RetVal: 0 if success
 *         -1 otherwise
 */
int ConvertDosToUnixStdio(CFlag *ipFlag)
{
    ipFlag->NewFile = 1;
    ipFlag->Quiet = 1;
    ipFlag->KeepDate = 0;
    ipFlag->Force = 1;

#ifdef WIN32

    /* stdin and stdout are by default text streams. We need
     * to set them to binary mode. Otherwise an LF will
     * automatically be converted to CR-LF on DOS/Windows.
     * Erwin */

    /* 'setmode' was deprecated by MicroSoft
     * since Visual C++ 2005. Use '_setmode' instead. */

    _setmode(fileno(stdout), O_BINARY);
    _setmode(fileno(stdin), O_BINARY);
    return (ConvertDosToUnix(stdin, stdout, ipFlag));
#elif defined(MSDOS) || defined(__OS2__)
    setmode(fileno(stdout), O_BINARY);
    setmode(fileno(stdin), O_BINARY);
    return (ConvertDosToUnix(stdin, stdout, ipFlag));
#else
    return (ConvertDosToUnix(stdin, stdout, ipFlag));
#endif
}
Beispiel #11
0
/*!
* \return	New Woolz object or NULL on error.
* \ingroup	WlzExtFF
* \brief	Reads a Woolz object from the given stream using the
*		ANALYZE 7.5 format. The given file name is used to
*		generate the '.hdr' and '.img' filenames.
* \param	gvnFileName		Given file name.
* \param	dstErr			Destination error code, may be NULL.
*/
WlzObject	*WlzEffReadObjAnl(const char *gvnFileName, WlzErrorNum *dstErr)
{
  int		idx,
  		timePoints = 0;
  FILE		*fP = NULL;
  char		*fileName = NULL,
  		*hdrFileName = NULL,
		*imgFileName = NULL;
  WlzVertex	org,
  		sz;
  WlzEffAnlDsr 	dsr;
  int 		swap = 0;
  WlzObject	*obj = NULL;
  WlzGreyType	gType = WLZ_GREY_ERROR;
  WlzPixelV	bgdV;
  WlzErrorNum	errNum = WLZ_ERR_NONE;

  sz.i3.vtX = sz.i3.vtY = sz.i3.vtZ = 0;
  /* Compute .hdr and .img file names. */
  if((gvnFileName == NULL) || (*gvnFileName == '\0'))
  {
    errNum = WLZ_ERR_PARAM_NULL;
  }
  else
  {
    errNum = WlzEffAnlFileNames(&fileName, &hdrFileName, &imgFileName,
				gvnFileName);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    if((hdrFileName == NULL) || (*hdrFileName == '\0') ||
       ((fP = fopen(hdrFileName, "r")) == NULL))
    {
      errNum = WLZ_ERR_READ_EOF;
    }
#ifdef _WIN32
    else
    {
      if(fP != NULL)
      {
	if(_setmode(_fileno(fP), 0x8000) == -1)
	{
	  errNum = WLZ_ERR_READ_EOF;
	}
      }
    }
#endif
  }
  /* Read the .hdr (header) file. */
  if(errNum == WLZ_ERR_NONE)
  {
    (void )memset((void *)&dsr, 0, sizeof(WlzEffAnlDsr));
    errNum = WlzEffReadAnlHdrKey(fP, &dsr, &swap);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffReadAnlHdrImageDim(fP, &dsr, swap);
  }
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffReadAnlHdrDataHistory(fP, &dsr, swap);
  }
  if(fP)
  {
    (void )fclose(fP);
    fP = NULL;
  }
  /* Check header data is valid. */
  if(errNum == WLZ_ERR_NONE)
  {
    if('r' != dsr.hk.regular)
    {
      errNum = WLZ_ERR_OBJECT_DATA;
    }
  }
  if(errNum == WLZ_ERR_NONE)
  {
    switch(dsr.dim.bitPix)
    {
      case 8:  /* FALLTHROUGH */
      case 16: /* FALLTHROUGH */
      case 32: /* FALLTHROUGH */
      case 64:
        break;
      case 1:
      default:
        errNum = WLZ_ERR_OBJECT_DATA;
	break;
    }
  }
  /* Compute the image parameters. */
  if(errNum == WLZ_ERR_NONE)
  {
    switch(dsr.dim.dataType)
    {
      case WLZEFF_ANL_DT_UNSIGNED_CHAR:
        gType = WLZ_GREY_UBYTE;
	bgdV.type = gType;
	bgdV.v.ubv = 0;
	break;
      case WLZEFF_ANL_DT_SIGNED_SHORT:
        gType = WLZ_GREY_SHORT;
	bgdV.type = gType;
	bgdV.v.shv = 0;
	break;
      case WLZEFF_ANL_DT_SIGNED_INT:
        gType = WLZ_GREY_INT;
	bgdV.type = gType;
	bgdV.v.inv = 0;
	break;
      case WLZEFF_ANL_DT_FLOAT:
        gType = WLZ_GREY_FLOAT;
	bgdV.type = gType;
	bgdV.v.flv = 0.0;
	break;
      case WLZEFF_ANL_DT_DOUBLE:
        gType = WLZ_GREY_DOUBLE;
	bgdV.type = gType;
	bgdV.v.dbv = 0.0;
	break;
      default:
	errNum = WLZ_ERR_GREY_TYPE;
	break;
    }
  }
  if(errNum == WLZ_ERR_NONE)
  {
    switch(dsr.dim.dim[0])
    {
      case 2:
	org.i2.vtX = 0;
	org.i2.vtY = 0;
	sz.i2.vtX = dsr.dim.dim[1];
	sz.i2.vtY = dsr.dim.dim[2];
	timePoints = 1;
	if((sz.i2.vtX < 1) || (sz.i2.vtY < 1))
	{
	  errNum = WLZ_ERR_OBJECT_DATA;
	}
	break;
      case 3:
        org.i3.vtX = 0;
	org.i3.vtY = 0;
	org.i3.vtZ = 0;
	sz.i3.vtX = dsr.dim.dim[1];
	sz.i3.vtY = dsr.dim.dim[2];
	sz.i3.vtZ = dsr.dim.dim[3];
	if((sz.i3.vtX < 1) || (sz.i3.vtY < 1) || (sz.i3.vtZ < 1))
	{
	  errNum = WLZ_ERR_OBJECT_DATA;
	}
        break;
      case 4:
        org.i3.vtX = 0;
	org.i3.vtY = 0;
	org.i3.vtZ = 0;
	sz.i3.vtX = dsr.dim.dim[1];
	sz.i3.vtY = dsr.dim.dim[2];
	sz.i3.vtZ = dsr.dim.dim[3];
	timePoints = dsr.dim.dim[4];
	if((sz.i3.vtX < 1) || (sz.i3.vtY < 1) || (sz.i3.vtZ < 1) ||
	   (timePoints < 1))
	{
	  errNum = WLZ_ERR_OBJECT_DATA;
	}
        break;
      default:
	errNum = WLZ_ERR_OBJECT_DATA;
        break;
        
    }
  }
  /* Create object. */
  if(errNum == WLZ_ERR_NONE)
  {
    if(timePoints > 1)
    {
      obj = (WlzObject *)
            WlzMakeCompoundArray(WLZ_3D_DOMAINOBJ, 1, timePoints, NULL,
	                         WLZ_3D_DOMAINOBJ, &errNum);
      if(obj)
      {
        idx = 0;
	do
	{
	  ((WlzCompoundArray *)obj)->o[idx] = WlzAssignObject(
		WlzMakeCuboid(org.i3.vtZ, org.i3.vtZ + sz.i3.vtZ - 1,
			      org.i3.vtY, org.i3.vtY + sz.i3.vtY - 1,
			      org.i3.vtX, org.i3.vtX + sz.i3.vtX - 1,
			      gType, bgdV, NULL, NULL, &errNum), NULL);
	} while((++idx < timePoints) && (WLZ_ERR_NONE == errNum));
      }
    }
    else if(3 <= dsr.dim.dim[0])
    {
      obj = WlzMakeCuboid(org.i3.vtZ, org.i3.vtZ + sz.i3.vtZ - 1,
                          org.i3.vtY, org.i3.vtY + sz.i3.vtY - 1,
			  org.i3.vtX, org.i3.vtX + sz.i3.vtX - 1,
			  gType, bgdV, NULL, NULL, &errNum);
    }
    else /* 2 == dsr.dim.dim[0] */
    {
      obj = WlzMakeRect(org.i2.vtY, org.i2.vtY + sz.i2.vtY - 1,
			org.i2.vtX, org.i2.vtX + sz.i2.vtX - 1,
			gType, NULL, bgdV, NULL, NULL, &errNum);
    }
  }
  /* Open the .img (image data) file. */
  if(errNum == WLZ_ERR_NONE)
  {
    if((imgFileName == NULL) || (*imgFileName == '\0') ||
       ((fP = fopen(imgFileName, "r")) == NULL))
    {
      errNum = WLZ_ERR_READ_EOF;
    }
#ifdef _WIN32
    else
    {
      if(fP != NULL)
      {
	if(_setmode(_fileno(fP), 0x8000) == -1)
	{
	  errNum = WLZ_ERR_READ_EOF;
	}
      }
    }
#endif
  }
  /* Read the object values. */
  if(errNum == WLZ_ERR_NONE)
  {
    errNum = WlzEffReadAnlImgData(obj, gType, &dsr, fP, swap);
  }
  if(fP)
  {
    (void )fclose(fP);
  }
  (void )AlcFree(fileName);
  (void )AlcFree(hdrFileName);
  (void )AlcFree(imgFileName);
  if(errNum != WLZ_ERR_NONE)
  {
    (void )WlzFreeObj(obj);
    obj = NULL;
  }
  if(dstErr)
  {
    *dstErr = errNum;
  }
  return(obj);
}
Beispiel #12
0
int main( int argc, char* argv[] ) {

#if defined(_WIN32) && !defined(__CYGWIN__)
 if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 ) {
    printf( "Cannot set stdout to binary mode.  Exiting." );
    return -1;
 }
#endif

  char*     userfilename = NULL;
  int       user_capk    = -1;
  double    user_centerx = 0.0;
  double    user_centery = 0.0;
  int       user_centeroverride = 0;
  double    user_julia_r = 0.0;
  double    user_julia_i = 0.0;
  int       MakeJuliaSet = 0;
  long      user_resolx = 0.0;
  long      user_resoly = 0.0;
  int       user_resolutionoverride = 0;
  double    user_zoomlevel = -1.0;

  long i;
  for ( i = 1; i < argc; ) {
    int ishyphen = argv[i][0] == '-';
    long len = strlen( argv[i] );
    long nextlen = (i+1) < argc ? strlen( argv[i+1] ) : -1;

    int argsprocessed = 0;
    if ( ishyphen && len > 1 )
      argsprocessed = 1;

    if ( argsprocessed >= 1 ) {
      char useroption = argv[i][1];
      char* optionvalue = NULL;
      if ( len >= 3 )
        optionvalue = &argv[i][2];

      switch ( useroption ) {
       case 'c':  // center point  (x,y)
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          user_centeroverride = !Get2Tuple( optionvalue, &user_centerx, &user_centery );
        break;
       case 'h':
        printusage();
        return 0;
        break;
       case 'j':  // julia set constant value (the real part and imaginary part)
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          MakeJuliaSet = !Get2Tuple( optionvalue, &user_julia_r, &user_julia_i );
        break;
       case 'm':  // maximum number of iterations per pixel
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          user_capk = abs(atoi( optionvalue ));
        break;
       case 'o':  // output file name
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          userfilename = strdup( optionvalue );
        break;
       case 'r':  // image resolution
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          user_resolutionoverride = !Get2Tuple( optionvalue, &user_resolx, &user_resoly );
        break;
       case 'v':
        printf( "fractals version %s\n", VersionStr );
        return 0;
        break;
       case 'z':
        if ( optionvalue == NULL && nextlen > 0 ) {
          optionvalue = argv[i+1];
          argsprocessed = 2;
        }
        if ( optionvalue != NULL )
          user_zoomlevel = fabs(atof( optionvalue ));
        break;
       default:
        break;
      }
    }

    if ( argsprocessed == 2 )
      i += 2;
    else
      i++;
  }

  double centerx = 0.0;
  double centery = 0.0;
  if ( !MakeJuliaSet )  // ie. Make the Mandelbrot Set
    centerx = -0.75;
  if ( user_centeroverride ) {
    centerx = user_centerx;
    centery = user_centery;
  }

  double c_r = 0.0;
  double c_i = 0.0;
  if ( MakeJuliaSet ) {
    c_r = user_julia_r;
    c_i = user_julia_i;
  }

  int capk = 2048;
  if ( user_capk > 0 && user_capk < 10000000 )
    capk = user_capk;

  FILE* fpout = stdout;
  if ( userfilename != NULL ) {
    FILE* fdtest = fopen( userfilename, "r" );
    if ( fdtest != NULL ) {
      printf("Output file \"%s\" already exists.  Refusing to overwrite.  Exiting.\n\n", userfilename );
      fclose( fdtest );
      free( userfilename );
      return -1;
    }
    fpout = fopen( userfilename, "wb" );
    if ( fpout == NULL ) {
      printf("Error: Could not open file \"%s\" for write.  Exiting.\n\n", userfilename );
      free( userfilename );
      return -1;
    }
  }

  long resolx = 1024;  // horizontal resolution in pixels
  long resoly = 768;   // vertical resolution in pixels
  if ( user_resolutionoverride ) {
    resolx = user_resolx;
    resoly = user_resoly;
  }

  double zoomlevel = 1.0;  // zoomlevel of 1.0 arbitrarily defined to be an x-width of 3.1.
  if ( user_zoomlevel > 0.00001 && user_zoomlevel < 10000000.0 )
    zoomlevel = user_zoomlevel;
  double fulldx = 3.1 / zoomlevel;
  double fulldy = (3.1 / zoomlevel) * ((double)resoly /(double)resolx);

  double pixelwidth = fulldx/(double)resolx;  // Could of just as easily been fulldy/(double)resoly
  double halfpixel = pixelwidth / 2.0;

  double xmin = centerx - fulldx / 2.0;
  double xminplushalf = xmin + halfpixel; // like to use the middles of pixels
  double ymax = centery + fulldy / 2.0;
  double ymaxlesshalf = ymax - halfpixel; // like to use the middles of pixels


  const double m  = 100.0;  // min norm to be considered an escapee


  struct pixel holdpal[256];
  initpal( holdpal );

  fprintf( fpout, "P6" );
  fwrite( CRLF, 1, 2, fpout );

  fprintf( fpout, "%ld %ld", resolx, resoly );
  fwrite( CRLF, 1, 2, fpout );

  fprintf( fpout, "255" );
  fwrite( CRLF, 1, 2, fpout );

  long x,y;
  for ( y = 0; y < resoly; y++ ) {
    for ( x = 0; x < resolx; x++ ) {
      double z_r = 0.0;
      double z_i = 0.0;

      if ( MakeJuliaSet ) {
        z_r = xminplushalf + x * pixelwidth;
        z_i = ymaxlesshalf - y * pixelwidth;
      }
      else {  // Make the Mandelbrot Set
        c_r = xminplushalf + x * pixelwidth;
        c_i = ymaxlesshalf - y * pixelwidth;
      }

      int k = -1;
      double norm = 0.0;

      double z_r_save = z_r;
      while ( norm < m && k < capk ) {  // repeatedly iterating z = z^2 + c  where z & c are complex numbers
        z_r_save = z_r;
        z_r = z_r_save * z_r_save - z_i * z_i + c_r;
        z_i = 2 * z_r_save * z_i + c_i;
        k++;
        norm = z_r * z_r + z_i * z_i;
      }

      if ( k == capk )
          k = 255;
      else
          k %= 254;

      fwrite( &holdpal[k], 1, 3, fpout );
    }
  }

  if ( fpout != stdout ) {
    fclose(fpout);
    fpout = NULL;
  }

  if ( userfilename != NULL ) {
    free( userfilename );
    userfilename = NULL;
  }

  return 0;
}
Beispiel #13
0
//HeadFile作成
int Initialize_stdin()
{
  // -i "filepath" -pipe が同時に指定されていた。
  if (NumLoadedFiles != 1)
    return 1;

  //HeadFile
  //  標準入力の先頭部をファイルに書き出す。
  //  ファイルにすることでseekに対応
  _setmode(_fileno(stdin), _O_BINARY);
  fdStdin = _fileno(stdin);

  //WindowsのTempフォルダにDGI_temp_0000000_2を作成
  {
    DWORD pid = GetCurrentProcessId();
    std::random_device rnd;
    std::mt19937 mt(rnd());
    UINT32 rnd_num = mt() % (1000 * 1000);
    std::string tmp_path;
    tmp_path = "DGI_temp_" + std::to_string(pid) + std::to_string(rnd_num) + "_";
    tmp_path = std::string(_tempnam(NULL, tmp_path.c_str()));
    HeadFilePath = tmp_path;
  }
  fdHeadFile = _open(HeadFilePath.c_str(), _O_CREAT | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);
  if (fdHeadFile == -1)
    return 1;
  int head_size;
  {
    const double mini_MB = 6.0;
    double size = HeadFileSize_CmdLine;
    size = mini_MB < size ? size : mini_MB;
    head_size = (int)(size * 1024 * 1024);
  }


  //標準入力からデータ取得、HeadFile書込
  const int buff_size = 1024 * 32;
  std::vector<BYTE> buff(buff_size);
  int cur_size = 0;                  //HeadFileに書込済サイズ

  while (cur_size < head_size)
  {
    int read = _read(fdStdin, &buff.front(), buff_size);
    if (read == -1)
    {
      Sleep(30);
      continue;//fail to connect. wait.
    }
    else if (read == 0)
      break;//end of stream.

    int written = _write(fdHeadFile, &buff.front(), read);
    if (written != read)
      return 1;
    cur_size += written;
  }
  if (head_size <= cur_size)
    head_size = cur_size;
  else
    return 1;//fail to read. too short stream.


  //Infileにセット
  strcpy(Infilename[0], HeadFilePath.c_str());
  Infile[0] = fdHeadFile;
  _lseeki64(Infile[0], 0, SEEK_SET);

  return 0;
}
Beispiel #14
0
int ShellExec(SHELL_PARAM* param)
{
#ifdef WIN32
	SECURITY_ATTRIBUTES saAttr={sizeof(SECURITY_ATTRIBUTES),NULL,TRUE};
	STARTUPINFO siStartInfo;
	BOOL fSuccess;
	char newPath[512],prevPath[512];
	HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
#else
	int fdin[2], fdout[2],pid,i;
	int fdStdinChild;
	int fdStdoutChild;
	char **args=NULL,*argString=NULL, *p;
	char *filePath;
 	char *newPath,*prevPath,*env[2];
#endif

#ifdef WIN32
	if (param->piProcInfo.hProcess || !param->pchCommandLine) return -1;

	_setmode( _fileno( stdin ), _O_BINARY );
	_setmode( _fileno( stdout ), _O_BINARY );

	// modify path variable
	if (param->pchPath) {
		GetEnvironmentVariable("PATH",prevPath,sizeof(prevPath));
		sprintf(newPath,"%s;s",param->pchPath,prevPath);
		SetEnvironmentVariable("PATH",newPath);
	}
	
	memset( &param->piProcInfo, 0, sizeof(PROCESS_INFORMATION) );
	memset( &siStartInfo, 0, sizeof(STARTUPINFO) );
	// Set up members of the STARTUPINFO structure.
	siStartInfo.cb = sizeof(STARTUPINFO);
	siStartInfo.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	siStartInfo.wShowWindow=(param->flags & SHELL_SHOW_WINDOW)?SW_SHOW:SW_HIDE;

///////////////////////////////////////////////////////////////////////
//	create redirecting pipes
///////////////////////////////////////////////////////////////////////

	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = NULL;

	
	if (param->flags & SHELL_REDIRECT_STDOUT) {
		// Create a pipe for the child process's STDOUT.
		if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
			return -1;
		}
		// Create noninheritable read handle and close the inheritable read
		// handle.
		fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
			GetCurrentProcess(), (LPHANDLE)&param->fdRead, 0,
				FALSE,
				DUPLICATE_SAME_ACCESS);
		if( !fSuccess ) return 0;
		CloseHandle(hChildStdoutRd);
		siStartInfo.hStdError = hChildStdoutWr;
		siStartInfo.hStdOutput = hChildStdoutWr;
	} else {
		siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
		siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	}
	if (param->flags & SHELL_REDIRECT_STDIN) {
		// Create a pipe for the child process's STDIN.
		if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) return 0;

		// Duplicate the write handle to the pipe so it is not inherited.
		fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
			GetCurrentProcess(), (LPHANDLE)&param->fdWrite, 0,
				FALSE,                  // not inherited
				DUPLICATE_SAME_ACCESS);
		if (! fSuccess) return -1;
		CloseHandle(hChildStdinWr);
		siStartInfo.hStdInput = hChildStdinRd;
	} else {
		siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	}

///////////////////////////////////////////////////////////////////////
//	create child process
///////////////////////////////////////////////////////////////////////
// Create the child process.

   fSuccess = CreateProcess(NULL,
	    param->pchCommandLine, // command line
		NULL,          // process security attributes
		NULL,          // primary thread security attributes
		TRUE,          // handles are inherited
		0,      // creation flags
		NULL,			 // process' environment
		param->pchCurDir,      // current directory
		&siStartInfo,  // STARTUPINFO pointer
		&param->piProcInfo);  // receives PROCESS_INFORMATION

	if (param->pchPath) SetEnvironmentVariable("PATH",prevPath);
	if (!fSuccess) return -1;
	WaitForInputIdle(param->piProcInfo.hProcess,INFINITE);

	if (param->flags & SHELL_REDIRECT_STDIN)
		CloseHandle(hChildStdinRd);
	if (param->flags & SHELL_REDIRECT_STDOUT)
		CloseHandle(hChildStdoutWr);
#else

	if (param->pid) return -1;

	if (param->flags & SHELL_REDIRECT_STDIN) {
		pipe(fdin);
		param->fdWrite = fdin[1];
		fdStdinChild=fdin[0];
	}
	if (param->flags & SHELL_REDIRECT_STDOUT) {
		pipe(fdout);
		param->fdRead = fdout[0];
		fdStdoutChild=fdout[1];
	}
	
	pid = fork();
	if (pid == -1) return -1;
	if (pid == 0) { /* chid process */
		//generate argument list
		for (p=param->pchCommandLine,i=2;*p;p++) {
			if (*p==' ') i++;
		}
		args=malloc(i*sizeof(char*));
		argString=strdup(param->pchCommandLine);
		i=0;
		if (argString) {
			p=strtok(argString," ");
			while (p) {
				args[i++]=p;
				p=strtok(NULL," ");
			}
		}
		args[i]=NULL;
		p=strrchr(args[0],'/');
		if (p) {
			filePath=args[0];
			args[0]=p+1;
		} else {
			filePath=NULL;
		}

		//set PATH
		env[0]=NULL;
		if (param->pchPath) {
			prevPath=getenv("PATH");
			env[0]=malloc(strlen(prevPath)+strlen(param->pchPath)+2+5);
			sprintf(env[0],"PATH=%s:%s",prevPath,param->pchPath);
			env[1]=NULL;
		}
		if (param->flags & SHELL_REDIRECT_STDIN) {
			close(fdin[1]);
			dup2(fdStdinChild, 0);
		}
		if (param->flags & SHELL_REDIRECT_STDOUT) {
			close(fdout[0]);
			dup2(fdStdoutChild, 1);
		}
		if (execve(filePath, args, env)<0) {
			printf("Error starting specified program\n");
		}
		return 0;
	}
	param->pid=pid;
#endif
	return 0;
}
void OsmAnd::DefaultLogSink::log(const LogSeverityLevel level, const char* format, va_list args)
{
    if (IsDebuggerPresent())
    {
        switch (level)
        {
            case LogSeverityLevel::Verbose:
                OutputDebugStringA("VERBOSE: ");
                break;
            case LogSeverityLevel::Debug:
                OutputDebugStringA("DEBUG: ");
                break;
            case LogSeverityLevel::Info:
                OutputDebugStringA("INFO: ");
                break;
            case LogSeverityLevel::Warning:
                OutputDebugStringA("WARN: ");
                break;
            case LogSeverityLevel::Error:
                OutputDebugStringA("ERROR: ");
                break;
        }

        int len = vsnprintf(nullptr, 0, format, args);
        char* buffer = new char[len + 1];
        vsnprintf(buffer, len, format, args);
        buffer[len] = 0;
        OutputDebugStringA(buffer);
        delete[] buffer;

        OutputDebugStringA("\n");
    }
    else
    {
        //NOTE: This ugly stuff is needed just because Win32 has no _getmode or fcntl API.
        const auto currentMode = _setmode(_fileno(stdout), _O_TEXT);
        if (currentMode != -1)
            _setmode(_fileno(stdout), currentMode);

        if (currentMode == -1 || (currentMode & (_O_U16TEXT | _O_U8TEXT | _O_WTEXT)) == 0)
        {
            switch (level)
            {
                case LogSeverityLevel::Verbose:
                    printf("VERBOSE: ");
                    break;
                case LogSeverityLevel::Debug:
                    printf("DEBUG: ");
                    break;
                case LogSeverityLevel::Info:
                    printf("INFO: ");
                    break;
                case LogSeverityLevel::Warning:
                    printf("WARN: ");
                    break;
                case LogSeverityLevel::Error:
                    printf("ERROR: ");
                    break;
            }

            vprintf(format, args);

            printf("\n");
        }
        else
        {
            switch (level)
            {
                case LogSeverityLevel::Verbose:
                    wprintf(L"VERBOSE: ");
                    break;
                case LogSeverityLevel::Debug:
                    wprintf(L"DEBUG: ");
                    break;
                case LogSeverityLevel::Info:
                    wprintf(L"INFO: ");
                    break;
                case LogSeverityLevel::Warning:
                    wprintf(L"WARN: ");
                    break;
                case LogSeverityLevel::Error:
                    wprintf(L"ERROR: ");
                    break;
            }

            int len = vsnprintf(nullptr, 0, format, args);
            char* buffer = new char[len + 1];
            vsnprintf(buffer, len, format, args);
            buffer[len] = 0;
            wprintf(L"%hs", buffer);

            wprintf(L"\n");
        }
    }
}
Beispiel #16
0
int main(int argc, char **argv)
{
  BuildCtx ctx_;
  BuildCtx *ctx = &ctx_;
  int status, binmode;

  if (sizeof(void *) != 4*LJ_32+8*LJ_64) {
    fprintf(stderr,"Error: pointer size mismatch in cross-build.\n");
    fprintf(stderr,"Try: make HOST_CC=\"gcc -m32\" CROSS=... TARGET=...\n\n");
    return 1;
  }

  UNUSED(argc);
  parseargs(ctx, argv);

  if ((status = build_code(ctx))) {
    fprintf(stderr,"Error: DASM error %08x\n", status);
    return 1;
  }

  switch (ctx->mode) {
  case BUILD_peobj:
  case BUILD_raw:
    binmode = 1;
    break;
  default:
    binmode = 0;
    break;
  }

  if (ctx->outname[0] == '-' && ctx->outname[1] == '\0') {
    ctx->fp = stdout;
#if defined(_WIN32)
    if (binmode)
      _setmode(_fileno(stdout), _O_BINARY);  /* Yuck. */
#endif
  } else if (!(ctx->fp = fopen(ctx->outname, binmode ? "wb" : "w"))) {
    fprintf(stderr, "Error: cannot open output file '%s': %s\n",
	    ctx->outname, strerror(errno));
    exit(1);
  }

  switch (ctx->mode) {
  case BUILD_elfasm:
  case BUILD_coffasm:
  case BUILD_machasm:
    emit_asm(ctx);
    emit_asm_debug(ctx);
    break;
  case BUILD_peobj:
    emit_peobj(ctx);
    break;
  case BUILD_raw:
    emit_raw(ctx);
    break;
  case BUILD_bcdef:
    emit_bcdef(ctx);
    emit_lib(ctx);
    break;
  case BUILD_vmdef:
    emit_vmdef(ctx);
    emit_lib(ctx);
    break;
  case BUILD_ffdef:
  case BUILD_libdef:
  case BUILD_recdef:
    emit_lib(ctx);
    break;
  case BUILD_folddef:
    emit_fold(ctx);
    break;
  default:
    break;
  }

  fflush(ctx->fp);
  if (ferror(ctx->fp)) {
    fprintf(stderr, "Error: cannot write to output file: %s\n",
	    strerror(errno));
    exit(1);
  }
  fclose(ctx->fp);

  return 0;
}
Beispiel #17
0
int main(int argc, char **argv)
{
    int c, i;
    int verbose = 0;
    int errors = 0;
    int open_mode = O_RDONLY;
    gost_subst_block *b = &GostR3411_94_CryptoProParamSet;
    FILE *check_file = NULL;
    gost_hash_ctx ctx;

    while ((c = getopt(argc, argv, "bc::tv")) != -1) {
        switch (c) {
        case 'v':
            verbose = 1;
            break;
        case 't':
            b = &GostR3411_94_TestParamSet;
            break;
        case 'b':
            open_mode |= O_BINARY;
            break;
        case 'c':
            if (optarg) {
                check_file = fopen(optarg, "r");
                if (!check_file) {
                    perror(optarg);
                    exit(2);
                }
            } else {
                check_file = stdin;
            }
            break;
        default:
            fprintf(stderr, "invalid option %c", optopt);
            help();
        }
    }
    init_gost_hash_ctx(&ctx, b);
    if (check_file) {
        char inhash[65], calcsum[65], filename[PATH_MAX];
        int failcount = 0, count = 0;
        errors = 0;
        if (check_file == stdin && optind < argc) {
            check_file = fopen(argv[optind], "r");
            if (!check_file) {
                perror(argv[optind]);
                exit(2);
            }
        }
        while (get_line(check_file, inhash, filename)) {
            count++;
            if (!hash_file(&ctx, filename, calcsum, open_mode)) {
                errors++;
                continue;
            }
            if (strncmp(calcsum, inhash, 65) == 0) {
                if (verbose) {
                    fprintf(stderr, "%s\tOK\n", filename);
                }
            } else {
                if (verbose) {
                    fprintf(stderr, "%s\tFAILED\n", filename);
                } else {
                    fprintf(stderr,
                            "%s: GOST hash sum check failed for '%s'\n",
                            argv[0], filename);
                }
                failcount++;
            }
        }
        if (errors) {
            fprintf(stderr,
                    "%s: WARNING %d of %d file(s) cannot be processed\n",
                    argv[0], errors, count);

        }
        if (verbose && failcount) {
            fprintf(stderr,
                    "%s: %d of %d file(f) failed GOST hash sum check\n",
                    argv[0], failcount, count);
        }
        exit((failcount || errors) ? 1 : 0);
    }
    if (optind == argc) {
        char sum[65];
#ifdef _WIN32
        if (open_mode & O_BINARY) {
            _setmode(fileno(stdin), O_BINARY);
        }
#endif
        if (!hash_stream(&ctx, fileno(stdin), sum)) {
            perror("stdin");
            exit(1);
        }
        printf("%s -\n", sum);
        exit(0);
    }
    for (i = optind; i < argc; i++) {
        char sum[65];
        if (!hash_file(&ctx, argv[i], sum, open_mode)) {
            errors++;
        } else {
            printf("%s %s\n", sum, argv[i]);
        }
    }
    exit(errors ? 1 : 0);
}
Beispiel #18
0
int main( int argc, char *argv[] )
{
    if( argc < 2 )
        return print_help( -1 );
    int dump_box = 1;
    int chapter = 0;
    char *filename;
    if( argc > 2 )
    {
        if( !strcasecmp( argv[1], "--box" ) )
            DO_NOTHING;
        else if( !strcasecmp( argv[1], "--chapter" ) )
            chapter = 1;
        else if( !strcasecmp( argv[1], "--timestamp" ) )
            dump_box = 0;
        else
            return print_help( -1 );
        filename = argv[2];
    }
    else
    {
        if( !strcasecmp( argv[1], "-h" ) || !strcasecmp( argv[1], "--help" ) )
            return print_help( 0 );
        filename = argv[1];
    }
#ifdef _WIN32
    _setmode( _fileno(stdin), _O_BINARY );
#endif
    lsmash_file_mode mode = LSMASH_FILE_MODE_READ;
    if( dump_box )
        mode |= LSMASH_FILE_MODE_DUMP;
    lsmash_root_t *root = lsmash_open_movie( filename, mode );
    if( !root )
    {
        fprintf( stderr, "Failed to open input file.\n" );
        return -1;
    }
    if( chapter )
    {
        if( lsmash_print_chapter_list( root ) )
            return BOXDUMPER_ERR( "Failed to extract chapter.\n" );
    }
    else if( dump_box )
    {
        if( lsmash_print_movie( root, "-" ) )
            return BOXDUMPER_ERR( "Failed to dump box structure.\n" );
    }
    else
    {
        lsmash_movie_parameters_t movie_param;
        lsmash_initialize_movie_parameters( &movie_param );
        lsmash_get_movie_parameters( root, &movie_param );
        uint32_t num_tracks = movie_param.number_of_tracks;
        for( uint32_t track_number = 1; track_number <= num_tracks; track_number++ )
        {
            uint32_t track_ID = lsmash_get_track_ID( root, track_number );
            if( !track_ID )
                return BOXDUMPER_ERR( "Failed to get track_ID.\n" );
            lsmash_media_parameters_t media_param;
            lsmash_initialize_media_parameters( &media_param );
            if( lsmash_get_media_parameters( root, track_ID, &media_param ) )
                return BOXDUMPER_ERR( "Failed to get media parameters.\n" );
            if( lsmash_construct_timeline( root, track_ID ) )
                return BOXDUMPER_ERR( "Failed to construct timeline.\n" );
            uint32_t timeline_shift;
            if( lsmash_get_composition_to_decode_shift_from_media_timeline( root, track_ID, &timeline_shift ) )
                return BOXDUMPER_ERR( "Failed to get timestamps.\n" );
            lsmash_media_ts_list_t ts_list;
            if( lsmash_get_media_timestamps( root, track_ID, &ts_list ) )
                return BOXDUMPER_ERR( "Failed to get timestamps.\n" );
            fprintf( stdout, "track_ID: %"PRIu32"\n", track_ID );
            fprintf( stdout, "Media timescale: %"PRIu32"\n", media_param.timescale );
            lsmash_media_ts_t *ts_array = ts_list.timestamp;
            if( !ts_array )
            {
                fprintf( stdout, "\n" );
                continue;
            }
            for( uint32_t i = 0; i < ts_list.sample_count; i++ )
                fprintf( stdout, "DTS = %"PRIu64", CTS = %"PRIu64"\n", ts_array[i].dts, ts_array[i].cts + timeline_shift );
            free( ts_array );
            fprintf( stdout, "\n" );
        }
    }
    lsmash_destroy_root( root );
    return 0;
}
Beispiel #19
0
int msSaveImageIM(imageObj* img, char *filename, outputFormatObj *format )

{
  FILE *stream;
  char workbuffer[5000];
  int nSize=0, size=0, iIndice=0;

  DEBUG_IF printf("msSaveImageIM\n<BR>");

  if(filename != NULL && strlen(filename) > 0) {
    stream = fopen(filename, "wb");
    if(!stream) {
      msSetError(MS_IOERR, "(%s)", "msSaveImage()", filename);
      return(MS_FAILURE);
    }
  } else { /* use stdout */

#ifdef _WIN32
    /*
     * Change stdout mode to binary on win32 platforms
     */
    if(_setmode( _fileno(stdout), _O_BINARY) == -1) {
      msSetError(MS_IOERR, "Unable to change stdout to binary mode.", "msSaveImage()");
      return(MS_FAILURE);
    }
#endif
    stream = stdout;
  }

  if( strcasecmp(format->driver,"imagemap") == 0 ) {
    DEBUG_IF printf("ALLOCD %d<BR>\n", img->size);
    /* DEBUG_IF printf("F %s<BR>\n", img->img.imagemap); */
    DEBUG_IF printf("FLEN %d<BR>\n", (int)strlen(img->img.imagemap));
    if (dxf == 2) {
      msIO_fprintf(stream, "%s", layerlist);
    } else if (dxf) {
      msIO_fprintf(stream, "  0\nSECTION\n  2\nHEADER\n  9\n$ACADVER\n  1\nAC1009\n0\nENDSEC\n  0\nSECTION\n  2\nTABLES\n  0\nTABLE\n%s0\nENDTAB\n0\nENDSEC\n  0\nSECTION\n  2\nBLOCKS\n0\nENDSEC\n  0\nSECTION\n  2\nENTITIES\n", layerlist);
    } else {
      msIO_fprintf(stream, "<map name=\"%s\" width=\"%d\" height=\"%d\">\n", mapName, img->width, img->height);
    }
    nSize = sizeof(workbuffer);

    size = strlen(img->img.imagemap);
    if (size > nSize) {
      iIndice = 0;
      while ((iIndice + nSize) <= size) {
        snprintf(workbuffer, sizeof(workbuffer), "%s", img->img.imagemap+iIndice );
        workbuffer[nSize-1] = '\0';
        msIO_fwrite(workbuffer, strlen(workbuffer), 1, stream);
        iIndice +=nSize-1;
      }
      if (iIndice < size) {
        sprintf(workbuffer, "%s", img->img.imagemap+iIndice );
        msIO_fprintf(stream, "%s", workbuffer);
      }
    } else
      msIO_fwrite(img->img.imagemap, size, 1, stream);
    if( strcasecmp("OFF",msGetOutputFormatOption( format, "SKIPENDTAG", "OFF" )) == 0) {
      if (dxf == 2)
        msIO_fprintf(stream, "END");
      else if (dxf)
        msIO_fprintf(stream, "0\nENDSEC\n0\nEOF\n");
      else
        msIO_fprintf(stream, "</map>");
    }
  } else {
    msSetError(MS_MISCERR, "Unknown output image type driver: %s.",
               "msSaveImage()", format->driver );
    return(MS_FAILURE);
  }

  if(filename != NULL && strlen(filename) > 0) fclose(stream);
  return(MS_SUCCESS);
}
Beispiel #20
0
int main(int argc, char **argv)
{
   int nb_samples, total_samples=0, nb_encoded;
   int c;
   int option_index = 0;
   char *inFile, *outFile;
   FILE *fin, *fout;
   short input[MAX_FRAME_SIZE];
   spx_int32_t frame_size;
   int quiet=0;
   spx_int32_t vbr_enabled=0;
   spx_int32_t vbr_max=0;
   int abr_enabled=0;
   spx_int32_t vad_enabled=0;
   spx_int32_t dtx_enabled=0;
   int nbBytes;
   const SpeexMode *mode=NULL;
   int modeID = -1;
   void *st;
   SpeexBits bits;
   char cbits[MAX_FRAME_BYTES];
   int with_skeleton = 0;
   struct option long_options[] =
   {
      {"wideband", no_argument, NULL, 0},
      {"ultra-wideband", no_argument, NULL, 0},
      {"narrowband", no_argument, NULL, 0},
      {"vbr", no_argument, NULL, 0},
      {"vbr-max-bitrate", required_argument, NULL, 0},
      {"abr", required_argument, NULL, 0},
      {"vad", no_argument, NULL, 0},
      {"dtx", no_argument, NULL, 0},
      {"quality", required_argument, NULL, 0},
      {"bitrate", required_argument, NULL, 0},
      {"nframes", required_argument, NULL, 0},
      {"comp", required_argument, NULL, 0},
#ifdef USE_SPEEXDSP
      {"denoise", no_argument, NULL, 0},
      {"agc", no_argument, NULL, 0},
#endif
      {"no-highpass", no_argument, NULL, 0},
      {"skeleton",no_argument,NULL, 0},
      {"help", no_argument, NULL, 0},
      {"quiet", no_argument, NULL, 0},
      {"le", no_argument, NULL, 0},
      {"be", no_argument, NULL, 0},
      {"8bit", no_argument, NULL, 0},
      {"16bit", no_argument, NULL, 0},
      {"stereo", no_argument, NULL, 0},
      {"rate", required_argument, NULL, 0},
      {"version", no_argument, NULL, 0},
      {"version-short", no_argument, NULL, 0},
      {"comment", required_argument, NULL, 0},
      {"author", required_argument, NULL, 0},
      {"title", required_argument, NULL, 0},
      {"print-rate", no_argument, NULL, 0},
      {0, 0, 0, 0}
   };
   int print_bitrate=0;
   spx_int32_t rate=0;
   spx_int32_t size;
   int chan=1;
   int fmt=16;
   spx_int32_t quality=-1;
   float vbr_quality=-1;
   int lsb=1;
   ogg_stream_state os;
   ogg_stream_state so; /* ogg stream for skeleton bitstream */
   ogg_page og;
   ogg_packet op;
   int bytes_written=0, ret, result;
   int id=-1;
   SpeexHeader header;
   int nframes=1;
   spx_int32_t complexity=3;
   const char* speex_version;
   char vendor_string[64];
   char *comments;
   int comments_length;
   int close_in=0, close_out=0;
   int eos=0;
   spx_int32_t bitrate=0;
   double cumul_bits=0, enc_frames=0;
   char first_bytes[12];
   int wave_input=0;
   spx_int32_t tmp;
#ifdef USE_SPEEXDSP
   SpeexPreprocessState *preprocess = NULL;
   int denoise_enabled=0, agc_enabled=0;
#endif
   int highpass_enabled=1;
   int output_rate=0;
   spx_int32_t lookahead = 0;

   speex_lib_ctl(SPEEX_LIB_GET_VERSION_STRING, (void*)&speex_version);
   snprintf(vendor_string, sizeof(vendor_string), "Encoded with Speex %s", speex_version);

   comment_init(&comments, &comments_length, vendor_string);

   /*Process command-line options*/
   while(1)
   {
      c = getopt_long (argc, argv, "nwuhvV",
                       long_options, &option_index);
      if (c==-1)
         break;

      switch(c)
      {
      case 0:
         if (strcmp(long_options[option_index].name,"narrowband")==0)
         {
            modeID = SPEEX_MODEID_NB;
         } else if (strcmp(long_options[option_index].name,"wideband")==0)
         {
            modeID = SPEEX_MODEID_WB;
         } else if (strcmp(long_options[option_index].name,"ultra-wideband")==0)
         {
            modeID = SPEEX_MODEID_UWB;
         } else if (strcmp(long_options[option_index].name,"vbr")==0)
         {
            vbr_enabled=1;
         } else if (strcmp(long_options[option_index].name,"vbr-max-bitrate")==0)
         {
            vbr_max=atoi(optarg);
            if (vbr_max<1)
            {
               fprintf (stderr, "Invalid VBR max bit-rate value: %d\n", vbr_max);
               exit(1);
            }
         } else if (strcmp(long_options[option_index].name,"abr")==0)
         {
            abr_enabled=atoi(optarg);
            if (!abr_enabled)
            {
               fprintf (stderr, "Invalid ABR value: %d\n", abr_enabled);
               exit(1);
            }
         } else if (strcmp(long_options[option_index].name,"vad")==0)
         {
            vad_enabled=1;
         } else if (strcmp(long_options[option_index].name,"dtx")==0)
         {
            dtx_enabled=1;
         } else if (strcmp(long_options[option_index].name,"quality")==0)
         {
            quality = atoi (optarg);
            vbr_quality=atof(optarg);
         } else if (strcmp(long_options[option_index].name,"bitrate")==0)
         {
            bitrate = atoi (optarg);
         } else if (strcmp(long_options[option_index].name,"nframes")==0)
         {
            nframes = atoi (optarg);
            if (nframes<1)
               nframes=1;
            if (nframes>10)
               nframes=10;
         } else if (strcmp(long_options[option_index].name,"comp")==0)
         {
            complexity = atoi (optarg);
#ifdef USE_SPEEXDSP
         } else if (strcmp(long_options[option_index].name,"denoise")==0)
         {
            denoise_enabled=1;
         } else if (strcmp(long_options[option_index].name,"agc")==0)
         {
            agc_enabled=1;
#endif
         } else if (strcmp(long_options[option_index].name,"no-highpass")==0)
         {
            highpass_enabled=0;
         } else if (strcmp(long_options[option_index].name,"skeleton")==0)
         {
            with_skeleton=1;
         } else if (strcmp(long_options[option_index].name,"help")==0)
         {
            usage();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"quiet")==0)
         {
            quiet = 1;
         } else if (strcmp(long_options[option_index].name,"version")==0)
         {
            version();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"version-short")==0)
         {
            version_short();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"print-rate")==0)
         {
            output_rate=1;
         } else if (strcmp(long_options[option_index].name,"le")==0)
         {
            lsb=1;
         } else if (strcmp(long_options[option_index].name,"be")==0)
         {
            lsb=0;
         } else if (strcmp(long_options[option_index].name,"8bit")==0)
         {
            fmt=8;
         } else if (strcmp(long_options[option_index].name,"16bit")==0)
         {
            fmt=16;
         } else if (strcmp(long_options[option_index].name,"stereo")==0)
         {
            chan=2;
         } else if (strcmp(long_options[option_index].name,"rate")==0)
         {
            rate=atoi (optarg);
         } else if (strcmp(long_options[option_index].name,"comment")==0)
         {
            if (!strchr(optarg, '='))
            {
               fprintf (stderr, "Invalid comment: %s\n", optarg);
               fprintf (stderr, "Comments must be of the form name=value\n");
               exit(1);
            }
           comment_add(&comments, &comments_length, NULL, optarg);
         } else if (strcmp(long_options[option_index].name,"author")==0)
         {
           comment_add(&comments, &comments_length, "author=", optarg);
         } else if (strcmp(long_options[option_index].name,"title")==0)
         {
           comment_add(&comments, &comments_length, "title=", optarg);
         }

         break;
      case 'n':
         modeID = SPEEX_MODEID_NB;
         break;
      case 'h':
         usage();
         exit(0);
         break;
      case 'v':
         version();
         exit(0);
         break;
      case 'V':
         print_bitrate=1;
         break;
      case 'w':
         modeID = SPEEX_MODEID_WB;
         break;
      case 'u':
         modeID = SPEEX_MODEID_UWB;
         break;
      case '?':
         usage();
         exit(1);
         break;
      }
   }
   if (argc-optind!=2)
   {
      usage();
      exit(1);
   }
   inFile=argv[optind];
   outFile=argv[optind+1];

   /*Initialize Ogg stream struct*/
   srand(time(NULL));
   if (ogg_stream_init(&os, rand())==-1)
   {
      fprintf(stderr,"Error: stream init failed\n");
      exit(1);
   }
   if (with_skeleton && ogg_stream_init(&so, rand())==-1)
   {
      fprintf(stderr,"Error: stream init failed\n");
      exit(1);
   }

   if (strcmp(inFile, "-")==0)
   {
#if defined WIN32 || defined _WIN32
         _setmode(_fileno(stdin), _O_BINARY);
#elif defined OS2
         _fsetmode(stdin,"b");
#endif
      fin=stdin;
   }
   else
   {
      fin = fopen(inFile, "rb");
      if (!fin)
      {
         perror(inFile);
         exit(1);
      }
      close_in=1;
   }

   {
      if (fread(first_bytes, 1, 12, fin) != 12)
      {
         perror("short file");
         exit(1);
      }
      if (strncmp(first_bytes,"RIFF",4)==0 || strncmp(first_bytes,"riff",4)==0)
      {
         if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1)
            exit(1);
         wave_input=1;
         lsb=1; /* CHECK: exists big-endian .wav ?? */
      }
   }

   if (modeID==-1 && !rate)
   {
      /* By default, use narrowband/8 kHz */
      modeID = SPEEX_MODEID_NB;
      rate=8000;
   } else if (modeID!=-1 && rate)
   {
      mode = speex_lib_get_mode (modeID);
      if (rate>48000)
      {
         fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate);
         exit(1);
      } else if (rate>25000)
      {
         if (modeID != SPEEX_MODEID_UWB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try ultra-wideband instead\n", mode->modeName , rate);
         }
      } else if (rate>12500)
      {
         if (modeID != SPEEX_MODEID_WB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try wideband instead\n", mode->modeName , rate);
         }
      } else if (rate>=6000)
      {
         if (modeID != SPEEX_MODEID_NB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try narrowband instead\n", mode->modeName , rate);
         }
      } else {
         fprintf (stderr, "Error: sampling rate too low: %d Hz\n", rate);
         exit(1);
      }
   } else if (modeID==-1)
   {
      if (rate>48000)
      {
         fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate);
         exit(1);
      } else if (rate>25000)
      {
         modeID = SPEEX_MODEID_UWB;
      } else if (rate>12500)
      {
         modeID = SPEEX_MODEID_WB;
      } else if (rate>=6000)
      {
         modeID = SPEEX_MODEID_NB;
      } else {
         fprintf (stderr, "Error: Sampling rate too low: %d Hz\n", rate);
         exit(1);
      }
   } else if (!rate)
   {
      if (modeID == SPEEX_MODEID_NB)
         rate=8000;
      else if (modeID == SPEEX_MODEID_WB)
         rate=16000;
      else if (modeID == SPEEX_MODEID_UWB)
         rate=32000;
   }

   if (!quiet)
      if (rate!=8000 && rate!=16000 && rate!=32000)
         fprintf (stderr, "Warning: Speex is only optimized for 8, 16 and 32 kHz. It will still work at %d Hz but your mileage may vary\n", rate);

   if (!mode)
      mode = speex_lib_get_mode (modeID);

   speex_init_header(&header, rate, 1, mode);
   header.frames_per_packet=nframes;
   header.vbr=vbr_enabled;
   header.nb_channels = chan;

   {
      char *st_string="mono";
      if (chan==2)
         st_string="stereo";
      if (!quiet)
         fprintf (stderr, "Encoding %d Hz audio using %s mode (%s)\n",
               header.rate, mode->modeName, st_string);
   }
   /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n",
     header.rate, mode->bitrate, mode->modeName);*/

   /*Initialize Speex encoder*/
   st = speex_encoder_init(mode);

   if (strcmp(outFile,"-")==0)
   {
#if defined WIN32 || defined _WIN32
      _setmode(_fileno(stdout), _O_BINARY);
#endif
      fout=stdout;
   }
   else
   {
      fout = fopen(outFile, "wb");
      if (!fout)
      {
         perror(outFile);
         exit(1);
      }
      close_out=1;
   }

   speex_encoder_ctl(st, SPEEX_GET_FRAME_SIZE, &frame_size);
   speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &complexity);
   speex_encoder_ctl(st, SPEEX_SET_SAMPLING_RATE, &rate);

   if (quality >= 0)
   {
      if (vbr_enabled)
      {
         if (vbr_max>0)
            speex_encoder_ctl(st, SPEEX_SET_VBR_MAX_BITRATE, &vbr_max);
         speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_quality);
      }
      else
         speex_encoder_ctl(st, SPEEX_SET_QUALITY, &quality);
   }
   if (bitrate)
   {
      if (quality >= 0 && vbr_enabled)
         fprintf (stderr, "Warning: --bitrate option is overriding --quality\n");
      speex_encoder_ctl(st, SPEEX_SET_BITRATE, &bitrate);
   }
   if (vbr_enabled)
   {
      tmp=1;
      speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp);
   } else if (vad_enabled)
   {
      tmp=1;
      speex_encoder_ctl(st, SPEEX_SET_VAD, &tmp);
   }
   if (dtx_enabled)
      speex_encoder_ctl(st, SPEEX_SET_DTX, &tmp);
   if (dtx_enabled && !(vbr_enabled || abr_enabled || vad_enabled))
   {
      fprintf (stderr, "Warning: --dtx is useless without --vad, --vbr or --abr\n");
   } else if ((vbr_enabled || abr_enabled) && (vad_enabled))
   {
      fprintf (stderr, "Warning: --vad is already implied by --vbr or --abr\n");
   }
   if (with_skeleton) {
      fprintf (stderr, "Warning: Enabling skeleton output may cause some decoders to fail.\n");
   }

   if (abr_enabled)
   {
      speex_encoder_ctl(st, SPEEX_SET_ABR, &abr_enabled);
   }

   speex_encoder_ctl(st, SPEEX_SET_HIGHPASS, &highpass_enabled);

   speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &lookahead);

#ifdef USE_SPEEXDSP
   if (denoise_enabled || agc_enabled)
   {
      preprocess = speex_preprocess_state_init(frame_size, rate);
      speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_DENOISE, &denoise_enabled);
      speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_AGC, &agc_enabled);
      lookahead += frame_size;
   }
#endif
   /* first packet should be the skeleton header. */

   if (with_skeleton) {
      add_fishead_packet(&so);
      if ((ret = flush_ogg_stream_to_file(&so, fout))) {
         fprintf (stderr,"Error: failed skeleton (fishead) header to output stream\n");
         exit(1);
      } else
         bytes_written += ret;
   }

   /*Write header*/
   {
      int packet_size;
      op.packet = (unsigned char *)speex_header_to_packet(&header, &packet_size);
      op.bytes = packet_size;
      op.b_o_s = 1;
      op.e_o_s = 0;
      op.granulepos = 0;
      op.packetno = 0;
      ogg_stream_packetin(&os, &op);
      free(op.packet);

      while((result = ogg_stream_flush(&os, &og)))
      {
         if(!result) break;
         ret = oe_write_page(&og, fout);
         if(ret != og.header_len + og.body_len)
         {
            fprintf (stderr,"Error: failed writing header to output stream\n");
            exit(1);
         }
         else
            bytes_written += ret;
      }

      op.packet = (unsigned char *)comments;
      op.bytes = comments_length;
      op.b_o_s = 0;
      op.e_o_s = 0;
      op.granulepos = 0;
      op.packetno = 1;
      ogg_stream_packetin(&os, &op);
   }

   /* fisbone packet should be write after all bos pages */
   if (with_skeleton) {
      add_fisbone_packet(&so, os.serialno, &header);
      if ((ret = flush_ogg_stream_to_file(&so, fout))) {
         fprintf (stderr,"Error: failed writing skeleton (fisbone )header to output stream\n");
         exit(1);
      } else
         bytes_written += ret;
   }

   /* writing the rest of the speex header packets */
   while((result = ogg_stream_flush(&os, &og)))
   {
      if(!result) break;
      ret = oe_write_page(&og, fout);
      if(ret != og.header_len + og.body_len)
      {
         fprintf (stderr,"Error: failed writing header to output stream\n");
         exit(1);
      }
      else
         bytes_written += ret;
   }

   free(comments);

   /* write the skeleton eos packet */
   if (with_skeleton) {
      add_eos_packet_to_stream(&so);
      if ((ret = flush_ogg_stream_to_file(&so, fout))) {
         fprintf (stderr,"Error: failed writing skeleton header to output stream\n");
         exit(1);
      } else
         bytes_written += ret;
   }


   speex_bits_init(&bits);

   if (!wave_input)
   {
      nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL);
   } else {
      nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size);
   }
   if (nb_samples==0)
      eos=1;
   total_samples += nb_samples;
   nb_encoded = -lookahead;
   /*Main encoding loop (one frame per iteration)*/
   while (!eos || total_samples>nb_encoded)
   {
      id++;
      /*Encode current frame*/
      if (chan==2)
         speex_encode_stereo_int(input, frame_size, &bits);

#ifdef USE_SPEEXDSP
      if (preprocess)
         speex_preprocess(preprocess, input, NULL);
#endif
      speex_encode_int(st, input, &bits);

      nb_encoded += frame_size;
      if (print_bitrate) {
         int tmp;
         char ch=13;
         speex_encoder_ctl(st, SPEEX_GET_BITRATE, &tmp);
         fputc (ch, stderr);
         cumul_bits += tmp;
         enc_frames += 1;
         if (!quiet)
         {
            if (vad_enabled || vbr_enabled || abr_enabled)
               fprintf (stderr, "Bitrate is use: %d bps  (average %d bps)   ", tmp, (int)(cumul_bits/enc_frames));
            else
               fprintf (stderr, "Bitrate is use: %d bps     ", tmp);
            if (output_rate)
               printf ("%d\n", tmp);
         }

      }

      if (wave_input)
      {
         nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size);
      } else {
         nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL);
      }
      if (nb_samples==0)
      {
         eos=1;
      }
      if (eos && total_samples<=nb_encoded)
         op.e_o_s = 1;
      else
         op.e_o_s = 0;
      total_samples += nb_samples;

      if ((id+1)%nframes!=0)
         continue;
      speex_bits_insert_terminator(&bits);
      nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES);
      speex_bits_reset(&bits);
      op.packet = (unsigned char *)cbits;
      op.bytes = nbBytes;
      op.b_o_s = 0;
      /*Is this redundent?*/
      if (eos && total_samples<=nb_encoded)
         op.e_o_s = 1;
      else
         op.e_o_s = 0;
      op.granulepos = (id+1)*frame_size-lookahead;
      if (op.granulepos>total_samples)
         op.granulepos = total_samples;
      /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/
      op.packetno = 2+id/nframes;
      ogg_stream_packetin(&os, &op);

      /*Write all new pages (most likely 0 or 1)*/
      while (ogg_stream_pageout(&os,&og))
      {
         ret = oe_write_page(&og, fout);
         if(ret != og.header_len + og.body_len)
         {
            fprintf (stderr,"Error: failed writing header to output stream\n");
            exit(1);
         }
         else
            bytes_written += ret;
      }
   }
   if ((id+1)%nframes!=0)
   {
      while ((id+1)%nframes!=0)
      {
         id++;
         speex_bits_pack(&bits, 15, 5);
      }
      nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES);
      op.packet = (unsigned char *)cbits;
      op.bytes = nbBytes;
      op.b_o_s = 0;
      op.e_o_s = 1;
      op.granulepos = (id+1)*frame_size-lookahead;
      if (op.granulepos>total_samples)
         op.granulepos = total_samples;

      op.packetno = 2+id/nframes;
      ogg_stream_packetin(&os, &op);
   }
   /*Flush all pages left to be written*/
   while (ogg_stream_flush(&os, &og))
   {
      ret = oe_write_page(&og, fout);
      if(ret != og.header_len + og.body_len)
      {
         fprintf (stderr,"Error: failed writing header to output stream\n");
         exit(1);
      }
      else
         bytes_written += ret;
   }

   speex_encoder_destroy(st);
   speex_bits_destroy(&bits);
   ogg_stream_clear(&os);

   if (close_in)
      fclose(fin);
   if (close_out)
      fclose(fout);
   return 0;
}
Beispiel #21
0
void cgiInit()
{
	_setmode( _fileno( stdin ), _O_BINARY );
	_setmode( _fileno( stdout ), _O_BINARY );
}
Beispiel #22
0
int main(){
  OggVorbis_File ov;
  int i,ret;
  ogg_int64_t pcmlength;
  double timelength;
  char *bigassbuffer;
  int dummy;

#ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  _setmode( _fileno( stdin ), _O_BINARY );
#endif


  /* open the file/pipe on stdin */
  if(ov_open_callbacks(stdin,&ov,NULL,-1,OV_CALLBACKS_NOCLOSE)<0){
    fprintf(stderr,"Could not open input as an OggVorbis file.\n\n");
    exit(1);
  }

  if(ov_seekable(&ov)){

    /* to simplify our own lives, we want to assume the whole file is
       stereo.  Verify this to avoid potentially mystifying users
       (pissing them off is OK, just don't confuse them) */
    for(i=0;i<ov.links;i++){
      vorbis_info *vi=ov_info(&ov,i);
      if(vi->channels!=2){
	fprintf(stderr,"Sorry; right now seeking_test can only use Vorbis files\n"
	       "that are entirely stereo.\n\n");
	exit(1);
      }
    }
    
    /* because we want to do sample-level verification that the seek
       does what it claimed, decode the entire file into memory */
    pcmlength=ov_pcm_total(&ov,-1);
    timelength=ov_time_total(&ov,-1);
    bigassbuffer=malloc(pcmlength*2); /* w00t */
    i=0;
    while(i<pcmlength*2){
      int ret=ov_read(&ov,bigassbuffer+i,pcmlength*2-i,1,1,1,&dummy);
      if(ret<0)continue;
      if(ret){
	i+=ret;
      }else{
	pcmlength=i/2;
      }
      fprintf(stderr,"\rloading.... [%ld left]              ",
	      (long)(pcmlength*2-i));
    }
    
    {
      ogg_int64_t length=ov.end;
      fprintf(stderr,"\rtesting raw seeking to random places in %ld bytes....\n",
	     (long)length);
    
      for(i=0;i<1000;i++){
	ogg_int64_t val=(double)rand()/RAND_MAX*length;
	fprintf(stderr,"\r\t%d [raw position %ld]...     ",i,(long)val);
	ret=ov_raw_seek(&ov,val);
	if(ret<0){
	  fprintf(stderr,"seek failed: %d\n",ret);
	  exit(1);
	}

	_verify(&ov,val,-1,-1.,pcmlength,bigassbuffer);

      }
    }

    fprintf(stderr,"\r");
    {
      fprintf(stderr,"testing pcm page seeking to random places in %ld samples....\n",
	     (long)pcmlength);
    
      for(i=0;i<1000;i++){
	ogg_int64_t val=(double)rand()/RAND_MAX*pcmlength;
	fprintf(stderr,"\r\t%d [pcm position %ld]...     ",i,(long)val);
	ret=ov_pcm_seek_page(&ov,val);
	if(ret<0){
	  fprintf(stderr,"seek failed: %d\n",ret);
	  exit(1);
	}

	_verify(&ov,-1,val,-1.,pcmlength,bigassbuffer);

      }
    }
    
    fprintf(stderr,"\r");
    {
      fprintf(stderr,"testing pcm exact seeking to random places in %ld samples....\n",
	     (long)pcmlength);
    
      for(i=0;i<1000;i++){
	ogg_int64_t val=(double)rand()/RAND_MAX*pcmlength;
	fprintf(stderr,"\r\t%d [pcm position %ld]...     ",i,(long)val);
	ret=ov_pcm_seek(&ov,val);
	if(ret<0){
	  fprintf(stderr,"seek failed: %d\n",ret);
	  exit(1);
	}
	if(ov_pcm_tell(&ov)!=val){
	  fprintf(stderr,"Declared position didn't perfectly match request: %ld != %ld\n",
		 (long)val,(long)ov_pcm_tell(&ov));
	  exit(1);
	}

	_verify(&ov,-1,val,-1.,pcmlength,bigassbuffer);

      }
    }

    fprintf(stderr,"\r");
    {
      fprintf(stderr,"testing time page seeking to random places in %f seconds....\n",
	     timelength);
    
      for(i=0;i<1000;i++){
	double val=(double)rand()/RAND_MAX*timelength;
	fprintf(stderr,"\r\t%d [time position %f]...     ",i,val);
	ret=ov_time_seek_page(&ov,val);
	if(ret<0){
	  fprintf(stderr,"seek failed: %d\n",ret);
	  exit(1);
	}

	_verify(&ov,-1,-1,val,pcmlength,bigassbuffer);

      }
    }

    fprintf(stderr,"\r");
    {
      fprintf(stderr,"testing time exact seeking to random places in %f seconds....\n",
	     timelength);
    
      for(i=0;i<1000;i++){
	double val=(double)rand()/RAND_MAX*timelength;
	fprintf(stderr,"\r\t%d [time position %f]...     ",i,val);
	ret=ov_time_seek(&ov,val);
	if(ret<0){
	  fprintf(stderr,"seek failed: %d\n",ret);
	  exit(1);
	}
	if(ov_time_tell(&ov)<val-1 || ov_time_tell(&ov)>val+1){
	  fprintf(stderr,"Declared position didn't perfectly match request: %f != %f\n",
		 val,ov_time_tell(&ov));
	  exit(1);
	}

	_verify(&ov,-1,-1,val,pcmlength,bigassbuffer);

      }
    }
    
    fprintf(stderr,"\r                                           \nOK.\n\n");


  }else{
    fprintf(stderr,"Standard input was not seekable.\n");
  }

  ov_clear(&ov);
  return 0;
}
Beispiel #23
0
/* 1 on success, 0 on failure */
int open_track(char *fname)
{
	filept=-1;
	httpdata_reset(&htd);
	if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, 0, 0))
	error1("Cannot (re)set ICY interval: %s", mpg123_strerror(mh));
	if(!strcmp(fname, "-"))
	{
		filept = STDIN_FILENO;
#ifdef WIN32
		_setmode(STDIN_FILENO, _O_BINARY);
#endif
		return open_track_fd();
	}
	else if (!strncmp(fname, "http://", 7)) /* http stream */
	{
#if defined (WANT_WIN32_SOCKETS)
	if(param.streamdump != NULL)
	{
		fprintf(stderr, "\nWarning: win32 networking conflicts with stream dumping. Aborting the dump.\n");
		dump_close();
	}
	/*Use recv instead of stdio functions */
	win32_net_replace(mh);
	filept = win32_net_http_open(fname, &htd);
#else
	filept = http_open(fname, &htd);
#endif
	network_sockets_used = 1;
/* utf-8 encoded URLs might not work under Win32 */
		
		/* now check if we got sth. and if we got sth. good */
		if(    (filept >= 0) && (htd.content_type.p != NULL)
			  && !APPFLAG(MPG123APP_IGNORE_MIME) && !(debunk_mime(htd.content_type.p) & IS_FILE) )
		{
			error1("Unknown mpeg MIME type %s - is it perhaps a playlist (use -@)?", htd.content_type.p == NULL ? "<nil>" : htd.content_type.p);
			error("If you know the stream is mpeg1/2 audio, then please report this as "PACKAGE_NAME" bug");
			return 0;
		}
		if(filept < 0)
		{
			error1("Access to http resource %s failed.", fname);
			return 0;
		}
		if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, htd.icy_interval, 0))
		error1("Cannot set ICY interval: %s", mpg123_strerror(mh));
		if(param.verbose > 1) fprintf(stderr, "Info: ICY interval %li\n", (long)htd.icy_interval);
	}

	if(param.icy_interval > 0)
	{
		if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, param.icy_interval, 0))
		error1("Cannot set ICY interval: %s", mpg123_strerror(mh));
		if(param.verbose > 1) fprintf(stderr, "Info: Forced ICY interval %li\n", param.icy_interval);
	}

	debug("OK... going to finally open.");
	/* Now hook up the decoder on the opened stream or the file. */
	if(network_sockets_used) 
	{
		return open_track_fd();
	}
	else if(mpg123_open(mh, fname) != MPG123_OK)
	{
		error2("Cannot open %s: %s", fname, mpg123_strerror(mh));
		return 0;
	}
	debug("Track successfully opened.");

	fresh = TRUE;
	return 1;
}
Beispiel #24
0
bool DBFFAM::AllocateBuffer(PGLOBAL g)
  {
  char c;
  int  rc;
  MODE mode = Tdbp->GetMode();

  Buflen = Blksize;
  To_Buf = (char*)PlugSubAlloc(g, NULL, Buflen);

  if (mode == MODE_INSERT) {
#if defined(WIN32)
    /************************************************************************/
    /*  Now we can revert to binary mode in particular because the eventual */
    /*  writing of a new header must be done in binary mode to avoid        */
    /*  translating 0A bytes (LF) into 0D0A (CRLF) by Windows in text mode. */
    /************************************************************************/
    if (_setmode(_fileno(Stream), _O_BINARY) == -1) {
      sprintf(g->Message, MSG(BIN_MODE_FAIL), strerror(errno));
      return true;
      } // endif setmode
#endif   // WIN32

    /************************************************************************/
    /*  If this is a new file, the header must be generated.                */
    /************************************************************************/
    int len = GetFileLength(g);

    if (!len) {
      // Make the header for this DBF table file
      struct tm  *datm;
      int         hlen, n = 0;
      ushort      reclen = 1;
      time_t      t;
      DBFHEADER  *header;
      DESCRIPTOR *descp;
      PCOLDEF     cdp;
      PDOSDEF     tdp = (PDOSDEF)Tdbp->GetDef();

      // Count the number of columns
      for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
        if (!(cdp->Flags & U_SPECIAL)) {
          reclen += cdp->GetLong();
          n++;
          } // endif Flags

      if (Lrecl != reclen) {
        sprintf(g->Message, MSG(BAD_LRECL), Lrecl, reclen);
        return true;
        } // endif Lrecl

      hlen = HEADLEN * (n + 1) + 2;
      header = (DBFHEADER*)PlugSubAlloc(g, NULL, hlen);
      memset(header, 0, hlen);
      header->Version = DBFTYPE;
      t = time(NULL) - (time_t)DTVAL::GetShift();
      datm = gmtime(&t);
      header->Filedate[0] = datm->tm_year - 100;
      header->Filedate[1] = datm->tm_mon + 1;
      header->Filedate[2] = datm->tm_mday;
      header->Headlen = (ushort)hlen;
      header->Reclen = (ushort)reclen;
      descp = (DESCRIPTOR*)header;

      // Currently only standard Xbase types are supported
      for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
        if (!(cdp->Flags & U_SPECIAL)) {
          descp++;
      
          switch ((c = *GetFormatType(cdp->GetType()))) {
            case 'S':           // Short integer
            case 'L':           // Large (big) integer
            case 'T':           // Tiny integer
              c = 'N';          // Numeric
            case 'N':           // Numeric (integer)
            case 'F':           // Float (double)
              descp->Decimals = (uchar)cdp->F.Prec;
            case 'C':           // Char
            case 'D':           // Date
              break;
            default:            // Should never happen
              sprintf(g->Message, "Unsupported DBF type %c for column %s",
                                  c, cdp->GetName());
              return true;
            } // endswitch c
      
          strncpy(descp->Name, cdp->GetName(), 11);
          descp->Type = c;
          descp->Length = (uchar)cdp->GetLong();
          } // endif Flags

      *(char*)(++descp) = EOH;

      //  Now write the header
      if (fwrite(header, 1, hlen, Stream) != (unsigned)hlen) {
        sprintf(g->Message, MSG(FWRITE_ERROR), strerror(errno));
        return true;
        } // endif fwrite

      Records = 0;
      Headlen = hlen;
    } else if (len < 0)
      return true;            // Error in GetFileLength

    /************************************************************************/
    /*  For Insert the buffer must be prepared.                             */
    /************************************************************************/
    memset(To_Buf, ' ', Buflen);
    Rbuf = Nrec;                     // To be used by WriteDB
  } else if (UseTemp) {
    // Allocate a separate buffer so block reading can be kept
    Dbflen = Nrec;
    DelBuf = PlugSubAlloc(g, NULL, Blksize);
  } // endif's

  if (!Headlen) {
    /************************************************************************/
    /*  Here is a good place to process the DBF file header                 */
    /************************************************************************/
    DBFHEADER header;

    if ((rc = dbfhead(g, Stream, Tdbp->GetFile(g), &header)) == RC_OK) {
      if (Lrecl != (int)header.Reclen) {
        sprintf(g->Message, MSG(BAD_LRECL), Lrecl, header.Reclen);
        return true;
        } // endif Lrecl

      Records = (int)header.Records;
      Headlen = (int)header.Headlen;
    } else if (rc == RC_NF) {
      Records = 0;
      Headlen = 0;
    } else              // RC_FX
      return true;                  // Error in dbfhead

    } // endif Headlen

  /**************************************************************************/
  /*  Position the file at the begining of the data.                        */
  /**************************************************************************/
  if (Tdbp->GetMode() == MODE_INSERT)
    rc = fseek(Stream, 0, SEEK_END);
  else
    rc = fseek(Stream, Headlen, SEEK_SET);

  if (rc) {
    sprintf(g->Message, MSG(BAD_DBF_FILE), Tdbp->GetFile(g));
    return true;
    } // endif fseek

  return false;
  } // end of AllocateBuffer
/**
 * Main function of the helper process to extract meta data.
 *
 * @param argc should be 3
 * @param argv [0] our binary name
 *             [1] name of the file or directory to process
 *             [2] "-" to disable extraction, NULL for defaults,
 *                 otherwise custom plugins to load from LE
 * @return 0 on success
 */
int main(int argc,
	 char *const *argv)
{
  const char *filename_expanded;
  const char *ex;
  struct ScanTreeNode *root;

#if WINDOWS
  /* We're using stdout to communicate binary data back to the parent; use
   * binary mode.
   */
  _setmode (1, _O_BINARY);
  /* Get utf-8-encoded arguments */
  if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
    return 5;
#else
  ignore_sigpipe ();
#endif

  /* parse command line */
  if ( (3 != argc) && (2 != argc) )
  {
    FPRINTF (stderr, 
	     "%s",
	     "gnunet-helper-fs-publish needs exactly one or two arguments\n");
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 1;
  }
  filename_expanded = argv[1];
  ex = argv[2];
  if ( (NULL == ex) ||
       (0 != strcmp (ex, "-")) )
  {
    plugins = EXTRACTOR_plugin_add_defaults (EXTRACTOR_OPTION_DEFAULT_POLICY);
    if (NULL != ex)
      plugins = EXTRACTOR_plugin_add_config (plugins, ex,
					     EXTRACTOR_OPTION_DEFAULT_POLICY);
  }

  /* scan tree to find out how much work there is to be done */
  if (GNUNET_OK != preprocess_file (filename_expanded, 
				    &root))
  {
    (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
    EXTRACTOR_plugin_remove_all (plugins);
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 2;
  }
  /* signal that we're done counting files, so that a percentage of 
     progress can now be calculated */
  if (GNUNET_OK !=
      write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE, NULL, 0))
  {
    EXTRACTOR_plugin_remove_all (plugins);
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 3;  
  }
  if (NULL != root)
  {
    if (GNUNET_OK !=
	extract_files (root))
    {
      (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
      free_tree (root);
      EXTRACTOR_plugin_remove_all (plugins);
#if WINDOWS
      GNUNET_free ((void*) argv);
#endif
      return 4;
    }
    free_tree (root);
  }
  /* enable "clean" shutdown by telling parent that we are done */
  (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED, NULL, 0);
  EXTRACTOR_plugin_remove_all (plugins);
#if WINDOWS
  GNUNET_free ((void*) argv);  
#endif
  return 0;
}
Beispiel #26
0
static int cell_draw( char *name,
                      char *mapset,
                      struct Colors *colors,
                      RASTER_MAP_TYPE data_type )
{
  int cellfile;
  void *xarray;
  int row;
  int ncols, nrows;
  static unsigned char *red, *grn, *blu, *set;
  int i;
  void *ptr;
  int big_endian;
  long one = 1;
  FILE *fo;

  big_endian = !( *(( char * )( &one ) ) );

  ncols = G_window_cols();
  nrows = G_window_rows();

  /* Make sure map is available */
  if (( cellfile = G_open_cell_old( name, mapset ) ) == -1 )
    G_fatal_error(( "Unable to open raster map <%s>" ), name );

  /* Allocate space for cell buffer */
  xarray = G_allocate_raster_buf( data_type );
  red = G_malloc( ncols );
  grn = G_malloc( ncols );
  blu = G_malloc( ncols );
  set = G_malloc( ncols );

  /* some buggy C libraries require BOTH setmode() and fdopen(bin) */
#ifdef WIN32
  if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 )
    G_fatal_error( "Cannot set stdout mode" );
#endif
  // Unfortunately this is not sufficient on Windows to switch stdout to binary mode
  fo = fdopen( fileno( stdout ), "wb" );

  /* loop for array rows */
  for ( row = 0; row < nrows; row++ )
  {
    G_get_raster_row( cellfile, xarray, row, data_type );
    ptr = xarray;

    G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors,
                            data_type );

    for ( i = 0; i < ncols; i++ )
    {
      unsigned char alpha = 255;
      if ( G_is_null_value( ptr, data_type ) )
      {
        alpha = 0;
      }
      ptr = G_incr_void_ptr( ptr, G_raster_size( data_type ) );


      // We need data suitable for QImage 32-bpp
      // the data are stored in QImage as QRgb which is unsigned int.
      // Because it depends on byte order of the platform we have to
      // consider byte order (well, middle endian ignored)
      if ( big_endian )
      {
        // I have never tested this
        fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] );
      }
      else
      {
        fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha );
      }
    }
  }

  G_close_cell( cellfile );
  return ( 0 );
}
Beispiel #27
0
void
__gnat_set_binary_mode (int handle)
{
  _setmode (handle, O_BINARY);
}
Beispiel #28
0
int
main(int argc, char **argv)
{
  register long address;
  char string[18];
  FILE *fp;

  progname = *argv++; --argc;

  /*
   ** -hex		hex dump
   ** -oct		Octal dump
   ** -group-by-8-bits
   ** -group-by-16-bits
   ** -group-by-32-bits
   ** -group-by-64-bits
   ** -iso		iso character set.
   ** -big-endian	Big Endian
   ** -little-endian	Little Endian
   ** -un || -de	from hexl format to binary.
   ** --		End switch list.
   ** <filename>	dump filename
   ** -		(as filename == stdin)
   */

  while (*argv && (*argv[0] == '-') && (*argv)[1])
    {
      /* A switch! */
      if (!strcmp(*argv, "--"))
	{
	  --argc; argv++;
	  break;
	}
      else if (!strcmp(*argv, "-un") || !strcmp(*argv, "-de"))
	{
	  un_flag = true;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-hex"))
	{
	  base = 16;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-iso"))
	{
	  iso_flag = true;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-oct"))
	{
	  base = 8;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-big-endian"))
	{
	  endian = true;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-little-endian"))
	{
	  endian = false;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-group-by-8-bits"))
	{
	  group_by = 0x00;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-group-by-16-bits"))
	{
	  group_by = 0x01;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-group-by-32-bits"))
	{
	  group_by = 0x03;
	  --argc; argv++;
	}
      else if (!strcmp(*argv, "-group-by-64-bits"))
	{
	  group_by = 0x07;
	  endian = false;
	  --argc; argv++;
	}
      else
	{
	  fprintf(stderr, "%s: invalid switch: \"%s\".\n", progname,
		  *argv);
	  usage();
	}
    }

  do {
    if (*argv == NULL)
      fp = stdin;
    else
      {
        char *filename = *argv++;

        if (!strcmp(filename, "-"))
          fp = stdin;
        else if ((fp = fopen(filename, "r")) == NULL)
          {
            perror(filename);
            continue;
          }
      }

    if (un_flag)
      {
        char buf[18];

#ifdef DOS_NT
# if (defined(__DJGPP__ && (__DJGPP__ >= 2)) || (defined(WINDOWSNT))
        if (!isatty(fileno(stdout)))
          setmode(fileno(stdout), O_BINARY);
# else
        (stdout)->_flag &= ~_IOTEXT; /* print binary */
        _setmode(fileno(stdout), O_BINARY);
# endif /* djgpp 2+ || WINDOWSNT */
#endif /* DOS_NT */
        for (;;)
          {
            register int i, c = 0, d;

#define hexchar(x) (isdigit(x) ? (x - '0') : (x - 'a' + 10))

            /* Skip 10 bytes: */
            if (fread(buf, 1, 10, fp) != 10)
              break;

            for (i = 0; i < 16; ++i)
              {
                if (((c = getc (fp)) == ' ') || (c == EOF))
                  break;

                d = getc(fp);
                c = (hexchar(c) * 0x10 + hexchar(d));
                putchar(c);

                if ((i & group_by) == group_by)
                  getc(fp);
              }

            if (c == ' ')
              {
                while (((c = getc(fp)) != '\n') && (c != EOF))
                  ;

                if (c == EOF)
                  break;
              }
            else
              {
                if (i < 16)
                  break;

                /* Skip 18 bytes: */
                if (fread(buf, 1, 18, fp) != 18)
                  break;
              }
          }
      }
    else
      {
#ifdef DOS_NT
# if (defined(__DJGPP__) && (__DJGPP__ >= 2)) || (defined(WINDOWSNT))
        if (!isatty(fileno(fp)))
          setmode(fileno(fp), O_BINARY);
# else
        (fp)->_flag &= ~_IOTEXT; /* read binary */
        _setmode(fileno(fp), O_BINARY);
# endif /* djgpp 2+ || WINDOWSNT */
#endif /* DOS_NT */
        address = 0;
        string[0] = ' ';
        string[17] = '\0';
        for (;;)
          {
            register int i, c = 0;

            for (i = 0; i < 16; ++i)
              {
                if ((c = getc(fp)) == EOF)
                  {
                    if (!i)
                      break;

                    fputs("  ", stdout);
                    string[i + 1] = '\0';
                  }
                else
                  {
                    if (!i)
                      printf("%08lx: ", (unsigned long)address);

                    if (iso_flag)
                      string[i + 1] =
                        (((c < 0x20) || ((c >= 0x7F) && (c < 0xa0)))
                         ? '.' : c);
                    else
                      string[i + 1] = (((c < 0x20) || (c >= 0x7F))
                                       ? '.' : c);

                    printf("%02x", (unsigned int)c);
                  }

                if ((i & group_by) == group_by)
                  putchar(' ');
              }

            if (i)
              puts(string);

            if (c == EOF)
              break;

            address += 0x10;
          }
      }

    if (fp != stdin)
      fclose(fp);
  } while (*argv != NULL);

  return EXIT_SUCCESS;
}
Beispiel #29
0
static long MS_CALLBACK file_ctrl(BIO *b, int cmd, long num, void *ptr)
{
    long ret = 1;
    FILE *fp = (FILE *)b->ptr;
    FILE **fpp;
    char p[4];

    switch (cmd) {
    case BIO_C_FILE_SEEK:
    case BIO_CTRL_RESET:
        if (b->flags & BIO_FLAGS_UPLINK)
            ret = (long)UP_fseek(b->ptr, num, 0);
        else
            ret = (long)fseek(fp, num, 0);
        break;
    case BIO_CTRL_EOF:
        if (b->flags & BIO_FLAGS_UPLINK)
            ret = (long)UP_feof(fp);
        else
            ret = (long)feof(fp);
        break;
    case BIO_C_FILE_TELL:
    case BIO_CTRL_INFO:
        if (b->flags & BIO_FLAGS_UPLINK)
            ret = UP_ftell(b->ptr);
        else
            ret = ftell(fp);
        break;
    case BIO_C_SET_FILE_PTR:
        file_free(b);
        b->shutdown = (int)num & BIO_CLOSE;
        b->ptr = ptr;
        b->init = 1;
#  if BIO_FLAGS_UPLINK!=0
#   if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES)
#    define _IOB_ENTRIES 20
#   endif
#   if defined(_IOB_ENTRIES)
        /* Safety net to catch purely internal BIO_set_fp calls */
        if ((size_t)ptr >= (size_t)stdin &&
            (size_t)ptr < (size_t)(stdin + _IOB_ENTRIES))
            BIO_clear_flags(b, BIO_FLAGS_UPLINK);
#   endif
#  endif
#  ifdef UP_fsetmod
        if (b->flags & BIO_FLAGS_UPLINK)
            UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b'));
        else
#  endif
        {
#  if defined(OPENSSL_SYS_WINDOWS)
            int fd = _fileno((FILE *)ptr);
            if (num & BIO_FP_TEXT)
                _setmode(fd, _O_TEXT);
            else
                _setmode(fd, _O_BINARY);
#  elif defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
            int fd = fileno((FILE *)ptr);
            /* Under CLib there are differences in file modes */
            if (num & BIO_FP_TEXT)
                setmode(fd, O_TEXT);
            else
                setmode(fd, O_BINARY);
#  elif defined(OPENSSL_SYS_MSDOS)
            int fd = fileno((FILE *)ptr);
            /* Set correct text/binary mode */
            if (num & BIO_FP_TEXT)
                _setmode(fd, _O_TEXT);
            /* Dangerous to set stdin/stdout to raw (unless redirected) */
            else {
                if (fd == STDIN_FILENO || fd == STDOUT_FILENO) {
                    if (isatty(fd) <= 0)
                        _setmode(fd, _O_BINARY);
                } else
                    _setmode(fd, _O_BINARY);
            }
#  elif defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
            int fd = fileno((FILE *)ptr);
            if (num & BIO_FP_TEXT)
                setmode(fd, O_TEXT);
            else
                setmode(fd, O_BINARY);
#  endif
        }
        break;
    case BIO_C_SET_FILENAME:
        file_free(b);
        b->shutdown = (int)num & BIO_CLOSE;
        if (num & BIO_FP_APPEND) {
            if (num & BIO_FP_READ)
                BUF_strlcpy(p, "a+", sizeof p);
            else
                BUF_strlcpy(p, "a", sizeof p);
        } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
            BUF_strlcpy(p, "r+", sizeof p);
        else if (num & BIO_FP_WRITE)
            BUF_strlcpy(p, "w", sizeof p);
        else if (num & BIO_FP_READ)
            BUF_strlcpy(p, "r", sizeof p);
        else {
            BIOerr(BIO_F_FILE_CTRL, BIO_R_BAD_FOPEN_MODE);
            ret = 0;
            break;
        }
#  if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
        if (!(num & BIO_FP_TEXT))
            strlcat(p, "b", sizeof(p));
        else
            strlcat(p, "t", sizeof(p));
#  endif
#  if defined(OPENSSL_SYS_NETWARE)
        if (!(num & BIO_FP_TEXT))
            strlcat(p, "b", sizeof(p));
        else
            strlcat(p, "t", sizeof(p));
#  endif
        fp = fopen(ptr, p);
        if (fp == NULL) {
            SYSerr(SYS_F_FOPEN, get_last_sys_error());
            ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
            BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
            ret = 0;
            break;
        }
        b->ptr = fp;
        b->init = 1;
        BIO_clear_flags(b, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
                                               * UPLINK */
        break;
    case BIO_C_GET_FILE_PTR:
        /* the ptr parameter is actually a FILE ** in this case. */
        if (ptr != NULL) {
            fpp = (FILE **)ptr;
            *fpp = (FILE *)b->ptr;
        }
        break;
    case BIO_CTRL_GET_CLOSE:
        ret = (long)b->shutdown;
        break;
    case BIO_CTRL_SET_CLOSE:
        b->shutdown = (int)num;
        break;
    case BIO_CTRL_FLUSH:
        if (b->flags & BIO_FLAGS_UPLINK)
            UP_fflush(b->ptr);
        else
            fflush((FILE *)b->ptr);
        break;
    case BIO_CTRL_DUP:
        ret = 1;
        break;

    case BIO_CTRL_WPENDING:
    case BIO_CTRL_PENDING:
    case BIO_CTRL_PUSH:
    case BIO_CTRL_POP:
    default:
        ret = 0;
        break;
    }
    return (ret);
}
Beispiel #30
0
int main(int iArgC, char *cArgV[])
{
#ifdef __GLIBCXX__
	// Set a better exception handler
	std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
#endif

#ifdef WIN32
	// Change stdout to be binary, so writing \x0A does not get changed to \x0D\x0A
	_setmode(0, _O_BINARY);
	_setmode(1, _O_BINARY);
	_setmode(2, _O_BINARY);
#endif

	// Disable stdin/printf/etc. sync for a speed boost
	std::ios_base::sync_with_stdio(false);

	// Declare the supported options.
	po::options_description poOptions("Options");
	poOptions.add_options()
		("apply,a",
			"apply the filter instead (compress/encrypt the input data) rather than "
			"the default of reversing the filter (to decompress/decrypt)")
		("list,l",
			"list all filters")
		("type,t", po::value<std::string>(),
			"specify the filter type")
	;

	po::options_description poHidden("Hidden parameters");
	poHidden.add_options()
		("help", "produce help message")
	;

	po::options_description poVisible("");
	poVisible.add(poOptions);

	po::options_description poComplete("Parameters");
	poComplete.add(poOptions).add(poHidden);
	po::variables_map mpArgs;

	auto pstdout = stream::open_stdout();
	ga::FilterManager::handler_t pFilterType;
	bool bApply = false;   // default is to reverse the algorithm (decompress)
	try {
		po::parsed_options pa = po::parse_command_line(iArgC, cArgV, poComplete);

		// Parse the global command line options
		for (std::vector<po::option>::iterator i = pa.options.begin(); i != pa.options.end(); i++) {
			if (i->string_key.empty()) {
				std::cerr << "Error: unexpected extra parameter (you can't list "
					"filenames on the command line, you must redirect stdin/out)"
					<< std::endl;
				return RET_BADARGS;
			} else if (i->string_key.compare("help") == 0) {
				std::cout <<
					"Copyright (C) 2010-2015 Adam Nielsen <*****@*****.**>\n"
					"This program comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
					"and you are welcome to change and redistribute it under certain conditions;\n"
					"see <http://www.gnu.org/licenses/> for details.\n"
					"\n"
					"Utility to apply and reverse compression and encryption algorithms used by\n"
					"games on their data files.\n"
					"Build date " __DATE__ " " __TIME__ << "\n"
					"\n"
					"Usage: gamecomp -t <type> < infile > outfile\n" << poVisible << "\n"
					<< std::endl;
				return RET_OK;
			} else if (
				(i->string_key.compare("t") == 0) ||
				(i->string_key.compare("type") == 0)
			) {
				if (i->value.size() == 0) {
					std::cerr << PROGNAME ": --type (-t) requires a parameter."
						<< std::endl;
					return RET_BADARGS;
				}
				pFilterType = ga::FilterManager::byCode(i->value[0]);
				if (!pFilterType) {
					std::cerr << PROGNAME ": Unknown filter code given by --type (-t) - "
						"use -l for a list." << std::endl;
					return RET_BADARGS;
				}
			} else if (
				(i->string_key.compare("a") == 0) ||
				(i->string_key.compare("apply") == 0)
			) {
				bApply = true;
			} else if (
				(i->string_key.compare("l") == 0) ||
				(i->string_key.compare("list") == 0)
			) {
				for (const auto& i : ga::FilterManager::formats()) {
					std::cout << i->code() << "\n";
				}
				std::cout << std::flush;
				return RET_OK;
			}
		}

		if (!pFilterType) {
			std::cerr << PROGNAME ": No filter type given (--type/-t).  Use -l for "
				"a list." << std::endl;
			return RET_BADARGS;
		}

		if (bApply) {
			// Apply the filter
			pstdout = pFilterType->apply(
				std::move(pstdout),
				camoto::stream::fn_notify_prefiltered_size()
			);

			// Copy filtered data to stdout
			stream::copy(*pstdout, *stream::open_stdin());

		} else {
			// Apply the filter
			auto in = pFilterType->apply(stream::open_stdin());

			// Copy filtered data to stdout
			stream::copy(*pstdout, *in);
		}
		pstdout->flush();

	} catch (const camoto::filter_error& e) {
		pstdout->flush(); // keep as much data as we could process
		std::cerr << PROGNAME ": Filtering failed.  " << e.what() << std::endl;
		return RET_SHOWSTOPPER;
	} catch (const stream::error& e) {
		std::cerr << PROGNAME ": I/O error - " << e.what() << std::endl;
		return RET_SHOWSTOPPER;
	} catch (const po::unknown_option& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< ".  Use --help for help." << std::endl;
		return RET_BADARGS;
	} catch (const po::invalid_command_line_syntax& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< ".  Use --help for help." << std::endl;
		return RET_BADARGS;
	}

	return RET_OK;
}