Example #1
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;
}
Example #2
0
void cgiInit()
{
	_setmode( _fileno( stdin ), _O_BINARY );
	_setmode( _fileno( stdout ), _O_BINARY );
}
Example #3
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;
}
Example #4
0
nfsstat3 CNFS3Prog::ProcedureSETATTR(void)
{
    char *path;
    sattr3 new_attributes;
    sattrguard3 guard;
    wcc_data obj_wcc;
    nfsstat3 stat;
    int nMode;
    FILE *pFile;
    HANDLE hFile;
    FILETIME fileTime;
    SYSTEMTIME systemTime;

    PrintLog("SETATTR");
    path = GetPath();
    Read(&new_attributes);
    Read(&guard);
    stat = CheckFile(path);
    obj_wcc.before.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.before.attributes);

    if (stat == NFS3_OK) {
        if (new_attributes.mode.set_it) {
            nMode = 0;

            if ((new_attributes.mode.mode & 0x100) != 0) {
                nMode |= S_IREAD;
            }

            // Always set read and write permissions (deliberately implemented this way)
            // if ((new_attributes.mode.mode & 0x80) != 0) {
            nMode |= S_IWRITE;
            // }

            // S_IEXEC is not availabile on windows
            // if ((new_attributes.mode.mode & 0x40) != 0) {
            //     nMode |= S_IEXEC;
            // }

            if (_chmod(path, nMode) != 0) {
                stat = NFS3ERR_INVAL;
            } else {

            }
        }   

        // deliberately not implemented because we cannot reflect uid/gid on windows (easliy)
        if (new_attributes.uid.set_it){}
        if (new_attributes.gid.set_it){}

        // deliberately not implemented
        if (new_attributes.mtime.set_it == SET_TO_CLIENT_TIME){}
        if (new_attributes.atime.set_it == SET_TO_CLIENT_TIME){}

        if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME || new_attributes.atime.set_it == SET_TO_SERVER_TIME){
            hFile = CreateFile(path, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
            if (hFile != INVALID_HANDLE_VALUE) {
                GetSystemTime(&systemTime);
                SystemTimeToFileTime(&systemTime, &fileTime);
                if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, NULL, &fileTime);
                }
                if (new_attributes.atime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, &fileTime, NULL);
                }
            }
            CloseHandle(hFile);
        }

        if (new_attributes.size.set_it){
            pFile = _fsopen(path, "r+b", _SH_DENYWR);
            int filedes = _fileno(pFile);
            _chsize_s(filedes, new_attributes.size.size);
            fclose(pFile);
        }
    }

    obj_wcc.after.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.after.attributes);

    Write(&stat);
    Write(&obj_wcc);

    return stat;
}
Example #5
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);
}
Example #6
0
void
    DumpFileToLog(
    char* path
    )
{
    FILE* fp;
    char buf[BUFFER_SIZE];
    char* p;

    fp = fopen_unsafe(path, "r");
    if (fp == NULL) {
        LogError("ERROR: DumpFileToLog couldn't open file '%s' with error '%s'", path, strerror_unsafe(errno));
    }
    else {
        int fd = _fileno(fp);
        struct _stat64 fileStats;
        if (fd != -1 && _fstat64(fd, &fileStats) != -1)
        {
            char creationTime[256];
            char accessTime[256];
            char currTime[256];
            __time64_t now = _time64(NULL);
            _ctime64_s(currTime, &now);
            _ctime64_s(creationTime, &fileStats.st_ctime);
            _ctime64_s(accessTime, &fileStats.st_atime);
            auto stripNewline = [](char *buf) {
                if (char *ptr = strchr(buf, '\n'))
                    *ptr = '\0';
            };
            stripNewline(creationTime);
            stripNewline(accessTime);
            stripNewline(currTime);

            LogOut("ERROR: name of output file: %s; size: %I64d; creation: %s, last access: %s, now: %s", path, fileStats.st_size, creationTime, accessTime, currTime);
        }
        if (!FNoProgramOutput)
        {
            bool printlines = !FOnlyAssertOutput;
            if (printlines)
            {
                LogOut("ERROR: bad output file follows ============");
            }
            while (fgets(buf, BUFFER_SIZE, fp) != NULL) {
                // Strip the newline, since LogOut adds one
                p = strchr(buf, '\n');
                if (p != NULL) {
                    *p = '\0';
                }
                if (!printlines && strlen(buf) > 8 && buf[0] == 'A' && buf[1] == 'S' && buf[2] == 'S' && buf[3] == 'E' && buf[4] == 'R' && buf[5] == 'T')
                {
                    printlines = true;
                    LogOut("ERROR: bad output file follows ============");
                }
                if (printlines)
                {
                    LogOut("%s", buf);
                }
            }
            if (printlines)
            {
                LogOut("ERROR: end of bad output file  ============");
            }
        }
        fclose(fp);
    }
}
Example #7
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];
    int st;

    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
        /* Safety net to catch purely internal BIO_set_fp calls */
#   if defined(_MSC_VER) && _MSC_VER>=1900
        if (ptr == stdin || ptr == stdout || ptr == stderr)
            BIO_clear_flags(b, BIO_FLAGS_UPLINK);
#   elif defined(_IOB_ENTRIES)
        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))
            strcat(p, "b");
        else
            strcat(p, "t");
