int get_file_size(FILE *f,__int64 *s) { _fseeki64(f,0,SEEK_END); s[0]=_ftelli64(f); return TRUE; }
int __gnat_fseek64 (FILE *stream, __int64 offset, int origin) { return _fseeki64 (stream, offset, origin); }
int winpr_image_bitmap_read_fp(wImage* image, FILE* fp) { int index; BOOL vFlip; BYTE* pDstData; WINPR_BITMAP_FILE_HEADER bf; WINPR_BITMAP_INFO_HEADER bi; if (fread((void*) &bf, sizeof(WINPR_BITMAP_FILE_HEADER), 1, fp) != 1) return -1; if ((bf.bfType[0] != 'B') || (bf.bfType[1] != 'M')) return -1; image->type = WINPR_IMAGE_BITMAP; if (fread((void*) &bi, sizeof(WINPR_BITMAP_INFO_HEADER), 1, fp) != 1) return -1; if (_ftelli64(fp) != bf.bfOffBits) { _fseeki64(fp, bf.bfOffBits, SEEK_SET); } image->width = bi.biWidth; if (bi.biHeight < 0) { vFlip = FALSE; image->height = -1 * bi.biHeight; } else { vFlip = TRUE; image->height = bi.biHeight; } image->bitsPerPixel = bi.biBitCount; image->bytesPerPixel = (image->bitsPerPixel / 8); image->scanline = (bi.biSizeImage / image->height); image->data = (BYTE*) malloc(bi.biSizeImage); if (!image->data) return -1; if (!vFlip) { if (fread((void*) image->data, bi.biSizeImage, 1, fp) != 1) { free(image->data); image->data = NULL; return -1; } } else { pDstData = &(image->data[(image->height - 1) * image->scanline]); for (index = 0; index < image->height; index++) { if (fread((void*) pDstData, image->scanline, 1, fp) != 1) { free(image->data); image->data = NULL; return -1; } pDstData -= image->scanline; } } return 1; }
static err_type _copyArchWithoutFile(FILE *archDst, FILE *archSrc, const char *fileName) { err_type result; File_Header fHead; uint8_t *buffer = NULL; uint8_t mask[_MAX_PATH] = "#@$%"; uint64_t readSize; int ch; if ((result = arch_checkMarkerBlock(archSrc)) != ERR_NO) return result; if ((result = arch_writeMarkerBlock(archDst)) != ERR_NO) return result; if ((buffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t))) == NULL) return ERR_NOMEM; ch = getc(archSrc); while (!feof(archSrc)) { ungetc(ch, archSrc); if ((result = File_Header_fread(archSrc, &fHead)) != ERR_NO) break; fHead.fileName[fHead.fileNameLength] = 0; if (strcmp(fHead.fileName, fileName) == 0) { if (_fseeki64(archSrc, fHead.fileSize, SEEK_CUR) != 0) { result = ERR_READ_FAILED; break; } if (fHead.fileSize > 0) { if (_fseeki64(archSrc, sizeof(fHead.fileCrc), SEEK_CUR) != 0) { result = ERR_READ_FAILED; break; } } break; } else { if ((result = File_Header_fwrite(archDst, &fHead)) != ERR_NO) break; if (fHead.fileSize > 0) { while (fHead.fileSize > 0) { readSize = min(BUFFER_SIZE, fHead.fileSize); if (fread(buffer, readSize * sizeof(uint8_t), 1, archSrc) == 0) { result = feof(archSrc) ? ERR_EOF : ERR_READ_FAILED; break; } if (fwrite(buffer, readSize * sizeof(uint8_t), 1, archDst) == 0) { result = ERR_WRITE_FAILED; break; } fHead.fileSize -= readSize; } if (result != ERR_NO) break; if (fread(&fHead.fileCrc, sizeof(fHead.fileCrc), 1, archSrc) == 0) { result = feof(archSrc) ? ERR_EOF : ERR_READ_FAILED; break; } if (fwrite(&fHead.fileCrc, sizeof(fHead.fileCrc), 1, archDst) == 0) { result = ERR_WRITE_FAILED; break; } } } ch = getc(archSrc); } if ((result == ERR_NO) && (!feof(archSrc))) { if ((fHead.attr & S_IFDIR) != 0) strcat(strcpy(mask, fHead.fileName), "\\"); ch = getc(archSrc); while (!feof(archSrc)) { ungetc(ch, archSrc); if ((result = File_Header_fread(archSrc, &fHead)) != ERR_NO) break; fHead.fileName[fHead.fileNameLength] = 0; if (strstr(fHead.fileName, mask) == fHead.fileName) { if (_fseeki64(archSrc, fHead.fileSize, SEEK_CUR) != 0) { result = ERR_READ_FAILED; break; } if (fHead.fileSize > 0) { if (_fseeki64(archSrc, sizeof(fHead.fileCrc), SEEK_CUR) != 0) { result = ERR_READ_FAILED; break; } } } else { if ((result = File_Header_fwrite(archDst, &fHead)) != ERR_NO) break; if (fHead.fileSize == 0) continue; while (fHead.fileSize > 0) { readSize = min(BUFFER_SIZE, fHead.fileSize); if (fread(buffer, readSize * sizeof(uint8_t), 1, archSrc) == 0) { result = feof(archSrc) ? ERR_EOF : ERR_READ_FAILED; break; } if (fwrite(buffer, readSize * sizeof(uint8_t), 1, archDst) == 0) { result = ERR_WRITE_FAILED; break; } fHead.fileSize -= readSize; } if (result != ERR_NO) break; if (fread(&fHead.fileCrc, sizeof(fHead.fileCrc), 1, archSrc) == 0) { result = feof(archSrc) ? ERR_EOF : ERR_READ_FAILED; break; } if (fwrite(&fHead.fileCrc, sizeof(fHead.fileCrc), 1, archDst) == 0) { result = ERR_WRITE_FAILED; break; } } ch = getc(archSrc); } } free(buffer); return result; }
/*enumerate directories*/ GF_EXPORT GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter) { #ifdef WIN32 wchar_t item_path[GF_MAX_PATH]; #else char item_path[GF_MAX_PATH]; #endif GF_FileEnumInfo file_info; #if defined(_WIN32_WCE) char _path[GF_MAX_PATH]; unsigned short path[GF_MAX_PATH]; unsigned short w_filter[GF_MAX_PATH]; char file[GF_MAX_PATH]; #elif defined(WIN32) wchar_t path[GF_MAX_PATH], *file; wchar_t w_filter[GF_MAX_PATH]; wchar_t w_dir[GF_MAX_PATH]; char *mbs_file, *mbs_item_path; #else char path[GF_MAX_PATH], *file; #endif #ifdef WIN32 WIN32_FIND_DATAW FindData; HANDLE SearchH; #else DIR *the_dir; struct dirent* the_file; struct stat st; #endif if (!dir || !enum_dir_fct) return GF_BAD_PARAM; if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL; memset(&file_info, 0, sizeof(GF_FileEnumInfo) ); if (!strcmp(dir, "/")) { #if defined(WIN32) && !defined(_WIN32_WCE) u32 len; char *drives, *volume; len = GetLogicalDriveStrings(0, NULL); drives = (char*)gf_malloc(sizeof(char)*(len+1)); drives[0]=0; GetLogicalDriveStrings(len, drives); len = (u32) strlen(drives); volume = drives; file_info.directory = GF_TRUE; file_info.drive = GF_TRUE; while (len) { enum_dir_fct(cbck, volume, "", &file_info); volume += len+1; len = (u32) strlen(volume); } gf_free(drives); return GF_OK; #elif defined(__SYMBIAN32__) RFs iFs; TDriveList aList; iFs.Connect(); iFs.DriveList(aList); for (TInt i=0; i<KMaxDrives; i++) { if (aList[i]) { char szDrive[10]; TChar aDrive; iFs.DriveToChar(i, aDrive); sprintf(szDrive, "%c:", (TUint)aDrive); enum_dir_fct(cbck, szDrive, "", &file_info); } } iFs.Close(); FlushItemList(); return GF_OK; #endif } #if defined (_WIN32_WCE) switch (dir[strlen(dir) - 1]) { case '/': case '\\': sprintf(_path, "%s*", dir); break; default: sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR); break; } CE_CharToWide(_path, path); CE_CharToWide((char *)filter, w_filter); #elif defined(WIN32) { const char* tmpdir = dir; gf_utf8_mbstowcs(w_dir, sizeof(w_dir), &tmpdir); } switch (w_dir[wcslen(w_dir) - 1]) { case '/': case '\\': swprintf(path, MAX_PATH, L"%s*", w_dir); break; default: swprintf(path, MAX_PATH, L"%s%c*", w_dir, GF_PATH_SEPARATOR); break; } { const char* tmpfilter = filter; gf_utf8_mbstowcs(w_filter, sizeof(w_filter), &tmpfilter); } #else strcpy(path, dir); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef WIN32 SearchH= FindFirstFileW(path, &FindData); if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR; #if defined (_WIN32_WCE) _path[strlen(_path)-1] = 0; #else path[wcslen(path)-1] = 0; #endif while (SearchH != INVALID_HANDLE_VALUE) { #else the_dir = opendir(path); if (the_dir == NULL) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno)); return GF_IO_ERR; } the_file = readdir(the_dir); while (the_file) { #endif memset(&file_info, 0, sizeof(GF_FileEnumInfo) ); #if defined (_WIN32_WCE) if (!wcscmp(FindData.cFileName, _T(".") )) goto next; if (!wcscmp(FindData.cFileName, _T("..") )) goto next; #elif defined(WIN32) if (!wcscmp(FindData.cFileName, L".")) goto next; if (!wcscmp(FindData.cFileName, L"..")) goto next; #else if (!strcmp(the_file->d_name, "..")) goto next; if (the_file->d_name[0] == '.') goto next; #endif #ifdef WIN32 file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE; if (!enum_directory && file_info.directory) goto next; if (enum_directory && !file_info.directory) goto next; #endif if (filter) { #if defined (_WIN32_WCE) short ext[30]; short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.'); if (!sep) goto next; wcscpy(ext, sep+1); wcslwr(ext); if (!wcsstr(w_filter, ext)) goto next; #elif defined(WIN32) wchar_t ext[30]; wchar_t *sep = wcsrchr(FindData.cFileName, L'.'); if (!sep) goto next; wcscpy(ext, sep+1); wcslwr(ext); if (!wcsstr(w_filter, ext)) goto next; #else char ext[30]; char *sep = strrchr(the_file->d_name, '.'); if (!sep) goto next; strcpy(ext, sep+1); strlwr(ext); if (!strstr(filter, sep+1)) goto next; #endif } #if defined(WIN32) file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE; file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE; file_info.size = MAXDWORD; file_info.size += 1; file_info.size *= FindData.nFileSizeHigh; file_info.size += FindData.nFileSizeLow; file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); #endif #if defined (_WIN32_WCE) CE_WideToChar(FindData.cFileName, file); strcpy(item_path, _path); strcat(item_path, file); #elif defined(WIN32) wcscpy(item_path, path); wcscat(item_path, FindData.cFileName); file = FindData.cFileName; #else strcpy(item_path, path); strcat(item_path, the_file->d_name); GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path)); if (stat( item_path, &st ) != 0) goto next; file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE; if (enum_directory && !file_info.directory) goto next; if (!enum_directory && file_info.directory) goto next; file_info.size = st.st_size; { struct tm _t = * gmtime(& st.st_mtime); file_info.last_modified = mktime(&_t); } file = the_file->d_name; if (file && file[0]=='.') file_info.hidden = 1; if (file_info.directory) { char * parent_name = strrchr(item_path, '/'); if (!parent_name) { file_info.drive = GF_TRUE; } else { struct stat st_parent; parent_name[0] = 0; if (stat(item_path, &st_parent) == 0) { if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) { file_info.drive = GF_TRUE; } } parent_name[0] = '/'; } } #endif #ifdef WIN32 mbs_file = wcs_to_utf8(file); mbs_item_path = wcs_to_utf8(item_path); if (!mbs_file || !mbs_item_path) { if (mbs_file) gf_free(mbs_file); if (mbs_item_path) gf_free(mbs_item_path); return GF_IO_ERR; } if (enum_dir_fct(cbck, mbs_file, mbs_item_path, &file_info)) { BOOL ret = FindClose(SearchH); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err)); } #else if (enum_dir_fct(cbck, file, item_path, &file_info)) { #endif break; } #ifdef WIN32 gf_free(mbs_file); gf_free(mbs_item_path); #endif next: #ifdef WIN32 if (!FindNextFileW(SearchH, &FindData)) { BOOL ret = FindClose(SearchH); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err)); } break; } #else the_file = readdir(the_dir); #endif } #ifndef WIN32 closedir(the_dir); #endif return GF_OK; } GF_EXPORT u64 gf_ftell(FILE *fp) { #if defined(_WIN32_WCE) return (u64) ftell(fp); #elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__) /* mingw or cygwin */ #if (_FILE_OFFSET_BITS >= 64) return (u64) ftello64(fp); #else return (u64) ftell(fp); #endif #elif defined(WIN32) return (u64) _ftelli64(fp); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) return (u64) ftello64(fp); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) return (u64) ftello(fp); #else return (u64) ftell(fp); #endif } GF_EXPORT u64 gf_fseek(FILE *fp, s64 offset, s32 whence) { #if defined(_WIN32_WCE) return (u64) fseek(fp, (s32) offset, whence); #elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__) /* mingw or cygwin */ #if (_FILE_OFFSET_BITS >= 64) return (u64) fseeko64(fp, offset, whence); #else return (u64) fseek(fp, (s32) offset, whence); #endif #elif defined(WIN32) return (u64) _fseeki64(fp, offset, whence); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) return fseeko64(fp, (off64_t) offset, whence); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) return fseeko(fp, (off_t) offset, whence); #else return fseek(fp, (s32) offset, whence); #endif } GF_EXPORT FILE *gf_fopen(const char *file_name, const char *mode) { FILE *res = NULL; #if defined(WIN32) wchar_t *wname; wchar_t *wmode; wname = utf8_to_wcs(file_name); wmode = utf8_to_wcs(mode); if (!wname || !wmode) { if (wname) gf_free(wname); if (wmode) gf_free(wmode); return NULL; } res = _wfsopen(wname, wmode, _SH_DENYNO); gf_free(wname); gf_free(wmode); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) res = fopen64(file_name, mode); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) res = fopen(file_name, mode); #else res = fopen(file_name, mode); #endif if (res) { gpac_file_handles++; GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] file %s opened in mode %s - %d file handles\n", file_name, mode, gpac_file_handles)); } else { if (strchr(mode, 'w') || strchr(mode, 'a')) { #if defined(WIN32) u32 err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err)); #else GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno)); #endif } } return res; } GF_EXPORT s32 gf_fclose(FILE *file) { if (file) { assert(gpac_file_handles); gpac_file_handles--; } return fclose(file); } #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) && !defined(WIN32) #define HAVE_STRERROR_R 1 #endif GF_EXPORT size_t gf_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) { return fread(ptr, size, nmemb, stream); } GF_EXPORT size_t gf_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t result = fwrite(ptr, size, nmemb, stream); if (result != nmemb) { #ifdef _WIN32_WCE GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data: %d blocks to write but %d blocks written\n", nmemb, result)); #else #if defined WIN32 && !defined(GPAC_CONFIG_WIN32) errno_t errno_save; _get_errno(&errno_save); #else int errno_save = errno; #endif //if (errno_save!=0) { #ifdef HAVE_STRERROR_R #define ERRSTR_BUF_SIZE 256 char errstr[ERRSTR_BUF_SIZE]; if(strerror_r(errno_save, errstr, ERRSTR_BUF_SIZE) != 0) { strerror_r(0, errstr, ERRSTR_BUF_SIZE); } #else char *errstr = (char*)strerror(errno_save); #endif GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data (%s): %d blocks to write but %d blocks written\n", errstr, nmemb, result)); } #endif } return result; }
static int portable_seek(FILE *f, AutoFile::fsize_t pos, int origin) { return _fseeki64(f, pos, origin); }
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prev_instance, char* command_line, int show_command) { #else int main(int argc, char*[] argv) { #endif radish_state* radish; radish_window host_window; radish_init_for_states(); radish = radish_create_state(L"main.lua"); radish->main_fiber = ConvertThreadToFiber(NULL); radish->script_fiber = radish_create_script_fiber(radish); radish_init_host_window(radish, &host_window); if (radish_script_step(radish)) { radish_create_window(radish, &host_window); radish_update_first(radish); // script may have terminated during the create window phase while (radish_script_running(radish)) { DWORD timeout = radish_update_timeout(radish); DWORD result = MsgWaitForMultipleObjects( radish->wait_object_count, radish->wait_objects, FALSE, timeout, QS_ALLINPUT); if (result == WAIT_OBJECT_0 + radish->wait_object_count) { while (PeekMessage(&radish->msg, NULL, 0, 0, PM_REMOVE)) { UINT message = radish->msg.message; HWND hwnd = radish->msg.hwnd; WPARAM wparam = radish->msg.wParam; LPARAM lparam = radish->msg.lParam; if (hwnd == NULL) { radish_script_step(radish); // overridable default behaviours if (radish->msg.message != WMRADISH_HANDLED) { switch (message) { case WMRADISH_DIALOG_REQUEST: radish_do_dialog(radish, (radish_dialog*)lparam); if (wparam != 0) { PostThreadMessage((UINT)wparam, WMRADISH_DIALOG_RESPONSE, 0, lparam); } else { radish->msg.message = WMRADISH_DIALOG_RESPONSE; radish->msg.lParam = lparam; radish_script_step(radish); radish_free_dialog(radish, (radish_dialog*)lparam); } break; } } // non-overridable default behaviours switch (message) { case WMRADISH_THREAD_TERMINATED: // TODO: make sure all strings etc are freed too free((radish_state*)lparam); break; case WMRADISH_THREAD_SEND_DATA: radish_buffer_free((radish_buffer*)lparam); break; } } else { if (radish->accelerator_table != NULL && TranslateAccelerator( radish->msg.hwnd, radish->accelerator_table, &radish->msg)) { // don't TranslateMessage } else { TranslateMessage(&radish->msg); DispatchMessageW(&radish->msg); } } } } else if (result >= WAIT_OBJECT_0 && result < (WAIT_OBJECT_0 + radish->wait_object_count)) { radish->msg.message = WMRADISH_WAIT_OBJECT_SIGNALLED; radish->msg.hwnd = NULL; radish->msg.lParam = (LPARAM)(result - WAIT_OBJECT_0); radish->msg.wParam = (WPARAM)radish->wait_objects[radish->msg.lParam]; radish_script_step(radish); radish_update_maybe(radish); } else if (result >= WAIT_ABANDONED_0 && result < (WAIT_ABANDONED_0 + radish->wait_object_count)) { radish->msg.message = WMRADISH_MUTEX_ABANDONED; radish->msg.hwnd = NULL; radish->msg.lParam = (LPARAM)(result - WAIT_ABANDONED_0); radish->msg.wParam = (WPARAM)radish->wait_objects[radish->msg.lParam]; radish_script_step(radish); radish_update_maybe(radish); } else if (result == WAIT_TIMEOUT) { radish_update_certain(radish); if (timeout == 0) Sleep(0); } else if (result == WAIT_FAILED) { radish->error = L"MsgWaitForMultipleObjects Error"; goto finalize; } else { radish->error = L"Unknown result from MsgWaitForMultipleObjects"; goto finalize; } } } finalize: if (radish->error != NULL) { MessageBoxW(NULL, radish->error, radish_get_title(), MB_OK | MB_ICONERROR); return EXIT_FAILURE; } return EXIT_SUCCESS; } int fseek64_wrap(FILE* f, __int64 off, int whence) { if(f == NULL) return -1; #ifdef __MINGW32__ return fseeko64(f, off, whence); #elif defined (_WIN32) return _fseeki64(f, off, whence); #else return fseek(f, off, whence); #endif }
//---------------------------------------------------------------------------------- bool TrKMclass::AdjustMemoryLimits() { FILE* pFile = NULL; if((pFile = fopen(data_file_name.c_str(), "rb")) == NULL) { perror("fopen"); cout << data_file_name.c_str() << "\n"; return false; } fread(&kmer_len, 1, 1, pFile); #ifdef WIN32 _fseeki64(pFile, 0L, SEEK_END); //Windows uint64 len_all = _ftelli64(pFile) - 8;// windows _fseeki64(pFile, len_all, SEEK_SET); // windows #else fseeko(pFile, 0L, SEEK_END); // linux uint64 len_all = ftello(pFile) - 8; // linux fseeko(pFile, len_all, SEEK_SET); // linux #endif //max_mem_binsKMER = ftell(pFile) + 256*256*8 + 100; // pamiec dla struktury z wszystkimi kmerami wczytanymi num_kmer=0; fread(&num_kmer, 1, sizeof(uint64), pFile); max_mem_binsKMER = 256 * (1 + 8 + 8*256 + 8) + 8 * num_kmer; cout << " No. of kmer: " << setw(12) << num_kmer << "\n"; fclose(pFile); if (max_mem_size <= max_mem_binsKMER) { cout << "max_mem_size <= max_mem_binsKMER\n"; return false; } uint64 m_rest = max_mem_size - max_mem_binsKMER; max_mem_seqKMER = m_rest; //wczytywane sekwencje z kmerami //part 2 m_rest = max_mem_size - max_mem_binsKMER; #ifdef DEBUG_MODE cout << "Splitters: " << m_splitters << "\n"; //cout << "Storer : " << max_mem_storer << "\n"; cout << "FASTQ : " << max_mem_fastq << "\n"; cout << "READS : " << max_mem_reads << "\n"; //cout << "Bin part : " << max_mem_bin_part << "\n"; cout << "Stage 2 : " << max_mem_stage2 << "\n"; #endif //if(max_mem_fastq < 2 * (uint32)fastq_buffer_size) //{ // cout << "max_mem_fastq < 2 * (uint32)fastq_buffer_size \n"; // return false; //} return true; }
/////////////////////////////////////////////////////////////////////////////////////////////////// //also needed by hasher, make it global u32 writeCompressFile(FILE* dstFile, u64 offset, FILE* srcFile, u32 srcFileSize, u32 chunkSize, u32& flag, std::vector<u8>& chunkData, std::vector<u8>& compressBuffer, std::vector<u32>& chunkPosBuffer) { _fseeki64(dstFile, offset, SEEK_SET); u32 chunkCount = (srcFileSize + chunkSize - 1) / chunkSize; chunkPosBuffer.resize(chunkCount); u32 packSize = 0; if (chunkCount > 1) { chunkPosBuffer[0] = chunkCount * sizeof(u32); fwrite(&chunkPosBuffer[0], chunkCount * sizeof(u32), 1, dstFile); } //BEGIN_PERF("compress"); u8* dstBuffer = &compressBuffer[0]; for (u32 i = 0; i < chunkCount; ++i) { u32 curChunkSize = chunkSize; if (i == chunkCount - 1 && srcFileSize % chunkSize != 0) { curChunkSize = srcFileSize % chunkSize; } fread(&chunkData[0], curChunkSize, 1, srcFile); u32 dstSize = chunkSize; int ret = compress(dstBuffer, &dstSize, &chunkData[0], curChunkSize); if (ret != Z_OK || dstSize >= curChunkSize) { //compress failed or compressed size greater than origin, write raw data fwrite(&chunkData[0], curChunkSize, 1, dstFile); dstSize = curChunkSize; } else { fwrite(dstBuffer, dstSize, 1, dstFile); } if (i + 1 < chunkCount) { chunkPosBuffer[i + 1] = chunkPosBuffer[i] + dstSize; } packSize += dstSize; } //END_PERF if (chunkCount > 1) { packSize += chunkCount * sizeof(u32); _fseeki64(dstFile, offset, SEEK_SET); fwrite(&chunkPosBuffer[0], chunkCount * sizeof(u32), 1, dstFile); } else if (packSize == srcFileSize) { //only 1 chunk and not compressed, entire file should not be compressed flag &= (~FILE_COMPRESS); } return packSize; }
void shift(uint64_t off) { if (_fp) { _offset += off; _fseeki64(_fp, _offset, SEEK_SET); } }
int fseeko64(FILE *fp, off64_t offset, int whence) { return _fseeki64(fp, (int64_t)offset, whence); }
void seek(uint64_t off) { if (_fp) { _offset = off; _fseeki64(_fp, off, SEEK_SET); } }
extern int output_mp4(struct mp4_context_t* mp4_context, unsigned int const* trak_sample_start, unsigned int const* trak_sample_end, struct bucket_t** buckets, struct mp4_split_options_t* options) { unsigned int i; uint64_t mdat_start = mp4_context->mdat_atom.start_; uint64_t mdat_size = mp4_context->mdat_atom.size_; int64_t offset; struct moov_t* moov = mp4_context->moov; unsigned char* moov_data = mp4_context->moov_data; uint64_t moov_size; long moov_time_scale = moov->mvhd_->timescale_; uint64_t skip_from_start = UINT64_MAX; uint64_t end_offset = 0; uint64_t moov_duration = 0; #if 1 uint64_t new_mdat_start = 0; { static char const free_data[] = { 0x0, 0x0, 0x0, 42, 'f', 'r', 'e', 'e', 'v', 'i', 'd', 'e', 'o', ' ', 's', 'e', 'r', 'v', 'e', 'd', ' ', 'b', 'y', ' ', 'm', 'o', 'd', '_', 'h', '2', '6', '4', '_', 's', 't', 'r', 'e', 'a', 'm', 'i', 'n', 'g' }; uint32_t size_of_header = (uint32_t)mp4_context->ftyp_atom.size_ + sizeof(free_data); unsigned char* buffer = (unsigned char*)malloc(size_of_header); if(mp4_context->ftyp_atom.size_) { _fseeki64(mp4_context->infile, mp4_context->ftyp_atom.start_, SEEK_SET); if(fread(buffer, (off_t)mp4_context->ftyp_atom.size_, 1, mp4_context->infile) != 1) { MP4_ERROR("%s", "Error reading ftyp atom\n"); free(buffer); return 0; } } // copy free data memcpy(buffer + mp4_context->ftyp_atom.size_, free_data, sizeof(free_data)); if(options->output_format == OUTPUT_FORMAT_MP4) { struct bucket_t* bucket = bucket_init_memory(buffer, size_of_header); bucket_insert_tail(buckets, bucket); } free(buffer); new_mdat_start += size_of_header; } new_mdat_start += mp4_context->moov_atom.size_; #endif offset = new_mdat_start - mp4_context->mdat_atom.start_; // subtract old moov size offset -= mp4_context->moov_atom.size_; for(i = 0; i != moov->tracks_; ++i) { struct trak_t* trak = moov->traks_[i]; struct stbl_t* stbl = trak->mdia_->minf_->stbl_; unsigned int start_sample = trak_sample_start[i]; unsigned int end_sample = trak_sample_end[i]; trak_update_index(mp4_context, trak, start_sample, end_sample); if(trak->samples_size_ == 0) { MP4_WARNING("Trak %u contains no samples. Maybe a fragmented file?", i); return 1; } { uint64_t skip = trak->samples_[start_sample].pos_ - trak->samples_[0].pos_; if(skip < skip_from_start) skip_from_start = skip; MP4_INFO("Trak can skip %llu bytes\n", skip); if(end_sample != trak->samples_size_) { uint64_t end_pos = trak->samples_[end_sample].pos_; if(end_pos > end_offset) end_offset = end_pos; MP4_INFO("New endpos=%llu\n", end_pos); MP4_INFO("Trak can skip %llu bytes at end\n", mdat_start + mdat_size - end_offset); } } { // fixup trak (duration) uint64_t trak_duration = stts_get_duration(stbl->stts_); long trak_time_scale = trak->mdia_->mdhd_->timescale_; { uint64_t duration = trak_time_to_moov_time(trak_duration, moov_time_scale, trak_time_scale); trak->mdia_->mdhd_->duration_= trak_duration; trak->tkhd_->duration_ = duration; MP4_INFO("trak: new_duration=%llu\n", duration); if(duration > moov_duration) moov_duration = duration; } } // MP4_INFO("stco.size=%d, ", read_int32(stbl->stco_ + 4)); // MP4_INFO("stts.size=%d samples=%d\n", read_int32(stbl->stts_ + 4), stts_get_samples(stbl->stts_)); // MP4_INFO("stsz.size=%d\n", read_int32(stbl->stsz_ + 8)); // MP4_INFO("stsc.samples=%d\n", stsc_get_samples(stbl->stsc_)); } moov->mvhd_->duration_ = moov_duration; MP4_INFO("moov: new_duration=%.2f seconds\n", moov_duration / (float)moov_time_scale); // subtract bytes we skip at the front of the mdat atom offset -= skip_from_start; MP4_INFO("%s", "moov: writing header\n"); moov_write(moov, moov_data); moov_size = read_32(moov_data); // add new moov size offset += moov_size; MP4_INFO("shifting offsets by %llu\n", offset); moov_shift_offsets_inplace(moov, offset); // traffic shaping: create offsets for each second create_traffic_shaping(moov, trak_sample_start, trak_sample_end, offset, options); #ifdef COMPRESS_MOOV_ATOM if(!options->client_is_flash) { compress_moov(mp4_context, moov, moov_data, &moov_size); } #endif mdat_start += skip_from_start; if(end_offset != 0) { mdat_size = end_offset; } mdat_size -= skip_from_start; bucket_insert_tail(buckets, bucket_init_memory(moov_data, moov_size)); { struct mp4_atom_t mdat_atom; mdat_atom.type_ = FOURCC('m', 'd', 'a', 't'); mdat_atom.short_size_ = 0; // TODO: use original small/wide mdat box if(options->adaptive) { // empty mdat atom mdat_atom.size_ = ATOM_PREAMBLE_SIZE; } else { mdat_atom.size_ = mdat_size; } { unsigned char buffer[32]; int mdat_header_size = mp4_atom_write_header(buffer, &mdat_atom); bucket_insert_tail(buckets, bucket_init_memory(buffer, mdat_header_size)); if(mdat_atom.size_ - mdat_header_size) { bucket_insert_tail(buckets, bucket_init_file(mdat_start + mdat_header_size, mdat_atom.size_ - mdat_header_size)); } } } return 1; }
LRESULT CALLBACK view_context_proc(HWND hwnd,UINT msg,WPARAM wparam,LPARAM lparam) { static HWND grippy=0; int lines,dir,do_scroll=FALSE,update_scroll_pos=TRUE; static int divider_drag=FALSE,org_row_width=90,row_width=90,last_pos=0; #ifdef _DEBUG if(FALSE) // if(message!=0x200&&message!=0x84&&message!=0x20&&message!=WM_ENTERIDLE) // if(msg!=WM_MOUSEFIRST&&msg!=WM_NCHITTEST&&msg!=WM_SETCURSOR&&msg!=WM_ENTERIDLE&&msg!=WM_DRAWITEM // &&msg!=WM_CTLCOLORBTN&&msg!=WM_CTLCOLOREDIT&&msg!=WM_CTLCOLORSCROLLBAR) if(msg!=WM_NCHITTEST&&msg!=WM_SETCURSOR&&msg!=WM_ENTERIDLE) { static DWORD tick=0; if((GetTickCount()-tick)>500) printf("--\n"); printf("v"); print_msg(msg,lparam,wparam); tick=GetTickCount(); } #endif switch(msg) { case WM_INITDIALOG: grippy=create_grippy(hwnd); init_context_win_anchor(hwnd); get_ini_value("CONTEXT_WINDOW","row_width",&row_width); set_context_divider(hwnd,row_width); restore_context_rel_pos(hwnd); SendDlgItemMessage(hwnd,IDC_CONTEXT_SCROLLBAR,SBM_SETRANGE,0,10000); { int tabstop=21; //4 fixed chars SendDlgItemMessage(hwnd,IDC_CONTEXT,EM_SETTABSTOPS,1,&tabstop); } set_context_font(hwnd); open_file(&gfh); if(gfh==0){ WCHAR str[MAX_PATH*2]; _snwprintf(str,sizeof(str)/sizeof(WCHAR),L"cant open %s",fname); str[sizeof(str)/sizeof(WCHAR)-1]=0; MessageBoxW(hwnd,str,L"error",MB_OK); EndDialog(hwnd,0); return 0; } get_file_size(gfh,&fsize); _fseeki64(gfh,start_offset,SEEK_SET); set_scroll_pos(hwnd,IDC_CONTEXT_SCROLLBAR,gfh); SetFocus(GetDlgItem(hwnd,IDC_CONTEXT_SCROLLBAR)); line_count=get_number_of_lines(hwnd,IDC_CONTEXT); fill_context(hwnd,IDC_CONTEXT,gfh); close_file(&gfh); last_pos=-1; orig_edit=SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT),GWL_WNDPROC,subclass_edit); orig_scroll=SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT_SCROLLBAR),GWL_WNDPROC,subclass_scroll); SetWindowTextW(hwnd,fname); return 0; case WM_DESTROY: save_context_rel_pos(hwnd); break; case WM_HELP: context_help(hwnd); return TRUE; break; case WM_SIZE: grippy_move(hwnd,grippy); set_context_divider(hwnd,row_width); line_count=get_number_of_lines(hwnd,IDC_CONTEXT); open_file(&gfh); fill_context(hwnd,IDC_CONTEXT,gfh); set_scroll_pos(hwnd,IDC_CONTEXT_SCROLLBAR,gfh); close_file(&gfh); break; case WM_RBUTTONDOWN: case WM_LBUTTONUP: ReleaseCapture(); if(divider_drag){ write_ini_value("CONTEXT_WINDOW","row_width",row_width); divider_drag=FALSE; } break; case WM_LBUTTONDOWN: SetCapture(hwnd); SetCursor(LoadCursor(NULL,IDC_SIZEWE)); divider_drag=TRUE; org_row_width=row_width; break; case WM_MOUSEFIRST: { int x=LOWORD(lparam); SetCursor(LoadCursor(NULL,IDC_SIZEWE)); if(divider_drag){ RECT rect; GetClientRect(hwnd,&rect); if((rect.right-x)>25 && x>5){ row_width=x; set_context_divider(hwnd,row_width); } } } break; case WM_MOUSEWHEEL: { short wheel=HIWORD(wparam); int flags=LOWORD(wparam); if(wheel>0){ dir=-1; if(flags&MK_RBUTTON) lines=line_count-2; else lines=3+1; } else{ dir=1; if(flags&MK_RBUTTON) lines=line_count-2-1; else lines=3; } do_scroll=TRUE; } break; case WM_VSCROLL: { int pos=HIWORD(wparam); switch(LOWORD(wparam)){ case SB_TOP: if(GetKeyState(VK_CONTROL)&0x8000){ last_offset=0; current_line=1; } else{ last_offset=start_offset; //_fseeki64(f,start_offset,SEEK_SET); current_line=start_line; } lines=dir=0; do_scroll=TRUE; break; case SB_PAGEUP: dir=-1; lines=line_count-2; if(lines<=0) lines=1; do_scroll=TRUE; break; case SB_PAGEDOWN: dir=1; lines=line_count-2-1; if(lines<=0) lines=1; do_scroll=TRUE; break; case SB_LINEUP: dir=-1; lines=2; do_scroll=TRUE; break; case SB_LINEDOWN: dir=1; lines=1; do_scroll=TRUE; break; case SB_THUMBTRACK: //printf("pos=%i last_pos=%i scroll_pos=%i line_count=%i\n",HIWORD(wparam),last_pos,scroll_pos,line_count); if(pos<last_pos){ dir=-1; lines=line_count/4; if(lines<=1) lines=2; do_scroll=TRUE; } else if(pos>last_pos){ dir=1; lines=line_count/4; if(lines==0) lines=1; do_scroll=TRUE; } if(last_pos==-1) do_scroll=FALSE; last_pos=pos; update_scroll_pos=FALSE; break; case SB_THUMBPOSITION: //dragged and released dir=lines=0; do_scroll=TRUE; break; case SB_ENDSCROLL: last_pos=-1; break; } } break; case WM_COMMAND: switch(LOWORD(wparam)){ case IDCANCEL: if(divider_drag){ divider_drag=FALSE; ReleaseCapture(); set_context_divider(hwnd,org_row_width); row_width=org_row_width; return 0; } if(gfh!=0) fclose(gfh); gfh=0; if(orig_edit!=0)SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT),GWL_WNDPROC,orig_edit); EndDialog(hwnd,0); return 0; } break; } if(do_scroll) do_scroll_proc(hwnd,lines,dir,update_scroll_pos); return 0; }
int WinFSeek(FileHndl &file, stream_length_type offset, int origin) { return _fseeki64(file.get(), offset, origin); }
HANDLE WhatsAppProto::SendFile(MCONTACT hContact, const TCHAR* desc, TCHAR **ppszFiles) { if (!isOnline()) return 0; ptrA jid(getStringA(hContact, "ID")); if (jid == NULL) return 0; // input validation char *name = mir_utf8encodeW(ppszFiles[0]); string mime = MediaUploader::getMimeFromExtension(split(name, '.')[1]); if (mime.empty()) return 0; // get file size FILE *hFile = _tfopen(ppszFiles[0], _T("rb")); if (hFile == NULL) { debugLogA(__FUNCTION__": cannot open file %s", ppszFiles[0]); return 0; } _fseeki64(hFile, 0, SEEK_END); uint64_t fileSize = _ftelli64(hFile); fclose(hFile); // get filetype from mimeType int fileType = FMessage::getMessage_WA_Type(split(mime, '/')[0]); // check max file sizes switch (fileType) { case FMessage::WA_TYPE_IMAGE: if (fileSize >= 5 * 1024 * 1024) return 0; break; case FMessage::WA_TYPE_AUDIO: if (fileSize >= 10 * 1024 * 1024) return 0; break; case FMessage::WA_TYPE_VIDEO: if (fileSize >= 20 * 1024 * 1024) return 0; break; default: return 0; } int msgId = GetSerial(); time_t now = time(NULL); std::string msgid = Utilities::intToStr(now) + "-" + Utilities::intToStr(msgId); FMessage * fmsg = new FMessage(std::string(jid), true, msgid); fmsg->media_url = name; fmsg->media_size = fileSize; fmsg->media_wa_type = fileType; fmsg->data = mir_utf8encodeW(desc); // calculate file hash unsigned char hash[MIR_SHA256_HASH_SIZE]; SHA256_CONTEXT sha256; mir_sha256_init(&sha256); FILE *fd = _tfopen(ppszFiles[0], _T("rb")); int read = 0; do { char buf[1024]; read = (int)fread(buf, 1, 1024, fd); mir_sha256_write(&sha256, buf, read); } while (read > 0); fclose(fd); mir_sha256_final(&sha256, hash); fmsg->media_name = mir_base64_encode((BYTE*)hash,sizeof(hash)); // request media upload url m_pConnection->sendMessage(fmsg); return (HANDLE)fmsg; // TODO what to return here to make the upload shown complete when done and how to handle errors? }
/*enumerate directories*/ GF_EXPORT GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter) { char item_path[GF_MAX_PATH]; GF_FileEnumInfo file_info; #if defined(_WIN32_WCE) char _path[GF_MAX_PATH]; unsigned short path[GF_MAX_PATH]; unsigned short w_filter[GF_MAX_PATH]; char file[GF_MAX_PATH]; #else char path[GF_MAX_PATH], *file; #endif #ifdef WIN32 WIN32_FIND_DATA FindData; HANDLE SearchH; #else DIR *the_dir; struct dirent* the_file; struct stat st; #endif if (!dir || !enum_dir_fct) return GF_BAD_PARAM; if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL; memset(&file_info, 0, sizeof(GF_FileEnumInfo) ); if (!strcmp(dir, "/")) { #if defined(WIN32) && !defined(_WIN32_WCE) u32 len; char *drives, *volume; len = GetLogicalDriveStrings(0, NULL); drives = (char*)gf_malloc(sizeof(char)*(len+1)); drives[0]=0; GetLogicalDriveStrings(len, drives); len = (u32) strlen(drives); volume = drives; file_info.directory = GF_TRUE; file_info.drive = GF_TRUE; while (len) { enum_dir_fct(cbck, volume, "", &file_info); volume += len+1; len = (u32) strlen(volume); } gf_free(drives); return GF_OK; #elif defined(__SYMBIAN32__) RFs iFs; TDriveList aList; iFs.Connect(); iFs.DriveList(aList); for (TInt i=0; i<KMaxDrives; i++) { if (aList[i]) { char szDrive[10]; TChar aDrive; iFs.DriveToChar(i, aDrive); sprintf(szDrive, "%c:", (TUint)aDrive); enum_dir_fct(cbck, szDrive, "", &file_info); } } iFs.Close(); FlushItemList(); return GF_OK; #endif } #if defined (_WIN32_WCE) switch (dir[strlen(dir) - 1]) { case '/': case '\\': sprintf(_path, "%s*", dir); break; default: sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR); break; } CE_CharToWide(_path, path); CE_CharToWide((char *)filter, w_filter); #elif defined(WIN32) switch (dir[strlen(dir) - 1]) { case '/': case '\\': sprintf(path, "%s*", dir); break; default: sprintf(path, "%s%c*", dir, GF_PATH_SEPARATOR); break; } #else strcpy(path, dir); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef WIN32 SearchH= FindFirstFile(path, &FindData); if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR; #if defined (_WIN32_WCE) _path[strlen(_path)-1] = 0; #else path[strlen(path)-1] = 0; #endif while (SearchH != INVALID_HANDLE_VALUE) { #else the_dir = opendir(path); if (the_dir == NULL) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno)); return GF_IO_ERR; } the_file = readdir(the_dir); while (the_file) { #endif memset(&file_info, 0, sizeof(GF_FileEnumInfo) ); #if defined (_WIN32_WCE) if (!wcscmp(FindData.cFileName, _T(".") )) goto next; if (!wcscmp(FindData.cFileName, _T("..") )) goto next; #elif defined(WIN32) if (!strcmp(FindData.cFileName, ".")) goto next; if (!strcmp(FindData.cFileName, "..")) goto next; #else if (!strcmp(the_file->d_name, "..")) goto next; if (the_file->d_name[0] == '.') goto next; #endif #ifdef WIN32 file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE; if (!enum_directory && file_info.directory) goto next; if (enum_directory && !file_info.directory) goto next; #endif if (filter) { #if defined (_WIN32_WCE) short ext[30]; short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.'); if (!sep) goto next; wcscpy(ext, sep+1); wcslwr(ext); if (!wcsstr(w_filter, ext)) goto next; #elif defined(WIN32) char ext[30]; char *sep = strrchr(FindData.cFileName, '.'); if (!sep) goto next; strcpy(ext, sep+1); strlwr(ext); if (!strstr(filter, ext)) goto next; #else char ext[30]; char *sep = strrchr(the_file->d_name, '.'); if (!sep) goto next; strcpy(ext, sep+1); strlwr(ext); if (!strstr(filter, sep+1)) goto next; #endif } #if defined(WIN32) file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE; file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE; file_info.size = MAXDWORD; file_info.size += 1; file_info.size *= FindData.nFileSizeHigh; file_info.size += FindData.nFileSizeLow; file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); #endif #if defined (_WIN32_WCE) CE_WideToChar(FindData.cFileName, file); strcpy(item_path, _path); strcat(item_path, file); #elif defined(WIN32) strcpy(item_path, path); strcat(item_path, FindData.cFileName); file = FindData.cFileName; #else strcpy(item_path, path); strcat(item_path, the_file->d_name); GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path)); if (stat( item_path, &st ) != 0) goto next; file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE; if (enum_directory && !file_info.directory) goto next; if (!enum_directory && file_info.directory) goto next; file_info.size = st.st_size; { struct tm _t = * gmtime(& st.st_mtime); file_info.last_modified = mktime(&_t); } file = the_file->d_name; if (file && file[0]=='.') file_info.hidden = 1; if (file_info.directory) { char * parent_name = strrchr(item_path, '/'); if (!parent_name) { file_info.drive = GF_TRUE; } else { struct stat st_parent; parent_name[0] = 0; if (stat(item_path, &st_parent) == 0) { if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) { file_info.drive = GF_TRUE; } } parent_name[0] = '/'; } } #endif if (enum_dir_fct(cbck, file, item_path, &file_info)) { #ifdef WIN32 BOOL ret = FindClose(SearchH); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err)); } #endif break; } next: #ifdef WIN32 if (!FindNextFile(SearchH, &FindData)) { BOOL ret = FindClose(SearchH); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err)); } break; } #else the_file = readdir(the_dir); #endif } #ifndef WIN32 closedir(the_dir); #endif return GF_OK; } GF_EXPORT u64 gf_ftell(FILE *fp) { #if defined(_WIN32_WCE) return (u64) ftell(fp); #elif defined(GPAC_CONFIG_WIN32) /* mingw or cygwin */ #if (_FILE_OFFSET_BITS >= 64) return (u64) ftello64(fp); #else return (u64) ftell(fp); #endif #elif defined(WIN32) return (u64) _ftelli64(fp); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) return (u64) ftello64(fp); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) return (u64) ftello(fp); #else return (u64) ftell(fp); #endif } GF_EXPORT u64 gf_fseek(FILE *fp, s64 offset, s32 whence) { #if defined(_WIN32_WCE) return (u64) fseek(fp, (s32) offset, whence); #elif defined(GPAC_CONFIG_WIN32) /* mingw or cygwin */ #if (_FILE_OFFSET_BITS >= 64) return (u64) fseeko64(fp, offset, whence); #else return (u64) fseek(fp, (s32) offset, whence); #endif #elif defined(WIN32) return (u64) _fseeki64(fp, offset, whence); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) return fseeko64(fp, (off64_t) offset, whence); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) return fseeko(fp, (off_t) offset, whence); #else return fseek(fp, (s32) offset, whence); #endif } GF_EXPORT FILE *gf_fopen(const char *file_name, const char *mode) { FILE *res; #if defined(WIN32) res = fopen(file_name, mode); #elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID) res = fopen64(file_name, mode); #elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN)) res = fopen(file_name, mode); #else res = fopen(file_name, mode); #endif if (res) { gpac_file_handles ++; } else { if (strchr(mode, 'w') || strchr(mode, 'a')) { #if defined(WIN32) u32 err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err)); #else GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno)); #endif } } return res; }
void tidySolutions(int attack, int knightNumber, int coverage, int counter) { FILE* inFile = mkSolDir(attack, coverage, knightNumber, maximisedFile, true, false, counter); FILE* duplicatesOutFile = NULL; FILE* tidiedOutFile = NULL; solution sol; solutionTree = (solutionLeaf *)malloc(sizeof(solutionLeaf) * MAX_SOLUTIONS); solutionLeaf* slot = solutionTree; unsigned long long count = 0; bool error = false; initialiseXYs(); int pos = knightsYX[attack][1] > knightsYX[attack][0] ? knightsYX[attack][1] : knightsYX[attack][0]; if (pos + HASH_BORDER >= MAX_GRID) { printf("Cannot hash more than %d rows", (MAX_GRID - HASH_BORDER)); return; } long long currentPosition = _ftelli64(inFile); size_t loop = readSolution(&sol, inFile); unsigned long long mask = _rotr64(MASK, pos); while (loop) { int offset = 0; int multiplierIndex = 0; unsigned long long rowHash = 0; unsigned long long hash = 0; for (int row = 0; row < pos; row++) { unsigned long long part = (sol.coverage[row] & mask); if (offset < pos) { part = _rotl64(part, pos - offset); } else if (offset > pos) { part = _rotr64(part, offset - pos); } rowHash |= part; offset += HASH_BORDER; if (offset > MAX_GRID) { offset -= MAX_GRID; if (multiplierIndex == 0) { hash |= rowHash; } else { hash |= (rowHash + 1) * multiplier[multiplierIndex]; multiplierIndex++; } } } for (int row = pos; row < pos + HASH_BORDER; row++) { hash |= (_rotr64(sol.coverage[row], MAX_GRID - HASH_BORDER - pos) + 1) * multiplier[multiplierIndex]; multiplierIndex++; } slot->hash = hash; slot->bigger = NULL; slot->equal = NULL; slot->lesser = NULL; slot->solutionOffset = currentPosition; if (count > 0) { solutionLeaf* root = solutionTree; while (true) { if (hash == root->hash) { if (root->equal == NULL) { root->equal = slot; break; } else { root = root->equal; } } else if (hash > root->hash) { if (root->bigger == NULL) { root->bigger = slot; break; } else { root = root->bigger; } } else if (hash < root->hash) { if (root->lesser == NULL) { root->lesser = slot; break; } else { root = root->lesser; } } } } slot++; count++; currentPosition = _ftelli64(inFile); loop = readSolution(&sol, inFile); if ((count == MAX_SOLUTIONS) && loop) { printf("Too many solutions to manage."); error = true; break; } } fclose(inFile); if (error) { return; } inFile = mkSolDir(attack, coverage, knightNumber, maximisedFile, true, false, counter); tidiedOutFile = mkSolDir(attack, coverage, knightNumber, tidiedFile, false, false, 0); slot = solutionTree; readSolution(&sol, inFile); solution compare; while (count) { if (slot->equal == NULL) { //Could be in a maximised file less than counter! writeSolution(&sol, tidiedOutFile); slot++; } else { solutionLeaf* test = slot->equal; int state = STATE_KEEP; while (test != NULL) { _fseeki64(inFile, test->solutionOffset, SEEK_SET); readSolution(&compare, inFile); int cmp = memcmp(sol.coverage, compare.coverage, sizeof(unsigned long long) * MAX_GRID); if (cmp == 0) { cmp = memcmp(sol.knights, compare.knights, sizeof(unsigned long long) * MAX_GRID); if (cmp == 0) { state = STATE_SCRAP; break; } else { state = STATE_DUPLICATE; } } test = test->equal; } if (state == STATE_KEEP) { writeSolution(&sol, tidiedOutFile); } else if (state == STATE_DUPLICATE) { if (duplicatesOutFile == NULL) { duplicatesOutFile = mkSolDir(attack, coverage, knightNumber, duplicatesFile, false, false, 0); } writeSolution(&sol, duplicatesOutFile); } slot++; _fseeki64(inFile, slot->solutionOffset, SEEK_SET); } readSolution(&sol, inFile); count--; } fclose(inFile); fclose(tidiedOutFile); if (duplicatesOutFile != NULL) { fclose(duplicatesOutFile); } }
forceinline int seek(int64_t offset, int origin = SEEK_SET) { return _fseeki64(handle, offset, origin); }
int64 MadDecoder::getDurationMs(unsigned char* buffer, size_t bufferSize) { struct mad_stream madStream; struct mad_frame madFrame; struct mad_header madHeader; mad_timer_t time = mad_timer_zero; bool depadded = false; bool vbr = false; size_t tagsize = 0; size_t consumed = 0; size_t numFrames = 0; size_t initialBitrate = 0; mad_stream_init(&madStream); mad_header_init(&madHeader); mad_frame_init(&madFrame); do // Read data from the MP3 file { int padding = 0; size_t leftover = madStream.bufend - madStream.next_frame; memcpy(buffer, madStream.this_frame, leftover); int bytesRead = fread(buffer + leftover, (size_t)1, bufferSize - leftover, handle_); if (bytesRead <= 0) { break; } for (; !depadded && padding < bytesRead && !buffer[padding]; ++padding); depadded = true; mad_stream_buffer(&madStream, buffer + padding, leftover + bytesRead - padding); while (true) // decode frame headers { madStream.error = MAD_ERROR_NONE; if (mad_header_decode(&madHeader, &madStream) == -1) { if (madStream.error == MAD_ERROR_BUFLEN) // Normal behaviour; get some more data from the file break; if (MAD_RECOVERABLE(madStream.error) == 0) break; if (madStream.error == MAD_ERROR_LOSTSYNC) { unsigned available = (madStream.bufend - madStream.this_frame); tagsize = getId3TagSize(madStream.this_frame, (size_t)available); if (tagsize) // It's some ID3 tags, so just skip { if (tagsize >= available) { _fseeki64(handle_, (int64)(tagsize - available), SEEK_CUR); depadded = false; } mad_stream_skip(&madStream, std::min(tagsize, available)); } } continue; // not an audio frame } mad_timer_add(&time, madHeader.duration); consumed += madStream.next_frame - madStream.this_frame; if (numFrames == 0) { initialBitrate = madHeader.bitrate; // Get the precise frame count from the XING header if present madFrame.header = madHeader; if (mad_frame_decode(&madFrame, &madStream) == -1) { if (MAD_RECOVERABLE(madStream.error) == 0) { break; } } if ((numFrames = xingFrames(madStream.anc_ptr, madStream.anc_bitlen))) { mad_timer_multiply(&time, (signed long)numFrames); break; } } else { vbr |= madHeader.bitrate != initialBitrate; } // If not VBR, we can time just a few frames then extrapolate (not exact!) if (++numFrames == 25 && !vbr) { struct stat st; fstat(fileno(handle_), &st); timerMultiply(&time, (double)(st.st_size - tagsize) / consumed); break; } } // while(true) } while (madStream.error == MAD_ERROR_BUFLEN); mad_frame_finish(&madFrame); mad_header_finish(&madHeader); mad_stream_finish(&madStream); rewind(handle_); return mad_timer_count(time, MAD_UNITS_MILLISECONDS); }
VolumeRAM* VolumeDiskRaw::loadVolume() const throw (tgt::Exception) { VolumeRAM* volume = 0; LDEBUG("Creating volume from diskrepr. " << getFileName() << " format: " << getFormat()); VolumeFactory vf; try { volume = vf.create(getFormat(), getDimensions()); } catch (std::bad_alloc&) { throw tgt::Exception("bad allocation"); } if (!volume) throw VoreenException("Failed to create VolumeRAM"); FILE* fin; fin = fopen(getFileName().c_str(),"rb"); if (fin == 0) { throw tgt::IOException("Unable to open raw file for reading", getFileName()); } size_t bytesPerVoxel = static_cast<size_t>(volume->getBitsAllocated() / 8); size_t numVoxels = hmul(getDimensions()); size_t numBytes = numVoxels * bytesPerVoxel; int64_t offset = getOffset(); if(offset < 0) { //Assume data is aligned to end of file. // get file size: fseek(fin, 0, SEEK_END); int64_t fileSize = ftell(fin); rewind(fin); //calculate real offset: offset = fileSize - numBytes; } #ifdef _MSC_VER _fseeki64(fin, offset, SEEK_SET); #else fseek(fin, offset, SEEK_SET); #endif if(fread(reinterpret_cast<char*>(volume->getData()), numBytes, 1, fin) != 1) { //LERRORC("voreen.RepresentationConverterLoadFromDisk", "fread() failed"); fclose(fin); delete volume; throw tgt::FileException("Failed to read from file: " + getFileName()); } fclose(fin); if (getSwapEndian()) { Volume* tempHandle = new Volume(volume, vec3(1.0f), vec3(0.0f)); VolumeOperatorSwapEndianness::APPLY_OP(tempHandle); tempHandle->releaseAllRepresentations(); delete tempHandle; } return volume; }
long ZCALLBACK fseek64_file_func(voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) { return _fseeki64((FILE*)stream, offset, origin); }
err_type archive_extractFile(const char *archiveName, const char *fileName, const char *dirPathOut) { FILE *arch = NULL, *file = NULL; struct stat objInfo; err_type result; FileName outFileName; File_Header header; char buffer[_MAX_PATH]; if ((archiveName == NULL) || (fileName == NULL) || (dirPathOut == NULL)) return ERR_PARAM_INVALID; if ((result = _getStat(dirPathOut, &objInfo)) != ERR_NO) { if (result == ERR_FILE_NOTEXISTS) return ERR_DIR_NOTEXISTS; else return result; } if ((objInfo.st_mode & S_IFDIR) == 0) return ERR_DIR_NOTEXISTS; if ((objInfo.st_mode & S_IWRITE) == 0) return ERR_NOWRITEACCESS; if ((result = _getStat(archiveName, &objInfo)) != ERR_NO) return result; if ((objInfo.st_mode & S_IFREG) == 0) return ERR_FILE_NOTEXISTS; if ((objInfo.st_mode & S_IREAD) == 0) return ERR_NOREADACCESS; if ((arch = fopen(archiveName, "rb")) == NULL) return ERR_READ_FAILED; if ((result = arch_checkMarkerBlock(arch)) != ERR_NO) { fclose(arch); return result; } _splitpath(dirPathOut, outFileName.drive, outFileName.dir, outFileName.fName, outFileName.ext); strcat(strcat(strcat(outFileName.dir, outFileName.fName), outFileName.ext), "\\"); outFileName.fName[0] = 0; outFileName.ext[0] = 0; if ((result = arch_findFile(arch, fileName, &header)) == ERR_NO) { header.fileName[header.fileNameLength] = 0; if ((header.attr & S_IFREG) != 0) { _splitpath(header.fileName, NULL, NULL, outFileName.fName, outFileName.ext); _makepath(buffer, outFileName.drive, outFileName.dir, outFileName.fName, outFileName.ext); if ((file = fopen(buffer, "wb")) == NULL) { result = ERR_WRITE_FAILED; goto finalization; } if (header.method == 0) result = arch_extractFile(arch, file, header.fileSize); else result = arch_extractFileCompress(arch, file, header.fileSize); } else if ((header.attr & S_IFDIR) != 0) { char dirName[_MAX_PATH]; strcpy(dirName, header.fileName); do { header.fileName[header.fileNameLength] = 0; if (strstr(header.fileName, dirName) == header.fileName) { _makepath(buffer, outFileName.drive, outFileName.dir, outFileName.fName, outFileName.ext); strcat(buffer, header.fileName); if ((header.attr & S_IFREG) != 0) { if ((file = fopen(buffer, "wb")) == NULL) { result = ERR_WRITE_FAILED; goto finalization; } if (header.method == 0) result = arch_extractFile(arch, file, header.fileSize); else result = arch_extractFileCompress(arch, file, header.fileSize); fclose(file); if (result != ERR_NO) { goto finalization; } } else if ((header.attr & S_IFDIR) != 0) { mkdir(buffer); } else { result = ERR_UNKNOWN_FILETYPE; goto finalization; } } else if (header.fileSize != 0) { if (_fseeki64(arch, header.fileSize + sizeof(header.fileCrc), SEEK_CUR) != 0) { result = ERR_READ_FAILED; goto finalization; } if (fgetc(arch) != EOF) { if (_fseeki64(arch, -1, SEEK_CUR) != 0) { result = ERR_READ_FAILED; goto finalization; } } else break; } } while ((result = File_Header_fread(arch, &header)) == ERR_NO); result = ERR_NO; } else { result = ERR_UNKNOWN_FILETYPE; goto finalization; } } finalization: if (arch != NULL) fclose(arch); return result; }
bool CreateJNXJpeg(JPEG_tile_list& tiles, long minx, long maxx, long miny, long maxy, CString mapname, long tileWidth, long tileHeight, int nDatabase, int nDrawOrder) { CProgressWindow wndProgress; wndProgress.Initialize(); // ToFix as this ain't right! double dMetersPerPixel = (double) MyMap.GetMetresPerTile()/MyMap.GetPixelsPerTile(); int nTileWidth = MyMap.GetMetresPerTile(); // JKL's code to create the JPEGs // long width, height; // long x,y; unsigned char * bitmap_memory = NULL; long bitmap_width, dest_bitmap_width; long bitmap_height, dest_bitmap_height; long bitmap_memory_size; // long square_width; // long square_height; unsigned char bitmap_palette[1024]; long bitmap_palette_length; if (minx > maxx) { long t = minx; minx = maxx; maxx = t; } if (miny > maxy) { long t = miny; miny = maxy; maxy = t; } // long collar = CalculateCollar(minx*1000, maxx*1000, miny*1000, maxy*1000); long collar = CalculateCollar(minx, maxx, miny, maxy); minx -= (collar/1000)*1000; maxx += (collar/1000)*1000; miny -= (collar/1000)*1000; maxy += (collar/1000)*1000; wndProgress.ResetProgressBar("Tile:", ((maxy-miny)*(maxx-minx))/1000*1000); bool successful = false; if (nDatabase == DBASE_LOCAL) { if (MyMap.GetCountry() == COUNTRY_FR && MyMap.GetProduct() == PRODUCT_02) { successful = IGN_ReadTiles(minx, maxx, miny, maxy, wndProgress, bitmap_palette, bitmap_palette_length, bitmap_memory , bitmap_memory_size, bitmap_width, dest_bitmap_width, bitmap_height, dest_bitmap_height); } else { successful = OSPro_ReadTiles(minx, maxx, miny, maxy, wndProgress, bitmap_palette, bitmap_palette_length, bitmap_memory , bitmap_memory_size, bitmap_width, dest_bitmap_width, bitmap_height, dest_bitmap_height); } } else { bool b_use_TL3 = nDatabase == DBASE_TRACKLOGS_3; successful = ReadTracklogsTile(minx, maxx, miny, maxy, wndProgress, bitmap_palette, bitmap_palette_length, bitmap_memory , bitmap_memory_size, bitmap_width, dest_bitmap_width, bitmap_height, dest_bitmap_height, b_use_TL3); } // dest_bitmap_width = 400*(maxx-minx-2*collar/1000); // dest_bitmap_height = 400*(maxy-miny-2*collar/1000); dest_bitmap_width = nTileWidth*((maxx-minx-(2*collar))/1000); dest_bitmap_height = nTileWidth*((maxy-miny-(2*collar))/1000); if (!successful) { if (bitmap_memory) free(bitmap_memory); return false; } if (bitmap_memory == NULL) { printf("No images to process\n"); return false; } Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); CLSID encoderClsid; // Get the CLSID of the JPEG encoder. GetEncoderClsid(L"image/jpeg", &encoderClsid); Gdiplus::EncoderParameters encoderParameters; encoderParameters.Count = 1; ULONG quality = 80; encoderParameters.Parameter[0].Guid = Gdiplus::EncoderQuality; encoderParameters.Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong; encoderParameters.Parameter[0].NumberOfValues = 1; encoderParameters.Parameter[0].Value = &quality; // xy // 00 10 20 30 40 // 01 11 21 31 41 // 02 12 22 32 42 // 03 13 23 33 43 /* minx *= 1000; maxx *= 1000; miny *= 1000; maxy *= 1000; */ double lat,lon; OZIGEN_NorthingEasting_to_LatLon(maxy-collar, minx+collar, &lat, &lon); double minlat = lat; double maxlat = lat; double minlon = lon; double maxlon = lon; OZIGEN_NorthingEasting_to_LatLon(maxy-collar, maxx-collar, &lat, &lon); if (lat < minlat) minlat = lat; if (lat > maxlat) maxlat = lat; if (lon < minlon) minlon = lon; if (lon > maxlon) maxlon = lon; OZIGEN_NorthingEasting_to_LatLon(miny+collar, minx+collar, &lat, &lon); if (lat < minlat) minlat = lat; if (lat > maxlat) maxlat = lat; if (lon < minlon) minlon = lon; if (lon > maxlon) maxlon = lon; OZIGEN_NorthingEasting_to_LatLon(miny+collar, maxx-collar, &lat, &lon); if (lat < minlat) minlat = lat; if (lat > maxlat) maxlat = lat; if (lon < minlon) minlon = lon; if (lon > maxlon) maxlon = lon; OZIGEN_LatLon_to_NorthingEasting(minlat, minlon, &lat, &lon); OZIGEN_LatLon_to_NorthingEasting(minlat, maxlon, &lat, &lon); OZIGEN_LatLon_to_NorthingEasting(maxlat, maxlon, &lat, &lon); OZIGEN_LatLon_to_NorthingEasting(maxlat, minlon, &lat, &lon); char jnxName[512]; GetCurrentDirectory(sizeof(jnxName), jnxName); CString Currdir = jnxName; // Save current directory // change directory to %TEMP% and make folder 'files' GetTempPath(sizeof(jnxName), jnxName); SetCurrentDirectory(jnxName); CreateDirectory("files", NULL); // sprintf(jnxName, "%s\\%s.kmz", Currdir, mapname); long nTilesAcross=(dest_bitmap_width+(tileWidth-1))/tileWidth; long nTilesDown=(dest_bitmap_height+(tileHeight-1))/tileHeight; // KMZ_tiles tiles; - gone global long across, down; for (across=0; across<nTilesAcross; across++) { for (down=0; down<nTilesDown; down++) { JPEG_tile * pTile = new JPEG_tile; pTile->fname.Format("files/c%02d%02d.jpg", down, across); pTile->lat_north = minlat+(maxlat-minlat)*(nTilesDown-down)/nTilesDown; pTile->lon_east = minlon+(maxlon-minlon)*(across+1)/nTilesAcross; pTile->lat_south = minlat+(maxlat-minlat)*(nTilesDown-down-1)/nTilesDown; pTile->lon_west = minlon+(maxlon-minlon)*across/nTilesAcross; pTile->offset_x0 = dest_bitmap_width*across/nTilesAcross; pTile->offset_x1 = dest_bitmap_width*(across+1)/nTilesAcross; pTile->offset_y0 = dest_bitmap_height*down/nTilesDown; pTile->offset_y1 = dest_bitmap_height*(down+1)/nTilesDown; tiles.AddTail(pTile); } } Global_AddToResultsWindow("Number of tiles = %d",tiles.GetCount()); // SNL wndProgress.ResetProgressBar("JPEG:",tiles.GetCount()); long tileCount=0; long index = 1; POSITION pos; for (pos=tiles.GetHeadPosition(); pos != NULL; tiles.GetNext(pos)) { wndProgress.ProgressBar(); if (wndProgress.m_Cancelled) return false; JPEG_tile * pTile = (JPEG_tile *)tiles.GetAt(pos); Gdiplus::Rect r(0, 0, pTile->offset_x1-pTile->offset_x0, pTile->offset_y1-pTile->offset_y0); Gdiplus::Bitmap bmp(r.GetRight(), r.GetBottom(), PixelFormat24bppRGB ); Gdiplus::BitmapData bmpData; bmp.LockBits(&r, Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, PixelFormat24bppRGB, &bmpData); long x,y; for (y=pTile->offset_y0; y<pTile->offset_y1; y++) { lat = maxlat-(maxlat-minlat)/dest_bitmap_height*y; unsigned char * dest_bitmap_offset = ((unsigned char *)bmpData.Scan0) + bmpData.Stride*(y-pTile->offset_y0); for (x=pTile->offset_x0; x<pTile->offset_x1; x++) { lon = minlon+(maxlon-minlon)/dest_bitmap_width*x; double northing, easting; OZIGEN_LatLon_to_NorthingEasting(lat, lon, &northing, &easting); northing += 0.5; easting += 0.5; if (northing < miny || easting < minx || northing > maxy || easting > maxx) { // No bitmap data present -- white *dest_bitmap_offset++ = 255; *dest_bitmap_offset++ = 255; *dest_bitmap_offset++ = 255; } else { // Look up colour of bitmap pixel unsigned char * pal = bitmap_palette + 4*bitmap_memory[(long)((maxy-northing)/dMetersPerPixel)*bitmap_width + (long)((easting-minx)/dMetersPerPixel)]; *dest_bitmap_offset++ = pal[0]; *dest_bitmap_offset++ = pal[1]; *dest_bitmap_offset++ = pal[2]; } } } bmp.UnlockBits(&bmpData); wchar_t wbuffer[64]; int i; for (i=0; i<pTile->fname.GetLength(); i++) wbuffer[i] = pTile->fname.GetAt(i); wbuffer[i] = 0; bmp.Save(wbuffer, &encoderClsid, &encoderParameters); tileCount++; } SetCurrentDirectory(Currdir); // tiles.RemoveAll(); /* if (nPoints) { free(points); nPoints = 0; points = NULL; } */ Gdiplus::GdiplusShutdown(gdiplusToken); free(bitmap_memory); // Next bit from Map2JNX // up to five levels. nLevels gives the actual count static level_t levels[5]; // information about all files static std::list<file_t> files; // the JNX file header to be copied to the outfile static jnx_hdr_t jnx_hdr; // the tile information table for all 5 levels static jnx_tile_t tileTable[JNX_MAX_TILES * 5]; const uint8_t dummy = 0; uint32_t tileTableStart = 0; uint32_t tileCnt = 0; const char *jnx_copyright = "Unknown"; const char *jnx_subscname = "BirdsEye"; const char *jnx_mapname = "Unknown"; char *copyright_buf = NULL; char *subscname_buf = NULL; char *mapname_buf = NULL; double right = -180.0; double top = -90.0; double left = 180.0; double bottom = 90.0; double scale = 0.0; // Number of used levels static int32_t nLevels = 1; FILE * fid = fopen(mapname+".jnx","wb"); if(fid == 0) { // Failed to create file. return false; } // New code writer start // POSITION pos; for (pos=tiles.GetHeadPosition(); pos != NULL; tiles.GetNext(pos)) { JPEG_tile * pTile = (JPEG_tile *)tiles.GetAt(pos); if (left > pTile->lon_west) left = pTile->lon_west; if (right < pTile->lon_east) right = pTile->lon_east; if (top < pTile->lat_north) top = pTile->lat_north; if (bottom > pTile->lat_south) bottom = pTile->lat_south; } nLevels = 1; // New code writer end jnx_hdr.zorder = nDrawOrder; jnx_hdr.left = (int32_t)((left * 0x7FFFFFFF) / 180); jnx_hdr.top = (int32_t)((top * 0x7FFFFFFF) / 180); jnx_hdr.right = (int32_t)((right * 0x7FFFFFFF) / 180); jnx_hdr.bottom = (int32_t)((bottom * 0x7FFFFFFF) / 180); jnx_hdr.details = nLevels; for(int i=0; i<HEADER_BLOCK_SIZE; i++) { fwrite(&dummy, sizeof(dummy), 1, fid); } _fseeki64(fid,0,SEEK_SET); fwrite(&jnx_hdr, sizeof(jnx_hdr), 1, fid); // get all information to write the table of detail levels and the dummy tile table int i=0; level_t& level = levels[i]; level.nTiles = tiles.GetCount(); level.offset = HEADER_BLOCK_SIZE; // still has to be offset by complete header level.scale = 1509; fwrite(&level.nTiles, sizeof(level.nTiles), 1, fid); fwrite(&level.offset, sizeof(level.offset), 1, fid); fwrite(&level.scale, sizeof(level.scale), 1, fid); fwrite(&level.dummy, sizeof(level.dummy), 1, fid); fwrite(jnx_copyright, strlen(jnx_copyright) + 1, 1, fid); // printf("\n Level %i: % 5i tiles, offset %08X, scale: %i, %ix%i", i, level.nTiles, level.offset, level.scale, level.tileSize, level.tileSize); // write map loader info block uint32_t blockVersion = 0x00000009; char GUID[40]; createGUID(GUID); fwrite(&blockVersion, sizeof(blockVersion), 1, fid); fwrite(GUID, 37, 1, fid); fwrite(jnx_subscname, strlen(jnx_subscname) + 1, 1, fid); fwrite(&dummy, sizeof(dummy), 1, fid); fwrite(&dummy, sizeof(dummy), 1, fid); fwrite(&dummy, sizeof(dummy), 1, fid); fwrite(jnx_mapname, strlen(jnx_mapname) + 1, 1, fid); fwrite(&nLevels , sizeof(nLevels), 1, fid); for(int i = 1; i <= nLevels; i++) { char str[40]; sprintf(str,"Level %i", i); fwrite(str, strlen(str) + 1, 1, fid); fwrite(str, strlen(str) + 1, 1, fid); fwrite(jnx_copyright, strlen(jnx_copyright) + 1, 1, fid); fwrite(&i,sizeof(i), 1, fid); } // write dummy tile table tileTableStart = HEADER_BLOCK_SIZE; _fseeki64(fid, tileTableStart, SEEK_SET); fwrite(tileTable, sizeof(jnx_tile_t), tileCount, fid); // New code writer start char TempPath[512]; GetTempPath(sizeof(TempPath), TempPath); CString tPath = TempPath; tPath = tPath + "\\"; wndProgress.ResetProgressBar("JNX:",tiles.GetCount()); for (pos=tiles.GetHeadPosition(); pos != NULL; tiles.GetNext(pos)) { JPEG_tile * pTile = (JPEG_tile *)tiles.GetAt(pos); // printf("JPEG %d of %d\r", tileCnt, tiles.GetCount()); jnx_tile_t& tile = tileTable[tileCnt++]; tile.left = (int32_t)(pTile->lon_west * 0x7FFFFFFF / 180); tile.top = (int32_t)(pTile->lat_north * 0x7FFFFFFF / 180); tile.right = (int32_t)(pTile->lon_east * 0x7FFFFFFF / 180); tile.bottom = (int32_t)(pTile->lat_south * 0x7FFFFFFF / 180); tile.width = (uint16_t)(pTile->offset_x1-pTile->offset_x0); tile.height = (uint16_t)(pTile->offset_y1-pTile->offset_y0); tile.offset = (uint32_t)(_ftelli64(fid) & 0x0FFFFFFFF); tile.size = appendJPG(tPath + pTile->fname, fid); } // New code writer end // terminate output file fwrite("BirdsEye", 8, 1, fid); // write final tile table _fseeki64(fid, tileTableStart, SEEK_SET); fwrite(tileTable, sizeof(jnx_tile_t), tileCount, fid); // done fclose(fid); exit_CreateJNXJpeg: // Clean up if (copyright_buf) free(copyright_buf); if (subscname_buf) free(subscname_buf); if (mapname_buf) free(mapname_buf); //POSITION pos; for (pos=tiles.GetHeadPosition(); pos != NULL; tiles.GetNext(pos)) { JPEG_tile * pTile = (JPEG_tile *)tiles.GetAt(pos); DeleteFile(pTile->fname); } tiles.RemoveAll(); return true; }
bool FileManager::loadFileData(Document doc, const TCHAR * filename, Utf8_16_Read * UnicodeConvertor, LangType language, int & encoding, formatType *pFormat) { const int blockSize = 128 * 1024; //128 kB char data[blockSize+8]; FILE *fp = generic_fopen(filename, TEXT("rb")); if (!fp) return false; //Get file size _fseeki64 (fp , 0 , SEEK_END); unsigned __int64 fileSize =_ftelli64(fp); rewind(fp); // size/6 is the normal room Scintilla keeps for editing, but here we limit it to 1MiB when loading (maybe we want to load big files without editing them too much) unsigned __int64 bufferSizeRequested = fileSize + min(1<<20,fileSize/6); // As a 32bit application, we cannot allocate 2 buffer of more than INT_MAX size (it takes the whole address space) if(bufferSizeRequested > INT_MAX) { ::MessageBox(NULL, TEXT("File is too big to be opened by Notepad++"), TEXT("File open problem"), MB_OK|MB_APPLMODAL); /* _nativeLangSpeaker.messageBox("NbFileToOpenImportantWarning", _pPublicInterface->getHSelf(), TEXT("File is too big to be opened by Notepad++"), TEXT("File open problem"), MB_OK|MB_APPLMODAL); */ fclose(fp); return false; } //Setup scratchtilla for new filedata _pscratchTilla->execute(SCI_SETSTATUS, SC_STATUS_OK); // reset error status _pscratchTilla->execute(SCI_SETDOCPOINTER, 0, doc); bool ro = _pscratchTilla->execute(SCI_GETREADONLY) != 0; if (ro) { _pscratchTilla->execute(SCI_SETREADONLY, false); } _pscratchTilla->execute(SCI_CLEARALL); #ifdef UNICODE WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance(); #endif if (language < L_EXTERNAL) { _pscratchTilla->execute(SCI_SETLEXER, ScintillaEditView::langNames[language].lexerID); } else { int id = language - L_EXTERNAL; TCHAR * name = NppParameters::getInstance()->getELCFromIndex(id)._name; #ifdef UNICODE const char *pName = wmc->wchar2char(name, CP_ACP); #else const char *pName = name; #endif _pscratchTilla->execute(SCI_SETLEXERLANGUAGE, 0, (LPARAM)pName); } if (encoding != -1) { _pscratchTilla->execute(SCI_SETCODEPAGE, SC_CP_UTF8); } bool success = true; int format = -1; __try { // First allocate enough memory for the whole file (this will reduce memory copy during loading) _pscratchTilla->execute(SCI_ALLOCATE, WPARAM(bufferSizeRequested)); if(_pscratchTilla->execute(SCI_GETSTATUS) != SC_STATUS_OK) throw; size_t lenFile = 0; size_t lenConvert = 0; //just in case conversion results in 0, but file not empty bool isFirstTime = true; int incompleteMultibyteChar = 0; do { lenFile = fread(data+incompleteMultibyteChar, 1, blockSize-incompleteMultibyteChar, fp) + incompleteMultibyteChar; // check if file contain any BOM if (isFirstTime) { if (Utf8_16_Read::determineEncoding((unsigned char *)data, lenFile) != uni8Bit) { // if file contains any BOM, then encoding will be erased, // and the document will be interpreted as UTF encoding = -1; } isFirstTime = false; } if (encoding != -1) { if (encoding == SC_CP_UTF8) { // Pass through UTF-8 (this does not check validity of characters, thus inserting a multi-byte character in two halfs is working) _pscratchTilla->execute(SCI_APPENDTEXT, lenFile, (LPARAM)data); } else { WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance(); int newDataLen = 0; const char *newData = wmc->encode(encoding, SC_CP_UTF8, data, lenFile, &newDataLen, &incompleteMultibyteChar); _pscratchTilla->execute(SCI_APPENDTEXT, newDataLen, (LPARAM)newData); } if (format == -1) format = getEOLFormatForm(data); } else { lenConvert = UnicodeConvertor->convert(data, lenFile); _pscratchTilla->execute(SCI_APPENDTEXT, lenConvert, (LPARAM)(UnicodeConvertor->getNewBuf())); } if(_pscratchTilla->execute(SCI_GETSTATUS) != SC_STATUS_OK) throw; if(incompleteMultibyteChar != 0) { // copy bytes to next buffer memcpy(data, data+blockSize-incompleteMultibyteChar, incompleteMultibyteChar); } } while (lenFile > 0); } __except(int e) { //TODO: should filter correctly for other exceptions; the old filter(GetExceptionCode(), GetExceptionInformation()) was only catching access violations ::MessageBox(NULL, TEXT("File is too big to be opened by Notepad++"), TEXT("File open problem"), MB_OK|MB_APPLMODAL); success = false; }
void CompressedFile::seekInPackage(u32 offset) { _fseeki64(m_package->m_stream, m_offset + offset, SEEK_SET); m_package->m_lastSeekFile = this; }
int64_t retro_vfs_file_seek_internal(libretro_vfs_implementation_file *stream, int64_t offset, int whence) { if (!stream) goto error; if ((stream->hints & RFILE_HINT_UNBUFFERED) == 0) /* VC2005 and up have a special 64-bit fseek */ #ifdef ATLEAST_VC2005 return _fseeki64(stream->fp, offset, whence); #elif defined(__CELLOS_LV2__) || defined(_MSC_VER) && _MSC_VER <= 1310 return fseek(stream->fp, (long)offset, whence); #elif defined(PS2) return fioLseek(fileno(stream->fp), (off_t)offset, whence); #else return fseeko(stream->fp, (off_t)offset, whence); #endif #ifdef HAVE_MMAP /* Need to check stream->mapped because this function is * called in filestream_open() */ if (stream->mapped && stream->hints & RETRO_VFS_FILE_ACCESS_HINT_FREQUENT_ACCESS) { /* fseek() returns error on under/overflow but * allows cursor > EOF for read-only file descriptors. */ switch (whence) { case SEEK_SET: if (offset < 0) goto error; stream->mappos = offset; break; case SEEK_CUR: if ((offset < 0 && stream->mappos + offset > stream->mappos) || (offset > 0 && stream->mappos + offset < stream->mappos)) goto error; stream->mappos += offset; break; case SEEK_END: if (stream->mapsize + offset < stream->mapsize) goto error; stream->mappos = stream->mapsize + offset; break; } return stream->mappos; } #endif if (lseek(stream->fd, offset, whence) < 0) goto error; return 0; error: return -1; }
VolumeRepresentation* RepresentationConverterLoadFromDisk::convert(const VolumeRepresentation* source) const { const VolumeDisk* dr = dynamic_cast<const VolumeDisk*>(source); if(dr) { VolumeRAM* volume = 0; LDEBUGC("voreen.RepresentationConverterLoadFromDisk", "creating volume from diskrepr. " << dr->getFileName() << " format: " << dr->getFormat()); VolumeFactory vf; volume = vf.create(dr->getFormat(), dr->getDimensions()); if(!volume) return 0; FILE* fin; fin = fopen(dr->getFileName().c_str(),"rb"); if (fin == 0) throw tgt::IOException("Unable to open raw file for reading", dr->getFileName()); size_t bytesPerVoxel = static_cast<size_t>(volume->getBitsAllocated() / 8); size_t numVoxels = hmul(dr->getDimensions()); size_t numBytes = numVoxels * bytesPerVoxel; int64_t offset = dr->getOffset(); if(offset < 0) { //Assume data is aligned to end of file. // get file size: fseek(fin, 0, SEEK_END); int64_t fileSize = ftell(fin); rewind(fin); //calculate real offset: offset = fileSize - numBytes; } #ifdef _MSC_VER _fseeki64(fin, offset, SEEK_SET); #else fseek(fin, offset, SEEK_SET); #endif if(fread(reinterpret_cast<char*>(volume->getData()), numBytes, 1, fin) != 1) { LERRORC("voreen.RepresentationConverterLoadFromDisk", "fread() failed"); fclose(fin); delete volume; return 0; } fclose(fin); if(dr->getSwapEndian()) { Volume* tempHandle = new Volume(volume, vec3(1.0f), vec3(0.0f)); VolumeOperatorSwapEndianness::APPLY_OP(tempHandle); tempHandle->releaseAllRepresentations(); } return volume; } else { //should have checked before... //LERROR("Failed to convert!"); return 0; } }
extern "C" DLL_EXPORT int getFileVerify(std::vector<std::string> &infile, std::vector<Result> &outre) { __int64 finishedSize = 0; std::vector<__int64> fSizes(infile.size()); std::string strFileSize; std::string strFileMD5; std::string strFileSHA1; std::string strFileSHA256; std::string strFileCRC32; //开始计算,循环处理每个文件 for (int i = 0; i < infile.size(); i++) { // Declaration for calculator char* path = const_cast<char*>(infile[i].c_str()); __int64 fsize = 0; finishedSize = 0; DataBuffer databuf; MD5_CTX mdContext; // MD5 context CSHA1 sha1; // SHA1 object char strSHA1[256]; SHA256_CTX sha256Ctx; // SHA256 context std::string strSHA256 =""; unsigned long ulCRC32; // CRC32 context ResultData result; result.strPath = infile[i]; //打开文件 FILE *fp = fopen(infile[i].c_str(), "rb+"); if (fp != NULL) { //成功打开文件 MD5Init(&mdContext, 0); // MD5开始 sha1.Reset(); // SHA1开始 sha256_init(&sha256Ctx); // SHA256开始 crc32Init(&ulCRC32); // CRC32开始 //获取文件信息 std::string lastModifiedTime; struct _stat64 info; _wstat64(AnsiToUnicode(infile[i].c_str()), &info); fsize = info.st_size; API_TimeToStringEX(lastModifiedTime, info.st_mtime); do { //读取文件 databuf.datalen = fread(databuf.data, 1, DataBuffer::preflen, fp); MD5Update(&mdContext, databuf.data, databuf.datalen); // MD5更新 sha1.Update(databuf.data, databuf.datalen); // SHA1更新 sha256_update(&sha256Ctx, databuf.data, databuf.datalen); // SHA256更新 crc32Update(&ulCRC32, databuf.data, databuf.datalen); // CRC32更新 finishedSize += databuf.datalen; //设置偏移 if (databuf.datalen >= DataBuffer::preflen) _fseeki64(fp, finishedSize, SEEK_SET); } while (databuf.datalen >= DataBuffer::preflen); fclose(fp);//关闭文件 MD5Final(&mdContext); // MD5完成 sha1.Final(); // SHA1完成 sha256_final(&sha256Ctx); // SHA256完成 crc32Finish(&ulCRC32); //CRC32完成 //格式化校验码 char _tempmd5[256] = { '\0' }; sprintf(_tempmd5, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mdContext.digest[0], mdContext.digest[1], mdContext.digest[2], mdContext.digest[3], mdContext.digest[4], mdContext.digest[5], mdContext.digest[6], mdContext.digest[7], mdContext.digest[8], mdContext.digest[9], mdContext.digest[10], mdContext.digest[11], mdContext.digest[12], mdContext.digest[13], mdContext.digest[14], mdContext.digest[15]); strFileMD5 = _tempmd5; sha1.ReportHash(strSHA1, CSHA1::REPORT_HEX); strFileSHA1 = (strSHA1); sha256_digest(&sha256Ctx, &strSHA256); strFileSHA256 = strSHA256; //strFileCRC32.Format(_T("%08X"), ulCRC32); char _tempcrc[128] = { '\0' }; sprintf(_tempcrc, "%08X", ulCRC32); strFileCRC32 = _tempcrc; result.bDone = TRUE; result.strPath = infile[i]; result.ulSize = fsize; result.strMDate = lastModifiedTime; // 在没做转换前,结果都是大写的 result.strMD5 = strFileMD5; result.strSHA1 = strFileSHA1; result.strSHA256 = strFileSHA256; result.strCRC32 = strFileCRC32; //转换大小写 } else { result.bDone = FALSE; result.strError = "Open file error"; } outre.push_back(result); } return 0; }
int fill_context(HWND hwnd,int ctrl,FILE *f) { char buf[512]; int i,len,count; __int64 offset,line; offset=_ftelli64(f); if(binary){ current_line=offset; line=offset-(line_count/2)*16; if(line<0)line=0; _fseeki64(f,line,SEEK_SET); fill_line_col(hwnd,IDC_ROWNUMBER,line); } else{ count=seek_line_relative(f,line_count/2,-1); line=current_line-count; if(line<=0) line=1; if(current_line<=0) current_line=1; fill_line_col(hwnd,IDC_ROWNUMBER,line); } SendDlgItemMessage(hwnd,ctrl,EM_GETSEL,&edit_sel_pos,0); SetDlgItemText(hwnd,ctrl,""); for(i=0;i<line_count;i++){ buf[0]=0; if(binary){ len=fread(buf,1,16,f); if(len<=0) break; buf[16]=0; format_hex_str(buf,len,buf+16,sizeof(buf)-16); strncpy(buf,buf+16,sizeof(buf)); len=strlen(buf); } else{ __int64 pos=0; int buf_size=sizeof(buf); pos=_ftelli64(f); if(fgets(buf,buf_size-1,f)==0) break; buf[buf_size-1]=0; pos=_ftelli64(f)-pos; len=(int)pos; if(len>buf_size-1) len=buf_size-1; sanitize_str(buf,len); if(buf[len-1]!='\n'){ char *s=buf+buf_size-3; purge_string(f,0x10000); if(len>buf_size-3) s=buf+buf_size-3; else s=buf+len-3; s[0]='\r'; s[1]='\n'; s[2]=0; } } add_line(hwnd,ctrl,buf); } SendDlgItemMessage(hwnd,ctrl,EM_SETSEL,edit_sel_pos,edit_sel_pos); _fseeki64(f,offset,SEEK_SET); return TRUE; }