#  endif
#  if defined(OPENSSL_SYS_NETWARE)
        if (!(num & BIO_FP_TEXT))
            strcat(p, "b");
        else
            strcat(p, "t");
#  endif
        fp = file_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:
        st = b->flags & BIO_FLAGS_UPLINK
                ? UP_fflush(b->ptr) : fflush((FILE *)b->ptr);
        if (st == EOF) {
            SYSerr(SYS_F_FFLUSH, get_last_sys_error());
            ERR_add_error_data(1, "fflush()");
            BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
            ret = 0;
        }
        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);
}
Example #8
0
/** LoadFile
DESCRIPTION		Read file into buffer in file structure
PARAM[IN]		  LPTSTR pFileName - name of file to open
PARAM[IN/OUT]	FILESTRUCT * pFS - pointer to file structure
RETURNS			  error_t error - error code
*/
error_t LoadFile(LPTSTR pFileName, FILESTRUCT * pFS)
{
  FILE * file = NULL;
  LPTSTR pBuffer;
  LPTSTR * ppString;
  int * pStrLen;
  int nFileSize, nStrNum, nMaxStrLen;
  int i, iStr;
  struct stat stFileStat;

#ifdef _MSC_VER
  fopen_s(&file, pFileName, "rb");
#else
  file = fopen(pFileName, "rb");
#endif
  if (file == NULL)
    return ERR_OPEN_FILE;

  // find out size of file
  fstat(_fileno(file), &stFileStat);
  nFileSize = stFileStat.st_size;

  // allocate memory for the text in file and read the text
  pBuffer = (LPTSTR)calloc(nFileSize, sizeof(TCHAR));
  if (pBuffer == NULL)
    return ERR_MEMORY_ALLOCATION;
  fread(pBuffer, sizeof(TCHAR), nFileSize, file);

  // calculate number of strings
  nStrNum = 1;
  for (i = 0; i < nFileSize; ++i)
    if (pBuffer[i] == '\n')
      nStrNum++;

  // allocate memory for array of strings and array of string lengths
  ppString = (LPTSTR*)calloc(nStrNum, sizeof(LPTSTR));
  if (ppString == NULL)
  {
    free(pBuffer);
    return ERR_MEMORY_ALLOCATION;
  }
  pStrLen = (int*)calloc(nStrNum, sizeof(int));
  if (pStrLen == NULL)
  {
    free(pBuffer);
    free(pStrLen);
    return ERR_MEMORY_ALLOCATION;
  }

  // fill array of strings and array of string lengths
  iStr = 0;
  nMaxStrLen = 0;
  ppString[0] = pBuffer;
  for (i = 0; i < nFileSize; ++i)
  {
    assert(iStr <= nStrNum);
    if (pBuffer[i] == '\n')
    {
      assert(iStr < nStrNum);
      pStrLen[iStr] = pBuffer + i - ppString[iStr];
      if (pStrLen[iStr] > nMaxStrLen)
        nMaxStrLen = pStrLen[iStr];
      ++iStr;
      if (iStr < nStrNum)
        ppString[iStr] = pBuffer + i + 1;
    }
  }
  pStrLen[nStrNum - 1] = pBuffer + nFileSize - ppString[nStrNum - 1];
  if (pStrLen[nStrNum - 1] > nMaxStrLen)
    nMaxStrLen = pStrLen[nStrNum - 1];

  // fill the file structure
  pFS->pBuffer    = pBuffer;
  pFS->ppString   = ppString;
  pFS->pStrLen    = pStrLen;
  pFS->nMaxStrLen = nMaxStrLen;
  pFS->nStrNum    = nStrNum;
  pFS->nFileSize  = nFileSize;
  pFS->nCaretPosX = pFS->nCaretPosY = 0;
  pFS->iCaretStr  = pFS->iCaretChar = 0;
  SetCaretPos(0, 0);
  fclose(file);
  return NO_ERR;
}
Example #9
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;
}
Example #10
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);
}
Example #11
0
int
main(int argc, char *argv[])
{
  NiceAgent *agent;
  gchar *stun_addr = NULL;
  guint stun_port = 0;
  gboolean controlling;

  // Parse arguments
  if (argc > 4 || argc < 2 || argv[1][1] != '\0') {
    fprintf(stderr, "Usage: %s 0|1 stun_addr [stun_port]\n", argv[0]);
    return EXIT_FAILURE;
  }
  controlling = argv[1][0] - '0';
  if (controlling != 0 && controlling != 1) {
    fprintf(stderr, "Usage: %s 0|1 stun_addr [stun_port]\n", argv[0]);
    return EXIT_FAILURE;
  }

  if (argc > 2) {
    stun_addr = argv[2];
    if (argc > 3)
      stun_port = atoi(argv[3]);
    else
      stun_port = 3478;

    g_debug("Using stun server '[%s]:%u'\n", stun_addr, stun_port);
  }

#if GLIB_CHECK_VERSION(2, 36, 0)
  g_networking_init();
#else
  g_type_init();
#endif

  gloop = g_main_loop_new(NULL, FALSE);
#ifdef G_OS_WIN32
  io_stdin = g_io_channel_win32_new_fd(_fileno(stdin));
#else
  io_stdin = g_io_channel_unix_new(fileno(stdin));
#endif

  // Create the nice agent
  agent = nice_agent_new(g_main_loop_get_context (gloop),
      NICE_COMPATIBILITY_RFC5245);
  if (agent == NULL)
    g_error("Failed to create agent");

  // Set the STUN settings and controlling mode
  if (stun_addr) {
    g_object_set(agent, "stun-server", stun_addr, NULL);
    g_object_set(agent, "stun-server-port", stun_port, NULL);
  }
  g_object_set(agent, "controlling-mode", controlling, NULL);

  // Connect to the signals
  g_signal_connect(agent, "candidate-gathering-done",
      G_CALLBACK(cb_candidate_gathering_done), NULL);
  g_signal_connect(agent, "new-selected-pair",
      G_CALLBACK(cb_new_selected_pair), NULL);
  g_signal_connect(agent, "component-state-changed",
      G_CALLBACK(cb_component_state_changed), NULL);

  // Create a new stream with one component
  stream_id = nice_agent_add_stream(agent, 1);
  if (stream_id == 0)
    g_error("Failed to add stream");

  // Attach to the component to receive the data
  // Without this call, candidates cannot be gathered
  nice_agent_attach_recv(agent, stream_id, 1,
      g_main_loop_get_context (gloop), cb_nice_recv, NULL);

  // Start gathering local candidates
  if (!nice_agent_gather_candidates(agent, stream_id))
    g_error("Failed to start candidate gathering");

  g_debug("waiting for candidate-gathering-done signal...");

  // Run the mainloop. Everything else will happen asynchronously
  // when the candidates are done gathering.
  g_main_loop_run (gloop);

  g_main_loop_unref(gloop);
  g_object_unref(agent);
  g_io_channel_unref (io_stdin);

  return EXIT_SUCCESS;
}
Example #12
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);
}
Example #13
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);
}
Example #14
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;
}
Example #15
0
static bool fixupDump( const char* _dumpPath, ULONG32 _timeStamp, const IMAGE_OPTIONAL_HEADER* _header, const char* _executablePath )
{
	FILE* fp = fopen(_dumpPath, "rb");
	if (!fp)
		return false;

	const long fileSize = _filelength(_fileno(fp));
	char* data = new char[fileSize];
	fread(data, fileSize, 1, fp);
	fclose(fp);

	MINIDUMP_HEADER* header = (MINIDUMP_HEADER*)data;
	header->CheckSum = 0;
	if (header->Signature != MINIDUMP_SIGNATURE)
	{
		delete[] data;
		return false;
	}


	MINIDUMP_DIRECTORY* directory = (MINIDUMP_DIRECTORY*)(data + header->StreamDirectoryRva);
	for (int ii = 0; ii < (int)header->NumberOfStreams; ++ii)
	{
		if (directory[ii].StreamType == ModuleListStream)
		{
			MINIDUMP_MODULE_LIST* moduleList = (MINIDUMP_MODULE_LIST*)(data + directory[ii].Location.Rva);

			for (int jj = 0; jj < (int)moduleList->NumberOfModules; ++jj)
			{
				MINIDUMP_MODULE* module = &moduleList->Modules[jj];
				MINIDUMP_STRING* moduleFilename =
					(MINIDUMP_STRING*)(data + module->ModuleNameRva);

				if (filenamesMatch(moduleFilename->Buffer, _executablePath))
				{
					module->ModuleNameRva = fileSize;
					module->CheckSum = _header->CheckSum;
					module->SizeOfImage = _header->SizeOfImage;
					module->TimeDateStamp = _timeStamp;
				}
			}
		}
	}

	fp = fopen(_dumpPath, "wb");
	if (!fp)
	{
		delete[] data;
		return false;
	}

	fwrite(data, fileSize, 1, fp);

	wchar_t fullPath[MAX_PATH];
	GetCurrentDirectoryW(MAX_PATH, fullPath);
	wcscat(fullPath, L"\\");
	ULONG32 newSize = strlen(_executablePath) * sizeof(wchar_t) + wcslen(fullPath);
	fwrite(&newSize, sizeof(newSize), 1, fp);
	fwprintf(fp, L"%s%S", fullPath, _executablePath);
	fputc(0, fp);
	fclose(fp);

	delete[] data;
	return true;
}
Example #16
0
// Redirects stdout/stderr to the provided handle.
// Example:
// If the handleToRedirecTo = 0x24
// Before:
// _fileno(stdout) = 1
// GetStdHandle(STD_OUTPUT_HANDLE) = 0x20
// After:
// _fileno(stdout) = 3
// GetStdHandle(STD_OUTPUT_HANDLE) = 0x28 <- Duplicated from 0x24
HRESULT
StdWrapper::StartRedirection()
{
    HANDLE stdHandle;

    // In IIS, stdout and stderr are set to null as w3wp is created with DETACHED_PROCESS,
    // so fileno(m_stdStream) returns -2.
    // Open a null file such that undoing the redirection succeeds and _dup2 works.
    // m_previousFileDescriptor will be used for restoring stdout/stderr
    if (_fileno(m_stdStream) == -2)
    {
        freopen_s((FILE**)&m_stdStream, "nul", "w", m_stdStream);
        m_previousFileDescriptor = _dup(_fileno(m_stdStream));
    }
    else
    {
        m_previousFileDescriptor = _dup(_fileno(m_stdStream));
    }

    if (!m_enableNativeRedirection)
    {
        RETURN_LAST_ERROR_IF(!SetStdHandle(m_stdHandleNumber, m_handleToRedirectTo));

        return S_OK;
    }
    // After setting the std handle, we need to set stdout/stderr to the current
    // output/error handle.

    // Duplicate the handle before opening the handle and associating a file pointer.
    // If we don't by calling close on the file, the same handle value will be closed
    // multiple times.
    // Note, by calling duplicate handle, the new handle returned will have a different value
    // than the original, but point to the same underlying file object.
    RETURN_LAST_ERROR_IF(!DuplicateHandle(
        /* hSourceProcessHandle*/ GetCurrentProcess(),
        /* hSourceHandle */ m_handleToRedirectTo,
        /* hTargetProcessHandle */ GetCurrentProcess(),
        /* lpTargetHandle */&stdHandle,
        /* dwDesiredAccess */ 0, // dwDesired is ignored if DUPLICATE_SAME_ACCESS is specified
        /* bInheritHandle */ TRUE,
        /* dwOptions  */ DUPLICATE_SAME_ACCESS));

    RETURN_LAST_ERROR_IF(!SetStdHandle(m_stdHandleNumber, stdHandle));

    // _open_osfhandle will associate a filedescriptor with the handle.
    const auto fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(stdHandle), _O_WTEXT | _O_TEXT);

    if (fileDescriptor == -1)
    {
        RETURN_HR(HRESULT_FROM_WIN32(ERROR_FILE_INVALID));
    }

    m_redirectedFile = _fdopen(fileDescriptor, "w");

    if (m_redirectedFile == nullptr)
    {
        RETURN_HR(HRESULT_FROM_WIN32(ERROR_FILE_INVALID));
    }

    // Set stdout/stderr to the newly created file.
    const auto dup2Result = _dup2(_fileno(m_redirectedFile), _fileno(m_stdStream));

    if (dup2Result != 0)
    {
        RETURN_HR(HRESULT_FROM_WIN32(ERROR_FILE_INVALID));
    }

    // Removes buffering from the output
    if (setvbuf(m_stdStream, nullptr, _IONBF, 0) != 0)
    {
        RETURN_HR(HRESULT_FROM_WIN32(ERROR_FILE_INVALID));
    }

    return S_OK;
}
Example #17
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 );
}
Example #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;
}
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");
        }
    }
}
Example #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;
}
Example #21
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 );
}
Example #22
0
/* SMTP: mail */
static int smtpMail(int sfd,char *to,char *cc,char *bcc,char *from,char *rrr,char *rt,
                    char *subject,char *attach_file,char *msg_body_file,
                    char *the_msg,int is_mime,int add_dateh)
{
    char
        *os="Unix",
        boundary[17],
        related[17],
        alternative[17],
        mbuf[1024];

    int
        newline_before;

    Sll
        *oneline_attachment_list,
        *attachment_list,
        *embed_image_list;

#ifdef WINNT
    os="Windows";
#else
    os="Unix";
#endif /* WINNT */

    memset(boundary, 0, sizeof(boundary));
    memset(related, 0, sizeof(related));
    memset(alternative, 0, sizeof(alternative));

    attachment_list=get_attachment_list();
    embed_image_list = get_embed_image_attachment_list();
    oneline_attachment_list = get_oneline_attachment_list();
    if (attachment_list || embed_image_list || oneline_attachment_list)
    {
        is_mime=1;
    }

    if (subject)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"Subject: %s\r\n",subject);

        msock_puts(buf);

        showVerbose(buf);
    }

    /* headers */
    if (from)
    {
        memset(buf,0,sizeof(buf));
        if (*g_from_name != '\0')
        {
            /* Name in From: */

            memset(buf,0,sizeof(buf));
            (void) snprintf(buf,sizeof(buf)-1,"From: %s <%s>\r\n",
                            g_from_name,from);
        }
        else
        {
            (void) snprintf(buf,sizeof(buf)-1,"From: %s\r\n",from);
        }
        msock_puts(buf);

        showVerbose(buf);
    }

    if (add_dateh)
    {
        /* add Date: header */
        char
            datebuf[65];

        memset(datebuf,0,sizeof(datebuf));
        if (rfc822_date(time(NULL),datebuf,sizeof(datebuf)-1) == 0)
        {
            memset(buf,0,sizeof(buf));
            (void) snprintf(buf,sizeof(buf)-1,"Date: %s\r\n",datebuf);
            msock_puts(buf);

            showVerbose(buf);
        }
    }
    
    if (to)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"To: %s\r\n",to);
        msock_puts(buf);

        showVerbose(buf);

    }

    if (cc)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"Cc: %s\r\n",cc);
        msock_puts(buf);
        showVerbose(buf);
    }

    /*
    if (bcc)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"Bcc: %s\r\n",bcc);
        msock_puts(buf);

        showVerbose(buf);
    }
    */

    if (rt != NULL)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"Reply-To: %s\r\n",rt);
        msock_puts(buf);
        showVerbose(buf);

    }
    if (rrr != NULL)
    {
        memset(buf,0,sizeof(buf));
        (void) snprintf(buf,sizeof(buf)-1,"Disposition-Notification-To: %s\r\n",rrr);
        msock_puts(buf);
        showVerbose(buf);
    }

    /* add custom headers if any. No verification is done */
    {
        Sll 
            *l,
            *custom_header_list;
        custom_header_list = get_custom_header_list();
        if (custom_header_list)
        {
            for (l = custom_header_list; l; l = l->next)
            {
                if (l->data)
                {
                    msock_puts((char *) l->data);
                    msock_puts("\r\n");
                    showVerbose((char *) l->data);
                    showVerbose("\r\n");
                }
            }
        }
    }


    memset(buf,0,sizeof(buf));
    (void) snprintf(buf,sizeof(buf)-1,"X-Mailer: %s (%s)\r\n",MAILSEND_VERSION,os);
    msock_puts(buf);
    showVerbose(buf);

    memset(buf,0,sizeof(buf));
    (void) snprintf(buf,sizeof(buf)-1,"X-Copyright: %s\r\n",NO_SPAM_STATEMENT);
    msock_puts(buf);
    showVerbose(buf);

    if (is_mime)
    {
        int
            rc;
        srand(time(NULL));
        memset(boundary,0,sizeof(boundary));
        mutilsGenerateMIMEBoundary(boundary,sizeof(boundary));

        /* if msg body file is specified, include and return */
        if (msg_body_file)
        {
            return (include_msg_body());
        }

        rc = print_content_type_header(boundary);
        RETURN_IF_NOT_ZERO(rc);

        rc = process_oneline_messages(boundary);
        RETURN_IF_NOT_ZERO(rc);

        rc = process_embeded_images(boundary);
        RETURN_IF_NOT_ZERO(rc);

        rc = process_attachments(boundary);
        RETURN_IF_NOT_ZERO(rc);

        /*
        ** if there were other kind of MIME types but no attachments,
        ** we have to print the last boundary 
        */
        print_end_boundary(boundary);

        /* handle MIME attachments ends */
        goto done;
    } /* is_mime */

    /* mail body */
    if (attach_file == NULL && the_msg == NULL) /* read from stdin */
    {

        /* if stdin is a terminal, print the instruction */
        if (isInConsole(_fileno(stdin)))
        {
            (void) printf("=========================================================================\n");
            (void) printf("Type . in a new line and press Enter to end the message, CTRL+C to abort\n");
            (void) printf("=========================================================================\n");
        }

#ifdef WINNT
        SetConsoleCtrlHandler(CntrlHandler,TRUE);
#endif /* WINNT */

        newline_before=1;
        msock_puts("\r\n"); /* RFC822 sec 3.1 */
        showVerbose("\r\n");
        while (fgets(mbuf,sizeof(mbuf)-1,stdin) && (break_out == 0))
        {
            if (newline_before && *mbuf == '.')
            {
                break;
            }
            else
            {
                int
                    len;
                /* vinicio qmail fix */
                len=strlen(mbuf);
                if (mbuf[len-1] != '\n')
                    strcat(mbuf,"\r\n");
                else
                {
                   mbuf[--len]='\0';
                   strcat(mbuf,"\r\n");
                }
                /* vinicio qmail fix */
                msock_puts(mbuf);
                showVerbose("[C] %s",mbuf);
            }
            newline_before=(*mbuf != '\0' && mbuf[strlen(mbuf)-1] == '\n');
            if (break_out == 1)
            {
                (void) fprintf(stderr," Breaking out\n");
                return (0);
            }
        }
    }
done:

    return (0);
}
Example #23
0
CTipDlg::CTipDlg(CWnd* pParent /*=NULL*/)
	: CDialog(IDD_TIP, pParent)
{
char fullfilename[MAX_PATH];
char filename [MAX_PATH];
char * p;

  // look for tips.txt in the same directory as the executable file
  if (GetModuleFileName (NULL, fullfilename, sizeof (fullfilename)))
   {

// remove last part of file name to get working directory

    strcpy (filename, fullfilename);

    p = strrchr (filename, '\\');
    if (p)
      *p = 0;

    strcat (filename, "\\tips.txt");
    }
  else
    strcpy (filename, "tips.txt");

	//{{AFX_DATA_INIT(CTipDlg)
	m_bStartup = TRUE;
	//}}AFX_DATA_INIT

	// We need to find out what the startup and file position parameters are
	// If startup does not exist, we assume that the Tips on startup is checked TRUE.
	CWinApp* pApp = AfxGetApp();
	m_bStartup = !App.db_get_int("control", szIntStartup, 0);
	UINT iFilePos = App.db_get_int("control", szIntFilePos, 0);

	// Now try to open the tips file
	m_pStream = fopen(filename, "r");
	if (m_pStream == NULL) 
	{
		m_strTip.LoadString(CG_IDS_FILE_ABSENT);
		return;
	} 

	// If the timestamp in the INI file is different from the timestamp of
	// the tips file, then we know that the tips file has been modified
	// Reset the file position to 0 and write the latest timestamp to the
	// ini file
	struct _stat buf;
	_fstat(_fileno(m_pStream), &buf);
	CString strCurrentTime = ctime(&buf.st_ctime);
	strCurrentTime.TrimRight();
	CString strStoredTime = 
		App.db_get_string("control", szTimeStamp, "");
	if (strCurrentTime != strStoredTime) 
	{
		iFilePos = 0;
		App.db_write_string("control", szTimeStamp, strCurrentTime);
	}

	if (fseek(m_pStream, iFilePos, SEEK_SET) != 0) 
	{
		AfxMessageBox(CG_IDP_FILE_CORRUPT);
	}
	else 
	{
		GetNextTipString(m_strTip);
	}
}
Example #24
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;
}
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);
}
Example #26
0
void
kpathsea_set_program_name (kpathsea kpse,  const_string argv0,
                           const_string progname)
{
  string ext, sdir, sdir_parent, sdir_grandparent;
  string s = getenv ("KPATHSEA_DEBUG");
#ifdef WIN32
  string debug_output = getenv("KPATHSEA_DEBUG_OUTPUT");
  string append_debug_output = getenv("KPATHSEA_DEBUG_APPEND");
  int err, olderr;
#endif

  /* Set debugging stuff first, in case we end up doing debuggable stuff
     during this initialization.  */
  if (s) {
    kpse->debug |= atoi (s);
  }

#if defined(WIN32)
  /* Set various info about user. Among many things,
     ensure that HOME is set.  */
  init_user_info();

  /* redirect stderr to debug_output. Easier to send logfiles. */
  if (debug_output) {
    int flags =  _O_CREAT | _O_TRUNC | _O_RDWR;
    err = -1;
    if (_stricmp(debug_output, "con") == 0
       || _stricmp(debug_output, "con:") == 0) {
      err = _fileno(stdout);
    } else {
      if (append_debug_output) {
        flags =  _O_CREAT | _O_APPEND | _O_WRONLY;
      } else {
        flags =  _O_CREAT | _O_TRUNC | _O_WRONLY;
        kpathsea_xputenv(kpse, "KPATHSEA_DEBUG_APPEND", "yes");
      }
    }

    if ((err < 0)
        && (err = _open(debug_output, flags, _S_IREAD | _S_IWRITE)) == -1)
    {
      WARNING1("Can't open %s for stderr redirection!\n", debug_output);
      perror(debug_output);
    } else if ((olderr = _dup(fileno(stderr))) == -1) {
      WARNING("Can't dup() stderr!\n");
      close(err);
    } else if (_dup2(err, fileno(stderr)) == -1) {
      WARNING1("Can't redirect stderr to %s!\n", debug_output);
      close(olderr);
      close(err);
    } else {
      close(err);
    }
  }
  /* Win95 always gives the short filename for argv0, not the long one.
     There is only this way to catch it. It makes all the kpse_selfdir
     stuff useless for win32. */
  {
    char short_path[PATH_MAX], path[PATH_MAX], *fp;

    /* SearchPath() always gives back an absolute directory */
    if (SearchPath(NULL, argv0, ".exe", PATH_MAX, short_path, &fp) == 0)
        LIB_FATAL1("Can't determine where the executable %s is.\n", argv0);
    if (!win32_get_long_filename(short_path, path, sizeof(path))) {
        LIB_FATAL1("This path points to an invalid file : %s\n", short_path);
    }
    /* slashify the dirname */
    for (fp = path; fp && *fp; fp++)
        if (IS_DIR_SEP(*fp)) *fp = DIR_SEP;
    /* sdir will be the directory of the executable, ie: c:/TeX/bin */
    sdir = xdirname(path);
    kpse->invocation_name = xstrdup(xbasename(path));
  }

#elif defined(__DJGPP__)

  /* DJGPP programs support long filenames on Windows 95, but ARGV0 there
     is always made with the short 8+3 aliases of all the pathname elements.
     If long names are supported, we need to convert that to a long name.

     All we really need is to call `_truename', but most of the code
     below is required to deal with the special case of networked drives.  */
  if (pathconf (argv0, _PC_NAME_MAX) > 12) {
    char long_progname[PATH_MAX];

    if (_truename (argv0, long_progname)) {
      char *fp;

      if (long_progname[1] != ':') {
        /* A complication: `_truename' returns network-specific string at
           the beginning of `long_progname' when the program resides on a
           networked drive, and DOS calls cannot grok such pathnames.  We
           need to convert the filesystem name back to a drive letter.  */
        char rootname[PATH_MAX], rootdir[4];

        if (argv0[0] && argv0[1] == ':')
          rootdir[0] = argv0[0]; /* explicit drive in `argv0' */
        else
          rootdir[0] = getdisk () + 'A';
        rootdir[1] = ':';
        rootdir[2] = '\\';
        rootdir[3] = '\0';
        if (_truename (rootdir, rootname)) {
          /* Find out where `rootname' ends in `long_progname' and replace
             it with the drive letter.  */
          int root_len = strlen (rootname);

          if (IS_DIR_SEP (rootname[root_len - 1]))
            root_len--; /* keep the trailing slash */
          long_progname[0] = rootdir[0];
          long_progname[1] = ':';
          memmove (long_progname + 2, long_progname + root_len,
                   strlen (long_progname + root_len) + 1);
        }
      }

      /* Convert everything to canonical form.  */
      if (long_progname[0] >= 'A' && long_progname[0] <= 'Z')
        long_progname[0] += 'a' - 'A'; /* make drive lower case, for beauty */
      for (fp = long_progname; *fp; fp++)
        if (IS_DIR_SEP (*fp))
          *fp = DIR_SEP;

      kpse->invocation_name = xstrdup (long_progname);
    }
    else
      /* If `_truename' failed, God help them, because we won't...  */
      kpse->invocation_name = xstrdup (argv0);
  }
  else
    kpse->invocation_name = xstrdup (argv0);

#else /* !WIN32 && !__DJGPP__ */
  kpse->invocation_name = xstrdup (argv0);
#endif

  /* We need to find SELFAUTOLOC *before* removing the ".exe" suffix from
     the program_name, otherwise the PATH search inside kpse_selfdir will fail,
     since `prog' doesn't exists as a file, there's `prog.exe' instead.  */
#ifndef WIN32
  sdir = kpathsea_selfdir (kpse, kpse->invocation_name);
#endif
  /* SELFAUTODIR is actually the parent of the invocation directory,
     and SELFAUTOPARENT the grandparent.  This is how teTeX did it.  */
  kpathsea_xputenv (kpse, "SELFAUTOLOC", sdir);
  sdir_parent = xdirname (sdir);
  kpathsea_xputenv (kpse, "SELFAUTODIR", sdir_parent);
  sdir_grandparent = xdirname (sdir_parent);
  kpathsea_xputenv (kpse, "SELFAUTOPARENT", sdir_grandparent);

#if defined(WIN32) || defined(__MINGW32__) || defined(__CYGWIN__)
  mk_suffixlist(kpse);
#endif /* WIN32 || __MINGW32__ || __CYGWIN__ */

  free (sdir);
  free (sdir_parent);
  free (sdir_grandparent);

  kpse->invocation_short_name
    = xstrdup (xbasename (kpse->invocation_name));

  if (progname) {
    kpse->program_name = xstrdup (progname);
  } else {
    /* If configured --enable-shared and running from the build directory
       with the wrapper scripts (e.g., for make check), the binaries will
       be named foo.exe instead of foo.  Or possibly if we're running on a
       DOSISH system.  */
    ext = find_suffix (kpse->invocation_short_name);
    if (ext && FILESTRCASEEQ (ext, "exe")) {
      kpse->program_name = remove_suffix (kpse->invocation_short_name);
    } else {
      kpse->program_name = xstrdup (kpse->invocation_short_name);
    }
  }

  /* Some of the utility routines (like atou() and xfopen()) will use
     FATAL and variations thereof (see lib.h) if there is a problem.

     The next trick makes it possible for that message to report some useful
     name instead of (NULL), if the backward compatible is compiled in. */

#if defined (KPSE_COMPAT_API)
  if (kpse!=kpse_def) {
    kpse_def->invocation_name = xstrdup(kpse->invocation_name);
    kpse_def->invocation_short_name = xstrdup(kpse->invocation_short_name);
  }
#endif

  kpathsea_xputenv (kpse, "progname", kpse->program_name);
}
Example #27
0
int _tmain(int argc, _TCHAR* argv[])
{
	// コンソール出力か?
	bool useConsole = _isatty(_fileno(stdout)) != 0;

	// メモリ状況の取得
	MEMORYSTATUSEX meminfo = {0};
	meminfo.dwLength = sizeof(MEMORYSTATUSEX);

	if (!GlobalMemoryStatusEx(&meminfo)) {
		_ftprintf(
			stderr,
			_T("GlobalMemoryStatusEx: errorcode: %ld\n"),
			GetLastError()
			);
		exit(1);
	}

	// 物理メモリ使用状況の表示
	size_t unit = 1024 * 1024; // 1 MegaBytes

	_ftprintf(
		stdout,
		_T("Phys: %I64d/%I64d MBytes\n"),
		meminfo.ullAvailPhys / unit,
		meminfo.ullTotalPhys / unit
		);

	// 最大ループ回数 = 空き物理メモリ(MB単位)
	size_t maxLoopCount = static_cast<size_t>(meminfo.ullAvailPhys / unit);
	if (argc > 1) {
		maxLoopCount = _ttoi(argv[1]);
	}

	// 現在のワーキングセットの取得
	HANDLE hProcess = GetCurrentProcess();
	SIZE_T curMinSize = 0;
	SIZE_T curMaxSize = 0;
	GetProcessWorkingSetSize(hProcess, &curMinSize, &curMaxSize);

	// ワーキングセットの設定
	SIZE_T maxMem = (maxLoopCount + 1) * unit + curMaxSize;
	if (!SetProcessWorkingSetSize(
		hProcess, maxMem, maxMem)) {
		_ftprintf(
			stderr,
			_T("SetProcessWorkingSetSizeEx: errorcode: %ld\n"),
			GetLastError()
			);
		// とりあえず継続してみる
	}

	// メモリを最大まで確保する.
	if (maxLoopCount > 0) {
		std::vector<void *> buf(maxLoopCount);
		for (size_t loopCount = 0; loopCount < maxLoopCount; loopCount++) {

			// コンソール出力であればプログレス表示
			if (useConsole) {
				_ftprintf(stderr, _T("allocating... %ld/%ld MBytes \r"), loopCount + 1, maxLoopCount);
			}

			// メモリの確保
			void *p = VirtualAlloc(NULL, unit, MEM_COMMIT, PAGE_READWRITE);
			if (p == NULL) {
				DWORD errcode = GetLastError();
				if (useConsole) {
					_ftprintf(stderr, _T("\n"));
				}
				_ftprintf(stderr, _T("VirtualAlloc: errorcode: %ld\n"), errcode);
				break;
			}
			
			// 確保済みメモリとして記憶する.
			buf[loopCount] = p;

			// 物理メモリをロックする
			if (!VirtualLock(p, unit)) {
				DWORD errcode = GetLastError();
				if (useConsole) {
					_ftprintf(stderr, _T("\n"));
				}
				_ftprintf(stderr, _T("VirtualLock: errorcode: %ld\n"), errcode);
				break;
			}
		}
		if (useConsole) {
			_ftprintf(stderr, _T("\n"));
		}

		// メモリを解放する
		for (size_t loopCount = 0; loopCount < maxLoopCount; loopCount++) {
			void *p = buf[loopCount];
			if (p) {
				VirtualUnlock(p, unit);
				VirtualFree(p, unit, MEM_DECOMMIT);
			}
		}
	}

	return 0;
}
Example #28
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
Example #29
0
//////////////////////////////////////////////////////////////////////////////////////////
// Delete the given data from the file.
XsensResultValue Cmt1f::deleteData (const CmtFilePos start, const uint32_t length)
{
	if (!m_isOpen)
		return m_lastResult = XRV_NOFILEOPEN;
	if (m_readOnly)
		return m_lastResult = XRV_READONLY;

	gotoWrite();

	CmtFilePos wPos = start;
	CmtFilePos rPos = wPos + length;

	size_t read1;
	CmtFilePos endPos = (start + (CmtFilePos) length);
	if (endPos < m_fileSize)
	{
		CmtFilePos remaining = m_fileSize - endPos;
		char buffer[512];

		// copy data
		FSEEK(rPos);

		while (remaining > 0)
		{
			if (remaining >= 512)
				read1 = fread(buffer,1,512,m_handle);
			else
				read1 = fread(buffer,1,(size_t) remaining,m_handle);

			remaining -= read1;
			rPos += read1;

			// write block to the correct position
			FSEEK(wPos);
			wPos += fwrite(buffer, 1, read1, m_handle);
			FSEEK(rPos);
		}
		m_fileSize -= length;
	}
	else
	{
		m_fileSize = start;
	}

#ifdef _WIN32
	int32_t rv = _chsize(_fileno(m_handle),(int32_t) m_fileSize);
#else
	int32_t rv = ftruncate(fileno(m_handle),(int32_t) m_fileSize);
#endif
	int32_t eno = 0;
	if (rv != 0)
		eno = errno;
	m_writePos = start;
	FSEEK(wPos);
	if (rv != 0)
	{
		switch(eno)
		{
		case EACCES:
			return m_lastResult = XRV_BUSY;
		case EBADF:
			return m_lastResult = XRV_INVALIDINSTANCE;
		case ENOSPC:
			return m_lastResult = XRV_OUTOFMEMORY;
		case EINVAL:
			return m_lastResult = XRV_INVALIDPARAM;
		default:
			return m_lastResult = XRV_ERROR;
		}
	}

	return m_lastResult = XRV_OK;
}	
Example #30
0
static UFILE*
finit_owner(FILE         *f,
              const char *locale,
              const char *codepage,
              UBool       takeOwnership
              )
{
    UErrorCode status = U_ZERO_ERROR;
    UFILE     *result;
    if(f == NULL) {
        return 0;
    }
    result = (UFILE*) uprv_malloc(sizeof(UFILE));
    if(result == NULL) {
        return 0;
    }

    uprv_memset(result, 0, sizeof(UFILE));
    result->fFileno = fileno(f);

#ifdef U_WINDOWS
    if (0 <= result->fFileno && result->fFileno <= 2) {
        /* stdin, stdout and stderr need to be special cased for Windows 98 */
#if _MSC_VER >= 1400
        result->fFile = &__iob_func()[_fileno(f)];
#else
        result->fFile = &_iob[_fileno(f)];
#endif
    }
    else
#endif
    {
        result->fFile = f;
    }

    result->str.fBuffer = result->fUCBuffer;
    result->str.fPos    = result->fUCBuffer;
    result->str.fLimit  = result->fUCBuffer;

#if !UCONFIG_NO_FORMATTING
        /* if locale is 0, use the default */
        if(u_locbund_init(&result->str.fBundle, locale) == 0) {
            /* DO NOT FCLOSE HERE! */
            uprv_free(result);
            return 0;
        }
#endif

    /* If the codepage is not "" use the ucnv_open default behavior */
    if(codepage == NULL || *codepage != '\0') {
        result->fConverter = ucnv_open(codepage, &status);
    }
    /* else result->fConverter is already memset'd to NULL. */

    if(U_SUCCESS(status)) {
        result->fOwnFile = takeOwnership;
    }
    else {
#if !UCONFIG_NO_FORMATTING
        u_locbund_close(&result->str.fBundle);
#endif
        /* DO NOT fclose here!!!!!! */
        uprv_free(result);
        result = NULL;
    }

    return result;
}