pax_global_header00006660000000000000000000000064146213314120014507gustar00rootroot0000000000000052 comment=40b2b14993b92980af1339145de3203432f036e5 bcmatroska2-5.3.101/000077500000000000000000000000001462133141200140665ustar00rootroot00000000000000bcmatroska2-5.3.101/.gitignore000066400000000000000000000001361462133141200160560ustar00rootroot00000000000000*_stdafx.[ch] *_project.h *.mak *.a GNUmakefile /release/ /spectool/spec.xml bcmatroska2.spec bcmatroska2-5.3.101/BCMatroska2Config.cmake.in000066400000000000000000000033401462133141200206730ustar00rootroot00000000000000############################################################################ # BCMatroska2Config.cmake # Copyright (C) 2015-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ # # Config file for the bcmatroska2 package. # # Targets # ^^^^^^^ # # The following targets are defined: # bcmatroska2 - The bcmatroska2 library target # # # Result variables # ^^^^^^^^^^^^^^^^ # # This config file will set the following variables in your project: # # BCMatroska2_FOUND - The bcmatroska2 library has been found # BCMatroska2_TARGET - The name of the CMake target for the bcmatroska2 library @PACKAGE_INIT@ include("${CMAKE_CURRENT_LIST_DIR}/BCMatroska2Targets.cmake") set(BCMatroska2_TARGET bcmatroska2) # We must propagate the public dependencies and the private dependencies for static build include(CMakeFindDependencyMacro) find_dependency(BCToolbox) check_required_components(BCMatroska2) bcmatroska2-5.3.101/CMakeLists.txt000066400000000000000000000057321462133141200166350ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2016-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ cmake_minimum_required(VERSION 3.1) project(BCMatroska2 VERSION 0.23 LANGUAGES C ) option(CONFIG_EBML_WRITING "Enable EBML file writing support" ON) option(CONFIG_EBML_UNICODE "Enable Unicode support" ON) option(CONFIG_DEBUGCHECKS "Enable internal checks" ON) option(CONFIG_STDIO "Use stdio.h for writing" ON) #option(CONFIG_FILEPOS_64 "Encode filepos_t on 64bits" ON) option(CONFIG_DEBUG_LEAKS "Enable internal menory leaks checking support" OFF) include(GNUInstallDirs) if(NOT CMAKE_INSTALL_RPATH AND CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}) message(STATUS "Setting install rpath to ${CMAKE_INSTALL_RPATH}") endif() if( CMAKE_SIZEOF_VOID_P EQUAL 8 ) set(CONFIG_64BITS_SYSTEM 1) endif() configure_file(config.h.cmake ${PROJECT_BINARY_DIR}/bcmatroska2_config.h) find_package(BCToolbox 5.3.0 REQUIRED) include_directories( ${PROJECT_BINARY_DIR} corec ) if(WIN32) add_compile_definitions( "EBML2_EXPORTS" "MATROSKA2_EXPORTS" "STR_EXPORTS" ) endif() add_compile_options(-w) add_subdirectory(corec/corec) add_subdirectory(libebml2) add_subdirectory(libmatroska2) install(FILES ${PROJECT_BINARY_DIR}/bcmatroska2_config.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec ) add_subdirectory(build) include(CMakePackageConfigHelpers) set(CMAKE_MODULES_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME}/cmake") configure_package_config_file("${PROJECT_NAME}Config.cmake.in" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" INSTALL_DESTINATION "${CMAKE_MODULES_INSTALL_DIR}" NO_SET_AND_CHECK_MACRO ) write_basic_package_version_file("${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION ${CMAKE_MODULES_INSTALL_DIR} ) install(EXPORT ${PROJECT_NAME}Targets FILE "${PROJECT_NAME}Targets.cmake" DESTINATION ${CMAKE_MODULES_INSTALL_DIR} ) bcmatroska2-5.3.101/Makefile000066400000000000000000000020351462133141200155260ustar00rootroot00000000000000PREFIX=/usr/local DEBUG=0 COREMAKE=./corec/tools/coremake/coremake bits_64=$(shell uname -a | grep x86_64) os_linux=$(shell uname -a | grep Linux) os_mac=$(shell uname -a |grep Darwin) os_mingw32=$(shell uname -a |grep MINGW32) ifneq ($(os_linux),) os=linux endif ifneq ($(os_mac),) os=osx endif ifneq ($(os_mingw32),) os=win32 endif ifneq ($(bits_64),) bits=_x64 endif ifeq ($(DEBUG), 1) debug=_debug endif flavor=gcc_$(os)$(bits)$(debug) libs=release/$(flavor)/libebml2.a release/$(flavor)/libmatroska2.a all: GNUmakefile $(MAKE) -f GNUmakefile $(COREMAKE): cd ./corec/tools/coremake/ && make GNUmakefile: $(COREMAKE) $(COREMAKE) $(flavor) install: mkdir -p $(DESTDIR)/$(PREFIX) cp -rf ./libmatroska2/matroska $(DESTDIR)/$(PREFIX)/include/. cp -rf ./corec/corec $(DESTDIR)/$(PREFIX)/include/. cp -rf ./libebml2/ebml $(DESTDIR)/$(PREFIX)/include/. cp -f ./config.h $(DESTDIR)/$(PREFIX)/include/corec/. cp -f ./corec/tools/coremake/config_helper.h $(DESTDIR)/$(PREFIX)/include/corec/. cp -rf $(libs) $(DESTDIR)/$(PREFIX)/lib/. bcmatroska2-5.3.101/build/000077500000000000000000000000001462133141200151655ustar00rootroot00000000000000bcmatroska2-5.3.101/build/CMakeLists.txt000066400000000000000000000034451462133141200177330ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2018-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ if(NOT CPACK_PACKAGE_NAME) string(TOLOWER "${PROJECT_NAME}" LOWERCASE_PROJECT_NAME) set(CPACK_PACKAGE_NAME "${LOWERCASE_PROJECT_NAME}") ENDIF() set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) set(CPACK_PACKAGE_FILE_NAME ${CPACK_PACKAGE_NAME}-${PROJECT_VERSION}) set(CPACK_SOURCE_GENERATOR "TGZ") set(CPACK_SOURCE_IGNORE_FILES "${CMAKE_BINARY_DIR}" "^${PROJECT_SOURCE_DIR}/.git*" ) message("-- Package file name is ${CPACK_PACKAGE_FILE_NAME}") set(CPACK_SOURCE_PACKAGE_FILE_NAME ${CPACK_PACKAGE_FILE_NAME}) if(UNIX AND NOT APPLE AND NOT ANDROID) configure_file("rpm/bcmatroska2.spec.cmake" "${PROJECT_SOURCE_DIR}/bcmatroska2.spec" @ONLY) endif() include(CPack) bcmatroska2-5.3.101/build/rpm/000077500000000000000000000000001462133141200157635ustar00rootroot00000000000000bcmatroska2-5.3.101/build/rpm/bcmatroska2.spec.cmake000077500000000000000000000054411462133141200221350ustar00rootroot00000000000000# -*- rpm-spec -*- %define _prefix @CMAKE_INSTALL_PREFIX@ %define pkg_prefix @BC_PACKAGE_NAME_PREFIX@ %define _datarootdir %{_prefix}/share %define _datadir %{_datarootdir} %define build_number 1 Name: @CPACK_PACKAGE_NAME@ Version: @PROJECT_VERSION@ Release: %{build_number}%{?dist} Summary: A libary to parse Matroska files (.mkv and .mka) Group: Applications/Multimedia License: BSD-3 Source0: %{name}-%{version}.tar.gz BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot Requires: %{pkg_prefix}bctoolbox %description A libary to parse Matroska files (.mkv and .mka). %package devel Summary: Headers, libraries and docs for the bcmatroska2 library Group: Development/Libraries Requires: %{name} = %{version} %description devel A libary to parse Matroska files (.mkv and .mka). This package contains header files and development libraries needed to develop programs using the bcmatroska2 library. %if 0%{?rhel} && 0%{?rhel} <= 7 %global cmake_name cmake3 %define ctest_name ctest3 %else %global cmake_name cmake %define ctest_name ctest %endif # This is for debian builds where debug_package has to be manually specified, whereas in centos it does not %define custom_debug_package %{!?_enable_debug_packages:%debug_package}%{?_enable_debug_package:%{nil}} %custom_debug_package %prep %setup -n %{name}-%{version} %build %{expand:%%%cmake_name} . -DCMAKE_BUILD_TYPE=@CMAKE_BUILD_TYPE@ -DCMAKE_PREFIX_PATH:PATH=%{_prefix} make %{?_smp_mflags} %install make install DESTDIR=%{buildroot} # Dirty workaround to give exec rights for all shared libraries. Debian packaging needs this # TODO : set CMAKE_INSTALL_SO_NO_EXE for a cleaner workaround chmod +x `find %{buildroot} *.so.*` %check %{ctest_name} -V %{?_smp_mflags} %clean rm -rf $RPM_BUILD_ROOT %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-,root,root,-) %{_libdir}/*.so.* %files devel %defattr(-,root,root,-) %{_includedir}/corec/*.h %{_includedir}/corec/array/*.h %{_includedir}/corec/helpers/charconvert/*.h %{_includedir}/corec/helpers/date/*.h %{_includedir}/corec/helpers/file/*.h %{_includedir}/corec/helpers/md5/*.h %{_includedir}/corec/helpers/parser/*.h %{_includedir}/corec/helpers/system/*.h %{_includedir}/corec/multithread/*.h %{_includedir}/corec/node/*.h %{_includedir}/corec/str/*.h %{_includedir}/ebml/*.h %{_includedir}/matroska/*.h %{_datadir}/bcmatroska2/cmake/*.cmake %if @ENABLE_STATIC@ %{_libdir}/*.a %endif %if @ENABLE_SHARED@ %{_libdir}/*.so %endif %changelog * Tue Nov 27 2018 ronan.abhamon - Do not set CMAKE_INSTALL_LIBDIR and never with _libdir! * Tue Mar 13 2018 ronan.abhamon - Initial RPM release. bcmatroska2-5.3.101/config.h000066400000000000000000000005171462133141200155070ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE #define CONFIG_EBML_WRITING #define CONFIG_EBML_UNICODE #define HAVE_EBML2 #define CONFIG_ZLIB #define CONFIG_MATROSKA2 #define USE_PRECOMPILED_HEADERS #define CONFIG_DEBUGCHECKS #define CONFIG_STDIO #define CONFIG_FILEPOS_64 #define COREMAKE_CONFIG_HELPER //#define CONFIG_DEBUG_LEAKS bcmatroska2-5.3.101/config.h.cmake000066400000000000000000000006571462133141200165730ustar00rootroot00000000000000#cmakedefine CONFIG_EBML_WRITING #cmakedefine CONFIG_EBML_UNICODE #cmakedefine CONFIG_DEBUGCHECKS #cmakedefine CONFIG_STDIO #cmakedefine CONFIG_DEBUG_LEAKS #cmakedefine CONFIG_64BITS_SYSTEM #if (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) || defined(CONFIG_64BITS_SYSTEM) /* Use CONFIG_FILEPOS_64 only on 64 bits systems or 32 bits systems that have _FILE_OFFSET_BITS set to 64. */ #define CONFIG_FILEPOS_64 1 #endif bcmatroska2-5.3.101/corec/000077500000000000000000000000001462133141200151615ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec.proj000066400000000000000000000001101462133141200171400ustar00rootroot00000000000000CONFIG_FILE config.h PLATFORM_FILES tools/coremake #include "*/*.proj" bcmatroska2-5.3.101/corec/corec/000077500000000000000000000000001462133141200162545ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/CMakeLists.txt000066400000000000000000000100251462133141200210120ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2016 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ set(COREC_SOURCES array/array.c helpers/file/bufstream.c helpers/file/memstream.c helpers/file/streams.c helpers/file/tools.c helpers/md5/md5.c helpers/parser/parser2.c helpers/parser/strtab.c helpers/parser/strtypes.c helpers/parser/dataheap.c helpers/parser/buffer.c helpers/parser/hotkey.c helpers/parser/nodelookup.c helpers/parser/urlpart.c node/node.c node/nodetree.c str/str.c ) if(WIN32) list(APPEND COREC_SOURCES helpers/charconvert/charconvert_win32.c helpers/date/date_win32.c helpers/file/file_bctbx_win32.c helpers/system/ccsystem_win32.c multithread/multithread_win32.c str/str_win32.c ) else() list(APPEND COREC_SOURCES helpers/date/date_libc.c helpers/file/file_bctbx.c multithread/multithread_pthread.c ) if (NOT IOS) list(APPEND COREC_SOURCES helpers/system/ccsystem_posix.c ) endif() if(APPLE) list(APPEND COREC_SOURCES helpers/charconvert/charconvert_osx.c str/str_osx.c ) elseif(ANDROID) list(APPEND COREC_SOURCES helpers/charconvert/charconvert_utf8.c str/str_linux.c ) elseif(QNX) list(APPEND COREC_SOURCES helpers/charconvert/charconvert_utf8.c str/str_utf8.c ) else() list(APPEND COREC_SOURCES helpers/charconvert/charconvert_linux.c str/str_linux.c ) endif() endif() if(CONFIG_STDIO) list(APPEND COREC_SOURCES helpers/file/stream_stdio.c ) endif() add_library(bcmatroska2-corec-objects OBJECT ${COREC_SOURCES}) set_target_properties(bcmatroska2-corec-objects PROPERTIES POSITION_INDEPENDENT_CODE TRUE) target_include_directories(bcmatroska2-corec-objects PRIVATE $) install(FILES banned.h confhelper.h corec.h err.h helper.h memalloc.h memheap.h portab.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec ) install(FILES array/array.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/array) install(FILES helpers/charconvert/charconvert.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/charconvert) install(FILES helpers/date/date.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/date) install(FILES helpers/file/file.h helpers/file/streams.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/file ) install(FILES helpers/md5/md5.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/md5) install(FILES helpers/parser/buffer.h helpers/parser/dataheap.h helpers/parser/hotkey.h helpers/parser/nodelookup.h helpers/parser/parser.h helpers/parser/strtab.h helpers/parser/strtypes.h helpers/parser/urlpart.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/parser ) install(FILES helpers/system/ccsystem.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/helpers/system) install(FILES multithread/multithread.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/multithread) install(FILES node/node.h node/node_internal.h node/nodebase.h node/nodetools.h node/nodetree.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/node ) install(FILES str/str.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/corec/str) bcmatroska2-5.3.101/corec/corec/array/000077500000000000000000000000001462133141200173725ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/array/array.c000066400000000000000000000351241462133141200206610ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "array.h" typedef struct datahead { size_t Size; } datahead; #define Data_Head(Name) ((datahead*)(Name)-1) #define Data_HeapHead(Name) ((dataheaphead*)(Name)-1) #define Data_IsHeap(Name) (Data_Head(Name)->Size & DATA_FLAG_HEAP) #define Data_IsMemHeap(Name) (Data_Head(Name)->Size & DATA_FLAG_MEMHEAP) #define Data_GetSize(Name) (Data_Head(Name)->Size & ~(DATA_FLAG_HEAP|DATA_FLAG_MEMHEAP)) size_t Data_Size(const uint8_t* a) { if (!a) return 0; return Data_GetSize(a); } NOINLINE bool_t Data_ReAlloc(uint8_t** a,size_t n) { uint8_t* p = *a; size_t oldsize; if (p) { if (!Data_Head(p)->Size) // const? return 0; oldsize = Data_GetSize(p); } else oldsize = 0; if (oldsizeHeap; dataheaphead* Head; if (!oldsize) Head = MemHeap_Alloc(Heap,n+sizeof(dataheaphead),0); else Head = MemHeap_ReAlloc(Heap,Data_HeapHead(p),oldsize+sizeof(dataheaphead),n+sizeof(dataheaphead)); if (!Head) return 0; Head->Heap = Heap; Head->Size = n|DATA_FLAG_HEAP|DATA_FLAG_MEMHEAP; *a = (uint8_t*)(Head+1); } else { datahead* Head; if (!p || !Data_IsHeap(p)) { uint8_t* old = p; Head = malloc(n+sizeof(datahead)); if (Head && old) memcpy(Head+1,old,oldsize); } else Head = realloc(Data_Head(p),n+sizeof(datahead)); if (!Head) return 0; Head->Size = n|DATA_FLAG_HEAP; *a = (uint8_t*)(Head+1); } } return 1; } NOINLINE void Data_Release(uint8_t** a) { uint8_t* p = *a; if (p) { *a = NULL; if (Data_IsHeap(p)) { if (Data_IsMemHeap(p)) { if (Data_GetSize(p)) MemHeap_Free(Data_HeapHead(p)->Heap,Data_HeapHead(p),Data_GetSize(p)+sizeof(dataheaphead)); } else free(Data_Head(p)); } } } NOINLINE void Data_Clear(uint8_t** a) { uint8_t* p = *a; if (p && Data_IsMemHeap(p)) { p = MemHeap_Null(Data_HeapHead(p)->Heap); Data_Release(a); *a = p; } else Data_Release(a); } bool_t Data_Set(uint8_t** a,const uint8_t* b,size_t pos,size_t len) { if (!Data_ReAlloc(a,pos+len)) return 0; memcpy(*a+pos,b,len); return 1; } size_t ArraySize(const array*p) { return p->_End-p->_Begin; } void ArrayInitEx(array* p,const cc_memheap* Heap) { p->_Begin = p->_End = Heap ? MemHeap_Null(Heap):NULL; } NOINLINE void ArrayClear(array* p) { Data_Clear(&p->_Begin); p->_End = p->_Begin; } void ArrayDrop(array* p) { p->_End = p->_Begin; } static size_t SizeAlign(size_t Total, size_t Align) { if (!Align) { for (Align=16;Align<16384;Align<<=1) if (Align*8 > Total) break; } --Align; return (Total + Align) & ~Align; } bool_t ArrayAlloc(array* p,size_t Total,size_t Align) { size_t Size = ArraySize(p); if (!Data_ReAlloc(&p->_Begin,SizeAlign(Total,Align))) return 0; p->_End = p->_Begin + Size; return 1; } void ArrayShrink(array* p, size_t Length) { p->_End -= Length; if (p->_End < p->_Begin) p->_End = p->_Begin; } bool_t ArrayInsert(array* p, size_t Ofs, const void* Ptr, size_t Width, size_t Align) { if (!ArrayAppend(p,NULL,Width,Align)) return 0; memmove(p->_Begin+Ofs+Width,p->_Begin+Ofs,(p->_End-p->_Begin)-Width-Ofs); if (Ptr) memcpy(p->_Begin+Ofs,Ptr,Width); return 1; } void ArrayDelete(array* p, size_t Ofs, size_t Width) { memmove(p->_Begin+Ofs,p->_Begin+Ofs+Width,(p->_End-p->_Begin)-Width-Ofs); p->_End -= Width; } bool_t ArrayAppendStr(array* p, const tchar_t* Ptr, bool_t Merge, size_t Align) { if (Ptr && (Ptr[0] || !Merge)) { if (Merge && !ARRAYEMPTY(*p) && ARRAYEND(*p,tchar_t)[-1]==0) ArrayShrink(p,sizeof(tchar_t)); return ArrayAppend(p,Ptr,(tcslen(Ptr)+1)*sizeof(tchar_t),Align); } return 1; } bool_t ArrayAppend(array* p, const void* Ptr, size_t Length, size_t Align) { size_t Total = p->_End - p->_Begin + Length; if (Total > Data_Size(p->_Begin) && !ArrayAlloc(p,Total,Align)) return 0; if (Ptr) memcpy(p->_End,Ptr,Length); p->_End += Length; return 1; } bool_t ArrayEq(const array* a, const array* b) { size_t an = a ? ArraySize(a):0; size_t bn = b ? ArraySize(b):0; return an == bn && (!an || memcmp(ARRAYBEGIN(*a,uint8_t),ARRAYBEGIN(*b,uint8_t),an)==0); } bool_t ArrayCopy(array* p, const array* q) { size_t Size = ArraySize(q); if (!ArrayResize(p,Size,0)) return 0; memcpy(ARRAYBEGIN(*p,uint8_t),ARRAYBEGIN(*q,uint8_t),Size); return 1; } bool_t ArrayResize(array* p,size_t Total, size_t Align) { if (Total > Data_Size(p->_Begin) && !ArrayAlloc(p,Total,Align)) return 0; p->_End = p->_Begin + Total; return 1; } void ArrayZero(array* p) { memset(p->_Begin,0,p->_End-p->_Begin); } #define QSORTMINLEN 16 static INLINE void InQSortSwap(uint_fast32_t* a, uint_fast32_t* b) { uint_fast32_t t = *a; *a = *b; *b = t; } static NOINLINE void InQSort(uint_fast32_t* First, uint_fast32_t* Last, arraycmp Cmp, const void* CmpParam) { while (Last > First + QSORTMINLEN) { uint_fast32_t* Mid = First + ((Last - First)>>1); uint_fast32_t* Ref = First; uint_fast32_t* Left; uint_fast32_t* Right; if (Cmp(CmpParam,First,Last) < 0) { if (Cmp(CmpParam,Last,Mid) < 0) Ref = Last; else if (Cmp(CmpParam,First,Mid) < 0) Ref = Mid; } else if (Cmp(CmpParam,First,Mid) >= 0) { if (Cmp(CmpParam,Last,Mid) < 0) Ref = Mid; else Ref = Last; } if (Ref != First) InQSortSwap(First,Ref); Left = First; Right = Last+1; for (;;) { while (++Left < Last && Cmp(CmpParam,First,Left) > 0) {} while (Cmp(CmpParam,First,--Right) < 0) {} if (Left >= Right) break; InQSortSwap(Left,Right); } if (Right == First) { ++First; } else { InQSortSwap(First,Right); --Right; if (Right - First < Last - Left) { if (Right > QSORTMINLEN + First) InQSort(First,Right,Cmp,CmpParam); First = Left; } else { if (Last > QSORTMINLEN + Left) InQSort(Left,Last,Cmp,CmpParam); Last = Right; } } } } void ArraySortEx(array* p, size_t Count, size_t Width, arraycmp Cmp, const void* CmpParam, bool_t Unique) { if (Count == ARRAY_AUTO_COUNT) Count = ArraySize(p)/Width; if (Count>1) { if (Width == sizeof(uint_fast32_t)) { uint_fast32_t* End = ARRAYBEGIN(*p,uint_fast32_t)+Count; uint_fast32_t* i; uint_fast32_t* j; InQSort(ARRAYBEGIN(*p,uint_fast32_t), End-1, Cmp, CmpParam); j = ARRAYBEGIN(*p,uint_fast32_t); for (i=j+1; i!=End; ++i) { if (Cmp(CmpParam,i,j) < 0) { uint_fast32_t Tmp = *i; do { j[1] = j[0]; if (j-- == ARRAYBEGIN(*p,uint_fast32_t)) break; } while (Cmp(CmpParam,&Tmp,j) < 0); j[1] = Tmp; } j = i; } if (Unique) { j = ARRAYBEGIN(*p,uint_fast32_t); for (i=j+1; i!=End; ++i) { if (Cmp(CmpParam,i,j) != 0) *(++j) = *i; } p->_End = (uint8_t*)(j+1); } } else { // dummy fallback... uint8_t* Tmp = (uint8_t*)alloca(Width); uint8_t* End = p->_Begin + Count*Width; uint8_t* i; uint8_t* j; j = p->_Begin; for (i=j+Width; i!=End; i+=Width) { if (Cmp(CmpParam,i,j) < 0) { memcpy(Tmp,i,Width); do { memcpy(j+Width,j,Width); if (j == p->_Begin) { j -= Width; break; } j -= Width; } while (Cmp(CmpParam,Tmp,j) < 0); memcpy(j+Width,Tmp,Width); } j = i; } if (Unique) { j = p->_Begin; for (i=j+Width; i!=End; i+=Width) { if (Cmp(CmpParam,i,j) != 0) { j += Width; memcpy(j,i,Width); } } p->_End = j+Width; } } } } intptr_t ArrayFindEx(const array* p, size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam, bool_t* Found) { if (ARRAYEMPTY(*p)) { *Found = 0; return 0; } if (Count == ARRAY_AUTO_COUNT) { Count = ArraySize(p)/Width; assert(Count*Width == ArraySize(p)); } if (Cmp) { int i; intptr_t Mid = 0; intptr_t Lower = 0; intptr_t Upper = Count-1; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; i = Cmp(CmpParam,p->_Begin+Width*Mid,Data); if (i>0) Upper = Mid-1; else if (i<0) Lower = Mid+1; else { *Found = 1; return Mid; } } *Found = 0; if (Upper == Mid - 1) return Mid; else return Lower; } else { intptr_t No = 0; const uint8_t* i; for (i=p->_Begin;Count--;i+=Width,++No) if (memcmp(i,Data,Width)==0) { *Found = 1; return No; } *Found = 0; return No; } } intptr_t ArrayAddEx(array* p,size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam, size_t Align) { intptr_t Pos; bool_t Found; Pos = ArrayFindEx(p,Count,Width,Data,Cmp,CmpParam,&Found); if (!Found) { if (!ArrayInsert(p,Width*Pos,Data,Width,Align)) return -1; } else memcpy(p->_Begin+Width*Pos,Data,Width); return Pos; } bool_t ArrayRemoveEx(array* p, size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam) { bool_t Found; size_t Pos = ArrayFindEx(p,Count,Width,Data,Cmp,CmpParam,&Found); if (Found) ArrayDelete(p,Pos*Width,Width); return Found; } static INLINE uint32_t Rand(uint32_t RndSeed) { return RndSeed*0x8088405U + 0x251001U; } void ArrayRandomize(array* Array,size_t Width,uint32_t RndSeed) { size_t i,j,Count = ArraySize(Array)/Width; uint8_t *Buf=alloca(Width); for (i=0;iBlock.Ptr) { FreeBlock(NULL,&p->Block); p->Array._Begin = NULL; p->Array._End = NULL; } else ArrayClear(&p->Array); } void ArrayBlockLock(arrayblock* p) { if (!p->Block.Ptr && p->Array._End != p->Array._Begin) { size_t n = p->Array._End-p->Array._Begin; if (AllocBlock(NULL,n,&p->Block,1,HEAP_STORAGE)) { WriteBlock(&p->Block,0,p->Array._Begin,n); ArrayClear(&p->Array); p->Array._Begin = (uint8_t*)p->Block.Ptr; p->Array._End = p->Array._Begin + n; } } } #endif void Fifo_Clear(cc_fifo* p) { ArrayClear(&p->_Base); p->_Read = NULL; } bool_t Fifo_Alloc(cc_fifo* p, size_t Total, size_t Align) { size_t n = p->_Read - p->_Base._Begin; if (!ArrayAlloc(&p->_Base,Total,Align)) return 0; p->_Read = p->_Base._Begin+n; return 1; } void Fifo_Drop(cc_fifo* p) { ArrayDrop(&p->_Base); p->_Read = p->_Base._Begin; } uint8_t* Fifo_Write(cc_fifo* p, const void* Ptr, size_t Length, size_t Align) { size_t Total = Data_Size(p->_Base._Begin); size_t Read = p->_Read - p->_Base._Begin; size_t End = p->_Base._End - p->_Base._Begin + Length + SAFETAIL; uint8_t* Result; if (End>Total && Read>0) { memmove(p->_Base._Begin,p->_Read,FIFO_SIZE(*p)); p->_Read = p->_Base._Begin; p->_Base._End -= Read; End -= Read; Read = 0; } if (End>Total) { if (!ArrayAlloc(&p->_Base,End,Align)) return NULL; p->_Read = p->_Base._Begin+Read; } Result = p->_Base._End; p->_Base._End += Length; if (Ptr) memcpy(Result,Ptr,Length); return Result; } bcmatroska2-5.3.101/corec/corec/array/array.h000066400000000000000000000143711462133141200206670ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __ARRAY_H #define __ARRAY_H #include "corec/corec.h" #include "corec/memheap.h" #ifdef __cplusplus extern "C" { #endif #if defined(ARRAY_EXPORTS) #define ARRAY_DLL DLLEXPORT #elif defined(ARRAY_IMPORTS) #define ARRAY_DLL DLLIMPORT #else #define ARRAY_DLL #endif #define Data_Var(type,name,len) struct { size_t n; type p[len]; } __##name; type* name = (__##name.n = sizeof(__##name.p),__##name.p) ARRAY_DLL bool_t Data_ReAlloc(uint8_t** a,size_t n); ARRAY_DLL size_t Data_Size(const uint8_t* a); ARRAY_DLL void Data_Release(uint8_t** a); ARRAY_DLL void Data_Clear(uint8_t** a); // release memory, but keep heap reference ARRAY_DLL bool_t Data_Set(uint8_t** a,const uint8_t* b,size_t pos,size_t len); typedef struct array { // these are private members, use ARRAY macros to access them uint8_t* _Begin; uint8_t* _End; } array; typedef int (*arraycmp)(const void* Param, const void* a,const void* b); #define ARRAY_AUTO_COUNT ((size_t)-1) static INLINE void ArrayInit(array* p) { p->_Begin = NULL; p->_End = NULL; } ARRAY_DLL void ArrayInitEx(array*,const cc_memheap*); ARRAY_DLL void ArrayClear(array*); ARRAY_DLL void ArrayDrop(array*); ARRAY_DLL size_t ArraySize(const array*); ARRAY_DLL bool_t ArrayEq(const array* a, const array* b); ARRAY_DLL bool_t ArrayCopy(array*,const array* In); ARRAY_DLL bool_t ArrayResize(array*,size_t Size,size_t Align); ARRAY_DLL void ArrayZero(array*); ARRAY_DLL intptr_t ArrayFindEx(const array* p, size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam, bool_t* Found); ARRAY_DLL bool_t ArrayAlloc(array* p,size_t Total,size_t Align); ARRAY_DLL bool_t ArrayAppend(array* p, const void* Ptr, size_t Length, size_t Align); ARRAY_DLL bool_t ArrayAppendStr(array* p, const tchar_t* Ptr, bool_t Merge, size_t Align); ARRAY_DLL void ArrayShrink(array* p, size_t Length); ARRAY_DLL intptr_t ArrayAddEx(array* p, size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam, size_t Align); ARRAY_DLL bool_t ArrayRemoveEx(array* p, size_t Count, size_t Width, const void* Data, arraycmp Cmp, const void* CmpParam); ARRAY_DLL void ArraySortEx(array* p, size_t Count, size_t Width, arraycmp Cmp, const void* CmpParam, bool_t Unique); ARRAY_DLL bool_t ArrayInsert(array* p, size_t Ofs, const void* Ptr, size_t Length, size_t Align); ARRAY_DLL void ArrayDelete(array* p, size_t Ofs, size_t Length); ARRAY_DLL void ArrayRandomize(array* Array,size_t Width,uint32_t RndSeed); #define ArrayAdd(p,type,Data,Cmp,CmpParam,Align) ArrayAddEx(p,ARRAYCOUNT(*p,type),sizeof(type),Data,Cmp,CmpParam,Align) #define ArrayRemove(p,type,Data,Cmp,CmpParam) ArrayRemoveEx(p,ARRAYCOUNT(*p,type),sizeof(type),Data,Cmp,CmpParam) #define ArrayFind(p,type,Data,Cmp,CmpParam,Found) ArrayFindEx(p,ARRAYCOUNT(*p,type),sizeof(type),Data,Cmp,CmpParam,Found) #define ArraySort(p,type,Cmp,CmpParam,Unique) ArraySortEx(p,ARRAYCOUNT(*p,type),sizeof(type),Cmp,CmpParam,Unique) #ifdef CONFIG_DEBUGCHECKS #define ARRAYBEGIN(Array,Type) (assert(&(Array)!=NULL),(Type*)((Array)._Begin)) #define ARRAYEND(Array,Type) (assert(&(Array)!=NULL),(Type*)((Array)._End)) #define ARRAYEMPTY(Array) (assert(&(Array)!=NULL),(Array)._Begin==(Array)._End) #else #define ARRAYBEGIN(Array,Type) ((Type*)((Array)._Begin)) #define ARRAYEND(Array,Type) ((Type*)((Array)._End)) #define ARRAYEMPTY(Array) ((Array)._Begin==(Array)._End) #endif #define ARRAYCOUNT(Array,Type) ((size_t)(ARRAYEND(Array,Type)-ARRAYBEGIN(Array,Type))) // TODO: move this to base/mem and depend on "mem" platform dependently(?) typedef struct block { const uint8_t* Ptr; uintptr_t Id; } block; //end TODO #ifdef TARGET_PALMOS typedef struct arrayblock { array Array; block Block; } arrayblock; ARRAY_DLL void ArrayBlockClear(arrayblock*); ARRAY_DLL void ArrayBlockLock(arrayblock*); #else typedef struct arrayblock { array Array; } arrayblock; #define ArrayBlockClear(a) ArrayClear(&(a)->Array) #define ArrayBlockLock(a) {} #endif #define SAFETAIL 256 typedef struct cc_fifo { // private members array _Base; uint8_t* _Read; } cc_fifo; static INLINE void Fifo_Init(cc_fifo* p) { ArrayInit(&p->_Base); p->_Read = NULL; } ARRAY_DLL void Fifo_Clear(cc_fifo*); ARRAY_DLL void Fifo_Drop(cc_fifo*); ARRAY_DLL bool_t Fifo_Alloc(cc_fifo* p, size_t Size, size_t Align); ARRAY_DLL uint8_t* Fifo_Write(cc_fifo*, const void* Ptr, size_t Length, size_t Align); static INLINE void Fifo_Readed(cc_fifo* p, size_t Length) { p->_Read += Length; } #define FIFO_SIZE(p) (ARRAYEND((p)._Base,uint8_t)-(p)._Read) #define FIFO_BEGIN(p) ((p)._Read) #define FIFO_END(p) ARRAYEND((p)._Base,uint8_t) #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/array/array.proj000066400000000000000000000000761462133141200214070ustar00rootroot00000000000000GROUP array { USE corec SOURCE array.c HEADER array.h } bcmatroska2-5.3.101/corec/corec/banned.h000066400000000000000000000103001462133141200176460ustar00rootroot00000000000000/*** * banned.h - list of Microsoft Security Development Lifecycle banned APIs * * Purpose: * This include file contains a list of banned API which should not be used in new code and * removed from legacy code over time * History * 01-Jan-2006 - mikehow - Initial Version * 22-Apr-2008 - mikehow - Updated to SDL 4.1, commented out recommendations and added memcpy * ***/ #ifndef _INC_BANNED # define _INC_BANNED #endif #ifdef _MSC_VER // Some of these functions are Windows specific # pragma once # pragma deprecated (strcpy, strcpyA, strcpyW, wcscpy, _tcscpy, _mbscpy, StrCpy, StrCpyA, StrCpyW, lstrcpy, lstrcpyA, lstrcpyW, _tccpy, _mbccpy) # pragma deprecated (strcat, strcatA, strcatW, wcscat, _tcscat, _mbscat, StrCat, StrCatA, StrCatW, lstrcat, lstrcatA, lstrcatW, StrCatBuff, StrCatBuffA, StrCatBuffW, StrCatChainW, _tccat, _mbccat) # pragma deprecated (wnsprintf, wnsprintfA, wnsprintfW, sprintfW, sprintfA, wsprintf, wsprintfW, wsprintfA, sprintf, swprintf, _stprintf, _snwprintf, _snprintf, _sntprintf) # pragma deprecated (wvsprintf, wvsprintfA, wvsprintfW, vsprintf, _vstprintf, vswprintf) # pragma deprecated (_vsnprintf, _vsnwprintf, _vsntprintf, wvnsprintf, wvnsprintfA, wvnsprintfW) # pragma deprecated (strncpy, wcsncpy, _tcsncpy, _mbsncpy, _mbsnbcpy, StrCpyN, StrCpyNA, StrCpyNW, StrNCpy, strcpynA, StrNCpyA, StrNCpyW, lstrcpyn, lstrcpynA, lstrcpynW) # pragma deprecated (strncat, wcsncat, _tcsncat, _mbsncat, _mbsnbcat, StrCatN, StrCatNA, StrCatNW, StrNCat, StrNCatA, StrNCatW, lstrncat, lstrcatnA, lstrcatnW, lstrcatn) # pragma deprecated (strtok, _tcstok, wcstok, _mbstok) # pragma deprecated (makepath, _tmakepath, _makepath, _wmakepath) # pragma deprecated (_splitpath, _tsplitpath, _wsplitpath) # pragma deprecated (scanf, wscanf, _tscanf, sscanf, swscanf, _stscanf, snscanf, snwscanf, _sntscanf) //# pragma deprecated (_itoa, _itow, _i64toa, _i64tow, _ui64toa, _ui64tot, _ui64tow, _ultoa, _ultot, _ultow) # pragma deprecated (gets, _getts, _gettws) # pragma deprecated (IsBadWritePtr, IsBadHugeWritePtr, IsBadReadPtr, IsBadHugeReadPtr, IsBadCodePtr, IsBadStringPtr) # pragma deprecated (CharToOem, CharToOemA, CharToOemW, OemToChar, OemToCharA, OemToCharW, CharToOemBuffA, CharToOemBuffW) //# pragma deprecated (alloca, _alloca) # pragma deprecated (strlen, wcslen, _mbslen, _mbstrlen, StrLen, lstrlen) # pragma deprecated (memcpy, RtlCopyMemory, CopyMemory) #else #ifdef __GNUC__ // Some of these functions are Windows specific, so you may want to add *nix specific banned function calls # pragma GCC poison strcpy strcpyA strcpyW wcscpy _tcscpy _mbscpy StrCpy StrCpyA StrCpyW lstrcpy lstrcpyA lstrcpyW _tccpy _mbccpy # pragma GCC poison strcat strcatA strcatW wcscat _tcscat _mbscat StrCat StrCatA StrCatW lstrcat lstrcatA lstrcatW StrCatBuff StrCatBuffA StrCatBuffW StrCatChainW _tccat _mbccat # pragma GCC poison wnsprintf wnsprintfA wnsprintfW sprintfW sprintfA wsprintf wsprintfW wsprintfA sprintf swprintf _stprintf _snwprintf _snprintf _sntprintf # pragma GCC poison wvsprintf wvsprintfA wvsprintfW vsprintf _vstprintf vswprintf # pragma GCC poison _vsnprintf _vsnwprintf _vsntprintf wvnsprintf wvnsprintfA wvnsprintfW # pragma GCC poison strncpy wcsncpy _tcsncpy _mbsncpy _mbsnbcpy StrCpyN StrCpyNA StrCpyNW StrNCpy strcpynA StrNCpyA StrNCpyW lstrcpyn lstrcpynA lstrcpynW # pragma GCC poison strncat wcsncat _tcsncat _mbsncat _mbsnbcat StrCatN StrCatNA StrCatNW StrNCat StrNCatA StrNCatW lstrncat lstrcatnA lstrcatnW lstrcatn # pragma GCC poison strtok _tcstok wcstok _mbstok # pragma GCC poison makepath _tmakepath _makepath _wmakepath # pragma GCC poison _splitpath _tsplitpath _wsplitpath # pragma GCC poison scanf wscanf _tscanf sscanf swscanf _stscanf snscanf snwscanf _sntscanf //# pragma GCC poison _itoa _itow _i64toa _i64tow _ui64toa _ui64tot _ui64tow _ultoa _ultot _ultow # pragma GCC poison gets _getts _gettws # pragma GCC poison IsBadWritePtr IsBadHugeWritePtr IsBadReadPtr IsBadHugeReadPtr IsBadCodePtr IsBadStringPtr # pragma GCC poison CharToOem CharToOemA CharToOemW OemToChar OemToCharA OemToCharW CharToOemBuffA CharToOemBuffW //# pragma GCC poison alloca _alloca # pragma GCC poison strlen wcslen _mbslen _mbstrlen StrLen lstrlen # pragma GCC poison memcpy RtlCopyMemory CopyMemory #endif #endif /* _INC_BANNED */ bcmatroska2-5.3.101/corec/corec/confhelper.h000066400000000000000000000074451462133141200205640ustar00rootroot00000000000000/* $Id$ Copyright (c) 2010, CoreCodec, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CoreCodec, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __CONFIG_HELPER_H #define __CONFIG_HELPER_H /**** SHOULD MATCH THE ONE OF COREMAKE ****/ /* force some defines */ #if defined(TARGET_WINCE) || defined(TARGET_SYMBIAN) #undef COREMAKE_UNICODE #define COREMAKE_UNICODE /* platforms where Unicode is mandatory */ #endif #if (defined(TARGET_PALMOS) && defined(IX86)) || defined(TARGET_SYMBIAN) #undef COREMAKE_STATIC /* platforms where dynamic libraries are not supported */ #define COREMAKE_STATIC #endif #if (defined(ARM) || defined(MIPS) || defined(SH3) || defined(SH4)) && !defined(TARGET_IPHONE_SDK) #undef CONFIG_DYNCODE #define CONFIG_DYNCODE /* platforms when dynamic code can be used */ #endif #if defined(IX86) || defined(IX86_64) #undef CONFIG_UNALIGNED_ACCESS #define CONFIG_UNALIGNED_ACCESS /* pointers can use unaligned memory */ #endif #if (!defined(CONFIG_FILEPOS_64)) && ( defined(TARGET_WIN32) || defined(TARGET_WIN64) || defined(TARGET_WINCE) || defined(TARGET_OSX) || defined(TARGET_LINUX)) #define CONFIG_FILEPOS_64 /* platforms where 64 bits file position/size should be favoured */ #endif #if defined(TARGET_WINCE) || defined(TARGET_SYMBIAN) || defined(TARGET_PALMOS) || defined(ARM) || defined(MIPS) #define CONFIG_FIXED_POINT /* platforms where fixed point arithmetic processing should favoured */ #endif /* forbid some defines */ #if defined(TARGET_PALMOS) || defined(TARGET_LINUX) || defined(TARGET_PS2SDK) #undef COREMAKE_UNICODE /* platforms where Unicode is handled via UTF-8 strings */ #endif #if defined(TARGET_PALMOS) #undef CONFIG_FILEPOS_64 /* platforms where 64 bits file position/size should not be used */ #endif #if !defined(ARM) || defined(TARGET_SYMBIAN) || defined(TARGET_IPHONE) #undef CONFIG_WMMX /* platforms that don't support Wireless MMX CPUs/instructions */ #endif #if !defined(ARM) || defined(TARGET_SYMBIAN) || defined(TARGET_PALMOS) #undef CONFIG_ARMV6 /* platforms that don't support ARMv6 CPUs/instructions */ #endif #if !defined(IX86) || defined(TARGET_SYMBIAN) #undef CONFIG_MMX /* platforms that don't support MMX CPUs/instructions */ #endif #if !defined(ARM) || (!defined(TARGET_IPHONE) && !defined(TARGET_ANDROID)) #undef CONFIG_NEON /* platforms that don't support NEON/ARMv7 instructions */ #endif #if !defined(POWERPC) #undef CONFIG_ALTIVEC #endif #endif /* __CONFIG_HELPER_H */ bcmatroska2-5.3.101/corec/corec/corec.h000066400000000000000000000043451462133141200175260ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef _COREC_H #define _COREC_H #ifdef __cplusplus extern "C" { #endif #if defined(_MSC_VER) && (_MSC_VER > 1000) #pragma once #pragma warning(push, 4) #pragma warning(disable : 4100 4710 4514 4201 4714 4115 4206 4055 4214 4998 4273 4127 4114 4512) #endif #include "portab.h" #include "memalloc.h" #include "err.h" #include "helper.h" #if defined(NDEBUG) && defined(CONFIG_DEBUGCHECKS) #undef CONFIG_DEBUGCHECKS #endif #if defined(NDEBUG) && defined(CONFIG_DEBUG_LEAKS) #undef CONFIG_DEBUG_LEAKS #endif #ifdef __cplusplus } #endif #endif /* _COREC_H */ bcmatroska2-5.3.101/corec/corec/corec.proj000066400000000000000000000004471462133141200202500ustar00rootroot00000000000000#include "*/*.proj" GROUP corec { INCLUDE .. EXPINCLUDE .. DEFINE HAVE_COREC_H EXPDEFINE HAVE_COREC_H HEADER corec.h HEADER err.h HEADER helper.h HEADER memalloc.h HEADER portab.h IF CONFIG_SAFE_C HEADER banned.h ENDIF HEADER(!COREMAKE_CONFIG_HELPER) confhelper.h } bcmatroska2-5.3.101/corec/corec/err.h000066400000000000000000000071331462133141200172210ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __ERR_H #define __ERR_H #define ERR_ID FOURCC('E','R','R','_') //---------------------------------------------------------------- // error codes #define ERR_NONE (err_t)0 #define ERR_BUFFER_FULL (err_t)-1 // 0xFFFFFFFF #define ERR_OUT_OF_MEMORY (err_t)-2 // 0xFFFFFFFE #define ERR_INVALID_DATA (err_t)-3 // 0xFFFFFFFD #define ERR_INVALID_PARAM (err_t)-4 // 0xFFFFFFFC #define ERR_NOT_SUPPORTED (err_t)-5 // 0xFFFFFFFB #define ERR_NEED_MORE_DATA (err_t)-6 // 0xFFFFFFFA // stream added 0xFFFFFFF9 #define ERR_FILE_NOT_FOUND (err_t)-8 // 0xFFFFFFF8 #define ERR_END_OF_FILE (err_t)-9 // 0xFFFFFFF7 #define ERR_DEVICE_ERROR (err_t)-10 // 0xFFFFFFF6 #define ERR_SYNCED (err_t)-11 // 0xFFFFFFF5 #define ERR_DATA_NOT_FOUND (err_t)-12 // 0xFFFFFFF4 #define ERR_PROTO_NOT_FOUND (err_t)-13 // 0xFFFFFFF3 #define ERR_NOT_DIRECTORY (err_t)-14 // 0xFFFFFFF2 #define ERR_NOT_COMPATIBLE (err_t)-15 // 0xFFFFFFF1 #define ERR_CONNECT_FAILED (err_t)-16 // 0xFFFFFFF0 #define ERR_DROPPING (err_t)-17 // 0xFFFFFFEF #define ERR_STOPPED (err_t)-18 // 0xFFFFFFEE #define ERR_UNAUTHORIZED (err_t)-19 // 0xFFFFFFED #define ERR_LOADING_HEADER (err_t)-20 // 0xFFFFFFEC #define ERR_READ (err_t)-21 // 0xFFFFFFEB #define ERR_WRITE (err_t)-22 // 0xFFFFFFEA #define ERR_UNRESOLVED_ADDR (err_t)-23 // 0xFFFFFFE9 #define ERR_NO_NETWORK (err_t)-24 // 0xFFFFFFE8 #define ERR_TIME_OUT (err_t)-25 // 0xFFFFFFE7 #define ERR_KEY_NOT_UNIQUE (err_t)-26 // 0xFFFFFFE6 #define ERR_NOT_CONST (err_t)-27 // 0xFFFFFFE5 #define ERR_REDIRECTED (err_t)-28 // 0xFFFFFFE4 #define ERR_CANCELED (err_t)-29 // 0xFFFFFFE3 #define ERR_STREAM_CACHED (err_t)-30 // 0xFFFFFFE2 #define ERR_SERVER_ERROR (err_t)-31 // 0xFFFFFFE1 #define ERR_NOT_USABLE (err_t)-32 // 0xFFFFFFE0 // buffer full: data is not processed, retry later // need more data: data is processed, but need more to continue #endif bcmatroska2-5.3.101/corec/corec/helper.h000066400000000000000000000220161462133141200177050ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __HELPER_H #define __HELPER_H #ifdef TARGET_LINUX #include #define OFS(name,item) offsetof(name,item) #else #define OFS(name,item) ((uintptr_t)&(((name*)NULL)->item)) #endif #define ALIGN64(x) (((x) + 63) & ~63) #define ALIGN16(x) (((x) + 15) & ~15) #define ALIGN8(x) (((x) + 7) & ~7) #define ALIGN4(x) (((x) + 3) & ~3) #define ALIGN2(x) (((x) + 1) & ~1) #define GET_R(x) ((uint8_t)(((x) >> 0) & 255)) #define GET_G(x) ((uint8_t)(((x) >> 8) & 255)) #define GET_B(x) ((uint8_t)(((x) >> 16) & 255)) #define SWAP32(a) ((((uint32_t)(a) >> 24) & 0x000000FF) | (((uint32_t)(a) >> 8) & 0x0000FF00)|\ (((uint32_t)(a) << 8) & 0x00FF0000) | (((uint32_t)(a) << 24) & 0xFF000000)) #define SWAP16(a) ((uint16_t)((((uint32_t)(a) >> 8) & 0xFF) | (((uint32_t)(a) << 8) & 0xFF00))) #define SWAP64(a) (((uint64_t)SWAP32(a) << 32) | SWAP32((uint64_t)(a)>>32)) #define LSHIFT(v,n) ((v)<<(n)) #define RSHIFT(v,n) ((v)>>(n)) #define RLSHIFT(v,n) (((n)>=0)?RSHIFT(v,n):LSHIFT(v,-(n))) #define RSHIFT_ROUND(v,n) (((v)+(1<<(n-1)))>>(n)) #define RSHIFT_ROUND_COND(v,n) ((n)>0 ? RSHIFT_ROUND(v,n) : v) #ifdef IS_BIG_ENDIAN #define INT64BE(a) (a) #define INT64LE(a) SWAP64(a) #define INT32BE(a) (a) #define INT32LE(a) SWAP32(a) #define INT16BE(a) (a) #define INT16LE(a) SWAP16(a) #else #define INT64LE(a) (a) #define INT64BE(a) SWAP64(a) #define INT32LE(a) (a) #define INT32BE(a) SWAP32(a) #define INT16LE(a) (a) #define INT16BE(a) SWAP16(a) #endif #define LOAD8(ptr,ofs) (((uint8_t*)(ptr))[ofs]) #if defined(CONFIG_UNALIGNED_ACCESS) #define LOAD16LE(ptr) INT16LE(*(uint16_t*)(ptr)) #define LOAD16BE(ptr) INT16BE(*(uint16_t*)(ptr)) #define LOAD32LE(ptr) INT32LE(*(uint32_t*)(ptr)) #define LOAD32BE(ptr) INT32BE(*(uint32_t*)(ptr)) #define LOAD64LE(ptr) INT64LE(*(uint64_t*)(ptr)) #define LOAD64BE(ptr) INT64BE(*(uint64_t*)(ptr)) #else #define LOAD16LE(ptr) ((uint16_t)((LOAD8(ptr,1)<<8)|LOAD8(ptr,0))) #define LOAD16BE(ptr) ((uint16_t)((LOAD8(ptr,0)<<8)|LOAD8(ptr,1))) #define LOAD32LE(ptr) ((LOAD8(ptr,3)<<24)|(LOAD8(ptr,2)<<16)|(LOAD8(ptr,1)<<8)|LOAD8(ptr,0)) #define LOAD32BE(ptr) ((LOAD8(ptr,0)<<24)|(LOAD8(ptr,1)<<16)|(LOAD8(ptr,2)<<8)|LOAD8(ptr,3)) #define LOAD64LE(ptr) ((((uint64_t)LOAD8(ptr,0)) )|(((uint64_t)LOAD8(ptr,1))<< 8)|(((uint64_t)LOAD8(ptr,2))<<16)|(((uint64_t)LOAD8(ptr,3))<<24)| \ (((uint64_t)LOAD8(ptr,4))<<32)|(((uint64_t)LOAD8(ptr,5))<<40)|(((uint64_t)LOAD8(ptr,6))<<48)|(((uint64_t)LOAD8(ptr,0))<<56)) #define LOAD64BE(ptr) ((((uint64_t)LOAD8(ptr,0))<<56)|(((uint64_t)LOAD8(ptr,1))<<48)|(((uint64_t)LOAD8(ptr,2))<<40)|(((uint64_t)LOAD8(ptr,3))<<32)| \ (((uint64_t)LOAD8(ptr,4))<<24)|(((uint64_t)LOAD8(ptr,5))<<16)|(((uint64_t)LOAD8(ptr,6))<< 8)|(((uint64_t)LOAD8(ptr,0)) )) #endif #define STORE8(p, o, i) ((uint8_t *) (p))[o] = (uint8_t) ((i) & 0xFF) #if defined(CONFIG_UNALIGNED_ACCESS) && defined(IS_BIG_ENDIAN) #define STORE16BE(p, i) *((uint16_t*)(p))=i #define STORE32BE(p, i) *((uint32_t*)(p))=i #define STORE64BE(p, i) *((uint64_t*)(p))=i #else #define STORE16BE(p, i) STORE8(p, 1, i), STORE8(p, 0, ((uint16_t)i) >> 8) #define STORE32BE(p, i) STORE8(p, 3, i), STORE8(p, 2, ((uint32_t)i) >> 8), STORE8(p, 1, ((uint32_t) i) >> 16), STORE8(p, 0, ((uint32_t) i) >> 24) #define STORE64BE(p, i) STORE8(p, 7, i), STORE8(p, 6, ((uint64_t)i) >> 8), STORE8(p, 5, ((uint64_t)i) >> 16), STORE8(p, 4, ((uint64_t)i) >> 24), \ STORE8(p, 3, ((uint64_t)i) >> 32), STORE8(p, 2, ((uint64_t)i) >> 40), STORE8(p, 1, ((uint64_t)i) >> 48), STORE8(p, 0, ((uint64_t)i) >> 56) #endif #if defined(CONFIG_UNALIGNED_ACCESS) && defined(IS_LITTLE_ENDIAN) #define STORE16LE(p, i) *((uint16_t*)(p))=i #define STORE32LE(p, i) *((uint32_t*)(p))=i #define STORE64LE(p, i) *((uint64_t*)(p))=i #else #define STORE16LE(p, i) STORE8(p, 0, i), STORE8(p, 1, ((uint16_t)i) >> 8) #define STORE32LE(p, i) STORE8(p, 0, i), STORE8(p, 1, ((uint32_t)i) >> 8), STORE8(p, 2, ((uint32_t)i) >> 16), STORE8(p, 3, ((uint32_t)i) >> 24) #define STORE64LE(p, i) STORE8(p, 0, i), STORE8(p, 1, ((uint64_t)i) >> 8), STORE8(p, 2, ((uint64_t)i) >> 16), STORE8(p, 3, ((uint64_t)i) >> 24), \ STORE8(p, 4, ((uint64_t)i) >> 32), STORE8(p, 5, ((uint64_t)i) >> 40), STORE8(p, 6, ((uint64_t)i) >> 48), STORE8(p, 7, ((uint64_t)i) >> 56) #endif #ifdef IS_BIG_ENDIAN #define LOAD16(ptr) LOAD16BE(ptr) #define LOAD32(ptr) LOAD32BE(ptr) #define LOAD64(ptr) LOAD64BE(ptr) #define LOAD16SW(ptr) LOAD16LE(ptr) #define LOAD32SW(ptr) LOAD32LE(ptr) #define LOAD64SW(ptr) LOAD64LE(ptr) #else #define LOAD16(ptr) LOAD16LE(ptr) #define LOAD32(ptr) LOAD32LE(ptr) #define LOAD64(ptr) LOAD64LE(ptr) #define LOAD16SW(ptr) LOAD16BE(ptr) #define LOAD32SW(ptr) LOAD32BE(ptr) #define LOAD64SW(ptr) LOAD64BE(ptr) #endif #if defined(__GNUC__) && defined(MIPS) #undef LOAD32 static INLINE uint32_t LOAD32(const void* ptr) { uint32_t v; asm ("ulw %0,0(%1)\n" : "=&r" (v) : "r" (ptr)); return v; } #endif // a=(a+c+1)/2 // b=(b+d+1)/2 #define AVG32R(a,b,c,d) \ c^=a; \ d^=b; \ a|=c; \ b|=d; \ c &= 0xFEFEFEFE; \ d &= 0xFEFEFEFE; \ a-=c>>1; \ b-=d>>1; #define AVG64R(a,b,c,d) \ c^=a; \ d^=b; \ a|=c; \ b|=d; \ c &= 0xFEFEFEFEFEFEFEFE; \ d &= 0xFEFEFEFEFEFEFEFE; \ a-=c>>1; \ b-=d>>1; // a=(a+c)/2 // b=(b+d)/2 #ifdef ARM #define AVG32NR(a,b,c,d) \ c^=a; \ d^=b; \ a &= ~c; \ b &= ~d; \ c &= 0xFEFEFEFE; \ d &= 0xFEFEFEFE; \ a+=c>>1; \ b+=d>>1; #else #define AVG32NR(a,b,c,d) \ c^=a; \ d^=b; \ a|=c; \ b|=d; \ a-=c & 0x01010101; \ b-=d & 0x01010101; \ c &= 0xFEFEFEFE; \ d &= 0xFEFEFEFE; \ a-=c>>1; \ b-=d>>1; #endif #define AVG64NR(a,b,c,d) \ c^=a; \ d^=b; \ a|=c; \ b|=d; \ a-=c & 0x0101010101010101; \ b-=d & 0x0101010101010101; \ c &= 0xFEFEFEFEFEFEFEFE; \ d &= 0xFEFEFEFEFEFEFEFE; \ a-=c>>1; \ b-=d>>1; #define _abs(a) (((a)>=0)?(a):-(a)) static INLINE int MIDDLE(int a, int b, int c) { int bb = b; if (a > b) { bb = a; a = b; } if (bb > c) bb = c; if (a > bb) bb = a; return bb; } static INLINE size_t _log2(uint32_t data) { size_t i; if (!data) ++data; for (i=0;data;++i) data >>= 1; return i; } static INLINE int64_t Scale64(int64_t v,int64_t Num,int64_t Den) { if (Den) return (v * Num) / Den; return 0; } static INLINE int Scale32(int64_t v, int64_t Num, int64_t Den) { return (int)Scale64(v,Num,Den); } #define SWAPVAL(type,a,b) { type __t = (a); (a)=(b); (b)=__t; } typedef int32_t datetime_t; #define INVALID_DATETIME_T 0 #define MIN_DATETIME_T ((datetime_t) 0xFFFFFFFF) #define MAX_DATETIME_T ((datetime_t) 0x7FFFFFFF) static INLINE int Fix16Mul(int a,int b) { return (int)(((int64_t)(a<<8)*(int64_t)(b<<8))>>32); } static INLINE uint32_t _ones(uint32_t x) { x -= ((x >> 1) & 0x55555555); x = (((x >> 2) & 0x33333333) + (x & 0x33333333)); x = (((x >> 4) + x) & 0x0f0f0f0f); x += (x >> 8); x += (x >> 16); return x & 0x0000003f; } static INLINE uint32_t _floor_log2(uint32_t x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return _ones(x) - 1; } #if !defined(min) && !defined(NOMINMAX) # define min(x,y) ((x)>(y)?(y):(x)) #endif #if !defined(max) && !defined(NOMINMAX) # define max(x,y) ((x)<(y)?(y):(x)) #endif #ifndef sign # define sign(x) ((x)<0?-1:1) #endif #define abs_diff(x,y) ((x)>(y)?((x)-(y)):((y)-(x))) #endif bcmatroska2-5.3.101/corec/corec/helpers/000077500000000000000000000000001462133141200177165ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/charconvert/000077500000000000000000000000001462133141200222345ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert.h000066400000000000000000000074551462133141200247360ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __CHARCONVERT_H #define __CHARCONVERT_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #if defined(CHARCONVERT_EXPORTS) #define CHARCONVERT_DLL DLLEXPORT #elif defined(CHARCONVERT_IMPORTS) #define CHARCONVERT_DLL DLLIMPORT #else #define CHARCONVERT_DLL #endif typedef struct charconv charconv; #define MAX_CHARSET_NAME 16 #define CHARSET_DEFAULT T("") #if defined(TARGET_WIN) #define CHARSET_WCHAR T("UCS-2") #elif SIZEOF_WCHAR==4 #define CHARSET_WCHAR T("UTF-32") #elif SIZEOF_WCHAR==2 #define CHARSET_WCHAR T("UTF-16") #else #error unsupported wchar_t size! #endif #define CHARSET_UTF8 T("UTF-8") #define CHARSET_UTF16 T("UTF-16") CHARCONVERT_DLL void CharConvDefault(tchar_t* Out, size_t OutLen); CHARCONVERT_DLL charconv* CharConvOpen(const tchar_t* From, const tchar_t* To); CHARCONVERT_DLL void CharConvClose(charconv*); CHARCONVERT_DLL void CharConvSS(charconv*, char* Out, size_t OutLen, const char* In); CHARCONVERT_DLL void CharConvWS(charconv*, wchar_t* Out, size_t OutLen, const char* In); CHARCONVERT_DLL void CharConvSW(charconv*, char* Out, size_t OutLen, const wchar_t* In); CHARCONVERT_DLL void CharConvWW(charconv*, wchar_t* Out, size_t OutLen, const wchar_t* In); #if SIZEOF_WCHAR==2 #define CharConvUS CharConvWS #define CharConvSU CharConvSW #define CharConvUW CharConvWW #define CharConvWU CharConvWW #else CHARCONVERT_DLL void CharConvUS(charconv*, utf16_t* Out, size_t OutLen, const char* In); CHARCONVERT_DLL void CharConvSU(charconv*, char* Out, size_t OutLen, const utf16_t* In); CHARCONVERT_DLL void CharConvUW(charconv*, utf16_t* Out, size_t OutLen, const wchar_t* In); CHARCONVERT_DLL void CharConvWU(charconv*, wchar_t* Out, size_t OutLen, const utf16_t* In); #endif #ifdef UNICODE #define CharConvTS CharConvWS #define CharConvTW CharConvWW #define CharConvST CharConvSW #define CharConvWT CharConvWW #define CharConvTU CharConvWU #define CharConvUT CharConvUW #else #define CharConvTS CharConvSS #define CharConvTW CharConvSW #define CharConvST CharConvSS #define CharConvWT CharConvWS #define CharConvTU CharConvSU #define CharConvUT CharConvUS #endif #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert.proj000066400000000000000000000007561462133141200254560ustar00rootroot00000000000000GROUP charconvert { USE corec USE str SOURCE(TARGET_WIN) charconvert_win32.c SOURCE(TARGET_LINUX && (!TARGET_QTOPIA || QTOPIA_WITH_ICONV)) charconvert_linux.c SOURCE(TARGET_QTOPIA && !QTOPIA_WITH_ICONV) charconvert_qtopia.cpp SOURCE(TARGET_PALMOS) charconvert_palmos.c SOURCE(TARGET_SYMBIAN) charconvert_symbian.cpp FRAMEWORK(TARGET_OSX) CoreFoundation SOURCE(TARGET_OSX) charconvert_osx.c SOURCE(TARGET_PS2SDK || TARGET_ANDROID) charconvert_utf8.c HEADER charconvert.h } bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_linux.c000066400000000000000000000161001462133141200261330ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_LINUX) || defined (TARGET_QNX) #include #include #include #include #ifndef ICONV_CONST #if defined(__GLIBC__) #define ICONV_CONST #else #define ICONV_CONST const #endif #endif void CharConvSS(charconv* CC, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = strlen(In)+1; char* _Out = Out; size_t _OutLen = OutLen; if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { size_t n = min(strlen(In),OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; if (CC && _InLen) { // DebugMessage("iconv failed: %d for '%s'",errno,In); iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } } else *_Out=0; } } void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = strlen(In)+1; char* _Out = (char*)Out; size_t _OutLen = OutLen*sizeof(wchar_t); if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (wchar_t)*In; *Out = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } else *(wchar_t*)_Out=0; } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = wcslen(In)+1; char* _Out = Out; size_t _OutLen = OutLen; if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (char)(*In>255?'*':*In); *Out = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } else *_Out=0; } } void CharConvUS(charconv* CC, utf16_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = strlen(In)+1; char* _Out = (char*)Out; size_t _OutLen = OutLen*sizeof(utf16_t); if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (utf16_t)*In; *Out = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } else *(utf16_t*)_Out=0; } } void CharConvSU(charconv* CC, char* Out, size_t OutLen, const utf16_t* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = utf16len(In)+1; char* _Out = Out; size_t _OutLen = OutLen; if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (char)(*In>255?'*':*In); *Out = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } else *_Out=0; } } void CharConvWW(charconv* CC, wchar_t* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = (wcslen(In)+1)*sizeof(wchar_t); char* _Out = (char*)Out; size_t _OutLen = OutLen*sizeof(wchar_t); if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { size_t n = min(wcslen(In),OutLen-1); memcpy(Out,In,n*sizeof(wchar_t)); Out[n] = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } else *(wchar_t*)_Out=0; } } static NOINLINE char * GetDefault() { setlocale(LC_ALL,""); // set default for all char *Current = setlocale(LC_CTYPE,""); if (Current) Current = strrchr(Current,'.'); if (Current) ++Current; else Current = ""; return Current; } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { iconv_t CC; char *Current = GetDefault(); if (!From || !From[0]) From = Current; if (!To || !To[0]) To = Current; if (tcsicmp(To,From)==0) return NULL; CC = iconv_open(To,From); if (CC == (iconv_t)-1) return NULL; return (charconv*)CC; } void CharConvClose(charconv* p) { if (p) iconv_close((iconv_t)p); } void CharConvDefault(tchar_t* Out, size_t OutLen) { char *Current = GetDefault(); tcscpy_s(Out,OutLen,Current); } #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_osx.c000066400000000000000000000203621462133141200256120ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_OSX) //#include #include #include #include #ifndef ICONV_CONST #if defined(__GLIBC__) #define ICONV_CONST #else #define ICONV_CONST const #endif #endif #include #define LOSSY_CHAR '.' static char *Current = NULL; typedef struct charconv_osx { CFStringBuiltInEncodings EncFrom; CFStringBuiltInEncodings EncTo; } charconv_osx; // char to char conversion void CharConvSS(charconv* Conv, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { charconv_osx *CC = (charconv_osx *)Conv; if (CC) { CFStringRef TmpIn = CFStringCreateWithCString(NULL, In, CC->EncFrom); CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, CC->EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); Out[Read]=0; } else { size_t n = min(In?strlen(In):0,OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; } } } // char to utf16_t conversion void CharConvUS(charconv* Conv, utf16_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { // assume wchar_t is 16 bits even if it's not true charconv_osx *CC = (charconv_osx *)Conv; if (CC) { CFStringRef TmpIn = CFStringCreateWithCString(NULL, In, CC->EncFrom); assert(TmpIn); if (TmpIn) { CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, CC->EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); memset((UInt8*)Out+Read,0,sizeof(uint16_t)); } else { Out[0]=0; } } else { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } } } // utf16_t to char conversion void CharConvSU(charconv* Conv, char* Out, size_t OutLen, const utf16_t* In) { if (OutLen>0) { // assume wchar_t is 16 bits even if it's not true CFStringEncoding EncFrom,EncTo; if (Conv) { EncFrom = ((charconv_osx *)Conv)->EncFrom; EncTo = ((charconv_osx *)Conv)->EncTo; } else { EncFrom = kCFStringEncodingUTF16; EncTo = kCFStringEncodingUTF8; } CFStringRef TmpIn = CFStringCreateWithBytes(NULL, (const UInt8*)In, (utf16len(In)+1)*sizeof(utf16_t), EncFrom, false); CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); Out[Read]=0; } } void CharConvSW(charconv* Conv, char* Out, size_t OutLen, const wchar_t* In) { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } void CharConvWS(charconv* Conv, wchar_t* Out, size_t OutLen, const char* In) { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } void CharConvUW(charconv* Conv, utf16_t* Out, size_t OutLen, const wchar_t* In) { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } void CharConvWU(charconv* Conv, wchar_t* Out, size_t OutLen, const utf16_t* In) { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } // wchar_t to wchar_t conversion void CharConvWW(charconv* Conv, wchar_t* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { // assume wchar_t is 16 bits even if it's not true charconv_osx *CC = (charconv_osx *)Conv; if (CC) { CFStringRef TmpIn = CFStringCreateWithBytes(NULL, (const UInt8*)In, (utf16len((const uint16_t*)In)+1)*sizeof(uint16_t), CC->EncFrom, false); assert(TmpIn); CFIndex Read; CFRange r; r.location = 0; r.length = CFStringGetLength(TmpIn); CFStringGetBytes(TmpIn, r, CC->EncTo, LOSSY_CHAR, /* no lossy conversion */ 0, /* not external representation */ (UInt8*)Out, OutLen, &Read); CFRelease(TmpIn); memset((UInt8*)Out+Read,0,sizeof(uint16_t)); } else { fprintf(stderr, "Not supported yet: %s with no CC\n", __FUNCTION__); } } } static NOINLINE void GetDefault() { if (!Current) { setlocale(LC_ALL,""); // set default for all Current = setlocale(LC_CTYPE,""); if (strcmp(Current,"C")==0) Current = "ASCII"; if (Current) Current = strrchr(Current,'.'); if (Current) ++Current; else Current = ""; } } static CFStringBuiltInEncodings GetEncoding(const tchar_t* From) { if (!From) return kCFStringEncodingUTF8; // use UTF-8 internally else if (!From[0]) return kCFStringEncodingASCII; // regular/default strings are ASCII else if (tcsicmp(From,T("ASCII"))==0) return kCFStringEncodingASCII; else if (tcsicmp(From,T("UTF-8"))==0) return kCFStringEncodingUTF8; else if (tcsicmp(From,T("UTF-16"))==0) return kCFStringEncodingUTF16; else if (tcsicmp(From,T("UTF-32"))==0) return kCFStringEncodingUTF32; else if (tcsnicmp(From,T("CP"),2)==0) return CFStringConvertWindowsCodepageToEncoding(atoi(From+2)); return (CFStringBuiltInEncodings)kCFStringEncodingInvalidId; } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { charconv_osx TmpConv; charconv_osx *CC; TmpConv.EncFrom = GetEncoding(From); TmpConv.EncTo = GetEncoding(To); if (TmpConv.EncFrom == kCFStringEncodingInvalidId || TmpConv.EncTo == kCFStringEncodingInvalidId || TmpConv.EncFrom == TmpConv.EncTo) return NULL; CC = malloc(sizeof(*CC)); CC->EncFrom = TmpConv.EncFrom; CC->EncTo = TmpConv.EncTo; return (charconv*)CC; } void CharConvClose(charconv* p) { if (p) free(p); } void CharConvDefault(tchar_t* Out, size_t OutLen) { GetDefault(); tcscpy_s(Out,OutLen,Current); } #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_palmos.c000066400000000000000000000107551462133141200263010ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_PALMOS) #include static NOINLINE size_t wcslen_(const wchar_t* s) { size_t n=0; for (;*s;++s) ++n; return n; } void CharConvSS(charconv* CC, char* Out, size_t OutLen, const char* In) { if (OutLen) { if (CC) { UInt16 InBytes = (UInt16)strlen(In); UInt16 OutBytes = (UInt16)--OutLen; TxtConvertEncoding(1,NULL,In,&InBytes,(uint8_t)(uintptr_t)CC,Out,&OutBytes,(uint8_t)((((uintptr_t)CC)>>16)),"*",1); Out[min(OutLen,OutBytes)]=0; } else tcscpy_s(Out,OutLen,In); } } void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { if (OutLen) { UInt16 InBytes = (UInt16)strlen(In); UInt16 OutBytes = (UInt16)(--OutLen*sizeof(wchar_t)); TxtConvertEncoding(1,NULL,In,&InBytes,(uint8_t)(uintptr_t)CC,(char*)Out,&OutBytes,(uint8_t)((((uintptr_t)CC)>>16)),(char*)(L"*"),sizeof(wchar_t)); Out[min(OutLen,OutBytes/sizeof(wchar_t))]=0; } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { if (OutLen) { UInt16 InBytes = (UInt16)(wcslen_(In)*sizeof(wchar_t)); UInt16 OutBytes = (UInt16)--OutLen; TxtConvertEncoding(1,NULL,(char*)In,&InBytes,(uint8_t)(uintptr_t)CC,Out,&OutBytes,(uint8_t)((((uintptr_t)CC)>>16)),"*",sizeof(char)); Out[min(OutLen,OutBytes)]=0; } } void CharConvWW(charconv* CC, wchar_t* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { size_t n = min(wcslen_(In),OutLen-1); memcpy(Out,In,n*sizeof(wchar_t)); Out[n] = 0; } } static NOINLINE UInt32 GetCharSet(const tchar_t* Name) { UInt32 Type; if (Name && Name[0]) { if (tcsicmp(Name,CHARSET_WCHAR)==0) return charEncodingUTF16LE; if (tcsicmp(Name,CHARSET_UTF8)==0) return charEncodingUTF8; // only unicode<->current charset supported on PalmOS //if ((Type = TxtNameToEncoding(Name)) != charEncodingUnknown) // return Type; } if (FtrGet(sysFtrCreator, sysFtrNumEncoding, &Type) != errNone) Type = charEncodingPalmLatin; return Type; } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { UInt32 FromType = GetCharSet(From); UInt32 ToType = GetCharSet(To); if (FromType == ToType) return NULL; return (charconv*)(FromType | (ToType << 16)); } void CharConvClose(charconv* p) { } void CharConvDefault(tchar_t* Out, size_t OutLen) { const tchar_t* Name; UInt32 Type; if (FtrGet(sysFtrCreator, sysFtrNumEncoding, &Type) != errNone) Type = charEncodingPalmLatin; Name = TxtEncodingName((CharEncodingType)Type); if (Name) tcscpy_s(Out,OutLen,Name); else *Out = 0; } #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_qtopia.cpp000066400000000000000000000161241462133141200266370ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include #include #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_QTOPIA) #include typedef struct charconv { QTextCodec *From; QTextCodec *To; } charconv; void CharConvSS(charconv* CC, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { size_t _InLen; if (!CC) { size_t n = min(strlen(In),OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; } else if (!(_InLen = strlen(In))) Out[0] = 0; else { QString From = CC->From->toUnicode(In); QByteArray To = CC->To->fromUnicode(From); tcscpy_s(Out,OutLen,To.constData()); } } } void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { size_t _InLen; if (!CC) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (wchar_t)*In; *Out = 0; } else if (!(_InLen = strlen(In))) Out[0] = 0; else { QString From = CC->From->toUnicode(In); #ifndef QTOPIA_PHONE std::wstring To = From.toStdWString(); const wchar_t *_In = To.c_str(); for (;OutLen>1 && *_In;++_In,--OutLen,++Out) *Out = (wchar_t)*_In; *Out = 0; #endif } } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { size_t _InLen; if (!CC) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (char)*In; *Out = 0; } else if (!(_InLen = wcslen(In))) Out[0] = 0; else { #ifndef QTOPIA_PHONE QString From = QString::fromStdWString(In); QByteArray To = CC->To->fromUnicode(From); tcscpy_s(Out,OutLen,To.constData()); #endif } } } void CharConvUS(charconv* CC, utf16_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { size_t _InLen; if (!CC) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (utf16_t)*In; *Out = 0; } else if (!(_InLen = strlen(In))) Out[0] = 0; else { QString From = CC->From->toUnicode(In); #ifndef QTOPIA_PHONE const ushort *_In = From.utf16(); for (;OutLen>1 && *_In;++_In,--OutLen,++Out) *Out = (utf16_t)*_In; *Out = 0; #endif } } } void CharConvSU(charconv* CC, char* Out, size_t OutLen, const utf16_t* In) { if (OutLen>0) { size_t _InLen; if (!CC) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (char)*In; *Out = 0; } else if (!(_InLen = utf16len(In))) Out[0] = 0; else { #ifndef QTOPIA_PHONE QString From = QString::fromUtf16((const ushort*)In); QByteArray To = CC->To->fromUnicode(From); tcscpy_s(Out,OutLen,To.constData()); #endif } } } void CharConvWW(charconv* CC, wchar_t* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { size_t _InLen; if (!CC) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = *In; *Out = 0; } else if (!(_InLen = wcslen(In))) Out[0] = 0; #if 0 ICONV_CONST char* _In = (ICONV_CONST char*)In; size_t _InLen = (wcslen(In)+1)*sizeof(wchar_t); char* _Out = (char*)Out; size_t _OutLen = OutLen*sizeof(wchar_t); if (!CC || !_InLen || iconv((iconv_t)CC, &_In, &_InLen, &_Out, &_OutLen) == -1 || iconv((iconv_t)CC, NULL, NULL, &_Out, &_OutLen) == -1) { size_t n = min(wcslen(In),OutLen-1); memcpy(Out,In,n*sizeof(wchar_t)); Out[n] = 0; if (CC && _InLen) iconv((iconv_t)CC, NULL, NULL, NULL, NULL); // reset state } #endif } } static bool_t CharConvWinCP(const tchar_t *Conv, tchar_t *Fill, size_t FillLen) { if (tcsicmp(Conv,T("CP1252"))==0) { tcscpy_s(Fill,FillLen,T("latin1")); return 1; } if (Conv && Conv[0] == 'C' && Conv[1] == 'P' && (Conv[2] <= '9' && Conv[2] >= '0')) { tcscpy_s(Fill,FillLen,T("Windows-")); tcscat_s(Fill,FillLen,Conv+2); return 1; } return 0; } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { charconv *p,CC = {NULL,NULL}; tchar_t AltCP[20]; if (!From || !From[0]) From = T("UTF-8"); else if (CharConvWinCP(From,AltCP,TSIZEOF(AltCP))) From = AltCP; if (!CC.From) CC.From = QTextCodec::codecForName(From); if (!To || !To[0]) To = T("UTF-8"); else if (CharConvWinCP(To,AltCP,TSIZEOF(AltCP))) To = AltCP; if (!CC.To) CC.To = QTextCodec::codecForName(To); if (!CC.To || !CC.From || CC.To == CC.From) return NULL; p = (charconv*)malloc(sizeof(charconv)); memcpy(p,&CC,sizeof(charconv)); return p; } void CharConvClose(charconv* p) { if (p) free(p); } void CharConvDefault(tchar_t* Out, size_t OutLen) { if (Out && OutLen) { QTextCodec *Locale = QTextCodec::codecForLocale(); if (Locale) tcscpy_s(Out,OutLen,Locale->name().constData()); } } #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_symbian.cpp000066400000000000000000000111021462133141200267730ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_SYMBIAN) #include #include void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { if (OutLen) { TPtrC8 _In((const uint8_t*)In); TPtr16 _Out((uint16_t*)Out,OutLen-1); int State = CCnvCharacterSetConverter::KStateDefault; if (CC) ((CCnvCharacterSetConverter*)CC)->ConvertToUnicode(_Out,_In,State); else CnvUtfConverter::ConvertToUnicodeFromUtf8(_Out,_In); Out[_Out.Length()]=0; } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { if (OutLen) { TPtrC16 _In((const uint16_t*)In); TPtr8 _Out((uint8_t*)Out,OutLen-1); if (CC) ((CCnvCharacterSetConverter*)CC)->ConvertFromUnicode(_Out,_In); else CnvUtfConverter::ConvertFromUnicodeToUtf8(_Out,_In); Out[_Out.Length()]=0; } } void CharConvWW(charconv* UNUSED_PARAM(CC), wchar_t* Out, size_t OutLen, const wchar_t* In) { tcscpy_s(Out,OutLen,In); } typedef struct codepage { const tchar_t* Name; uint16_t CodePage; } codepage; static const codepage CodePage[] = { {T("Shift_JIS"), 932}, {T("GB2312"), 936}, {T("BIG5"), 950}, {T("ISO-8859-1"), 1252}, {T("ISO-8859-2"), 1250}, {T("ISO-8859-3"), 1254}, {T("ISO-8859-4"), 1257}, {T("ISO-8859-5"), 1251}, {T("ISO-8859-6"), 1256}, {T("ISO-8859-7"), 1253}, {T("ISO-8859-8"), 1255}, {NULL}, }; charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { const tchar_t* Name = From ? From:To; if (!Name || tcsicmp(Name,CHARSET_WCHAR)==0 || tcsicmp(Name,CHARSET_UTF8)==0) return NULL; tchar_t Default[MAX_CHARSET_NAME]; if (!Name[0]) { CharConvDefault(Default,TSIZEOF(Default)); Name = Default; } int CP; if (stscanf(Name,T("CP%d"),&CP)==1 || stscanf(Name,T("windows-%d"),&CP)==1) { const codepage* i; for (i=CodePage;i->Name;++i) { if (i->CodePage == CP) { Name = i->Name; break; } } } TBuf8 Name8; CnvUtfConverter::ConvertFromUnicodeToUtf8(Name8,TPtrC((TText*)Name)); RFs FsSession; FsSession.Connect(); CCnvCharacterSetConverter* p = CCnvCharacterSetConverter::NewL(); TUint Id = p->ConvertStandardNameOfCharacterSetToIdentifierL(Name8,FsSession); if (!Id || CCnvCharacterSetConverter::EAvailable != p->PrepareToConvertToOrFromL(Id,FsSession)) { delete p; p = NULL; } FsSession.Close(); return (charconv*)p; } void CharConvClose(charconv* p) { if (p) delete (CCnvCharacterSetConverter*)p; } void CharConvDefault(tchar_t* Out, size_t OutLen) { tcscpy_s(Out,OutLen,T("ISO-8859-1")); } #endif bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_utf8.c000066400000000000000000000534741462133141200257010ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "charconvert.h" #include "corec/str/str.h" static const uint16_t codepage_1250[128] = { 0x20ac,0x0081,0x201a,0x0083,0x201e,0x2026,0x2020,0x2021,0x0088,0x2030,0x0160,0x2039,0x015a,0x0164,0x017d,0x0179, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x0098,0x2122,0x0161,0x203a,0x015b,0x0165,0x017e,0x017a, 0x00a0,0x02c7,0x02d8,0x0141,0x00a4,0x0104,0x00a6,0x00a7,0x00a8,0x00a9,0x015e,0x00ab,0x00ac,0x00ad,0x00ae,0x017b, 0x00b0,0x00b1,0x02db,0x0142,0x00b4,0x00b5,0x00b6,0x00b7,0x00b8,0x0105,0x015f,0x00bb,0x013d,0x02dd,0x013e,0x017c, 0x0154,0x00c1,0x00c2,0x0102,0x00c4,0x0139,0x0106,0x00c7,0x010c,0x00c9,0x0118,0x00cb,0x011a,0x00cd,0x00ce,0x010e, 0x0110,0x0143,0x0147,0x00d3,0x00d4,0x0150,0x00d6,0x00d7,0x0158,0x016e,0x00da,0x0170,0x00dc,0x00dd,0x0162,0x00df, 0x0155,0x00e1,0x00e2,0x0103,0x00e4,0x013a,0x0107,0x00e7,0x010d,0x00e9,0x0119,0x00eb,0x011b,0x00ed,0x00ee,0x010f, 0x0111,0x0144,0x0148,0x00f3,0x00f4,0x0151,0x00f6,0x00f7,0x0159,0x016f,0x00fa,0x0171,0x00fc,0x00fd,0x0163,0x02d9 }; static const uint8_t codepage_1250_r[128] = { 0x01,0x03,0x08,0x10,0x18,0x20,0x24,0x26,0x27,0x28,0x29,0x2b,0x2c,0x2d,0x2e,0x30, 0x31,0x34,0x35,0x36,0x37,0x38,0x3b,0x41,0x42,0x44,0x47,0x49,0x4b,0x4d,0x4e,0x53, 0x54,0x56,0x57,0x5a,0x5c,0x5d,0x5f,0x61,0x62,0x64,0x67,0x69,0x6b,0x6d,0x6e,0x73, 0x74,0x76,0x77,0x7a,0x7c,0x7d,0x43,0x63,0x25,0x39,0x46,0x66,0x48,0x68,0x4f,0x6f, 0x50,0x70,0x4a,0x6a,0x4c,0x6c,0x45,0x65,0x3c,0x3e,0x23,0x33,0x51,0x71,0x52,0x72, 0x55,0x75,0x40,0x60,0x58,0x78,0x0c,0x1c,0x2a,0x3a,0x0a,0x1a,0x5e,0x7e,0x0d,0x1d, 0x59,0x79,0x5b,0x7b,0x0f,0x1f,0x2f,0x3f,0x0e,0x1e,0x21,0x22,0x7f,0x32,0x3d,0x16, 0x17,0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19 }; static const uint16_t codepage_1251[128] = { 0x0402,0x0403,0x201a,0x0453,0x201e,0x2026,0x2020,0x2021,0x20ac,0x2030,0x0409,0x2039,0x040a,0x040c,0x040b,0x040f, 0x0452,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x0098,0x2122,0x0459,0x203a,0x045a,0x045c,0x045b,0x045f, 0x00a0,0x040e,0x045e,0x0408,0x00a4,0x0490,0x00a6,0x00a7,0x0401,0x00a9,0x0404,0x00ab,0x00ac,0x00ad,0x00ae,0x0407, 0x00b0,0x00b1,0x0406,0x0456,0x0491,0x00b5,0x00b6,0x00b7,0x0451,0x2116,0x0454,0x00bb,0x0458,0x0405,0x0455,0x0457, 0x0410,0x0411,0x0412,0x0413,0x0414,0x0415,0x0416,0x0417,0x0418,0x0419,0x041a,0x041b,0x041c,0x041d,0x041e,0x041f, 0x0420,0x0421,0x0422,0x0423,0x0424,0x0425,0x0426,0x0427,0x0428,0x0429,0x042a,0x042b,0x042c,0x042d,0x042e,0x042f, 0x0430,0x0431,0x0432,0x0433,0x0434,0x0435,0x0436,0x0437,0x0438,0x0439,0x043a,0x043b,0x043c,0x043d,0x043e,0x043f, 0x0440,0x0441,0x0442,0x0443,0x0444,0x0445,0x0446,0x0447,0x0448,0x0449,0x044a,0x044b,0x044c,0x044d,0x044e,0x044f }; static const uint8_t codepage_1251_r[128] = { 0x18,0x20,0x24,0x26,0x27,0x29,0x2b,0x2c,0x2d,0x2e,0x30,0x31,0x35,0x36,0x37,0x3b, 0x28,0x00,0x01,0x2a,0x3d,0x32,0x2f,0x23,0x0a,0x0c,0x0e,0x0d,0x21,0x0f,0x40,0x41, 0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51, 0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,0x60,0x61, 0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71, 0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,0x38,0x10, 0x03,0x3a,0x3e,0x33,0x3f,0x3c,0x1a,0x1c,0x1e,0x1d,0x22,0x1f,0x25,0x34,0x16,0x17, 0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x08,0x39,0x19 }; static const uint16_t codepage_1252[128] = { 0x20ac,0x0081,0x201a,0x0192,0x201e,0x2026,0x2020,0x2021,0x02c6,0x2030,0x0160,0x2039,0x0152,0x008d,0x017d,0x008f, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x02dc,0x2122,0x0161,0x203a,0x0153,0x009d,0x017e,0x0178, 0x00a0,0x00a1,0x00a2,0x00a3,0x00a4,0x00a5,0x00a6,0x00a7,0x00a8,0x00a9,0x00aa,0x00ab,0x00ac,0x00ad,0x00ae,0x00af, 0x00b0,0x00b1,0x00b2,0x00b3,0x00b4,0x00b5,0x00b6,0x00b7,0x00b8,0x00b9,0x00ba,0x00bb,0x00bc,0x00bd,0x00be,0x00bf, 0x00c0,0x00c1,0x00c2,0x00c3,0x00c4,0x00c5,0x00c6,0x00c7,0x00c8,0x00c9,0x00ca,0x00cb,0x00cc,0x00cd,0x00ce,0x00cf, 0x00d0,0x00d1,0x00d2,0x00d3,0x00d4,0x00d5,0x00d6,0x00d7,0x00d8,0x00d9,0x00da,0x00db,0x00dc,0x00dd,0x00de,0x00df, 0x00e0,0x00e1,0x00e2,0x00e3,0x00e4,0x00e5,0x00e6,0x00e7,0x00e8,0x00e9,0x00ea,0x00eb,0x00ec,0x00ed,0x00ee,0x00ef, 0x00f0,0x00f1,0x00f2,0x00f3,0x00f4,0x00f5,0x00f6,0x00f7,0x00f8,0x00f9,0x00fa,0x00fb,0x00fc,0x00fd,0x00fe,0x00ff }; static const uint8_t codepage_1252_r[128] = { 0x01,0x0d,0x0f,0x10,0x1d,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a, 0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a, 0x3b,0x3c,0x3d,0x3e,0x3f,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a, 0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a, 0x5b,0x5c,0x5d,0x5e,0x5f,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a, 0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a, 0x7b,0x7c,0x7d,0x7e,0x7f,0x0c,0x1c,0x0a,0x1a,0x1f,0x0e,0x1e,0x03,0x08,0x18,0x16, 0x17,0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19 }; static const uint16_t codepage_1253[128] = { 0x20ac,0x0081,0x201a,0x0192,0x201e,0x2026,0x2020,0x2021,0x0088,0x2030,0x008a,0x2039,0x008c,0x008d,0x008e,0x008f, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x0098,0x2122,0x009a,0x203a,0x009c,0x009d,0x009e,0x009f, 0x00a0,0x0385,0x0386,0x00a3,0x00a4,0x00a5,0x00a6,0x00a7,0x00a8,0x00a9,0xf8f9,0x00ab,0x00ac,0x00ad,0x00ae,0x2015, 0x00b0,0x00b1,0x00b2,0x00b3,0x0384,0x00b5,0x00b6,0x00b7,0x0388,0x0389,0x038a,0x00bb,0x038c,0x00bd,0x038e,0x038f, 0x0390,0x0391,0x0392,0x0393,0x0394,0x0395,0x0396,0x0397,0x0398,0x0399,0x039a,0x039b,0x039c,0x039d,0x039e,0x039f, 0x03a0,0x03a1,0xf8fa,0x03a3,0x03a4,0x03a5,0x03a6,0x03a7,0x03a8,0x03a9,0x03aa,0x03ab,0x03ac,0x03ad,0x03ae,0x03af, 0x03b0,0x03b1,0x03b2,0x03b3,0x03b4,0x03b5,0x03b6,0x03b7,0x03b8,0x03b9,0x03ba,0x03bb,0x03bc,0x03bd,0x03be,0x03bf, 0x03c0,0x03c1,0x03c2,0x03c3,0x03c4,0x03c5,0x03c6,0x03c7,0x03c8,0x03c9,0x03ca,0x03cb,0x03cc,0x03cd,0x03ce,0xf8fb }; static const uint8_t codepage_1253_r[128] = { 0x01,0x08,0x0a,0x0c,0x0d,0x0e,0x0f,0x10,0x18,0x1a,0x1c,0x1d,0x1e,0x1f,0x20,0x23, 0x24,0x25,0x26,0x27,0x28,0x29,0x2b,0x2c,0x2d,0x2e,0x30,0x31,0x32,0x33,0x35,0x36, 0x37,0x3b,0x3d,0x03,0x34,0x21,0x22,0x38,0x39,0x3a,0x3c,0x3e,0x3f,0x40,0x41,0x42, 0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x53, 0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,0x60,0x61,0x62,0x63, 0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73, 0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x16,0x17,0x2f,0x11,0x12, 0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19,0x2a,0x52,0x7f }; static const uint16_t codepage_1254[128] = { 0x20ac,0x0081,0x201a,0x0192,0x201e,0x2026,0x2020,0x2021,0x02c6,0x2030,0x0160,0x2039,0x0152,0x008d,0x008e,0x008f, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x02dc,0x2122,0x0161,0x203a,0x0153,0x009d,0x009e,0x0178, 0x00a0,0x00a1,0x00a2,0x00a3,0x00a4,0x00a5,0x00a6,0x00a7,0x00a8,0x00a9,0x00aa,0x00ab,0x00ac,0x00ad,0x00ae,0x00af, 0x00b0,0x00b1,0x00b2,0x00b3,0x00b4,0x00b5,0x00b6,0x00b7,0x00b8,0x00b9,0x00ba,0x00bb,0x00bc,0x00bd,0x00be,0x00bf, 0x00c0,0x00c1,0x00c2,0x00c3,0x00c4,0x00c5,0x00c6,0x00c7,0x00c8,0x00c9,0x00ca,0x00cb,0x00cc,0x00cd,0x00ce,0x00cf, 0x011e,0x00d1,0x00d2,0x00d3,0x00d4,0x00d5,0x00d6,0x00d7,0x00d8,0x00d9,0x00da,0x00db,0x00dc,0x0130,0x015e,0x00df, 0x00e0,0x00e1,0x00e2,0x00e3,0x00e4,0x00e5,0x00e6,0x00e7,0x00e8,0x00e9,0x00ea,0x00eb,0x00ec,0x00ed,0x00ee,0x00ef, 0x011f,0x00f1,0x00f2,0x00f3,0x00f4,0x00f5,0x00f6,0x00f7,0x00f8,0x00f9,0x00fa,0x00fb,0x00fc,0x0131,0x015f,0x00ff }; static const uint8_t codepage_1254_r[128] = { 0x01,0x0d,0x0e,0x0f,0x10,0x1d,0x1e,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28, 0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38, 0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48, 0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x5b,0x5c,0x5f,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b, 0x6c,0x6d,0x6e,0x6f,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c, 0x7f,0x50,0x70,0x5d,0x7d,0x0c,0x1c,0x5e,0x7e,0x0a,0x1a,0x1f,0x03,0x08,0x18,0x16, 0x17,0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19 }; static const uint16_t codepage_1255[128] = { 0x20ac,0x0081,0x201a,0x0192,0x201e,0x2026,0x2020,0x2021,0x02c6,0x2030,0x008a,0x2039,0x008c,0x008d,0x008e,0x008f, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x02dc,0x2122,0x009a,0x203a,0x009c,0x009d,0x009e,0x009f, 0x00a0,0x00a1,0x00a2,0x00a3,0x20aa,0x00a5,0x00a6,0x00a7,0x00a8,0x00a9,0x00d7,0x00ab,0x00ac,0x00ad,0x00ae,0x00af, 0x00b0,0x00b1,0x00b2,0x00b3,0x00b4,0x00b5,0x00b6,0x00b7,0x00b8,0x00b9,0x00f7,0x00bb,0x00bc,0x00bd,0x00be,0x00bf, 0x05b0,0x05b1,0x05b2,0x05b3,0x05b4,0x05b5,0x05b6,0x05b7,0x05b8,0x05b9,0x05ba,0x05bb,0x05bc,0x05bd,0x05be,0x05bf, 0x05c0,0x05c1,0x05c2,0x05c3,0x05f0,0x05f1,0x05f2,0x05f3,0x05f4,0xf88d,0xf88e,0xf88f,0xf890,0xf891,0xf892,0xf893, 0x05d0,0x05d1,0x05d2,0x05d3,0x05d4,0x05d5,0x05d6,0x05d7,0x05d8,0x05d9,0x05da,0x05db,0x05dc,0x05dd,0x05de,0x05df, 0x05e0,0x05e1,0x05e2,0x05e3,0x05e4,0x05e5,0x05e6,0x05e7,0x05e8,0x05e9,0x05ea,0xf894,0xf895,0x200e,0x200f,0xf896 }; static const uint8_t codepage_1255_r[128] = { 0x01,0x0a,0x0c,0x0d,0x0e,0x0f,0x10,0x1a,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23, 0x25,0x26,0x27,0x28,0x29,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x34,0x35, 0x36,0x37,0x38,0x39,0x3b,0x3c,0x3d,0x3e,0x3f,0x2a,0x3a,0x03,0x08,0x18,0x40,0x41, 0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51, 0x52,0x53,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d, 0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x54,0x55,0x56, 0x57,0x58,0x7d,0x7e,0x16,0x17,0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05, 0x09,0x0b,0x1b,0x24,0x00,0x19,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,0x7b,0x7c,0x7f }; static const uint16_t codepage_1256[128] = { 0x20ac,0x067e,0x201a,0x0192,0x201e,0x2026,0x2020,0x2021,0x02c6,0x2030,0x0679,0x2039,0x0152,0x0686,0x0698,0x0688, 0x06af,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x06a9,0x2122,0x0691,0x203a,0x0153,0x200c,0x200d,0x06ba, 0x00a0,0x060c,0x00a2,0x00a3,0x00a4,0x00a5,0x00a6,0x00a7,0x00a8,0x00a9,0x06be,0x00ab,0x00ac,0x00ad,0x00ae,0x00af, 0x00b0,0x00b1,0x00b2,0x00b3,0x00b4,0x00b5,0x00b6,0x00b7,0x00b8,0x00b9,0x061b,0x00bb,0x00bc,0x00bd,0x00be,0x061f, 0x06c1,0x0621,0x0622,0x0623,0x0624,0x0625,0x0626,0x0627,0x0628,0x0629,0x062a,0x062b,0x062c,0x062d,0x062e,0x062f, 0x0630,0x0631,0x0632,0x0633,0x0634,0x0635,0x0636,0x00d7,0x0637,0x0638,0x0639,0x063a,0x0640,0x0641,0x0642,0x0643, 0x00e0,0x0644,0x00e2,0x0645,0x0646,0x0647,0x0648,0x00e7,0x00e8,0x00e9,0x00ea,0x00eb,0x0649,0x064a,0x00ee,0x00ef, 0x064b,0x064c,0x064d,0x064e,0x00f4,0x064f,0x0650,0x00f7,0x0651,0x00f9,0x0652,0x00fb,0x00fc,0x200e,0x200f,0x06d2 }; static const uint8_t codepage_1256_r[128] = { 0x20,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31, 0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3b,0x3c,0x3d,0x3e,0x57,0x60,0x62,0x67, 0x68,0x69,0x6a,0x6b,0x6e,0x6f,0x74,0x77,0x79,0x7b,0x7c,0x0c,0x1c,0x03,0x08,0x21, 0x3a,0x3f,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e, 0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f, 0x61,0x63,0x64,0x65,0x66,0x6c,0x6d,0x70,0x71,0x72,0x73,0x75,0x76,0x78,0x7a,0x0a, 0x01,0x0d,0x0f,0x1a,0x0e,0x18,0x10,0x1f,0x2a,0x40,0x7f,0x1d,0x1e,0x7d,0x7e,0x16, 0x17,0x11,0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19 }; static const uint16_t codepage_1257[128] = { 0x20ac,0x0081,0x201a,0x0083,0x201e,0x2026,0x2020,0x2021,0x0088,0x2030,0x008a,0x2039,0x008c,0x00a8,0x02c7,0x00b8, 0x0090,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x0098,0x2122,0x009a,0x203a,0x009c,0x00af,0x02db,0x009f, 0x00a0,0xf8fc,0x00a2,0x00a3,0x00a4,0xf8fd,0x00a6,0x00a7,0x00d8,0x00a9,0x0156,0x00ab,0x00ac,0x00ad,0x00ae,0x00c6, 0x00b0,0x00b1,0x00b2,0x00b3,0x00b4,0x00b5,0x00b6,0x00b7,0x00f8,0x00b9,0x0157,0x00bb,0x00bc,0x00bd,0x00be,0x00e6, 0x0104,0x012e,0x0100,0x0106,0x00c4,0x00c5,0x0118,0x0112,0x010c,0x00c9,0x0179,0x0116,0x0122,0x0136,0x012a,0x013b, 0x0160,0x0143,0x0145,0x00d3,0x014c,0x00d5,0x00d6,0x00d7,0x0172,0x0141,0x015a,0x016a,0x00dc,0x017b,0x017d,0x00df, 0x0105,0x012f,0x0101,0x0107,0x00e4,0x00e5,0x0119,0x0113,0x010d,0x00e9,0x017a,0x0117,0x0123,0x0137,0x012b,0x013c, 0x0161,0x0144,0x0146,0x00f3,0x014d,0x00f5,0x00f6,0x00f7,0x0173,0x0142,0x015b,0x016b,0x00fc,0x017c,0x017e,0x02d9 }; static const uint8_t codepage_1257_r[128] = { 0x01,0x03,0x08,0x0a,0x0c,0x10,0x18,0x1a,0x1c,0x1f,0x20,0x22,0x23,0x24,0x26,0x27, 0x0d,0x29,0x2b,0x2c,0x2d,0x2e,0x1d,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x0f, 0x39,0x3b,0x3c,0x3d,0x3e,0x44,0x45,0x2f,0x49,0x53,0x55,0x56,0x57,0x28,0x5c,0x5f, 0x64,0x65,0x3f,0x69,0x73,0x75,0x76,0x77,0x38,0x7c,0x42,0x62,0x40,0x60,0x43,0x63, 0x48,0x68,0x47,0x67,0x4b,0x6b,0x46,0x66,0x4c,0x6c,0x4e,0x6e,0x41,0x61,0x4d,0x6d, 0x4f,0x6f,0x59,0x79,0x51,0x71,0x52,0x72,0x54,0x74,0x2a,0x3a,0x5a,0x7a,0x50,0x70, 0x5b,0x7b,0x58,0x78,0x4a,0x6a,0x5d,0x7d,0x5e,0x7e,0x0e,0x7f,0x1e,0x16,0x17,0x11, 0x12,0x02,0x13,0x14,0x04,0x06,0x07,0x15,0x05,0x09,0x0b,0x1b,0x00,0x19,0x21,0x25 }; typedef struct codepage codepage; typedef uint_fast32_t (readcodepage)(const codepage* p, const char** In); typedef size_t (writecodepage)(const codepage* p, char** Out, size_t OutLen, uint_fast32_t ch); struct codepage { int CodePage; const tchar_t* Name; const uint16_t* UTF; const uint8_t* Index; readcodepage* Read; writecodepage* Write; }; struct charconv { const codepage* From; const codepage* To; }; static uint_fast32_t Read_Simple(const codepage* p, const char** InPtr) { uint_fast32_t ch; assert(p->UTF); ch=*(const uint8_t*)(*InPtr); ++(*InPtr); if (ch & 0x80) ch = p->UTF[ch-128]; return ch; } static uint_fast32_t Read_UTF8(const codepage* p, const char** InPtr) { uint_fast32_t ch; const uint8_t* In = (const uint8_t*)*InPtr; if ((In[0]&0x80)==0) // most of the time { ++(*InPtr); return In[0]; } if ((In[0]&0xe0)==0xc0 && (In[1]&0xc0)==0x80) { ch=((In[0]&0x1f)<<6)+(In[1]&0x3f); In+=2; } else if ((In[0]&0xf0)==0xe0 && (In[1]&0xc0)==0x80 && (In[2]&0xc0)==0x80) { ch=((In[0]&0x0f)<<12)+((In[1]&0x3f)<<6)+(In[2]&0x3f); In+=3; } else if ((In[0]&0xf8)==0xf0 && (In[1]&0xc0)==0x80 && (In[2]&0xc0)==0x80 && (In[3]&0xc0)==0x80) { ch=((In[0]&0x07)<<18)+((In[1]&0x3f)<<12)+((In[2]&0x3f)<<6)+(In[3]&0x3f); In+=4; } else { ch=In[0]; ++In; } *InPtr = (const char*)In; return ch; } static size_t Write_Simple(const codepage* p, char** OutPtr, size_t OutLen, uint_fast32_t ch) { assert(p->UTF && p->Index); if (OutLen>1) { if (ch>=128 && (ch>=256 || p->UTF[ch-128]!=ch)) { intptr_t Mid; intptr_t Lower = 0; intptr_t Upper = 127; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; if (p->UTF[p->Index[Mid]]>ch) Upper = Mid-1; else if (p->UTF[p->Index[Mid]]Index[Mid]+128; goto found; } } ch='?'; } found: *((*OutPtr)++) = (char)ch; --OutLen; } return OutLen; } static size_t Write_UTF8(const codepage* p, char** OutPtr, size_t OutLen, uint_fast32_t ch) { uint8_t* Out=(uint8_t*)*OutPtr; if (ch<0x80 && OutLen>1) { *Out=(uint8_t)ch; ++Out; --OutLen; } else if (ch<0x800 && OutLen>2) { Out[0]=(uint8_t)(0xc0|((ch>>6)&0x1f)); Out[1]=(uint8_t)(0x80|(ch&0x3f)); Out+=2; OutLen-=2; } else if (ch<0x10000 && OutLen>3) { Out[0]=(uint8_t)(0xe0|((ch>>12)&0x0f)); Out[1]=(uint8_t)(0x80|((ch>>6)&0x3f)); Out[2]=(uint8_t)(0x80|(ch&0x3f)); Out+=3; OutLen-=3; } else if (OutLen>4) { Out[0]=(uint8_t)(0xf0|((ch>>18)&0x07)); Out[1]=(uint8_t)(0x80|((ch>>12)&0x3f)); Out[2]=(uint8_t)(0x80|((ch>>6)&0x3f)); Out[3]=(uint8_t)(0x80|(ch&0x3f)); Out+=4; OutLen-=4; } *OutPtr=(char*)Out; return OutLen; } void CharConvSS(charconv* CC, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { if (CC) { const codepage* From=CC->From; const codepage* To=CC->To; while (*In) { uint_fast32_t ch = From->Read(From,&In); OutLen=To->Write(To,&Out,OutLen,ch); } *Out = 0; } else { size_t n = min(strlen(In),OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; } } } #if SIZEOF_WCHAR!=2 void CharConvUS(charconv* CC, utf16_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { const codepage* From=CC->From; while (*In) { uint_fast32_t ch = From->Read(From,&In); if (ch>=0x10000 && OutLen>2) { Out[0]=(uint16_t)((((ch-0x10000)>>10)&0x3ff)|0xd800); Out[1]=(uint16_t)(((ch-0x10000)&0x3ff)|0xdc00); Out+=2; OutLen-=2; } else if (OutLen>1) { *Out=(uint16_t)ch; ++Out; --OutLen; } } *Out = 0; } } void CharConvSU(charconv* CC, char* Out, size_t OutLen, const utf16_t* In) { if (OutLen>0) { const codepage* To=CC->To; while (*In) { uint_fast32_t ch; if ((In[0]&~0x3ff)==0xd800 && (In[1]&~0x3ff)==0xdc00) { ch=(((In[0]&0x3ff)<<10)|(In[1]&0x3ff))+0x10000; In+=2; } else { ch=*(const uint16_t*)In; ++In; } OutLen=To->Write(To,&Out,OutLen,ch); } *Out = 0; } } #endif void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { if (OutLen>0) { const codepage* From=CC->From; while (*In && OutLen>1) { *Out = (wchar_t)From->Read(From,&In); ++Out; --OutLen; } *Out = 0; } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { if (OutLen>0) { const codepage* To=CC->To; while (*In) { uint_fast32_t ch = *(In++); OutLen=To->Write(To,&Out,OutLen,ch); } *Out = 0; } } static const codepage CodePage[] = { {1252, T("ISO-8859-1"), codepage_1252,codepage_1252_r, Read_Simple, Write_Simple}, {1250, T("ISO-8859-2"), codepage_1250,codepage_1250_r, Read_Simple, Write_Simple}, {1254, T("ISO-8859-3"), codepage_1254,codepage_1254_r, Read_Simple, Write_Simple}, {1257, T("ISO-8859-4"), codepage_1257,codepage_1257_r, Read_Simple, Write_Simple}, {1251, T("ISO-8859-5"), codepage_1251,codepage_1251_r, Read_Simple, Write_Simple}, {1256, T("ISO-8859-6"), codepage_1256,codepage_1256_r, Read_Simple, Write_Simple}, {1253, T("ISO-8859-7"), codepage_1253,codepage_1253_r, Read_Simple, Write_Simple}, {1255, T("ISO-8859-8"), codepage_1255,codepage_1255_r, Read_Simple, Write_Simple}, {65001,T("UTF-8"), NULL,NULL, Read_UTF8, Write_UTF8}, {-1, T("UTF-16"), NULL,NULL}, {-1, T("UTF-32"), NULL,NULL}, {0, NULL}, }; static NOINLINE const codepage* GetCodePage(const tchar_t* Name) { const codepage* i; int CP; if (!Name) Name = "UTF-8"; if (stscanf(Name,T("CP%d"),&CP)<1 && stscanf(Name,T("windows-%d"),&CP)<1) CP=0; for (i=CodePage;i->Name;++i) if (tcsisame_ascii(Name,i->Name) || i->CodePage==CP) return i; return CodePage; //defaults to 1252 } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { charconv* CC = NULL; const codepage* FromCP = GetCodePage(From); const codepage* ToCP = GetCodePage(To); if (FromCP!=ToCP) { CC = malloc(sizeof(charconv)); if (CC) { CC->From = FromCP; CC->To = ToCP; } } return CC; } void CharConvClose(charconv* p) { free(p); } void CharConvDefault(tchar_t* Out, size_t OutLen) { tcscpy_s(Out,OutLen,GetCodePage(T(""))->Name); } bcmatroska2-5.3.101/corec/corec/helpers/charconvert/charconvert_win32.c000066400000000000000000000111051462133141200257360ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "charconvert.h" #include "corec/str/str.h" #if defined(TARGET_WIN) #ifndef STRICT #define STRICT #endif #include #ifndef CP_UTF8 #define CP_UTF8 65001 #endif #ifndef CP_UTF7 #define CP_UTF7 65000 #endif void CharConvSS(charconv* CC, char* Out, size_t OutLen, const char* In) { if (OutLen>0) { WCHAR Temp[1024]; UINT OutCode = LOWORD((DWORD)CC); UINT InCode = HIWORD((DWORD)CC); if (InCode == OutCode || !MultiByteToWideChar(InCode,0,In,-1,Temp,512) || !WideCharToMultiByte(OutCode,0,Temp,-1,Out,OutLen,0,0)) { size_t n = min(strlen(In),OutLen-1); memcpy(Out,In,n*sizeof(char)); Out[n] = 0; } } } void CharConvWS(charconv* CC, wchar_t* Out, size_t OutLen, const char* In) { UINT InCode = HIWORD((DWORD)CC); if (!MultiByteToWideChar(InCode,0,In,-1,Out,OutLen)) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (wchar_t)*In; *Out = 0; } } void CharConvSW(charconv* CC, char* Out, size_t OutLen, const wchar_t* In) { UINT OutCode = LOWORD((DWORD)CC); if (!WideCharToMultiByte(OutCode,0,In,-1,Out,OutLen,0,0)) { for (;OutLen>1 && *In;++In,--OutLen,++Out) *Out = (char)(*In>255?'*':*In); *Out = 0; } } void CharConvWW(charconv* UNUSED_PARAM(CC), wchar_t* Out, size_t OutLen, const wchar_t* In) { #ifdef UNICODE tcscpy_s(Out,OutLen,In); #else if (OutLen>0) { size_t n = min(wcslen(In),OutLen-1); memcpy(Out,In,n*sizeof(wchar_t)); Out[n] = 0; } #endif } typedef struct codepage { const tchar_t* Name; uint16_t CodePage; uint16_t CodePage2; } codepage; static const codepage CodePage[] = { {T("UTF-7"), CP_UTF7,0}, {T("UTF-8"), CP_UTF8,0}, {T("Shift_JIS"), 932,0}, {T("GB2312"), 936,0}, {T("BIG5"), 950,0}, {T("ISO-8859-1"), 28591,1252}, {T("ISO-8859-2"), 28592,1250}, {T("ISO-8859-3"), 28593,1254}, {T("ISO-8859-4"), 28594,1257}, {T("ISO-8859-5"), 28595,1251}, {T("ISO-8859-6"), 28596,1256}, {T("ISO-8859-7"), 28597,1253}, {T("ISO-8859-8"), 28598,1255}, {NULL,0,0} }; static NOINLINE UINT GetCodePage(const tchar_t* Name, bool_t To) { if (Name && Name[0]) { const codepage* i; int CP; if (stscanf(Name, T("CP%d"), &CP) == 1 || stscanf(Name, T("windows-%d"), &CP) == 1) return CP; for (i = CodePage;i->Name;++i) if (tcsisame_ascii(Name, i->Name)) { if (IsValidCodePage(i->CodePage)) return i->CodePage; if (i->CodePage2 && IsValidCodePage(i->CodePage2)) return i->CodePage2; break; } } if (To) #ifndef WINDOWS_DESKTOP return CP_OEMCP; #else return GetOEMCP(); #endif else return CP_ACP; } charconv* CharConvOpen(const tchar_t* From, const tchar_t* To) { return (charconv*)MAKELONG(GetCodePage(To,1),GetCodePage(From,0)); } void CharConvClose(charconv* UNUSED_PARAM(p)) { } void CharConvDefault(tchar_t* UNUSED_PARAM(Out), size_t UNUSED_PARAM(OutLen)) { *Out = 0; } #endif bcmatroska2-5.3.101/corec/corec/helpers/date/000077500000000000000000000000001462133141200206335ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/date/date.h000066400000000000000000000055311462133141200217250ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __DATE_H #define __DATE_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #if defined(DATE_EXPORTS) #define DATE_DLL DLLEXPORT #elif defined(DATE_IMPORTS) #define DATE_DLL DLLIMPORT #else #define DATE_DLL #endif DATE_DLL systick_t GetTimeTick(void); #if defined(TARGET_WIN) || defined(TARGET_PS2SDK) || defined(TARGET_LINUX) || defined(TARGET_OSX) || defined(TARGET_ANDROID) || defined(TARGET_QNX) #define GetTimeFreq() 1000 #else DATE_DLL int GetTimeFreq(); #endif typedef struct datepack_t { intptr_t Year; // 2001, 2007, etc intptr_t Month; // 1-12 intptr_t Day; // 1-31 intptr_t Hour; // 24-hour intptr_t Minute; // 0-59 intptr_t Second; // 0-59 intptr_t WeekDay; // 1 = Sunday, 2 = Monday, etc } datepack_t; DATE_DLL datetime_t GetTimeDate(void); // UTC in s (reference is 1st January 2001 00:00:00.000 UTC, use a helper to get the localized string value) DATE_DLL datetime_t TimePackToRel(const datepack_t *tp, bool_t FromLocal); DATE_DLL bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t ToLocal); DATE_DLL bool_t GetIsDst(datetime_t t); // may not be correct on all platforms #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/helpers/date/date.proj000066400000000000000000000006461462133141200224520ustar00rootroot00000000000000GROUP date { USE corec HEADER date.h SOURCE(TARGET_WIN) date_win32.c SOURCE(TARGET_LINUX || TARGET_OSX || TARGET_ANDROID) date_libc.c SOURCE(TARGET_SYMBIAN) date_symbian.cpp SOURCE(TARGET_PALMOS) date_palmos.c SOURCE(TARGET_PS2SDK) date_ps2sdk.c USE(TARGET_PS2SDK) ps2timer USE(TARGET_PS2SDK) ps2sdk_cdvd LIBS(TARGET_WIN && !TARGET_WINCE) winmm.lib LIBS(TARGET_SYMBIAN && SYMBIAN90) tzclient.lib } bcmatroska2-5.3.101/corec/corec/helpers/date/date_libc.c000066400000000000000000000072341462133141200227130ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "date.h" #define DATETIME_OFFSET 0x3A4FC880 #include #include systick_t GetTimeTick() { struct timeval t; gettimeofday(&t,NULL); return t.tv_sec*1000 + t.tv_usec/1000; } datetime_t LinuxToDateTime(time_t t) { // reference is 1st January 2001 00:00:00.000 UTC t -= (time_t)DATETIME_OFFSET; if (t==INVALID_DATETIME_T) t++; return (datetime_t)t; } static time_t DateTimeTZOffset(time_t t) { time_t offset = 0; struct tm *tmp = NULL; tmp = localtime(&t); if (tmp) { offset = mktime(tmp); tmp = gmtime(&t); if (tmp) { offset -= mktime(tmp); } else { offset = 0; } } return offset; } datetime_t GetTimeDate() { return LinuxToDateTime(time(NULL)); } datetime_t TimePackToRel(const datepack_t *tp, bool_t Local) { struct tm date; time_t ot = 0; if (!tp) return INVALID_DATETIME_T; date.tm_sec = (int)tp->Second; date.tm_min = (int)tp->Minute; date.tm_hour = (int)tp->Hour; date.tm_mday = (int)tp->Day; date.tm_mon = (int)tp->Month - 1; date.tm_year = (int)tp->Year - 1900; date.tm_isdst = -1; // use auto ot = mktime(&date); if (ot == (time_t) -1) return INVALID_DATETIME_T; if (!Local) ot += DateTimeTZOffset(ot); return LinuxToDateTime(ot); } bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t Local) { time_t ot; struct tm *date; if (!tp || t == INVALID_DATETIME_T) return 0; ot = t + DATETIME_OFFSET; if (Local) date = localtime(&ot); else date = gmtime(&ot); if (date) { tp->Second = date->tm_sec; tp->Minute = date->tm_min; tp->Hour = date->tm_hour; tp->Day = date->tm_mday; tp->Month = date->tm_mon + 1; tp->Year = date->tm_year + 1900; tp->WeekDay = date->tm_wday + 1; return 1; } return 0; } bool_t GetIsDst(datetime_t t) { time_t ot; struct tm *date; if (t == INVALID_DATETIME_T) return 0; ot = t + DATETIME_OFFSET; date = localtime(&ot); return date->tm_isdst; } bcmatroska2-5.3.101/corec/corec/helpers/date/date_palmos.c000066400000000000000000000072541462133141200232770ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "date.h" #if defined(TARGET_PALMOS) #include int GetTimeFreq() { return SysTicksPerSecond(); } systick_t GetTimeTick() { return TimGetTicks(); } datetime_t PalmToDateTime(UInt32 v) { // reference is 1st January 2001 00:00:00.000 UTC datetime_t Date = (datetime_t)(v - 0xB6757900); if (Date==INVALID_DATETIME_T) ++Date; return Date; } UInt32 DateTimeToPalm(datetime_t v) { // reference is 1st January 2001 00:00:00.000 UTC return (UInt32)(v + 0xB6757900); } datetime_t GetTimeDate() { return PalmToDateTime(TimGetSeconds()); } datetime_t TimePackToRel(const datepack_t *tp, bool_t Local) { DateTimeType Date; UInt32 ot; if (!tp) return INVALID_DATETIME_T; Date.second = (int16_t)tp->Second; Date.minute = (int16_t)tp->Minute; Date.hour = (int16_t)tp->Hour; Date.day = (int16_t)tp->Day; Date.month = (int16_t)tp->Month; Date.year = (int16_t)tp->Year; Date.weekDay = (int16_t)(tp->WeekDay-1); ot = TimDateTimeToSeconds(&Date); if (Local) ot = TimTimeZoneToUTC(ot, PrefGetPreference(prefTimeZone), PrefGetPreference(prefDaylightSavingAdjustment)); return PalmToDateTime(ot); } bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t Local) { DateTimeType Date; UInt32 ot; if (!tp || t == INVALID_DATETIME_T) return 0; memset(&Date, 0, sizeof(DateTimeType)); ot = DateTimeToPalm(t); if (Local) ot = TimUTCToTimeZone(ot, PrefGetPreference(prefTimeZone), PrefGetPreference(prefDaylightSavingAdjustment)); TimSecondsToDateTime(ot, &Date); tp->Second = Date.second; tp->Minute = Date.minute; tp->Hour = Date.hour; tp->Day = Date.day; tp->Month = Date.month; tp->Year = Date.year; tp->WeekDay = Date.weekDay; return 1; } bool_t GetIsDst(datetime_t t) { UInt32 ot = DateTimeToPalm(t); return TimUTCToTimeZone(ot, PrefGetPreference(prefTimeZone), 0) != TimUTCToTimeZone(ot, PrefGetPreference(prefTimeZone), PrefGetPreference(prefDaylightSavingAdjustment)); } #endif bcmatroska2-5.3.101/corec/corec/helpers/date/date_ps2sdk.c000066400000000000000000000114551462133141200232100ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "date.h" #include #include #include #include #include systick_t GetTimeTick() { return EventTick; } static int Bcd2Dec(int v) { return ((v>>4) & 15)*10 + (v & 15); } datetime_t GetTimeDate() { datetime_t t; datepack_t tp; CdvdClock_t clock; if (!cdReadClock(&clock)) return INVALID_DATETIME_T; tp.Year = Bcd2Dec(clock.year)+2000; tp.Month = Bcd2Dec(clock.month); tp.Day = Bcd2Dec(clock.day); tp.Hour = Bcd2Dec(clock.hour); tp.Minute = Bcd2Dec(clock.minute); tp.Second = Bcd2Dec(clock.second); tp.WeekDay = 0; t = TimePackToRel(&tp,0); if (t != INVALID_DATETIME_T) { t -= 9*60*60; //adjust JST to GMC if (t == INVALID_DATETIME_T) ++t; } return t; } static bool_t LeapYear(int v) { return (v%4)==0 && ((v%100)!=0 || (v%400)==0); } datetime_t TimePackToRel(const datepack_t *tp, bool_t Local) { static uint8_t Month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; datetime_t t; int a; if (tp->Year<1933 || tp->Year>=2069 || tp->Month<1 || tp->Month>12 || tp->Day<1 || tp->Day>31 || tp->Hour<0 || tp->Hour>=24 || tp->Minute<0 || tp->Minute>=60 || tp->Second<0 || tp->Second>=60) return INVALID_DATETIME_T; t = -2145916800; t += (tp->Day-1)*24*60*60; t += tp->Hour*60*60; t += tp->Minute*60; t += tp->Second; for (a=1933;aYear;++a) t += 24*60*60*(LeapYear(a) ? 366:365); for (a=1;aMonth;++a) { t += Month[a-1]*24*60*60; if (a==2 && LeapYear(tp->Year)) t += 24*60*60; } if (Local) { int Timezone = configGetTimezone(); int DaylightSaving = configIsDaylightSavingEnabled(); t -= (Timezone + DaylightSaving * 60)*60; } return t; } bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t Local) { static const uint16_t Days[12] = { 0, 31, 31+28, 31+28+31, 31+28+31+30, 31+28+31+30+31, 31+28+31+30+31+30, 31+28+31+30+31+30+31, 31+28+31+30+31+30+31+31, 31+28+31+30+31+30+31+31+30, 31+28+31+30+31+30+31+31+30+31, 31+28+31+30+31+30+31+31+30+31+30, }; unsigned int a; unsigned int b; unsigned int c; if (!tp || t == INVALID_DATETIME_T) return 0; if (t<-2145916800) return 0; if (Local) { int Timezone = configGetTimezone(); int DaylightSaving = configIsDaylightSavingEnabled(); t += (Timezone + DaylightSaving * 60)*60; } a = t+2145916800; //2001 -> 1933 b = a % (24*60*60); a = a / (24*60*60); tp->Second = b %60; b /= 60; tp->Minute = b %60; tp->Hour = b /60; tp->WeekDay = 1 + a % 7; for (b=1933;;++b) { c = LeapYear(b) ? 366:365; if (a >= c) a -= c; else break; } tp->Year = b; tp->Day = 1; if (LeapYear(b) && a>58) { if (a==59) tp->Day = 2; --a; } for (b = 11; b && (Days[b] > a); --b) {} tp->Month = b+1; tp->Day += a - Days[b]; return 1; } bool_t GetIsDst(datetime_t t) { //TODO: use t instead of current time return configIsDaylightSavingEnabled(); } bcmatroska2-5.3.101/corec/corec/helpers/date/date_symbian.cpp000066400000000000000000000124651462133141200240060ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "date.h" #if defined(TARGET_SYMBIAN) #undef T #undef NULL #include #include #ifdef SYMBIAN90 #include #include #endif #ifndef SYMBIAN90 static INLINE TInt64 ToInt64(int64_t i) { return TInt64((int32_t)(i>>32),(uint32_t)i); } #else #define ToInt64(a) (a) #endif int GetTimeFreq() { TTimeIntervalMicroSeconds32 n; UserHal::TickPeriod(n); return Scale32(1000000,1,n.Int()); } systick_t GetTimeTick() { return User::TickCount(); } datetime_t SymbianToDateTime(TTime Time) { // reference is 1st January 2001 00:00:00.000 UTC datetime_t Date = INVALID_DATETIME_T; TTime Reference(ToInt64(LL(0x00e05776f452a000))); TTimeIntervalSeconds Diff; if (Time.SecondsFrom(Reference,Diff) == KErrNone) { Date = Diff.Int(); if (Date==INVALID_DATETIME_T) ++Date; } return Date; } TTime DateTimeToSymbian(datetime_t Time) { // reference is 1st January 2001 00:00:00.000 UTC TTime Reference(ToInt64(LL(0x00e05776f452a000))); TTimeIntervalSeconds Diff; Diff = Time; return Reference + Diff; } datetime_t GetTimeDate() { TTime Now; Now.UniversalTime(); return SymbianToDateTime(Now); } datetime_t TimePackToRel(const datepack_t *tp, bool_t Local) { TDateTime Date; TTime ot; if (!tp) return INVALID_DATETIME_T; Date.SetYear(tp->Year); Date.SetMonth((TMonth)(tp->Month-1)); Date.SetDay(tp->Day-1); Date.SetHour(tp->Hour); Date.SetMinute(tp->Minute); Date.SetSecond(tp->Second); ot = TTime(Date); if (Local) { #ifndef SYMBIAN90 TLocale locale; TTimeIntervalSeconds universalTimeOffset(locale.UniversalTimeOffset()); ot -= universalTimeOffset; if (locale.QueryHomeHasDaylightSavingOn()) { TTimeIntervalHours daylightSaving(1); ot -= daylightSaving; } #else RTz TzServer; if (TzServer.Connect()==KErrNone) { CTzConverter* Converter = CTzConverter::NewL(TzServer); Converter->ConvertToUniversalTime(ot); delete Converter; TzServer.Close(); } #endif } return SymbianToDateTime(ot); } bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t Local) { TDateTime Date; TTime ot; if (!tp || t == INVALID_DATETIME_T) return 0; ot = DateTimeToSymbian(t); if (Local) { #ifndef SYMBIAN90 TLocale locale; TTimeIntervalSeconds universalTimeOffset(locale.UniversalTimeOffset()); ot += universalTimeOffset; if (locale.QueryHomeHasDaylightSavingOn()) { TTimeIntervalHours daylightSaving(1); ot += daylightSaving; } #else RTz TzServer; if (TzServer.Connect()==KErrNone) { CTzConverter* Converter = CTzConverter::NewL(TzServer); Converter->ConvertToLocalTime(ot); delete Converter; TzServer.Close(); } #endif } Date = ot.DateTime(); tp->Year = Date.Year(); tp->Month = (int)Date.Month() + 1; tp->Day = Date.Day()+1; tp->Hour = Date.Hour(); tp->Minute = Date.Minute(); tp->Second = Date.Second(); return 1; } bool_t GetIsDst(datetime_t UNUSED_PARAM(t)) { #ifndef SYMBIAN90 TLocale locale; return locale.QueryHomeHasDaylightSavingOn(); #else TBool IsDst=EFalse; RTz TzServer; if (TzServer.Connect()==KErrNone) { CTzConverter* Converter = CTzConverter::NewL(TzServer); CTzId* TzId = CTzId::NewL(Converter->CurrentTzId()); IsDst = TzServer.IsDaylightSavingOnL(*TzId); delete TzId; delete Converter; TzServer.Close(); } return IsDst; #endif } #endif bcmatroska2-5.3.101/corec/corec/helpers/date/date_win32.c000066400000000000000000000263461462133141200227510ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "date.h" #if defined(TARGET_WIN) //#define TARGET_WIN2K // currently we dont use the TzSpecific (Win2K+) implementation at all #ifndef STRICT #define STRICT #endif #include #if defined(__MINGW32__) || !defined(WINAPI_FAMILY_PARTITION) || !defined(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_FAMILY_PARTITION) #if defined(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_PARTITION_PHONE_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #define WINDOWS_PHONE 1 #elif defined(WINAPI_PARTITION_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define WINDOWS_UNIVERSAL 1 #endif #endif #define MIN_CACHED_YEAR 1990 #define MAX_CACHED_YEAR 2015 static TIME_ZONE_INFORMATION fix_tz; static int fix_tz_ready; static FILETIME fTimeCache[MAX_CACHED_YEAR - MIN_CACHED_YEAR + 2][2]; #ifndef TIME_ZONE_ID_INVALID #define TIME_ZONE_ID_INVALID ((DWORD)0xFFFFFFFF) #endif #if defined(TARGET_WINCE) systick_t GetTimeTick() { return GetTickCount(); } #else systick_t GetTimeTick() { #ifndef WINDOWS_DESKTOP return (systick_t)GetTickCount64(); #else return timeGetTime(); #endif } #endif datetime_t FileTimeToRel(FILETIME *fTime) { int64_t int64time; int64time = fTime->dwHighDateTime; int64time <<= 32; int64time += fTime->dwLowDateTime; /* Convert from 100ns to seconds. */ int64time /= 10000000; int64time -= LL(0x2F0605980); // reference is 1st January 2001 00:00:00.000 UTC if (int64time==INVALID_DATETIME_T) ++int64time; return (datetime_t)int64time; } void RelToFileTime(datetime_t t, FILETIME *fTime) { int64_t int64time = t; int64time += LL(0x2F0605980); // reference is 1st January 2001 00:00:00.000 UTC /* Convert from seconds to 100ns. */ int64time *= 10000000; fTime->dwLowDateTime = (DWORD)int64time; int64time >>= 32; fTime->dwHighDateTime = (DWORD)int64time; } static void GetFixedTZ() { if (fix_tz_ready == 0) { fix_tz_ready = GetTimeZoneInformation(&fix_tz) == TIME_ZONE_ID_INVALID? -1 : 1; if (fix_tz_ready == -1) { // default US rules fix_tz.DaylightDate.wYear = 0; fix_tz.DaylightDate.wHour = 2; // 2AM fix_tz.DaylightDate.wMinute = 0; fix_tz.DaylightDate.wSecond = 0; fix_tz.DaylightDate.wDayOfWeek = 0; // month and dayofweek are only set when year is known in getisdst() memcpy(&fix_tz.StandardDate, &fix_tz.DaylightDate, sizeof(SYSTEMTIME)); fix_tz.DaylightBias = -60; fix_tz.Bias = 0; // default timezone? } } } /* static int CompareFileTime(FILETIME *fTime1, FILETIME *fTime2) { if (fTime1->dwHighDateTime > fTime2->dwHighDateTime) return 1; else if (fTime1->dwHighDateTime > fTime2->dwHighDateTime) return -1; else if (fTime1->dwLowDateTime > fTime2->dwLowDateTime) return 1; else if (fTime1->dwLowDateTime < fTime2->dwLowDateTime) return -1; return 0; }*/ static void ConvertDaylightDateToFileTime(int Year, SYSTEMTIME *Date, FILETIME *fTime) { SYSTEMTIME TimeStruct = {0}; int Day, Leap; int MonthDays[2][12] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; TimeStruct.wYear = (WORD) Year; TimeStruct.wMonth = Date->wMonth; TimeStruct.wHour = Date->wHour; TimeStruct.wMinute = Date->wMinute; TimeStruct.wSecond = Date->wSecond; if (Date->wYear > 0) TimeStruct.wDay = Date->wDay; else { TimeStruct.wDay = 1; SystemTimeToFileTime(&TimeStruct, fTime); FileTimeToSystemTime(fTime, &TimeStruct); // to calculate day of week Day = 1 + Date->wDayOfWeek - TimeStruct.wDayOfWeek; if (Day < 0) Day += 7; Day += (Date->wDay - 1) * 7; Leap = (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); if (Date->wDay == 5 && Day > MonthDays[Leap][Date->wMonth]) Day -= 7; TimeStruct.wDay = (WORD) Day; } SystemTimeToFileTime(&TimeStruct, fTime); } datetime_t GetTimeDate() { SYSTEMTIME sysTimeStruct; FILETIME fTime; GetSystemTime( &sysTimeStruct ); if ( SystemTimeToFileTime( &sysTimeStruct, &fTime ) ) return FileTimeToRel(&fTime); return INVALID_DATETIME_T; } datetime_t TimePackToRel(const datepack_t *tp, bool_t Local) { SYSTEMTIME TimeStruct = {0}; FILETIME fTime; datetime_t t; if (!tp) return INVALID_DATETIME_T; TimeStruct.wMilliseconds = (WORD)0; TimeStruct.wSecond = (WORD)tp->Second; TimeStruct.wMinute = (WORD)tp->Minute; TimeStruct.wHour = (WORD)tp->Hour; TimeStruct.wDay = (WORD)tp->Day; TimeStruct.wMonth = (WORD)tp->Month; TimeStruct.wYear = (WORD)tp->Year; TimeStruct.wDayOfWeek = (WORD)(tp->WeekDay ? tp->WeekDay-1:0); #if defined(TARGET_WIN2K) || !defined(WINDOWS_DESKTOP) if (Local) { SYSTEMTIME sysTimeStruct; TIME_ZONE_INFORMATION timeZoneInfo; GetTimeZoneInformation(&timeZoneInfo); if (!TzSpecificLocalTimeToSystemTime(&timeZoneInfo, &TimeStruct, &sysTimeStruct)) return INVALID_DATETIME_T; if (!SystemTimeToFileTime( &sysTimeStruct, &fTime )) return INVALID_DATETIME_T; } else #endif if (!SystemTimeToFileTime( &TimeStruct, &fTime )) return INVALID_DATETIME_T; t = FileTimeToRel(&fTime); #if !defined(TARGET_WIN2K) || defined(WINDOWS_DESKTOP) if (Local) { GetFixedTZ(); t += fix_tz.Bias * 60; if (GetIsDst(t)) // test with UTC time without daylight (not perfect at the edges) t += fix_tz.DaylightBias * 60; else t += fix_tz.StandardBias * 60; if (t==INVALID_DATETIME_T) ++t; } #endif return t; } bool_t GetDatePacked(datetime_t t, datepack_t *tp, bool_t Local) { SYSTEMTIME TimeStruct = {0}; FILETIME fTime = {0}; if (!tp || t == INVALID_DATETIME_T) return 0; #if !defined(TARGET_WIN2K) || defined(WINDOWS_DESKTOP) if (Local) { GetFixedTZ(); if (GetIsDst(t)) t -= fix_tz.DaylightBias * 60; else t -= fix_tz.StandardBias * 60; t -= fix_tz.Bias * 60; } #endif RelToFileTime(t, &fTime); #if defined(TARGET_WIN2K) || !defined(WINDOWS_DESKTOP) if (Local) { SYSTEMTIME sysTimeStruct = {0}; TIME_ZONE_INFORMATION timeZoneInfo; if (!FileTimeToSystemTime(&fTime, &sysTimeStruct)) return 0; GetTimeZoneInformation(&timeZoneInfo); SystemTimeToTzSpecificLocalTime(&timeZoneInfo, &sysTimeStruct, &TimeStruct); } else #endif if (!FileTimeToSystemTime(&fTime, &TimeStruct)) return 0; tp->Year = TimeStruct.wYear; tp->Month = TimeStruct.wMonth; tp->Day = TimeStruct.wDay; tp->Hour = TimeStruct.wHour; tp->Minute = TimeStruct.wMinute; tp->Second = TimeStruct.wSecond; tp->WeekDay = TimeStruct.wDayOfWeek+1; return 1; } bool_t GetIsDst(datetime_t t) { #if defined(TARGET_WIN2K) || !defined(WINDOWS_DESKTOP) FILETIME fTime = {0}; TIME_ZONE_INFORMATION timeZoneInfo; SYSTEMTIME sysTimeStruct = {0}; SYSTEMTIME TimeStruct = {0}; int Hour; if (t == INVALID_DATETIME_T) return 0; RelToFileTime(t, &fTime); if (!FileTimeToSystemTime(&fTime, &sysTimeStruct)) return 0; GetTimeZoneInformation(&timeZoneInfo); if (!SystemTimeToTzSpecificLocalTime(&timeZoneInfo, &sysTimeStruct, &TimeStruct)) return 0; Hour = TimeStruct.wHour; timeZoneInfo.DaylightBias = 0; timeZoneInfo.DaylightDate.wMonth = 0; timeZoneInfo.StandardDate.wMonth = 0; if (!SystemTimeToTzSpecificLocalTime(&timeZoneInfo, &sysTimeStruct, &TimeStruct)) return 0; return Hour != TimeStruct.wHour; #else FILETIME fTime; FILETIME fTime1, fTime2; FILETIME *fTimeStart, *fTimeEnd; int Year; int YearIndex; SYSTEMTIME TimeStruct = {0}; if (t == INVALID_DATETIME_T) return 0; GetFixedTZ(); if (fix_tz.DaylightBias == 0 || fix_tz.DaylightDate.wMonth == 0) return 0; t -= fix_tz.Bias * 60; // we need local (biased) time RelToFileTime(t, &fTime); if (!FileTimeToSystemTime(&fTime, &TimeStruct)) return 0; Year = TimeStruct.wYear; if (fix_tz_ready == -1) { // default US rules if (Year >= 2007) { fix_tz.DaylightDate.wMonth = 3; fix_tz.DaylightDate.wDayOfWeek = 2; fix_tz.StandardDate.wMonth = 11; fix_tz.StandardDate.wDayOfWeek = 1; } else { fix_tz.DaylightDate.wMonth = 4; fix_tz.DaylightDate.wDayOfWeek = 1; fix_tz.StandardDate.wMonth = 10; fix_tz.StandardDate.wDayOfWeek = 5; } } if (Year < MIN_CACHED_YEAR || Year > MAX_CACHED_YEAR ) { YearIndex = 0; fTimeStart = &fTime1; fTimeEnd = &fTime2; } else { YearIndex = Year - MIN_CACHED_YEAR + 1; fTimeStart = &(fTimeCache[YearIndex][0]); fTimeEnd = &(fTimeCache[YearIndex][1]); } if (YearIndex == 0 || (fTimeStart->dwLowDateTime == 0 && fTimeStart->dwHighDateTime == 0)) { ConvertDaylightDateToFileTime(Year, &fix_tz.DaylightDate, fTimeStart); ConvertDaylightDateToFileTime(Year, &fix_tz.StandardDate, fTimeEnd); } if (CompareFileTime(&fTime, fTimeStart) < 0 || CompareFileTime(&fTime, fTimeEnd) >= 0) return 0; return 1; #endif } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/000077500000000000000000000000001462133141200206355ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/file/bufstream.c000066400000000000000000000107051462133141200227740ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #define BUFSTREAM_SIZE 4096 typedef struct bufstream { stream Base; stream* Stream; size_t ReadPos; size_t ReadSize; size_t WritePos; uint8_t Buffer[BUFSTREAM_SIZE]; } bufstream; static NOINLINE err_t BufFlush(bufstream* p) { err_t Err = ERR_NONE; if (p->Stream && p->WritePos>0) { Err = Stream_Write(p->Stream,p->Buffer,p->WritePos,NULL); if (Err == ERR_NONE) p->WritePos = 0; } return Err; } static err_t BufStream(bufstream* p,dataid UNUSED_PARAM(Id),stream** Data,size_t UNUSED_PARAM(Size)) { BufFlush(p); p->Stream = Data?*Data:NULL; p->ReadPos = 0; p->ReadSize = 0; p->WritePos = 0; return ERR_NONE; } static void BufDelete(bufstream* p) { BufFlush(p); if (p->Stream) NodeDelete((node*)p->Stream); } static err_t BufRead(bufstream* p,uint8_t* Data,size_t Size,size_t* Readed) { err_t Err = ERR_NONE; size_t Pos = 0; size_t Left; while ((Left = (Size - Pos)) > 0) { if (p->ReadSize <= p->ReadPos) { if (Left > BUFSTREAM_SIZE) { Err = Stream_Read(p->Stream,Data+Pos,Left,&Left); if (Readed) *Readed = Pos+Left; return Err; } p->ReadPos = 0; Err = Stream_Read(p->Stream,p->Buffer,BUFSTREAM_SIZE,&p->ReadSize); if (p->ReadSize <= 0) break; } if (Left > p->ReadSize - p->ReadPos) Left = p->ReadSize - p->ReadPos; memcpy(Data+Pos,p->Buffer+p->ReadPos,Left); Pos += Left; p->ReadPos += Left; } if (Readed) *Readed = Pos; if (Pos >= Size) Err = ERR_NONE; //override possible end of file in later of the buffer return Err; } static err_t BufWrite(bufstream* p,const uint8_t* Data,size_t Size,size_t* Written) { err_t Err = ERR_NONE; size_t Pos = 0; size_t Left; while ((Left = (Size - Pos)) > 0) { if (p->WritePos >= BUFSTREAM_SIZE && (Err = BufFlush(p)) != ERR_NONE) break; if (!p->WritePos && Left > BUFSTREAM_SIZE) { Err = Stream_Write(p->Stream,Data+Pos,Left,&Left); Pos += Left; break; } if (Left > BUFSTREAM_SIZE - p->WritePos) Left = BUFSTREAM_SIZE - p->WritePos; memcpy(p->Buffer+p->WritePos,Data+Pos,Left); Pos += Left; p->WritePos += Left; } if (Written) *Written = Pos; return Err; } META_START(BufStream_Class,BUFSTREAM_CLASS) META_CLASS(SIZE,sizeof(bufstream)) META_CLASS(DELETE,BufDelete) META_VMT(TYPE_FUNC,stream_vmt,Read,BufRead) META_VMT(TYPE_FUNC,stream_vmt,Write,BufWrite) META_PARAM(SET,BUFSTREAM_STREAM,BufStream) META_END(STREAM_CLASS) bcmatroska2-5.3.101/corec/corec/helpers/file/file.h000066400000000000000000000135031462133141200217270ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __FILE_H #define __FILE_H #include "corec/node/node.h" #include "corec/helpers/date/date.h" #ifdef __cplusplus extern "C" { #endif #if defined(FILE_EXPORTS) #define FILE_DLL DLLEXPORT #elif defined(FILE_IMPORTS) #define FILE_DLL DLLIMPORT #else #define FILE_DLL #endif #define FILE_CLASS FOURCC('F','I','L','E') #define VFS_CLASS FOURCC('V','F','S','_') FILE_DLL bool_t FileExists(nodecontext*, const tchar_t*); FILE_DLL bool_t FileMove(nodecontext*, const tchar_t* In,const tchar_t* Out); FILE_DLL datetime_t FileDateTime(nodecontext*, const tchar_t*); FILE_DLL bool_t PathIsFolder(nodecontext*, const tchar_t*); FILE_DLL bool_t FolderCreate(nodecontext*, const tchar_t*); // \param Force erase even if the file is read-only // \param Safe put in the OS trash rather than a permanent erase FILE_DLL bool_t FileErase(nodecontext*, const tchar_t*, bool_t Force, bool_t Safe); FILE_DLL bool_t FolderErase(nodecontext*, const tchar_t*, bool_t Force, bool_t Safe); FILE_DLL void FindFiles(nodecontext*,const tchar_t* Path, const tchar_t* Mask,void(*Process)(const tchar_t*,void*),void* Param); FILE_DLL int64_t GetPathFreeSpace(nodecontext*,const tchar_t* Path); FILE_DLL void RemovePathDelimiter(tchar_t* Path); FILE_DLL void AddPathDelimiter(tchar_t* Path,size_t PathLen); FILE_DLL const tchar_t* GetProtocol(const tchar_t* URL, tchar_t *_Protocol, int ProtoLen, bool_t* HasHost); FILE_DLL fourcc_t GetProtocolKind(anynode*, tchar_t *_Protocol); FILE_DLL void SplitPath(const tchar_t* Path, tchar_t* Dir, int DirLen, tchar_t* Name, int NameLen, tchar_t* Ext, int ExtLen); FILE_DLL void SplitURL(const tchar_t* URL, tchar_t* Mime, int MimeLen, tchar_t* Host, int HostLen, int* Port, tchar_t* Path, int PathLen); FILE_DLL bool_t SplitAddr(const tchar_t* URL, tchar_t* Peer, int PeerLen, tchar_t* Local, int LocalLen); FILE_DLL bool_t SetFileExt(tchar_t* URL, size_t URLLen, const tchar_t* Ext); FILE_DLL int CheckExts(const tchar_t* URL, const tchar_t* Exts); FILE_DLL void AbsPath(tchar_t* Abs, int AbsLen, const tchar_t* Path, const tchar_t* Base); FILE_DLL void AbsPathNormalize(tchar_t* Abs, size_t AbsLen); FILE_DLL void ReduceLocalPath(tchar_t* Abs, size_t AbsLen); FILE_DLL void RelPath(tchar_t* Rel, int RelLen, const tchar_t* Path, const tchar_t* Base); FILE_DLL bool_t UpperPath(tchar_t* Path, tchar_t* Last, size_t LastLen); FILE_DLL void StreamLoginInfo(node* p, tchar_t* URL, bool_t Proxy); //URL updated FILE_DLL tchar_t* FirstSepar(const tchar_t *Path); FILE_DLL void SplitURLLogin(const tchar_t *URL, tchar_t *UserName, size_t UserNameLen, tchar_t *Password, size_t PasswordLen, tchar_t *URL2, size_t URL2Len); FILE_DLL void SplitShare(const tchar_t *Path, tchar_t *Share, size_t ShareLen, tchar_t *Path2, size_t Path2Len); FILE_DLL tchar_t *MergeURL(tchar_t *URL, size_t URLLen, const tchar_t *Proto, const tchar_t *Host, int Port, const tchar_t *Path); FILE_DLL tchar_t *GetIP(tchar_t *sIP, size_t IPLen, long IP); FILE_DLL void SplitURLParams(const tchar_t* URL, tchar_t* URL2, int URL2Len, tchar_t* Params, int ParamsLen); FILE_DLL tchar_t *AddCacheURL(tchar_t* Out, size_t Len, const tchar_t *In); FILE_DLL bool_t CheckRemoveCacheURL(const tchar_t** URL); FILE_DLL bool_t RemoveURLParam(tchar_t* URL, const tchar_t* Param); static INLINE size_t FileBlockSize(filepos_t Start,filepos_t End) { End -= Start; if (End<0 || End>INT_MAX) return 0; return (size_t)End; } #include "corec/helpers/file/streams.h" FILE_DLL stream *FileTemp(anynode*); FILE_DLL bool_t FileTempName(anynode*,tchar_t *Out, size_t OutLen); FILE_DLL err_t FileStat(nodecontext* p, const tchar_t* Path, streamdir* Item); #if defined(TARGET_PALMOS) FILE_DLL const tchar_t* VFSToVol(const tchar_t* URL,uint16_t* Vol); FILE_DLL bool_t VFSFromVol(uint16_t Vol,const tchar_t* Path,tchar_t* URL,int URLLen); FILE_DLL bool_t DBFrom(uint16_t Card,uint32_t DB,tchar_t* URL,int URLLen); #endif #ifdef __cplusplus } #endif #if defined(TARGET_SYMBIAN) && defined(__cplusplus) // symbian headers are not compatible with C #include #include #include static INLINE RFs& Node_FsSession(anynode *AnyNode) { return *static_cast(Node_Context(AnyNode)->FsSession); } #endif #endif bcmatroska2-5.3.101/corec/corec/helpers/file/file.proj000066400000000000000000000017121462133141200224510ustar00rootroot00000000000000GROUP file { USE node USE date HEADER file.h HEADER streams.h SOURCE bufstream.c {class BufStream_Class:1} SOURCE memstream.c {class MemStream_Class:1} SOURCE streams.c {class Streams_Class:1} SOURCE tools.c SOURCE(TARGET_LINUX || TARGET_OSX || TARGET_ANDROID) file_bctbx.c {class File_Class:1} SOURCE(TARGET_PALMOS) file_palmos.c {class File_Class:1} SOURCE(TARGET_PALMOS) filedb_palmos.c {class FileDb_Class:1} SOURCE(TARGET_PALMOS) filevfs_palmos.c {class VFS_Class:1} SOURCE(TARGET_PS2SDK) file_ps2sdk.c {class File_Class:1 reg FileXio:2} SOURCE(TARGET_SYMBIAN) file_symbian.cpp {class File_Class:1} SOURCE(TARGET_WIN) file_bctbx_win32.c {class File_Class:1} SOURCE(CONFIG_STDIO && !TARGET_PALMOS) stream_stdio.c {class Stdio_Class:2} USE(TARGET_PS2SDK) ps2sdk_filexio USE(TARGET_PS2SDK) ps2sdk_iomanx_irx USE(TARGET_PS2SDK) ps2sdk_filexio_irx USE(TARGET_PS2SDK) ps2sdk_usbd_irx USE(TARGET_PS2SDK) ps2sdk_usbhdfsd_irx } bcmatroska2-5.3.101/corec/corec/helpers/file/file_bctbx.c000066400000000000000000000233671462133141200231150ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "bcmatroska2_config.h" #ifdef CONFIG_FILEPOS_64 #define __USE_FILE_OFFSET64 #endif #include #include #include #include #include #include #include #define bool_t bctbx_bool_t #include #undef bool_t // Do not move. Define TARGET_*. #include "file.h" #if defined(TARGET_OSX) #include #elif defined(TARGET_QNX) #include #else #include #endif #if defined(O_ACCMODE) #define _RW_ACCESS_FILE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) #define _RW_ACCESS_DIR (S_IRWXU|S_IRWXG|S_IRWXO) #elif defined(S_IREAD) && defined(S_IWRITE) #define _RW_ACCESS_FILE (S_IREAD|S_IWRITE) #define _RW_ACCESS_DIR (S_IREAD|S_IWRITE|S_IEXEC) #endif typedef struct filestream { stream Stream; bctbx_vfs_file_t *fp; tchar_t URL[MAXPATH]; // TODO: turn into a dynamic data filepos_t Length; int Flags; tchar_t DirPath[MAXPATH]; // TODO: turn into a dynamic data DIR *FindDir; } filestream; static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->fp != -1) bctbx_file_close(p->fp); p->Length = INVALID_FILEPOS_T; p->fp = NULL; if (URL && URL[0]) { struct stat file_stats; int mode = 0; if (Flags & SFLAG_WRONLY && !(Flags & SFLAG_RDONLY)) mode = O_WRONLY; else if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) mode = O_RDONLY; else mode = O_RDWR; if (Flags & SFLAG_CREATE) mode |= O_CREAT|O_TRUNC; //TODO: verify it works with Unicode files too p->fp = bctbx_file_open2(bctbx_vfs_get_default(), URL, mode); if (p->fp == NULL) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); if (stat(URL, &file_stats) == 0) p->Length = file_stats.st_size; } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { err_t Err; ssize_t n = bctbx_file_read2(p->fp, Data, Size); if (n<0) { n=0; Err = ERR_READ; } else Err = ((size_t)n != Size) ? ERR_END_OF_FILE:ERR_NONE; if (Readed) *Readed = (size_t)n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { err_t Err; ssize_t n = bctbx_file_write2(p->fp, Data, Size); if (n<0) { n=0; Err = ERR_WRITE; } else Err = (n != Size) ? ERR_WRITE:ERR_NONE; if (Written) *Written = (size_t)n; return Err; } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { off_t NewPos = bctbx_file_seek(p->fp, Pos, SeekMode); if (NewPos<0) return INVALID_FILEPOS_T; return NewPos; } static err_t SetLength(filestream* p,dataid Id,const filepos_t* Data,size_t Size) { if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; if (bctbx_file_truncate(p->fp, *Data)!=0) return ERR_BUFFER_FULL; return ERR_NONE; } static err_t OpenDir(filestream* p,const tchar_t* Path,int UNUSED_PARAM(Flags)) { if (p->FindDir) closedir(p->FindDir); if (Path[0]==0) Path = T("/"); p->FindDir = opendir(Path); if (!p->FindDir) { if (errno == ENOTDIR) return ERR_NOT_DIRECTORY; else return ERR_FILE_NOT_FOUND; } tcscpy_s(p->DirPath,TSIZEOF(p->DirPath),Path); AddPathDelimiter(p->DirPath,TSIZEOF(p->DirPath)); return ERR_NONE; } extern datetime_t LinuxToDateTime(time_t); static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { struct dirent *Dirent; if (!p->FindDir) return ERR_END_OF_FILE; Item->FileName[0] = 0; Item->Size = INVALID_FILEPOS_T; while (!Item->FileName[0] && (Dirent = readdir(p->FindDir)) != NULL) { tchar_t FilePath[MAXPATH]; struct stat file_stats; if (Dirent->d_name[0]=='.') // skip hidden files and current directory continue; tcscpy_s(FilePath, TSIZEOF(FilePath), p->DirPath); tcscat_s(FilePath, TSIZEOF(FilePath), Dirent->d_name); tcscpy_s(Item->FileName,TSIZEOF(Item->FileName), Dirent->d_name); stat(FilePath, &file_stats); Item->ModifiedDate = LinuxToDateTime(file_stats.st_mtime); if (S_ISDIR(file_stats.st_mode)) { Item->Type = FTYPE_DIR; Item->Size = INVALID_FILEPOS_T; } else { Item->Size = file_stats.st_size; Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } if (!Item->FileName[0]) { closedir(p->FindDir); p->FindDir = NULL; return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { if (p->fp != NULL) { bctbx_file_close(p->fp); p->fp = NULL; } if (p->FindDir) closedir(p->FindDir); } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_CONST(TYPE_INT,filestream,fp,NULL) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_DATA_RDONLY(TYPE_STRING,STREAM_ENUM_BASE,filestream,DirPath) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END(STREAM_CLASS) bool_t FileExists(nodecontext *p,const tchar_t* Path) { struct stat file_stats; return stat(Path, &file_stats) == 0; } bool_t FileErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { if ((file_stats.st_mode & S_IWUSR)==0) { file_stats.st_mode |= S_IWUSR; chmod(Path,file_stats.st_mode); } } } return unlink(Path) == 0; } bool_t FolderErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { if ((file_stats.st_mode & S_IWUSR)==0) { file_stats.st_mode |= S_IWUSR; chmod(Path,file_stats.st_mode); } } } return rmdir(Path) == 0; } bool_t PathIsFolder(nodecontext *p,const tchar_t* Path) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { return (file_stats.st_mode & S_IFDIR) == S_IFDIR; } return 0; } datetime_t FileDateTime(nodecontext *p,const tchar_t* Path) { datetime_t Date = INVALID_DATETIME_T; struct stat file_stats; if (stat(Path, &file_stats) == 0) Date = LinuxToDateTime(file_stats.st_mtime); return Date; } bool_t FileMove(nodecontext *p,const tchar_t* In,const tchar_t* Out) { return rename(In,Out) == 0; } bool_t FolderCreate(nodecontext *p,const tchar_t* Path) { return mkdir(Path,_RW_ACCESS_DIR) == 0; } void FindFiles(nodecontext *p,const tchar_t* Path, const tchar_t* Mask,void(*Process)(const tchar_t*,void*),void* Param) { DIR* Directory; struct dirent* DirectoryInfo; tchar_t TPathToFile[MAXPATH]; Directory = opendir(Path); if (Directory) { while ( (DirectoryInfo = readdir(Directory)) != NULL ) { char* FileExtension = 0; FileExtension = strrchr(DirectoryInfo->d_name, '.'); if(FileExtension) { if (strcmp(Mask, FileExtension ) == 0 ) { tcscpy_s(TPathToFile, TSIZEOF(TPathToFile), Path); tcscat_s(TPathToFile, TSIZEOF(TPathToFile), DirectoryInfo->d_name); Process(TPathToFile, Param); } } } closedir(Directory); } } stream *FileTemp(anynode *Any) { #ifndef TODO assert(NULL); // not supported yet #endif return NULL; } bool_t FileTempName(anynode *Any,tchar_t *Out, size_t OutLen) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { #ifndef TODO // need to an include (see at includes) #if defined(TARGET_QNX) struct statvfs st; if (statvfs(Path, &st) < 0) #else struct statfs st; if (statfs(Path, &st) < 0) #endif return -1; return (int64_t)st.f_bsize * (int64_t)st.f_bavail; #else return -1; #endif } bcmatroska2-5.3.101/corec/corec/helpers/file/file_bctbx_win32.c000066400000000000000000000346311462133141200241330ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #define bool_t bctbx_bool_t #include #undef bool_t #if defined(TARGET_WIN) #define FILE_FUNC_ID FOURCC('F','L','I','D') #ifndef STRICT #define STRICT #endif #define WIN32_LEAN_AND_MEAN #include #include #include #ifndef FO_DELETE #define FO_DELETE 3 #endif #ifndef FOF_NO_UI #define FOF_NO_UI (0x04|0x10|0x400|0x200) #endif #if defined(TARGET_WINCE) static HMODULE CEShellDLL = NULL; #endif #ifdef WINDOWS_DESKTOP static int (WINAPI* FuncSHFileOperation)(SHFILEOPSTRUCT*) = NULL; #else static void *FuncSHFileOperation = NULL; #endif #ifndef ERROR_INVALID_DRIVE_OBJECT #define ERROR_INVALID_DRIVE_OBJECT 4321L #endif #ifndef ERROR_DEVICE_NOT_AVAILABLE #define ERROR_DEVICE_NOT_AVAILABLE 4319L #endif #ifndef ERROR_DEVICE_REMOVED #define ERROR_DEVICE_REMOVED 1617L #endif #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif typedef struct filestream { stream Stream; tchar_t URL[MAXPATH]; bctbx_vfs_file_t *fp; filepos_t Length; filepos_t Pos; int Flags; void* Find; WIN32_FIND_DATA FindData; int DriveNo; } filestream; static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->fp != -1) bctbx_file_close(p->fp); p->Length = INVALID_FILEPOS_T; p->fp = NULL; if (URL && URL[0]) { struct stat file_stats; int mode = 0; #ifdef UNICODE char url_buffer[1024]; memset(url_buffer, 0, sizeof(url_buffer)); #ifdef _WIN32 if(WideCharToMultiByte(CP_ACP, 0, URL, -1, url_buffer, sizeof(url_buffer), 0, 0) == 0) { #else if (wcstombs_s(&return_length, url_buffer, sizeof(url_buffer), URL, sizeof(url_buffer) - 1) != 0) { #endif NodeReportError(p, NULL, ERR_ID, ERR_INVALID_PARAM, URL); return ERR_INVALID_PARAM; } #else const char* url_buffer = URL; #endif if (Flags & SFLAG_WRONLY && !(Flags & SFLAG_RDONLY)) mode = O_WRONLY; else if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) mode = O_RDONLY; else mode = O_RDWR; if (Flags & SFLAG_CREATE) mode |= O_CREAT|O_TRUNC; p->fp = bctbx_file_open2(bctbx_vfs_get_default(), url_buffer, mode); if (p->fp == NULL) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND, url_buffer); return ERR_FILE_NOT_FOUND; } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); if (stat(url_buffer, &file_stats) == 0) p->Length = file_stats.st_size; } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { err_t Err; int n = bctbx_file_read2(p->fp, Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_READ; } else Err = ((size_t)n != Size) ? ERR_END_OF_FILE:ERR_NONE; if (Readed) *Readed = n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { err_t Err; int n = bctbx_file_write2(p->fp, Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_WRITE; } else Err = (n != Size) ? ERR_WRITE:ERR_NONE; if (Written) *Written = n; return Err; } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { off_t NewPos = bctbx_file_seek(p->fp, Pos, SeekMode); if (NewPos<0) return INVALID_FILEPOS_T; return NewPos; } static err_t SetLength(filestream* p,dataid Id,const filepos_t* Data,size_t Size) { if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; if (bctbx_file_truncate(p->fp, *Data)!=0) return ERR_BUFFER_FULL; return ERR_NONE; } static err_t OpenDir(filestream* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; #else DWORD Attrib; #endif tchar_t Path[MAXPATHFULL]; if (p->Find != INVALID_HANDLE_VALUE) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } p->DriveNo = -1; #if !defined(TARGET_WINCE) if (!URL[0]) { p->DriveNo = 0; } else #endif { #ifndef WINDOWS_DESKTOP if (GetFileAttributesEx(URL, GetFileExInfoStandard, &attr_data) == 0) return ERR_FILE_NOT_FOUND; if (!(attr_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return ERR_NOT_DIRECTORY; #else Attrib = GetFileAttributes(URL); if (Attrib == (DWORD)-1) return ERR_FILE_NOT_FOUND; if (!(Attrib & FILE_ATTRIBUTE_DIRECTORY)) return ERR_NOT_DIRECTORY; #endif tcscpy_s(Path,TSIZEOF(Path),URL); AddPathDelimiter(Path,TSIZEOF(Path)); tcscat_s(Path,TSIZEOF(Path),T("*.*")); #ifndef WINDOWS_DESKTOP WIN32_FIND_DATA FileData; p->Find = FindFirstFileEx(Path, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0); #else p->Find = FindFirstFile(Path, &p->FindData); #endif } return ERR_NONE; } extern datetime_t FileTimeToRel(FILETIME*); static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { Item->FileName[0] = 0; Item->DisplayName[0] = 0; #if !defined(TARGET_WINCE) && defined(WINDOWS_DESKTOP) if (p->DriveNo>=0) { size_t n = GetLogicalDriveStrings(0,NULL); tchar_t* Drives = alloca((n+1)*sizeof(tchar_t)); if (GetLogicalDriveStrings((DWORD)n,Drives)) { int No = p->DriveNo++; while (Drives[0] && --No>=0) Drives += tcslen(Drives)+1; if (Drives[0]) { size_t n = tcslen(Drives); if (Drives[n-1] == '\\') Drives[n-1] = 0; tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),Drives); Item->ModifiedDate = INVALID_DATETIME_T; Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } } } else #endif { while (!Item->FileName[0] && p->Find != INVALID_HANDLE_VALUE) { if (p->FindData.cFileName[0]!='.' && // skip unix/mac hidden files and . .. directory entries !(p->FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) { tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),p->FindData.cFileName); Item->ModifiedDate = FileTimeToRel(&p->FindData.ftLastWriteTime); if (p->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } else { Item->Size = (filepos_t)(((int64_t)p->FindData.nFileSizeHigh << 32) | p->FindData.nFileSizeLow); Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } if (!FindNextFile(p->Find,&p->FindData)) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } } } if (!Item->FileName[0]) { if (p->Find != INVALID_HANDLE_VALUE) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } p->DriveNo = -1; return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { Open(p,NULL,0); if (p->Find != INVALID_HANDLE_VALUE) FindClose(p->Find); } static err_t CreateFunc(node* UNUSED_PARAM(p)) { #if defined(TARGET_WINCE) CEShellDLL = LoadLibrary(T("ceshell.dll")); if (CEShellDLL) *(FARPROC*)(void*)&FuncSHFileOperation = GetProcAddress(CEShellDLL,MAKEINTRESOURCE(14)); #elif defined(ENABLE_MICROSOFT_STORE_APP) FuncSHFileOperation = NULL; #elif defined(WINDOWS_DESKTOP) FuncSHFileOperation = SHFileOperation; #endif return ERR_NONE; } static void DeleteFunc(node* UNUSED_PARAM(p)) { #if defined(TARGET_WINCE) if (CEShellDLL) FreeLibrary(CEShellDLL); #endif } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_CONST(TYPE_PTR,filestream,Find,INVALID_HANDLE_VALUE) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END_CONTINUE(STREAM_CLASS) META_START_CONTINUE(FILE_FUNC_ID) META_CLASS(FLAGS,CFLAG_SINGLETON) META_CLASS(CREATE,CreateFunc) META_CLASS(DELETE,DeleteFunc) META_END(NODE_CLASS) bool_t FolderCreate(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { return CreateDirectory(Path,NULL) != FALSE; } bool_t FileExists(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; return GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0; #else return GetFileAttributes(Path) != (DWORD)-1; #endif } #ifdef WINDOWS_DESKTOP static bool_t FileRecycle(const tchar_t* Path) { tchar_t PathEnded[MAXPATHFULL]; SHFILEOPSTRUCT DelStruct; int Ret; size_t l; memset(&DelStruct,0,sizeof(DelStruct)); DelStruct.wFunc = FO_DELETE; l = min(tcslen(Path)+1,TSIZEOF(PathEnded)-1); tcscpy_s(PathEnded,TSIZEOF(PathEnded),Path); PathEnded[l]=0; DelStruct.pFrom = PathEnded; DelStruct.fFlags = FOF_ALLOWUNDO|FOF_NO_UI; Ret = FuncSHFileOperation(&DelStruct); return Ret == 0; } #endif bool_t FileErase(nodecontext* UNUSED_PARAM(p),const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; if ((GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && (attr_data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { attr_data.dwFileAttributes ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path, attr_data.dwFileAttributes); } #else DWORD attr = GetFileAttributes(Path); if ((attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_READONLY)) { attr ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path,attr); } #endif } #ifndef WINDOWS_DESKTOP return DeleteFile(Path) != FALSE; #else if (!Safe || !FuncSHFileOperation) return DeleteFile(Path) != FALSE; else return FileRecycle(Path); #endif } bool_t FolderErase(nodecontext* UNUSED_PARAM(p),const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; if ((GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && (attr_data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { attr_data.dwFileAttributes ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path, attr_data.dwFileAttributes); } #else DWORD attr = GetFileAttributes(Path); if ((attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_READONLY)) { attr ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path,attr); } #endif } #ifndef WINDOWS_DESKTOP return RemoveDirectory(Path) != FALSE; #else if (!Safe || !FuncSHFileOperation) return RemoveDirectory(Path) != FALSE; else return FileRecycle(Path); #endif } bool_t PathIsFolder(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; return (GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && ((attr_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY); #else DWORD attr = GetFileAttributes(Path); return (attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; #endif } datetime_t FileDateTime(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { datetime_t Date = INVALID_DATETIME_T; HANDLE Find; WIN32_FIND_DATA FindData; #ifndef WINDOWS_DESKTOP WIN32_FIND_DATA FileData; Find = FindFirstFileEx(Path, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0); #else Find = FindFirstFile(Path, &FindData); #endif if (Find != INVALID_HANDLE_VALUE) { Date = FileTimeToRel(&FindData.ftLastWriteTime); FindClose(Find); } return Date; } bool_t FileMove(nodecontext* UNUSED_PARAM(p),const tchar_t* In,const tchar_t* Out) { #ifndef WINDOWS_DESKTOP return MoveFileEx(In, Out, 0); #else return MoveFile(In,Out) != 0; #endif } stream *FileTemp(anynode* UNUSED_PARAM(Any)) { #ifndef TODO assert(NULL); // not supported yet #endif return NULL; } bool_t FileTempName(anynode* UNUSED_PARAM(Any),tchar_t* UNUSED_PARAM(Out), size_t UNUSED_PARAM(OutLen)) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } FILE_DLL int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { ULARGE_INTEGER lpFreeBytesAvailable; ULARGE_INTEGER lpTotal; if (!GetDiskFreeSpaceEx(Path, &lpFreeBytesAvailable, &lpTotal, NULL)) return -1; return (int64_t)lpFreeBytesAvailable.QuadPart; } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/file_libc.c000066400000000000000000000243421462133141200227160ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "bcmatroska2_config.h" #ifdef CONFIG_FILEPOS_64 #define __USE_FILE_OFFSET64 #endif #include #include #include #include #include #include #include // Do not move. Define TARGET_*. #include "file.h" #if defined(TARGET_OSX) #include #elif defined(TARGET_QNX) #include #else #include #endif #if defined(O_ACCMODE) #define _RW_ACCESS_FILE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) #define _RW_ACCESS_DIR (S_IRWXU|S_IRWXG|S_IRWXO) #elif defined(S_IREAD) && defined(S_IWRITE) #define _RW_ACCESS_FILE (S_IREAD|S_IWRITE) #define _RW_ACCESS_DIR (S_IREAD|S_IWRITE|S_IEXEC) #endif typedef struct filestream { stream Stream; int fd; tchar_t URL[MAXPATH]; // TODO: turn into a dynamic data filepos_t Length; int Flags; tchar_t DirPath[MAXPATH]; // TODO: turn into a dynamic data DIR *FindDir; } filestream; static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->fd != -1) close(p->fd); p->Length = INVALID_FILEPOS_T; p->fd = -1; if (URL && URL[0]) { struct stat file_stats; int mode = 0; if (Flags & SFLAG_WRONLY && !(Flags & SFLAG_RDONLY)) mode = O_WRONLY; else if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) mode = O_RDONLY; else mode = O_RDWR; if (Flags & SFLAG_CREATE) mode |= O_CREAT|O_TRUNC; //TODO: verify it works with Unicode files too p->fd = open(URL, mode, _RW_ACCESS_FILE); if (p->fd == -1) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); if (stat(URL, &file_stats) == 0) p->Length = file_stats.st_size; } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { err_t Err; int n = read(p->fd, Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_READ; } else Err = ((size_t)n != Size) ? ERR_END_OF_FILE:ERR_NONE; if (Readed) *Readed = n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { err_t Err; int n = write(p->fd, Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_WRITE; } else Err = (n != Size) ? ERR_WRITE:ERR_NONE; if (Written) *Written = n; return Err; } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { off_t NewPos = lseek(p->fd, Pos, SeekMode); if (NewPos<0) return INVALID_FILEPOS_T; return NewPos; } static err_t SetLength(filestream* p,dataid Id,const filepos_t* Data,size_t Size) { if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; if (ftruncate(p->fd, *Data)!=0) return ERR_BUFFER_FULL; return ERR_NONE; } static err_t OpenDir(filestream* p,const tchar_t* Path,int UNUSED_PARAM(Flags)) { if (p->FindDir) closedir(p->FindDir); if (Path[0]==0) Path = T("/"); p->FindDir = opendir(Path); if (!p->FindDir) { if (errno == ENOTDIR) return ERR_NOT_DIRECTORY; else return ERR_FILE_NOT_FOUND; } tcscpy_s(p->DirPath,TSIZEOF(p->DirPath),Path); AddPathDelimiter(p->DirPath,TSIZEOF(p->DirPath)); return ERR_NONE; } extern datetime_t LinuxToDateTime(time_t); static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { struct dirent *Dirent; if (!p->FindDir) return ERR_END_OF_FILE; Item->FileName[0] = 0; Item->Size = INVALID_FILEPOS_T; while (!Item->FileName[0] && (Dirent = readdir(p->FindDir)) != NULL) { tchar_t FilePath[MAXPATH]; struct stat file_stats; if (Dirent->d_name[0]=='.') // skip hidden files and current directory continue; tcscpy_s(FilePath, TSIZEOF(FilePath), p->DirPath); tcscat_s(FilePath, TSIZEOF(FilePath), Dirent->d_name); tcscpy_s(Item->FileName,TSIZEOF(Item->FileName), Dirent->d_name); stat(FilePath, &file_stats); Item->ModifiedDate = LinuxToDateTime(file_stats.st_mtime); if (S_ISDIR(file_stats.st_mode)) { Item->Type = FTYPE_DIR; Item->Size = INVALID_FILEPOS_T; } else { Item->Size = file_stats.st_size; Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } if (!Item->FileName[0]) { closedir(p->FindDir); p->FindDir = NULL; return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { if (p->fd != -1) { close(p->fd); p->fd = -1; } if (p->FindDir) closedir(p->FindDir); } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_CONST(TYPE_INT,filestream,fd,-1) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_DATA_RDONLY(TYPE_STRING,STREAM_ENUM_BASE,filestream,DirPath) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END(STREAM_CLASS) bool_t FileExists(nodecontext *p,const tchar_t* Path) { struct stat file_stats; return stat(Path, &file_stats) == 0; } bool_t FileErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { if ((file_stats.st_mode & S_IWUSR)==0) { file_stats.st_mode |= S_IWUSR; chmod(Path,file_stats.st_mode); } } } return unlink(Path) == 0; } bool_t FolderErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { if ((file_stats.st_mode & S_IWUSR)==0) { file_stats.st_mode |= S_IWUSR; chmod(Path,file_stats.st_mode); } } } return rmdir(Path) == 0; } bool_t PathIsFolder(nodecontext *p,const tchar_t* Path) { struct stat file_stats; if (stat(Path, &file_stats) == 0) { return (file_stats.st_mode & S_IFDIR) == S_IFDIR; } return 0; } datetime_t FileDateTime(nodecontext *p,const tchar_t* Path) { datetime_t Date = INVALID_DATETIME_T; struct stat file_stats; if (stat(Path, &file_stats) == 0) Date = LinuxToDateTime(file_stats.st_mtime); return Date; } bool_t FileMove(nodecontext *p,const tchar_t* In,const tchar_t* Out) { return rename(In,Out) == 0; } bool_t FolderCreate(nodecontext *p,const tchar_t* Path) { return mkdir(Path,_RW_ACCESS_DIR) == 0; } void FindFiles(nodecontext *p,const tchar_t* Path, const tchar_t* Mask,void(*Process)(const tchar_t*,void*),void* Param) { DIR* Directory; struct dirent* DirectoryInfo; tchar_t TPathToFile[MAXPATH]; Directory = opendir(Path); if (Directory) { while ( (DirectoryInfo = readdir(Directory)) != NULL ) { char* FileExtension = 0; FileExtension = strrchr(DirectoryInfo->d_name, '.'); if(FileExtension) { if (strcmp(Mask, FileExtension ) == 0 ) { tcscpy_s(TPathToFile, TSIZEOF(TPathToFile), Path); tcscat_s(TPathToFile, TSIZEOF(TPathToFile), DirectoryInfo->d_name); Process(TPathToFile, Param); } } } closedir(Directory); } } stream *FileTemp(anynode *Any) { #ifndef TODO assert(NULL); // not supported yet #endif return NULL; } bool_t FileTempName(anynode *Any,tchar_t *Out, size_t OutLen) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { #ifndef TODO // need to an include (see at includes) #if defined(TARGET_QNX) struct statvfs st; if (statvfs(Path, &st) < 0) #else struct statfs st; if (statfs(Path, &st) < 0) #endif return -1; return (int64_t)st.f_bsize * (int64_t)st.f_bavail; #else return -1; #endif } bcmatroska2-5.3.101/corec/corec/helpers/file/file_palmos.c000066400000000000000000000071651462133141200233040ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" // this is not a real file reader // just directory listing for different storage places #if defined(TARGET_PALMOS) #include "pace.h" typedef struct file { stream Stream; bool_t FileDb; UInt32 Iter; } file; static err_t OpenDir(file* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { p->FileDb = 0; if (NodeEnumClass(p,NULL,VFS_CLASS)) p->Iter = vfsIteratorStart; else p->Iter = vfsIteratorStop; return ERR_NONE; } static err_t EnumDir(file* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { UInt16 Ref; Item->FileName[0] = 0; Item->DisplayName[0] = 0; Item->Size = INVALID_FILEPOS_T; Item->ModifiedDate = INVALID_DATETIME_T; Item->Type = FTYPE_DIR; while (!Item->FileName[0] && p->Iter != vfsIteratorStop && VFSVolumeEnumerate(&Ref,&p->Iter)==errNone) VFSFromVol(Ref,NULL,Item->FileName,TSIZEOF(Item->FileName)); if (!Item->FileName[0] && !p->FileDb) { p->FileDb = 1; tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),T("mem://")); } return Item->FileName[0] ? ERR_NONE : ERR_END_OF_FILE; } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(file)) META_CLASS(PRIORITY,PRI_MINIMUM) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END(STREAM_CLASS) stream *FileTemp(anynode *Any) { #ifndef TODO assert(NULL); // not supported yet #endif return NULL; } bool_t FileTempName(anynode *Any,tchar_t *Out, size_t OutLen) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { #ifndef TODO assert(NULL); // TODO: not supported yet UInt16 volRefNum; UInt32 volumeUsed, volumeTotal; if (!VFSToVol(Path, &volRefNum)) return -1; if (VFSVolumeSize(volRefNum, &volumeUsedP, &volumeTotalP) != errNone) return -1; return volumeTotal - volumeUsed; #else return -1; #endif } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/file_ps2sdk.c000066400000000000000000000310141462133141200232050ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #if defined(TARGET_PS2SDK) #include #include #include #include #include typedef struct filestream { stream Stream; int fd; tchar_t URL[MAXPATH]; // TODO: turn into a dynamic data filepos_t Length; int Flags; tchar_t DirPath[MAXPATH]; // TODO: turn into a dynamic data int FindDir; int DevNo; } filestream; const char* CdromPath(const char* Path, char* Tmp, size_t TmpLen) { if (strnicmp(Path,"cdrom",5)==0) { // 8.3 upper case name size_t a,b,c; for (a=0,b=0,c=32;b+1=16) continue; c=16; } else { if (c==8) continue; if (c==16+3) continue; if (c<32) ch=toupper(ch); ++c; } Tmp[b++]=ch; } Tmp[b]=0; Path = Tmp; } return Path; } static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->fd>=0) fileXioClose(p->fd); p->Length = INVALID_FILEPOS_T; p->fd = -1; if (URL && URL[0]) { tchar_t Tmp[MAXPATH]; int size; int mode = 0; URL = CdromPath(URL,Tmp,TSIZEOF(Tmp)); if (Flags & SFLAG_WRONLY && !(Flags & SFLAG_RDONLY)) mode = O_WRONLY; else if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) mode = O_RDONLY; else mode = O_RDWR; if (Flags & SFLAG_CREATE) mode |= O_CREAT|O_TRUNC; p->fd = fileXioOpen(URL, mode, FIO_S_IRUSR | FIO_S_IWUSR | FIO_S_IXUSR | FIO_S_IRGRP | FIO_S_IWGRP | FIO_S_IXGRP | FIO_S_IROTH | FIO_S_IWOTH | FIO_S_IXOTH ); if (p->fd<0) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); if ((size = fileXioLseek(p->fd, 0, SEEK_END)) >= 0) { fileXioLseek(p->fd, 0, SEEK_SET); p->Length = size; } } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { err_t Err; int n; n = fileXioRead(p->fd, Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_READ; } else Err = ((size_t)n != Size) ? ERR_END_OF_FILE:ERR_NONE; if (Readed) *Readed = n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { err_t Err; int n; n = fileXioWrite(p->fd, (void*)Data, (unsigned int)Size); if (n<0) { n=0; Err = ERR_WRITE; } else Err = (n != Size) ? ERR_WRITE:ERR_NONE; if (Written) *Written = n; return Err; } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { int Pos = fileXioLseek(p->fd, Pos, SeekMode); if (Pos<0) return INVALID_FILEPOS_T; return Pos; } static err_t SetLength(filestream* p,dataid Id,const int* Data,size_t Size) { #ifndef TODO assert(NULL); // not supported yet #endif return ERR_NOT_SUPPORTED; } static err_t OpenDir(filestream* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { if (p->FindDir>=0) { fileXioDclose(p->FindDir); p->FindDir=-1; } if (!URL[0]) { p->DevNo = 0; return ERR_NONE; } p->DevNo = -1; p->FindDir = fileXioDopen(URL); if (p->FindDir<0) { int fd = fileXioOpen(URL,O_RDONLY,0); if (fd >= 0) { fileXioClose(fd); return ERR_NOT_DIRECTORY; } else return ERR_FILE_NOT_FOUND; } tcscpy_s(p->DirPath,TSIZEOF(p->DirPath),URL); AddPathDelimiter(p->DirPath,TSIZEOF(p->DirPath)); return ERR_NONE; } static datetime_t PS2ToDateTime(unsigned char time[8]) { datetime_t t; datepack_t p; p.Year = time[6] + (time[7]<<8); p.Month = time[5]; p.Day = time[4]; p.Hour = time[3]; p.Minute = time[2]; p.Second = time[1]; t = TimePackToRel(&p,0); if (t != INVALID_DATETIME_T) { t -= 9*60*60; //adjust JST to GMC if (t == INVALID_DATETIME_T) ++t; } return t; } static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { iox_dirent_t Dirent; Item->FileName[0] = 0; Item->DisplayName[0] = 0; if (p->DevNo>=0) { static const tchar_t* const Devices[] = { "mass:", //"cdrom:", //driver doesn't support directory listing "hdd:", //"host:", //driver doesn't support directory listing "cdda:", "cdfs:", "smb:", NULL, }; for (;!Item->FileName[0];++p->DevNo) { int fd; const tchar_t* URL = Devices[p->DevNo]; if (!URL) break; fd = fileXioDopen(URL); if (fd>=0) { fileXioDclose(fd); tcscpy_s(Item->FileName,TSIZEOF(Item->FileName), URL); Item->ModifiedDate = INVALID_DATETIME_T; Item->Type = FTYPE_DIR; Item->Size = INVALID_FILEPOS_T; } } } else { if (p->FindDir<0) return ERR_END_OF_FILE; while (!Item->FileName[0]) { if (fileXioDread(p->FindDir,&Dirent)<=0) break; if (Dirent.name[0]=='.') // skip unix/mac hidden files continue; tcscpy_s(Item->FileName,TSIZEOF(Item->FileName), Dirent.name); Item->ModifiedDate = PS2ToDateTime(Dirent.stat.mtime); if (FIO_S_ISDIR(Dirent.stat.mode)) { Item->Type = FTYPE_DIR; Item->Size = INVALID_FILEPOS_T; } else { Item->Size = Dirent.stat.size; Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } } if (!Item->FileName[0]) { if (p->FindDir>=0) { fileXioDclose(p->FindDir); p->FindDir = -1; } return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { if (p->fd>=0) { fileXioClose(p->fd); p->fd = -1; } if (p->FindDir>=0) { fileXioDclose(p->FindDir); p->FindDir = -1; } } bool_t LoadIRX(anynode* AnyNode,const char* Name,size_t ParamCount,const char* Param) { int ret; fourcc_t Data; //tchar_t Path[MAXPATH]; size_t ParamSize=0; const char* s = Param; for (;ParamCount>0;--ParamCount) { ParamSize += strlen(s)+1; s += strlen(s)+1; } /* // try external file if (GetResourcePath(AnyNode,0,Path,TSIZEOF(Path))==ERR_NONE) { tchar_t Tmp[MAXPATH]; tcscat_s(Path,TSIZEOF(Path),Name); if (SifExecModuleFile(CdromPath(Path,Tmp,TSIZEOF(Tmp)), ParamSize, Param, &ret)>=0) return ret>=0; } */ // try core-c resource Data = NodeEnumClassStr(AnyNode,NULL,RESOURCEDATA_ID,NODE_NAME,Name); if (Data) { size_t size = (size_t)NodeClass_Meta(NodeContext_FindClass(AnyNode,Data),RESOURCEDATA_SIZE,META_PARAM_CUSTOM); void* ptr = (void*)NodeClass_Meta(NodeContext_FindClass(AnyNode,Data),RESOURCEDATA_PTR,META_PARAM_CUSTOM); if (ptr && size) { SifExecModuleBuffer(ptr, size, ParamSize, Param, &ret); return ret>=0; } } return 0; } void USB_Init(anynode* p) { LoadIRX(p,"usbd.irx",0,NULL); LoadIRX(p,"usbhdfsd.irx",0,NULL); } void FileXio_Init(nodemodule* p) { LoadIRX(p,"fastmem.irx",0,NULL); LoadIRX(p,"poweroff.irx",0,NULL); LoadIRX(p,"iomanx.irx",0,NULL); LoadIRX(p,"filexio.irx",0,NULL); #ifndef CONFIG_NODRIVERS USB_Init(p); #endif } void FileXio_Done(nodemodule* p) { } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_CONST(TYPE_INT,filestream,fd,-1) META_CONST(TYPE_INT,filestream,FindDir,-1) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END_CONTINUE(STREAM_CLASS) META_START_CONTINUE(RESOURCEDATA_ID) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_END(NODE_CLASS) bool_t FileExists(nodecontext *p,const tchar_t* Path) { // not all file systems supports fileXioGetstat tchar_t Tmp[MAXPATH]; int fd = fileXioOpen(CdromPath(Path,Tmp,TSIZEOF(Tmp)),O_RDONLY,0); if (fd >= 0) { fileXioClose(fd); return 1; } return 0; } bool_t FileErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { bool_t Result = fileXioRemove(Path)==0; fileXioRmdir(Path); // workaround for the bug in the ROM that creates a directory right after removing the file return Result; } bool_t FolderErase(nodecontext *p,const tchar_t* Path, bool_t Force, bool_t Safe) { return fileXioRmdir(Path) == 0; } bool_t PathIsFolder(nodecontext *p,const tchar_t* Path) { // not all file systems supports fileXioGetstat if (tcsnicmp(Path,T("cdrom"),5)!=0) { int fd = fileXioDopen(Path); if (fd >= 0) { fileXioDclose(fd); return 1; } } return 0; } datetime_t FileDateTime(nodecontext *p,const tchar_t* Path) { iox_stat_t Stat; if (fileXioGetStat(Path,&Stat)==0) return PS2ToDateTime(Stat.mtime); return INVALID_DATETIME_T; } bool_t FileMove(nodecontext *p,const tchar_t* In,const tchar_t* Out) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } bool_t FolderCreate(nodecontext *p,const tchar_t* Path) { return fileXioMkdir(Path,FIO_S_IRUSR | FIO_S_IWUSR | FIO_S_IXUSR | FIO_S_IRGRP | FIO_S_IWGRP | FIO_S_IXGRP | FIO_S_IROTH | FIO_S_IWOTH | FIO_S_IXOTH)==0; } stream *FileTemp(anynode *Any) { #ifndef TODO assert(NULL); // TODO: not supported yet #endif return NULL; } bool_t FileTempName(anynode *Any,tchar_t *Out, size_t OutLen) { #ifndef TODO assert(NULL); // TODO: not supported yet #endif return 0; } int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { #ifndef TODO assert(NULL); // TODO: not supported yet #endif return -1; } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/file_symbian.cpp000066400000000000000000000302071462133141200240040ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #if defined(TARGET_SYMBIAN) #ifndef SYMBIAN90 #define EFileShareReadersOrWriters EFileShareAny #endif typedef struct filestream { stream Stream; tchar_t URL[MAXPATH]; RFile* File; filepos_t Length; filepos_t Pos; int Flags; CDir* Dir; TInt DirPos; TInt DrivePos; } filestream; static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->File) { p->File->Close(); delete p->File; p->File = NULL; } p->Length = INVALID_FILEPOS_T; if (URL != p->URL) p->URL[0] = 0; if (URL) { RFs& Session = Node_FsSession(p); TPtrC _URL((const TText*)URL); RFile* File = new RFile; TInt Result; TInt Mode; if (!File) return ERR_OUT_OF_MEMORY; if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) Mode = EFileRead; else Mode = EFileWrite; // readwrite mode, no writeonly Mode |= EFileShareReadersOrWriters; if (Flags & SFLAG_CREATE) Result = File->Replace(Session,_URL,Mode); else Result = File->Open(Session,_URL,Mode); if (Result != KErrNone) { delete File; if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } if (Flags & SFLAG_CREATE) { if (Flags & SFLAG_HIDDEN) File->SetAtt(KEntryAttHidden,0); else File->SetAtt(0,KEntryAttHidden); } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); p->Flags = Flags & ~SFLAG_REOPEN; p->File = File; if (File->Size(p->Length) != KErrNone) p->Length = INVALID_FILEPOS_T; if (Flags & SFLAG_REOPEN) File->Seek(ESeekStart,p->Pos); else p->Pos = 0; } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { if (Readed) *Readed = 0; if (!p->File) return ERR_INVALID_DATA; err_t Err; size_t n; TPtr8 Buffer((uint8_t*)Data,0,Size); TInt Result = p->File->Read(Buffer,Size); if (Result == KErrNone) { n = Buffer.Length(); p->Pos += n; Err = (n == Size) ? ERR_NONE : ERR_END_OF_FILE; } else { //todo: reopen when card reinserted... Err = ERR_READ; n = 0; } if (Readed) *Readed = n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { if (!p->File) return INVALID_FILEPOS_T; TSeek Mode; switch (SeekMode) { default: case SEEK_SET: Mode = ESeekStart; break; case SEEK_CUR: Mode = ESeekCurrent; break; case SEEK_END: Mode = ESeekEnd; break; } if (p->File->Seek(Mode,Pos) != KErrNone) return INVALID_FILEPOS_T; p->Pos = Pos; return Pos; } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { if (Written) *Written = 0; if (!p->File) return ERR_INVALID_DATA; size_t n; err_t Err; TPtrC8 Buffer((const uint8_t*)Data,Size); int Result = p->File->Write(Buffer,Size); if (Result == KErrNone) { n = Buffer.Length(); p->Pos += n; Err = (n == Size) ? ERR_NONE : ERR_WRITE; } else { n = 0; Err = ERR_WRITE; } if (Written) *Written = n; return Err; } static err_t SetLength(filestream* p, dataid UNUSED_PARAM(Id),const filepos_t* Data,size_t Size) { if (!p->File) return ERR_INVALID_DATA; err_t Result = ERR_NONE; filepos_t Pos = 0; if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; if (p->File->SetSize(*Data) != KErrNone) Result = ERR_BUFFER_FULL; if (p->File->Seek(ESeekCurrent,Pos) == KErrNone) p->Pos = Pos; return Result; } static err_t OpenDir(filestream* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { TInt Result; TBool Folder; if (p->Dir) { delete p->Dir; p->Dir = NULL; } p->DrivePos = -1; if (!URL[0]) { p->DrivePos = EDriveA; } else { TFileName Path; Path = (const TText*)URL; if (EikFileUtils::IsFolder(Path,Folder)==KErrNone && !Folder) return ERR_NOT_DIRECTORY; Path.Append(_L("\\")); if (!EikFileUtils::PathExists(Path)) return ERR_FILE_NOT_FOUND; Path.Append(_L("*.*")); TFindFile Find(Node_FsSession(p)); Result = Find.FindWildByPath(Path,NULL,p->Dir); if (Result != KErrNone) return ERR_END_OF_FILE; p->DirPos = 0; } return ERR_NONE; } extern datetime_t SymbianToDateTime(TTime); static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { Item->FileName[0] = 0; Item->DisplayName[0] = 0; if (p->DrivePos>=0) { RFs& Session = Node_FsSession(p); while (!Item->FileName[0] && p->DrivePos <= EDriveZ) { TChar ch; TDriveInfo Info; Session.Drive(Info,p->DrivePos); if ((TInt)Info.iDriveAtt != (TInt)KDriveAbsent && Session.DriveToChar(p->DrivePos,ch)==KErrNone) { Item->FileName[0] = (tchar_t)ch; Item->FileName[1] = ':'; Item->FileName[2] = 0; Item->ModifiedDate = INVALID_DATETIME_T; Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } ++p->DrivePos; } } else { while (!Item->FileName[0] && p->Dir && p->DirPosDir->Count()) { const TEntry* Entry = &(*p->Dir)[p->DirPos]; if (Entry->iName.Length()>0 && Entry->iName[0]!='.' && // skip unix/mac hidden files and . .. directory entries !Entry->IsHidden() && Entry->iName.CompareF(_L("_PAlbTN"))!=0) // skip thumb directory { TPtr Name((TText*)Item->FileName,TSIZEOF(Item->FileName)-1); Name = Entry->iName; Item->FileName[Name.Length()] = 0; Item->ModifiedDate = SymbianToDateTime(Entry->iModified); if (Entry->IsDir()) { Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } else { Item->Size = Entry->iSize; Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } ++p->DirPos; } } if (!Item->FileName[0]) { if (p->Dir) { delete p->Dir; p->Dir = NULL; } p->DrivePos = -1; return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { Open(p,NULL,0); if (p->Dir) delete p->Dir; } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END(STREAM_CLASS) datetime_t FileDateTime(nodecontext *p, const tchar_t* URL) { datetime_t Date = INVALID_DATETIME_T; RFs& Session = Node_FsSession(p); TPtrC _URL((const TText*)URL); TTime Time; if (Session.Modified(_URL,Time) == KErrNone) Date = SymbianToDateTime(Time); return Date; } bool_t FileExists(nodecontext *p, const tchar_t* URL) { return BaflUtils::FileExists(Node_FsSession(p),TPtrC((const TText*)URL)) != 0; } bool_t FileErase(nodecontext *p, const tchar_t* URL, bool_t Force, bool_t Safe) { if (Force) { TUint Attribs; if (Node_FsSession(p).Att(TPtrC((const TText*)URL),Attribs) == KErrNone && (Attribs & KEntryAttReadOnly)!=0) { Node_FsSession(p).SetAtt(TPtrC((const TText*)URL),0,KEntryAttReadOnly); } } return BaflUtils::DeleteFile(Node_FsSession(p),TPtrC((const TText*)URL)) != KErrNone; } bool_t FolderErase(nodecontext *p, const tchar_t* URL, bool_t Force, bool_t Safe) { TFileName Path; Path = (const TText*)URL; Path.Append(_L("\\")); if (Force) { TUint Attribs; if (Node_FsSession(p).Att(Path,Attribs) == KErrNone && (Attribs & KEntryAttReadOnly)!=0) { Node_FsSession(p).SetAtt(Path,0,KEntryAttReadOnly); } } return Node_FsSession(p).RmDir(Path) == KErrNone; } bool_t PathIsFolder(nodecontext *p, const tchar_t* URL) { TBool IsFolder; if ((!IsAlpha(URL[0]) || URL[1]!=':') && (URL[0]!='\\')) return 0; if (BaflUtils::IsFolder(Node_FsSession(p),TPtrC((const TText*)URL),IsFolder)!=KErrNone) return 0; return (IsFolder!=0); } bool_t FileMove(nodecontext *p, const tchar_t* In,const tchar_t* Out) { TPtrC _In((const TText*)In); TPtrC _Out((const TText*)Out); return BaflUtils::RenameFile(Node_FsSession(p),_In,_Out) == KErrNone; } bool_t FolderCreate(nodecontext *p, const tchar_t* URL) { TFileName Path; Path = (const TText*)URL; Path.Append(_L("\\")); return Node_FsSession(p).MkDir(Path) == KErrNone; } void FindFiles(nodecontext *p, const tchar_t* URL, const tchar_t* Mask,void(*Process)(const tchar_t*,void*),void* Param) { tchar_t FindPath[MAXPATH]; CDir* Dir = NULL; TFindFile Find(Node_FsSession(p)); TPtrC _Mask((const TText*)Mask); TFileName Path; Path = (const TText*)URL; Path.Append(_Mask); if (Find.FindWildByPath(Path,NULL,Dir) == KErrNone && Dir) { for (TInt i=0;iCount();++i) { const TEntry* Entry = &(*Dir)[i]; if (Entry->iName.Length()>0 && Entry->iName[0]!='.') // skip unix/mac hidden files and . .. directory entries { tcscpy_s(FindPath,TSIZEOF(FindPath),URL); size_t n = tcslen(FindPath); TPtr Name((TText*)(FindPath+n),TSIZEOF(FindPath)-1-n); Name = Entry->iName; FindPath[n+Name.Length()] = 0; Process(FindPath,Param); } } } if (Dir) delete Dir; } stream *FileTemp(anynode* UNUSED_PARAM(Any)) { #ifndef TODO assert(NULL); // TODO: not supported yet #endif return NULL; } bool_t FileTempName(anynode* UNUSED_PARAM(Any),tchar_t* UNUSED_PARAM(Out), size_t UNUSED_PARAM(OutLen)) { #ifndef TODO assert(NULL); // TODO: not supported yet #endif return 0; } int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { #ifndef TODO assert(NULL); // TODO: not supported yet //TVolumeInfo volumeInfo; //return volumeInfo.iFree; return -1; #endif } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/file_win32.c000066400000000000000000000454411462133141200227520ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #if defined(TARGET_WIN) #define FILE_FUNC_ID FOURCC('F','L','I','D') #ifndef STRICT #define STRICT #endif #define WIN32_LEAN_AND_MEAN #include #include #include #ifndef FO_DELETE #define FO_DELETE 3 #endif #ifndef FOF_NO_UI #define FOF_NO_UI (0x04|0x10|0x400|0x200) #endif #if defined(TARGET_WINCE) static HMODULE CEShellDLL = NULL; #endif #ifdef WINDOWS_DESKTOP static int (WINAPI* FuncSHFileOperation)(SHFILEOPSTRUCT*) = NULL; #else static void *FuncSHFileOperation = NULL; #endif #ifndef ERROR_INVALID_DRIVE_OBJECT #define ERROR_INVALID_DRIVE_OBJECT 4321L #endif #ifndef ERROR_DEVICE_NOT_AVAILABLE #define ERROR_DEVICE_NOT_AVAILABLE 4319L #endif #ifndef ERROR_DEVICE_REMOVED #define ERROR_DEVICE_REMOVED 1617L #endif #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif typedef struct filestream { stream Stream; tchar_t URL[MAXPATH]; HANDLE Handle; filepos_t Length; filepos_t Pos; int Flags; void* Find; WIN32_FIND_DATA FindData; int DriveNo; } filestream; static filepos_t SetFilePointerFP(HANDLE hFile, filepos_t DistanceToMove, DWORD dwMoveMethod) { LARGE_INTEGER li; li.QuadPart = DistanceToMove; #ifndef WINDOWS_DESKTOP BOOL ret = SetFilePointerEx(hFile, li, &li, dwMoveMethod); if (ret == FALSE) return -1; #else li.LowPart = SetFilePointer(hFile, li.LowPart, &li.HighPart, dwMoveMethod); if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) return -1; #endif return (filepos_t)li.QuadPart; } static err_t Open(filestream* p, const tchar_t* URL, int Flags) { if (p->Handle) CloseHandle(p->Handle); p->Handle = 0; p->Length = INVALID_FILEPOS_T; if (URL != p->URL) p->URL[0] = 0; else Sleep(200); if (URL) { DWORD FileSizeLow; DWORD FileSizeHigh; HANDLE Handle; #ifndef WINDOWS_DESKTOP Handle = CreateFile2(URL, ((Flags & SFLAG_RDONLY || !(Flags & SFLAG_WRONLY)) ? GENERIC_READ : 0) | ((Flags & SFLAG_WRONLY || !(Flags & SFLAG_RDONLY)) ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE, (Flags & SFLAG_CREATE) ? CREATE_ALWAYS : OPEN_EXISTING, NULL); #else Handle = CreateFile(URL,((Flags & SFLAG_RDONLY || !(Flags & SFLAG_WRONLY))?GENERIC_READ:0)| ((Flags & SFLAG_WRONLY || !(Flags & SFLAG_RDONLY))?GENERIC_WRITE:0), FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,(Flags & SFLAG_CREATE)?CREATE_ALWAYS:OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL); #endif if (Handle == INVALID_HANDLE_VALUE) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) { if (Flags & SFLAG_WRONLY) NodeReportError(p,NULL,ERR_ID,ERR_DEVICE_ERROR,URL); else NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); } return ERR_FILE_NOT_FOUND; } tcscpy_s(p->URL,TSIZEOF(p->URL),URL); p->Flags = Flags & ~SFLAG_REOPEN; p->Handle = Handle; #ifndef WINDOWS_DESKTOP { WIN32_FILE_ATTRIBUTE_DATA attr_data; GetFileAttributesEx(URL, GetFileExInfoStandard, &attr_data); FileSizeLow = attr_data.nFileSizeLow; FileSizeHigh = attr_data.nFileSizeHigh; } #else FileSizeLow = GetFileSize(Handle,&FileSizeHigh); #endif if (FileSizeLow != INVALID_FILE_SIZE || GetLastError()==NO_ERROR) p->Length = (filepos_t)(((int64_t)FileSizeHigh << 32) | FileSizeLow); if (Flags & SFLAG_REOPEN) p->Pos = SetFilePointerFP(p->Handle,p->Pos,FILE_BEGIN); else { p->Pos = 0; #if defined(TARGET_WINCE) // wince shortcut handling if (p->Length < MAXPATH && !(Flags & (SFLAG_CREATE|SFLAG_WRONLY))) { uint32_t Readed; char ShortCut[MAXPATH]; tchar_t URL[MAXPATH]; char* ch; if (ReadFile(p->Handle,ShortCut,(DWORD)p->Length,&Readed,NULL)) { ShortCut[Readed] = 0; for (ch=ShortCut;*ch && *ch!='#';++ch) if (!IsDigit(*ch)) break; if (ch[0] == '#' && ch[1]!=':') { char* Head = ++ch; char* Tail; if (*ch == '"') { Head++; ch = strchr(ch+1,'"'); if (ch) *(ch++) = 0; } if (ch) { Tail = strchr(ch,13); if (Tail) { *Tail = 0; ch = Tail+1; } if (!strchr(ch,13)) { ch = strchr(ch,10); if (!ch || !strchr(ch+1,10)) { if (ch) *ch = 0; // we don't want to depend on parser and charconvert in file // Node_FromStr(p,URL,TSIZEOF(URL),Head); #ifdef COREMAKE_UNICODE if (!MultiByteToWideChar(CP_ACP,0,Head,-1,URL,TSIZEOF(URL))) { tchar_t* Out = URL; size_t OutLen = TSIZEOF(URL); for (;OutLen>1 && *Head;++Head,--OutLen,++Out) *Out = (char)(*Head>255?'*':*Head); *Out = 0; } #endif return Open(p,URL,Flags); } } } } p->Pos = SetFilePointer(p->Handle,0,NULL,FILE_BEGIN); } } #endif } } return ERR_NONE; } static err_t Read(filestream* p,void* Data,size_t Size,size_t* Readed) { err_t Err; DWORD n; if (ReadFile(p->Handle,Data,(DWORD)Size,&n,NULL)) { p->Pos += n; Err = (n == Size) ? ERR_NONE : ERR_END_OF_FILE; } else { DWORD Error = GetLastError(); if (Error == ERROR_DEVICE_REMOVED || Error == ERROR_DEVICE_NOT_AVAILABLE || Error == ERROR_INVALID_HANDLE || Error == ERROR_INVALID_DRIVE_OBJECT || Error == ERROR_DEV_NOT_EXIST || Error == ERROR_GEN_FAILURE) Open(p,p->URL,p->Flags|SFLAG_REOPEN); Err = ERR_READ; n = 0; } if (Readed) *Readed = n; return Err; } static err_t ReadBlock(filestream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { return Read(p,(void*)(Block->Ptr+Ofs),Size,Readed); } static filepos_t Seek(filestream* p,filepos_t Pos,int SeekMode) { int ReTry=3; filepos_t Result; DWORD Error; switch (SeekMode) { default: case SEEK_SET: SeekMode = FILE_BEGIN; break; case SEEK_CUR: SeekMode = FILE_CURRENT; break; case SEEK_END: SeekMode = FILE_END; break; } do { Result = SetFilePointerFP(p->Handle,Pos,SeekMode); if (Result != -1) { p->Pos = Result; break; } Error = GetLastError(); if (Error != ERROR_DEVICE_REMOVED && Error != ERROR_INVALID_HANDLE) break; Open(p,p->URL,p->Flags|SFLAG_REOPEN); } while (--ReTry>0); if (Result==-1) Result = INVALID_FILEPOS_T; return Result; } static err_t Write(filestream* p,const void* Data,size_t Size,size_t* Written) { DWORD n; err_t Err; if (WriteFile(p->Handle,Data,(DWORD)Size,&n,NULL)) { p->Pos += n; Err = (n == Size) ? ERR_NONE : ERR_WRITE; } else { n = 0; Err = ERR_WRITE; } if (Written) *Written = n; return Err; } static err_t SetLength(filestream* p,dataid UNUSED_PARAM(Id),const filepos_t* Data,size_t UNUSED_PARAM(Size)) { err_t Result = ERR_NONE; filepos_t Pos; if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; Pos = SetFilePointerFP(p->Handle,0,SEEK_CUR); if (Pos == -1) return ERR_NOT_SUPPORTED; if (SetFilePointerFP(p->Handle,*Data,SEEK_SET) == -1) return ERR_NOT_SUPPORTED; if (!SetEndOfFile(p->Handle)) Result = ERR_BUFFER_FULL; Pos = SetFilePointerFP(p->Handle,Pos,SEEK_SET); if (Pos != -1) p->Pos = Pos; return Result; } static err_t OpenDir(filestream* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; #else DWORD Attrib; #endif tchar_t Path[MAXPATHFULL]; if (p->Find != INVALID_HANDLE_VALUE) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } p->DriveNo = -1; #if !defined(TARGET_WINCE) if (!URL[0]) { p->DriveNo = 0; } else #endif { #ifndef WINDOWS_DESKTOP if (GetFileAttributesEx(URL, GetFileExInfoStandard, &attr_data) == 0) return ERR_FILE_NOT_FOUND; if (!(attr_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return ERR_NOT_DIRECTORY; #else Attrib = GetFileAttributes(URL); if (Attrib == (DWORD)-1) return ERR_FILE_NOT_FOUND; if (!(Attrib & FILE_ATTRIBUTE_DIRECTORY)) return ERR_NOT_DIRECTORY; #endif tcscpy_s(Path,TSIZEOF(Path),URL); AddPathDelimiter(Path,TSIZEOF(Path)); tcscat_s(Path,TSIZEOF(Path),T("*.*")); #ifndef WINDOWS_DESKTOP WIN32_FIND_DATA FileData; p->Find = FindFirstFileEx(Path, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0); #else p->Find = FindFirstFile(Path, &p->FindData); #endif } return ERR_NONE; } extern datetime_t FileTimeToRel(FILETIME*); static err_t EnumDir(filestream* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { Item->FileName[0] = 0; Item->DisplayName[0] = 0; #if !defined(TARGET_WINCE) && defined(WINDOWS_DESKTOP) if (p->DriveNo>=0) { size_t n = GetLogicalDriveStrings(0,NULL); tchar_t* Drives = alloca((n+1)*sizeof(tchar_t)); if (GetLogicalDriveStrings((DWORD)n,Drives)) { int No = p->DriveNo++; while (Drives[0] && --No>=0) Drives += tcslen(Drives)+1; if (Drives[0]) { size_t n = tcslen(Drives); if (Drives[n-1] == '\\') Drives[n-1] = 0; tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),Drives); Item->ModifiedDate = INVALID_DATETIME_T; Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } } } else #endif { while (!Item->FileName[0] && p->Find != INVALID_HANDLE_VALUE) { if (p->FindData.cFileName[0]!='.' && // skip unix/mac hidden files and . .. directory entries !(p->FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) { tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),p->FindData.cFileName); Item->ModifiedDate = FileTimeToRel(&p->FindData.ftLastWriteTime); if (p->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } else { Item->Size = (filepos_t)(((int64_t)p->FindData.nFileSizeHigh << 32) | p->FindData.nFileSizeLow); Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) Item->FileName[0] = 0; // skip } } if (!FindNextFile(p->Find,&p->FindData)) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } } } if (!Item->FileName[0]) { if (p->Find != INVALID_HANDLE_VALUE) { FindClose(p->Find); p->Find = INVALID_HANDLE_VALUE; } p->DriveNo = -1; return ERR_END_OF_FILE; } return ERR_NONE; } static void Delete(filestream* p) { Open(p,NULL,0); if (p->Find != INVALID_HANDLE_VALUE) FindClose(p->Find); } static err_t CreateFunc(node* UNUSED_PARAM(p)) { #if defined(TARGET_WINCE) CEShellDLL = LoadLibrary(T("ceshell.dll")); if (CEShellDLL) *(FARPROC*)(void*)&FuncSHFileOperation = GetProcAddress(CEShellDLL,MAKEINTRESOURCE(14)); #elif defined(ENABLE_MICROSOFT_STORE_APP) FuncSHFileOperation = NULL; #elif defined(WINDOWS_DESKTOP) FuncSHFileOperation = SHFileOperation; #endif return ERR_NONE; } static void DeleteFunc(node* UNUSED_PARAM(p)) { #if defined(TARGET_WINCE) if (CEShellDLL) FreeLibrary(CEShellDLL); #endif } META_START(File_Class,FILE_CLASS) META_CLASS(SIZE,sizeof(filestream)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_CONST(TYPE_PTR,filestream,Find,INVALID_HANDLE_VALUE) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filestream,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filestream,URL) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,filestream,Length) META_PARAM(STRING,NODE_PROTOCOL,T("file")) META_END_CONTINUE(STREAM_CLASS) META_START_CONTINUE(FILE_FUNC_ID) META_CLASS(FLAGS,CFLAG_SINGLETON) META_CLASS(CREATE,CreateFunc) META_CLASS(DELETE,DeleteFunc) META_END(NODE_CLASS) bool_t FolderCreate(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { return CreateDirectory(Path,NULL) != FALSE; } bool_t FileExists(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; return GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0; #else return GetFileAttributes(Path) != (DWORD)-1; #endif } #ifdef WINDOWS_DESKTOP static bool_t FileRecycle(const tchar_t* Path) { tchar_t PathEnded[MAXPATHFULL]; SHFILEOPSTRUCT DelStruct; int Ret; size_t l; memset(&DelStruct,0,sizeof(DelStruct)); DelStruct.wFunc = FO_DELETE; l = min(tcslen(Path)+1,TSIZEOF(PathEnded)-1); tcscpy_s(PathEnded,TSIZEOF(PathEnded),Path); PathEnded[l]=0; DelStruct.pFrom = PathEnded; DelStruct.fFlags = FOF_ALLOWUNDO|FOF_NO_UI; Ret = FuncSHFileOperation(&DelStruct); return Ret == 0; } #endif bool_t FileErase(nodecontext* UNUSED_PARAM(p),const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; if ((GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && (attr_data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { attr_data.dwFileAttributes ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path, attr_data.dwFileAttributes); } #else DWORD attr = GetFileAttributes(Path); if ((attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_READONLY)) { attr ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path,attr); } #endif } #ifndef WINDOWS_DESKTOP return DeleteFile(Path) != FALSE; #else if (!Safe || !FuncSHFileOperation) return DeleteFile(Path) != FALSE; else return FileRecycle(Path); #endif } bool_t FolderErase(nodecontext* UNUSED_PARAM(p),const tchar_t* Path, bool_t Force, bool_t Safe) { if (Force) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; if ((GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && (attr_data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { attr_data.dwFileAttributes ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path, attr_data.dwFileAttributes); } #else DWORD attr = GetFileAttributes(Path); if ((attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_READONLY)) { attr ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(Path,attr); } #endif } #ifndef WINDOWS_DESKTOP return RemoveDirectory(Path) != FALSE; #else if (!Safe || !FuncSHFileOperation) return RemoveDirectory(Path) != FALSE; else return FileRecycle(Path); #endif } bool_t PathIsFolder(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { #ifndef WINDOWS_DESKTOP WIN32_FILE_ATTRIBUTE_DATA attr_data; return (GetFileAttributesEx(Path, GetFileExInfoStandard, &attr_data) != 0) && ((attr_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY); #else DWORD attr = GetFileAttributes(Path); return (attr != (DWORD)-1) && (attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; #endif } datetime_t FileDateTime(nodecontext* UNUSED_PARAM(p),const tchar_t* Path) { datetime_t Date = INVALID_DATETIME_T; HANDLE Find; WIN32_FIND_DATA FindData; #ifndef WINDOWS_DESKTOP WIN32_FIND_DATA FileData; Find = FindFirstFileEx(Path, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0); #else Find = FindFirstFile(Path, &FindData); #endif if (Find != INVALID_HANDLE_VALUE) { Date = FileTimeToRel(&FindData.ftLastWriteTime); FindClose(Find); } return Date; } bool_t FileMove(nodecontext* UNUSED_PARAM(p),const tchar_t* In,const tchar_t* Out) { #ifndef WINDOWS_DESKTOP return MoveFileEx(In, Out, 0); #else return MoveFile(In,Out) != 0; #endif } void FindFiles(nodecontext* UNUSED_PARAM(p),const tchar_t* Path, const tchar_t* Mask, void(*Process)(const tchar_t*,void*),void* Param) { WIN32_FIND_DATA FindData; tchar_t FindPath[MAXPATH]; HANDLE Find; tcscpy_s(FindPath,TSIZEOF(FindPath),Path); tcscat_s(FindPath,TSIZEOF(FindPath),Mask); #ifndef WINDOWS_DESKTOP WIN32_FIND_DATA FileData; Find = FindFirstFileEx(Path, FindExInfoStandard, &FileData, FindExSearchNameMatch, NULL, 0); #else Find = FindFirstFile(FindPath,&FindData); #endif if (Find != INVALID_HANDLE_VALUE) { do { tcscpy_s(FindPath,TSIZEOF(FindPath),Path); tcscat_s(FindPath,TSIZEOF(FindPath),FindData.cFileName); Process(FindPath,Param); } while (FindNextFile(Find,&FindData)); FindClose(Find); } } stream *FileTemp(anynode* UNUSED_PARAM(Any)) { #ifndef TODO assert(NULL); // not supported yet #endif return NULL; } bool_t FileTempName(anynode* UNUSED_PARAM(Any),tchar_t* UNUSED_PARAM(Out), size_t UNUSED_PARAM(OutLen)) { #ifndef TODO assert(NULL); // not supported yet #endif return 0; } FILE_DLL int64_t GetPathFreeSpace(nodecontext* UNUSED_PARAM(p), const tchar_t* Path) { ULARGE_INTEGER lpFreeBytesAvailable; ULARGE_INTEGER lpTotal; if (!GetDiskFreeSpaceEx(Path, &lpFreeBytesAvailable, &lpTotal, NULL)) return -1; return (int64_t)lpFreeBytesAvailable.QuadPart; } #endif bcmatroska2-5.3.101/corec/corec/helpers/file/filedb_palmos.c000066400000000000000000000156241462133141200236110ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" // TODO: don't depend on this or a part of it #include "common.h" //end TODO #if defined(TARGET_PALMOS) #define FILEDB_ID FOURCC('F','I','D','B') #include "pace.h" typedef struct filedb { stream Stream; FileHand File; filepos_t Length; int Flags; DmSearchStateType SearchState; LocalID CurrentDB; Boolean NewEnum; tchar_t URL[MAXPATH]; } filedb; static err_t Read(filedb* p,void* Data,size_t Size,size_t* Readed) { err_t Result; Err Error; Int32 n = FileRead(p->File,Data,1,Size,&Error); if (n<0) n=0; if ((size_t)n != Size) Result = (Error == fileErrEOF) ? ERR_END_OF_FILE : ERR_READ; else Result = ERR_NONE; if (Readed) *Readed = n; return Result; } static err_t ReadBlock(filedb* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { err_t Result; Err Error; Int32 n; if (IsHeapStorage(Block)) n = FileDmRead(p->File,(void*)Block->Ptr,Ofs,1,Size,&Error); else n = FileRead(p->File,(void*)(Block->Ptr+Ofs),1,Size,&Error); if (n<0) n=0; if ((size_t)n != Size) { Result = (Error == fileErrEOF) ? ERR_END_OF_FILE : ERR_READ; n=0; } else Result = ERR_NONE; if (Readed) *Readed = n; return Result; } static err_t Write(filedb* p,const void* Data,size_t Size,size_t* Written) { err_t Result; Err Error; Int32 n = FileWrite(p->File,Data,1,Size,&Error); if (n<=0) { Result = ERR_WRITE; n = 0; } else Result = ((size_t)n == Size) ? ERR_NONE : ERR_WRITE; if (Written) *Written = n; return Result; } static filepos_t Seek(filedb* p,filepos_t Pos,int SeekMode) { FileOriginEnum Origin; Err Error; switch (SeekMode) { default: case SEEK_SET: Origin = fileOriginBeginning; break; case SEEK_CUR: Origin = fileOriginCurrent; break; case SEEK_END: Origin = fileOriginEnd; break; } Error = FileSeek(p->File,Pos,Origin); if (Error == errNone || Error == fileErrEOF) return FileTell(p->File,NULL,NULL); return INVALID_FILEPOS_T; } static err_t Open(filedb* p, const tchar_t* URL, int Flags) { if (p->File) { FileClose(p->File); p->File = NULL; } p->Length = INVALID_FILEPOS_T; p->URL[0] = 0; if (URL) { UInt32 Mode; if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) Mode = fileModeReadOnly; else Mode = fileModeUpdate; // readwrite mode, no writeonly Mode | = fileModeAnyTypeCreator; p->File = FileOpen(0,GetProtocol(URL,NULL,0,NULL), 0, 0, Mode, NULL); if (!p->File) { if (!(Flags & SFLAG_SILENT)) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } p->Flags = Flags; tcscpy_s(p->URL,TSIZEOF(p->URL),URL); if (Flags & SFLAG_CREATE) FileTruncate(p->File,0); else { if (FileSeek(p->File,0,fileOriginEnd) == errNone) p->Length = FileTell(p->File,NULL,NULL); FileSeek(p->File,0,fileOriginBeginning); } } return ERR_NONE; } bool_t DBFrom(uint16_t Card,uint32_t DB,tchar_t* URL,int URLLen) { char Name[48]; UInt16 Attr = 0; DmDatabaseInfo(Card,DB,Name,&Attr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); if (Attr & dmHdrAttrStream) { stprintf_s(URL,URLLen,T("mem://%s"),Name); return 1; } return 0; } static err_t OpenDir(filedb* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { const tchar_t* Name = GetProtocol(URL,NULL,0,NULL); if (Name[0]) { FileHand File = FileOpen(0,GetProtocol(URL,NULL,0,NULL), 0, 0, fileModeReadOnly | fileModeAnyTypeCreator, NULL); if (File) FileClose(File); return File ? ERR_NOT_DIRECTORY:ERR_FILE_NOT_FOUND; } p->CurrentDB = 0; p->NewEnum = 1; return ERR_NONE; } extern datetime_t PalmToDateTime(UInt32); static err_t EnumDir(filedb* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { UInt16 card; Item->FileName[0] = 0; Item->DisplayName[0] = 0; while (DmGetNextDatabaseByTypeCreator(p->NewEnum, &p->SearchState, 0, 0, 0, &card, &p->CurrentDB)==errNone) { char Name[48]; UInt16 Attr = 0; UInt32 Date = 0; UInt32 Size = 0; DmDatabaseInfo(card,p->CurrentDB,Name,&Attr,NULL,NULL,&Date,NULL,NULL,NULL,NULL,NULL,NULL); if (Attr & dmHdrAttrStream) { Item->Type = CheckExts(Name,Exts); if (Item->Type || !ExtFilter) { DmDatabaseSize(card,p->CurrentDB,NULL,NULL,&Size); tcscpy_s(Item->FileName,TSIZEOF(Item->FileName),Name); Item->ModifiedDate = PalmToDateTime(Date); Item->Size = Size; return ERR_NONE; } } p->NewEnum = 0; } return ERR_END_OF_FILE; } static void Delete(filedb* p) { Open(p,NULL,0); } META_START(FileDb_Class,FILEDB_ID) META_CLASS(SIZE,sizeof(filedb)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,filedb,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,filedb,URL) META_DATA_RDONLY(TYPE_FILEPOS,STREAM_LENGTH,filedb,Length) META_PARAM(STRING,NODE_PROTOCOL,T("mem,conf")) META_END(STREAM_CLASS) #endif bcmatroska2-5.3.101/corec/corec/helpers/file/filevfs_palmos.c000066400000000000000000000340761462133141200240240ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" // TODO: don't depend on this or a part of it #include "common.h" //end TODO #if defined(TARGET_PALMOS) #include "pace.h" typedef struct vfs { stream Stream; UInt16 Vol; FileRef File; filepos_t Length; filepos_t Pos; int Flags; UInt32 Iter; tchar_t URL[MAXPATH]; } vfs; static err_t Open(vfs* p, const tchar_t* URL, int Flags); static err_t Read(vfs* p,void* Data,size_t Size,size_t* Readed) { err_t Result; uint32_t n = 0; Err Error = VFSFileRead(p->File,Size,Data,&n); if ((Error==errNone && n>0) || Error==vfsErrFileEOF) { p->Pos += n; Result = Error==vfsErrFileEOF ? ERR_END_OF_FILE : ERR_NONE; } else { n = 0; if (Error == vfsErrFileBadRef) Open(p,p->URL,p->Flags | SFLAG_REOPEN); Result = ERR_READ; } if (Readed) *Readed = n; return Result; } static err_t Write(vfs* p,const void* Data,size_t Size,size_t* Written) { err_t Result; uint32_t n = 0; Err Error = VFSFileWrite(p->File,Size,Data,&n); if (Error==errNone) { p->Pos += n; Result = (n == Size) ? ERR_NONE : ERR_WRITE; } else { n = 0; Result = ERR_WRITE; } if (Written) *Written = n; return Result; } static err_t ReadBlock(vfs* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { err_t Result; uint32_t n = 0; Err Error; if (IsHeapStorage(Block)) Error = VFSFileReadData(p->File,Size,(void*)Block->Ptr,Ofs,&n); else Error = VFSFileRead(p->File,Size,(void*)(Block->Ptr+Ofs),&n); if ((Error==errNone && n>0) || Error==vfsErrFileEOF) { p->Pos += n; Result = Error==vfsErrFileEOF ? ERR_END_OF_FILE : ERR_NONE; } else { n = 0; if (Error == vfsErrFileBadRef) Open(p,p->URL,p->Flags | SFLAG_REOPEN); Result = ERR_READ; } if (Readed) *Readed = n; return Result; } static filepos_t Seek(vfs* p,filepos_t Pos,int SeekMode) { FileOrigin Origin; Err Error; switch (SeekMode) { default: case SEEK_SET: Origin = vfsOriginBeginning; break; case SEEK_CUR: Origin = vfsOriginCurrent; break; case SEEK_END: Origin = vfsOriginEnd; break; } Error = VFSFileSeek(p->File,Origin,Pos); if (Error == errNone || Error == vfsErrFileEOF) { UInt32 Pos; if (VFSFileTell(p->File,&Pos) == errNone) p->Pos = Pos; return p->Pos; } return INVALID_FILEPOS_T; } static err_t SetLength(vfs* p,dataid Id,const filepos_t* Data,size_t Size) { err_t Result = ERR_NONE; UInt32 Pos; if (Size != sizeof(filepos_t)) return ERR_INVALID_DATA; if (VFSFileResize(p->File,*Data) != errNone) Result = ERR_BUFFER_FULL; if (VFSFileTell(p->File,&Pos) == errNone) p->Pos = Pos; return Result; } static UInt16 FindVol(int Slot) { UInt16 Ref; UInt32 Iter = vfsIteratorStart; while (Iter != vfsIteratorStop && VFSVolumeEnumerate(&Ref,&Iter)==errNone) { VolumeInfoType Info; VFSVolumeInfo(Ref,&Info); if (Slot==0 && Info.mediaType == 'pose') return Ref; if (Slot<0 && Info.mountClass == vfsMountClass_Simulator && Info.slotRefNum==0xFFFF+Slot) return Ref; if (Slot>0 && Info.mountClass == vfsMountClass_SlotDriver && Info.slotRefNum==Slot) return Ref; } return vfsInvalidVolRef; } const tchar_t* VFSToVol(const tchar_t* URL,uint16_t* Vol) { int Slot = 0; bool_t Found = 0; tchar_t Mime[MAXPATH]; const tchar_t* Name = GetProtocol(URL,Mime,TSIZEOF(Mime),NULL); if (Name != URL) --Name; // need the '/' if (tcsncmp(Mime,"pose",4)==0 || stscanf(Mime,"slot%d",&Slot)==1 || stscanf(Mime,"vol%d",&Slot)==1) Found = 1; else if (stscanf(Mime,"simu%d",&Slot)==1) { Found = 1; Slot = -Slot; } if (Found && (*Vol=FindVol(Slot))!=vfsInvalidVolRef) return Name; return NULL; } bool_t VFSFromVol(uint16_t Vol,const tchar_t* Path,tchar_t* URL,int URLLen) { int Slot; VolumeInfoType Info; VFSVolumeInfo(Vol,&Info); Slot = Info.slotRefNum; if (Slot > 0xFFF0) Slot = 0xFFFF-Slot; URL[0] = 0; if (!Path) Path = T("/"); if (Info.mediaType == 'pose') { stprintf_s(URL,URLLen,T("pose:/%s"),Path); return 1; } if (Info.mountClass == vfsMountClass_Simulator) { stprintf_s(URL,URLLen,T("simu%d:/%s"),Slot,Path); return 1; } if (Info.mountClass == vfsMountClass_SlotDriver) { stprintf_s(URL,URLLen,(Info.attributes & vfsVolumeAttrNonRemovable)?T("vol%d:/%s"):T("slot%d:/%s"),Slot,Path); return 1; } return 0; } extern datetime_t PalmToDateTime(UInt32); static bool_t IsMem(const tchar_t* URL) { tchar_t Mime[MAXPROTOCOL]; GetProtocol(URL,Mime,TSIZEOF(Mime),NULL); return tcsisame_ascii(Mime,T("mem")); } datetime_t FileDateTime(nodecontext *p,const tchar_t* URL) { // only VFS support... const tchar_t* Name; UInt16 Vol; UInt32 Value; datetime_t Date = INVALID_DATETIME_T; FileRef File = 0; Name = VFSToVol(URL,&Vol); if (Name) { VFSFileOpen(Vol,Name,vfsModeRead,&File); if (File) { if (VFSFileGetDate(File,vfsFileDateModified,&Value)==errNone) Date = PalmToDateTime(Value); VFSFileClose(File); } } return Date; } bool_t FileExists(nodecontext *p,const tchar_t* URL) { if (IsMem(URL)) { FileHand File = FileOpen(0,GetProtocol(URL,NULL,0,NULL), 0, 0, fileModeReadOnly | fileModeAnyTypeCreator, NULL); if (File) FileClose(File); return File!=NULL; } else { const tchar_t* Name; UInt16 Vol; FileRef File = 0; Name = VFSToVol(URL,&Vol); if (!Name) return 0; VFSFileOpen(Vol,Name,vfsModeRead,&File); if (!File) return 0; VFSFileClose(File); return 1; } } bool_t FileErase(nodecontext *p,const tchar_t* URL, bool_t Force, bool_t Safe) { if (IsMem(URL)) { const tchar_t *Name = GetProtocol(URL,NULL,0,NULL); if (Force) { LocalID Id; Id = DmFindDatabase(0,Name); if (Id) { UInt16 Attr; DmDatabaseInfo(0,Id,NULL,&Attr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); if ((Attr & dmHdrAttrReadOnly)!=0) { Attr ^= dmHdrAttrReadOnly; DmSetDatabaseInfo(0,Id,NULL,&Attr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); } } } return FileDelete(0,Name) == errNone; } else { const tchar_t* Name; UInt16 Vol; Name = VFSToVol(URL,&Vol); if (!Name) return 0; if (Force) { FileRef File = 0; UInt32 Attrib; VFSFileOpen(Vol,Name,vfsModeRead,&File); if (File) { if (VFSFileGetAttributes(File,&Attrib)) { if ((Attrib & vfsFileAttrReadOnly) != 0) { Attrib |= vfsFileAttrReadOnly; VFSFileSetAttributes(File,Attrib); } } VFSFileClose(File); } } if (errNone == VFSFileDelete(Vol,Name)) return 1; return 0; } } bool_t FolderErase(nodecontext *p,const tchar_t* URL, bool_t Force, bool_t Safe) { return FileErase(p,URL,Force,Safe); // a folder is a file with folder attribute } bool_t PathIsFolder(nodecontext *p,const tchar_t* URL) { if (IsMem(URL)) { return 0; } else { const tchar_t* Name; UInt16 Vol; FileRef File = 0; UInt32 Attrib; Name = VFSToVol(URL,&Vol); if (!Name) return 0; VFSFileOpen(Vol,Name,vfsModeRead,&File); if (!File || !VFSFileGetAttributes(File,&Attrib)) return 0; VFSFileClose(File); return (Attrib & vfsFileAttrDirectory)==vfsFileAttrDirectory; } } bool_t FolderCreate(nodecontext *p,const tchar_t* URL) { if (IsMem(URL)) { return 0; } else { const tchar_t* Name; UInt16 Vol; Name = VFSToVol(URL,&Vol); if (!Name) return 0; return VFSDirCreate(Vol,Name)==errNone; } } bool_t FileMove(nodecontext *p,const tchar_t* In,const tchar_t* Out) { // only VFS support... const tchar_t *NameIn,*NameOut; UInt16 VolIn; UInt16 VolOut; NameIn = VFSToVol(In,&VolIn); NameOut = VFSToVol(Out,&VolOut); if (!NameIn || !NameOut || VolIn!=VolOut) return 0; return VFSFileRename(VolIn,NameIn,NameOut) == errNone; } static bool_t InternalOpen(vfs* p,const tchar_t* URL, int Flags) { const tchar_t* Name; if (p->File) { VFSFileClose(p->File); p->File = 0; } Name = VFSToVol(URL,&p->Vol); if (Name) { uint_fast16_t Mode = 0; if (Flags & SFLAG_WRONLY && !(Flags & SFLAG_RDONLY)) Mode = vfsModeWrite; else if (Flags & SFLAG_RDONLY && !(Flags & SFLAG_WRONLY)) Mode = vfsModeRead; else Mode = vfsModeReadWrite; if (Flags & SFLAG_CREATE) Mode |= vfsModeTruncate|vfsModeCreate; VFSFileOpen(p->Vol,Name,(UInt16)Mode,&p->File); } if (!p->File) return 0; tcscpy_s(p->URL,TSIZEOF(p->URL),URL); p->Flags = Flags & ~SFLAG_REOPEN; return 1; } static err_t Open(vfs* p, const tchar_t* URL, int Flags) { if (p->File) { VFSFileClose(p->File); p->File = 0; } p->Length = INVALID_FILEPOS_T; if (URL != p->URL) p->URL[0] = 0; if (URL) { UInt32 Pos = 0; if (!InternalOpen(p,URL,Flags)) { if ((Flags & (SFLAG_REOPEN|SFLAG_SILENT))==0) NodeReportError(p,NULL,ERR_ID,ERR_FILE_NOT_FOUND,URL); return ERR_FILE_NOT_FOUND; } if (Flags & SFLAG_REOPEN) VFSFileSeek(p->File,vfsOriginBeginning,p->Pos); else { if (VFSFileSize(p->File,&Pos)==errNone) p->Length = Pos; } if (VFSFileTell(p->File,&Pos) == errNone) p->Pos = Pos; } return ERR_NONE; } static err_t OpenDir(vfs* p,const tchar_t* URL,int UNUSED_PARAM(Flags)) { UInt32 Attrib = 0; if (!InternalOpen(p,URL,SFLAG_RDONLY)) return ERR_FILE_NOT_FOUND; VFSFileGetAttributes(p->File,&Attrib); if (!(Attrib & vfsFileAttrDirectory)) return ERR_NOT_DIRECTORY; p->Iter = vfsIteratorStart; return ERR_NONE; } static err_t EnumDir(vfs* p,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item) { tchar_t Path[MAXPATH]; FileInfoType Info; Item->DisplayName[0] = 0; if (p->File) { Info.nameP = Item->FileName; Info.nameBufLen = sizeof(Item->FileName); while (p->Iter != vfsIteratorStop && VFSDirEntryEnumerate(p->File,&p->Iter,&Info)==errNone) { UInt32 Value; FileRef File = 0; if (Item->FileName[0]=='.' || (Info.attributes & vfsFileAttrHidden)) // skip unix/mac hidden files continue; AbsPath(Path,TSIZEOF(Path),Item->FileName,GetProtocol(p->URL,NULL,0,NULL)); //currently Date and Size is not needed //VFSFileOpen(p->Vol,Path,vfsModeRead,&File); Item->ModifiedDate = INVALID_DATETIME_T; if (File && VFSFileGetDate(File,vfsFileDateModified,&Value)==errNone) Item->ModifiedDate = PalmToDateTime(Value); if (Info.attributes & vfsFileAttrDirectory) { Item->Size = INVALID_FILEPOS_T; Item->Type = FTYPE_DIR; } else { if (File && VFSFileSize(File,&Value)==errNone) Item->Size = Value; else Item->Size = 0; Item->Type = CheckExts(Item->FileName,Exts); if (!Item->Type && ExtFilter) { if (File) VFSFileClose(File); continue; } } if (File) VFSFileClose(File); return ERR_NONE; } VFSFileClose(p->File); p->File = 0; } Item->FileName[0] = 0; return ERR_END_OF_FILE; } static void Delete(vfs* p) { Open(p,NULL,0); } static err_t CheckVFS(fourcc_t ClassId, void* VMT) { UInt32 Version; UInt32 CompanyID; if (FtrGet(sysFileCExpansionMgr, expFtrIDVersion, &Version) == errNone && Version >= 1 && FtrGet(sysFileCVFSMgr, vfsFtrIDVersion, &Version) == errNone && Version >= 1) return ERR_NONE; // simulator? FtrGet(sysFtrCreator, sysFtrNumOEMCompanyID, &CompanyID); if (CompanyID == 'psys') return ERR_NONE; return ERR_NOT_SUPPORTED; } META_START(VFS_Class,VFS_CLASS) META_CLASS(SIZE,sizeof(vfs)) META_CLASS(PRIORITY,PRI_MINIMUM) META_CLASS(VMT_CREATE,CheckVFS) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,OpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,EnumDir) META_DATA_RDONLY(TYPE_INT,STREAM_FLAGS,vfs,Flags) META_DATA_RDONLY(TYPE_STRING,STREAM_URL,vfs,URL) META_PARAM(SET,STREAM_LENGTH,SetLength) META_DATA(TYPE_FILEPOS,STREAM_LENGTH,vfs,Length) META_PARAM(STRING,NODE_PROTOCOL,T("pose,slot1,slot2,slot3,slot4,slot5,slot6,slot7,slot8,simu1,simu2,simu3,simu4,simu5,simu6,simu7,simu8,vol1,vol2,vol3,vol4,vol5,vol6,vol7,vol8")) META_END(STREAM_CLASS) #endif bcmatroska2-5.3.101/corec/corec/helpers/file/memstream.c000066400000000000000000000074151462133141200230020ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" static err_t MemRead(memstream* p,void* Data,size_t Size,size_t* Readed) { err_t Err = ERR_NONE; size_t Pos = p->Pos; assert(Pos <= p->Size); if (Size > p->Size - Pos) { Size = p->Size - Pos; Err = ERR_END_OF_FILE; } memcpy(Data,p->Ptr+Pos,Size); p->Pos = Pos+Size; if (Readed) *Readed = Size; return Err; } static err_t MemWrite(memstream* p, const void* Data, size_t Size, size_t* Written) { *Written = 0; if (Size + p->Pos > p->Size) return ERR_INVALID_PARAM; assert(p->Ptr!=NULL); memcpy((uint8_t*)p->Ptr + p->Pos, Data, Size); p->Pos += Size; *Written = Size; return ERR_NONE; } static filepos_t MemSeek(memstream* p,filepos_t VirtualPos,int SeekMode) { switch (SeekMode) { default: case SEEK_SET: break; case SEEK_CUR: VirtualPos += p->Pos + p->VirtualOffset; break; case SEEK_END: VirtualPos += p->Size + p->VirtualOffset; break; } // TODO: these safety checks should return an error if (VirtualPos<0) { assert(VirtualPos>=0); VirtualPos=0; } if (VirtualPos>(filepos_t)p->Size + p->VirtualOffset) { assert(VirtualPos<=(filepos_t)p->Size); VirtualPos=p->Size + p->VirtualOffset; } p->Pos = (size_t)(VirtualPos - p->VirtualOffset); return VirtualPos; } static err_t MemLength(memstream* p, dataid UNUSED_PARAM(Id), filepos_t* Data, size_t UNUSED_PARAM(Size)) { *Data = p->Size; return ERR_NONE; } static err_t MemData(memstream* p, dataid UNUSED_PARAM(Id), const void* Data, size_t Size) { assert(Size==0 || Data!=NULL); p->Ptr = (const uint8_t*)Data; p->Size = Size; p->Pos = 0; return ERR_NONE; } META_START(MemStream_Class,MEMSTREAM_CLASS) META_CLASS(SIZE,sizeof(memstream)) META_VMT(TYPE_FUNC,stream_vmt,Read,MemRead) META_VMT(TYPE_FUNC,stream_vmt,Write,MemWrite) META_VMT(TYPE_FUNC,stream_vmt,Seek,MemSeek) META_PARAM(GET,STREAM_LENGTH,MemLength) META_PARAM(SET,MEMSTREAM_DATA,MemData) META_DATA(TYPE_FILEPOS,MEMSTREAM_OFFSET,memstream,VirtualOffset) META_DATA_RDONLY(TYPE_PTR,MEMSTREAM_PTR,memstream,Ptr) META_END(STREAM_CLASS) bcmatroska2-5.3.101/corec/corec/helpers/file/stream_stdio.c000066400000000000000000000106121462133141200234760ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" #include #if defined(TARGET_WIN) #if !defined(TARGET_WINCE) #include #include #endif #else #include #endif #define STDIO_CLASS FOURCC('S','T','I','O') typedef struct stdio_stream { stream Base; FILE *Stream; } stdio_stream; static err_t Write(stdio_stream *p,const void* Data,size_t Size,size_t* Written) { size_t written; if (!Written) Written = &written; *Written = fwrite(Data,1,Size,p->Stream); return (*Written == Size) ? ERR_NONE : ERR_DEVICE_ERROR; } static err_t Read(stdio_stream *p, void* Data, size_t Size, size_t* Readed) { size_t readed; if (!Readed) Readed = &readed; *Readed = fread(Data,1,Size,p->Stream); return (*Readed == Size) ? ERR_NONE : ERR_DEVICE_ERROR; } static err_t ReadOneOrMore(stdio_stream* p,char* Data,size_t UNUSED_PARAM(Size),size_t* Readed) { *Data = (char)fgetc(p->Stream); if (Readed) *Readed = 1; return ERR_NONE; } static err_t Flush(stdio_stream *p) { return fflush(p->Stream)==0 ? ERR_NONE : ERR_DEVICE_ERROR; } static err_t CreateStdIn(stdio_stream *p) { #if defined(TARGET_WIN) && !defined(TARGET_WINCE) _setmode(_fileno(stdin),_O_BINARY); #endif p->Stream = stdin; return ERR_NONE; } static err_t GetTty(stdio_stream *p, dataid UNUSED_PARAM(Id), bool_t *Value, size_t UNUSED_PARAM(Size)) { #if defined(TARGET_WINCE) || defined(TARGET_PS2SDK) *Value = 0; #elif defined(TARGET_WIN) *Value = _isatty(_fileno(p->Stream))!=0; #else *Value = isatty(fileno(p->Stream))!=0; #endif return ERR_NONE; } static err_t CreateStdOut(stdio_stream *p) { #if defined(TARGET_WIN) && !defined(TARGET_WINCE) _setmode(_fileno(stdout),_O_BINARY); #endif p->Stream = stdout; return ERR_NONE; } static err_t CreateStdErr(stdio_stream *p) { #if defined(TARGET_WIN) && !defined(TARGET_WINCE) _setmode(_fileno(stderr),_O_BINARY); #endif p->Stream = stderr; return ERR_NONE; } META_START(Stdio_Class,STDIO_CLASS) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_CLASS(SIZE,sizeof(stdio_stream)) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadOneOrMore,ReadOneOrMore) META_VMT(TYPE_FUNC,stream_vmt,Flush,Flush) META_END_CONTINUE(STREAM_CLASS) META_START_CONTINUE(STDIN_ID) META_CLASS(FLAGS,CFLAG_SINGLETON) META_CLASS(CREATE,CreateStdIn) META_PARAM(TYPE,STREAM_ISTTY,TYPE_BOOLEAN) META_PARAM(GET,STREAM_ISTTY,GetTty) META_END_CONTINUE(STDIO_CLASS) META_START_CONTINUE(STDOUT_ID) META_CLASS(FLAGS,CFLAG_SINGLETON) META_CLASS(CREATE,CreateStdOut) META_END_CONTINUE(STDIO_CLASS) META_START_CONTINUE(STDERR_ID) META_CLASS(FLAGS,CFLAG_SINGLETON) META_CLASS(CREATE,CreateStdErr) META_END(STDIO_CLASS) bcmatroska2-5.3.101/corec/corec/helpers/file/streams.c000066400000000000000000000271601462133141200224650ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" //TODO: include from somewhere else or not depend on them at all #ifdef CONFIG_BLOCK_RDONLY #include "common.h" #endif //end TODO static err_t DummySkip(void* p, intptr_t* Skip) { uint8_t Buf[1024]; size_t Readed; intptr_t n = *Skip; err_t Err = ERR_NONE; while (n>0 && Err == ERR_NONE) { Err = Stream_Read(p,Buf,min(n,(intptr_t)sizeof(Buf)),&Readed); n -= Readed; } *Skip = n; return Err; } static err_t DummyOpen(void* UNUSED_PARAM(p),const tchar_t* Name, int UNUSED_PARAM(Flags)) { if (Name) return ERR_NOT_SUPPORTED; return ERR_NONE; } static stream* DummyDuplicate(void* p,int Flags) { tchar_t URL[MAXPATHFULL]; if (Node_Get(p,STREAM_URL,URL,sizeof(URL)) != ERR_NONE) return NULL; return StreamOpen(p,URL,Flags); } static err_t DummyBlocking(void* UNUSED_PARAM(p),bool_t State) { if (!State) return ERR_NOT_SUPPORTED; return ERR_NONE; } static err_t DummyRead(void* UNUSED_PARAM(p),void* UNUSED_PARAM(Data),size_t UNUSED_PARAM(Size),size_t* Readed) { if (Readed) *Readed = 0; return ERR_NOT_SUPPORTED; } static err_t DummyReadOneOrMore(void* p,void* Data,size_t Size,size_t* Readed) { return Stream_Read(p,Data,Size,Readed); } static filepos_t DummySeek(void* UNUSED_PARAM(p),filepos_t UNUSED_PARAM(Pos),int UNUSED_PARAM(SeekMode)) { return INVALID_FILEPOS_T; } static err_t DummyWrite(void* UNUSED_PARAM(This),const void* UNUSED_PARAM(Data),size_t UNUSED_PARAM(Size), size_t* Written) { if (Written) *Written = 0; return ERR_NOT_SUPPORTED; } static err_t DummyOpenDir(void* UNUSED_PARAM(p),const tchar_t* UNUSED_PARAM(URL), int UNUSED_PARAM(Flags)) { return ERR_NOT_DIRECTORY; } static err_t DummyEnumDir(void* UNUSED_PARAM(p),const tchar_t* UNUSED_PARAM(Exts), bool_t UNUSED_PARAM(ExtFilter),streamdir* UNUSED_PARAM(Item)) { return ERR_END_OF_FILE; } static err_t DummyReadBlock(stream* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { #ifdef CONFIG_BLOCK_RDONLY uint8_t Buf[2048]; // MAX_NETWORK_PACKET has to fit... err_t Err = ERR_NONE; size_t Pos = 0; size_t Left; while ((Left = (Size - Pos)) > 0) { if (Left > sizeof(Buf)) Left = sizeof(Buf); Err = Stream_Read(p,Buf,Left,&Left); if (!Left) break; WriteBlock(Block,Ofs+Pos,Buf,Left); Pos += Left; if (Left < sizeof(Buf)) break; } if (Readed) *Readed = Pos; return Err; #else return Stream_Read(p,(uint8_t*)Block->Ptr+Ofs,Size,Readed); #endif } static err_t DummyWait(void* UNUSED_PARAM(p),bool_t UNUSED_PARAM(Read),streamselect* UNUSED_PARAM(Select)) { return ERR_NOT_SUPPORTED; } static err_t DummyFlush(void* UNUSED_PARAM(p)) { return ERR_NOT_SUPPORTED; } static err_t DummyResetReadTimeout(void* UNUSED_PARAM(p)) { return ERR_NOT_SUPPORTED; } static err_t ProcessBlocking(void* p,bool_t State) { stream* Input; if (Node_GET(p,STREAMPROCESS_INPUT,&Input) == ERR_NONE && Input) return Stream_Blocking(Input,State); return DummyBlocking(p,State); } static err_t ProcessWait(void* p,bool_t Read,streamselect* Select) { stream* Input; if (Node_GET(p,STREAMPROCESS_INPUT,&Input) == ERR_NONE && Input) return Stream_Wait(Input,Read,Select); return ERR_NOT_SUPPORTED; } META_START(Streams_Class,MEDIA_CLASS) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_END_CONTINUE(NODE_CLASS) META_START_CONTINUE(STREAM_CLASS) META_CLASS(VMT_SIZE,sizeof(stream_vmt)) META_CLASS(SIZE,sizeof(stream)) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_PARAM(TYPE,STREAM_KIND,TYPE_FOURCC|TFLAG_RDONLY) META_PARAM(CUSTOM,STREAM_KIND,STREAM_KIND_LOCAL) META_PARAM(NAME,STREAM_URL,T("URL")) META_PARAM(TYPE,STREAM_URL,TYPE_STRING) META_PARAM(NAME,STREAM_LENGTH,T("Length")) META_PARAM(TYPE,STREAM_LENGTH,TYPE_FILEPOS) META_PARAM(NAME,STREAM_FLAGS,T("Flags")) META_PARAM(TYPE,STREAM_FLAGS,TYPE_INT) META_PARAM(NAME,STREAM_CONTENTTYPE,T("ContentType")) META_PARAM(TYPE,STREAM_CONTENTTYPE,TYPE_STRING|TFLAG_RDONLY) META_PARAM(NAME,STREAM_PRAGMA_SEND,T("PragmaSet")) META_PARAM(TYPE,STREAM_PRAGMA_SEND,TYPE_STRING|TFLAG_RDONLY) META_PARAM(NAME,STREAM_PRAGMA_GET,T("PragmaGet")) META_PARAM(TYPE,STREAM_PRAGMA_GET,TYPE_STRING|TFLAG_RDONLY) META_PARAM(NAME,STREAM_META,T("Meta")) META_PARAM(TYPE,STREAM_META,TYPE_META) META_PARAM(NAME,STREAM_SCOUTING,T("Scouting")) META_PARAM(TYPE,STREAM_SCOUTING,TYPE_BOOLEAN) META_PARAM(NAME,STREAM_TIMEOUT,T("TimeOut")) META_PARAM(TYPE,STREAM_TIMEOUT,TYPE_INT) // TODO: TYPE_SYSTICK META_PARAM(TYPE,STREAM_DATE,TYPE_DATETIME) META_PARAM(NAME,STREAM_FULL_URL,T("FullURL")) META_PARAM(TYPE,STREAM_FULL_URL,TYPE_STRING) META_PARAM(TYPE,STREAM_PLAYING,TYPE_BOOLEAN) META_PARAM(TYPE,STREAM_ENUM_BASE,TYPE_STRING) META_PARAM(TYPE,STREAM_TIME,TYPE_TICK) META_PARAM(TYPE,STREAM_NATIVE_HANDLER,TYPE_PTR|TFLAG_RDONLY) META_PARAM(TYPE,STREAM_CACHING,TYPE_BOOLEAN) META_PARAM(TYPE,STREAM_USERNAME,TYPE_STRING) META_DYNAMIC(TYPE_STRING,STREAM_USERNAME) META_PARAM(TYPE,STREAM_PASSWORD,TYPE_STRING) META_DYNAMIC(TYPE_STRING,STREAM_PASSWORD) META_PARAM(TYPE,STREAM_PROXY_USERNAME,TYPE_STRING) META_DYNAMIC(TYPE_STRING,STREAM_PROXY_USERNAME) META_PARAM(TYPE,STREAM_PROXY_PASSWORD,TYPE_STRING) META_DYNAMIC(TYPE_STRING,STREAM_PROXY_PASSWORD) META_PARAM(TYPE,STREAM_CACHE_CLASS,TYPE_FOURCC|TFLAG_RDONLY) META_VMT(TYPE_FUNC,stream_vmt,Open,DummyOpen) META_VMT(TYPE_FUNC,stream_vmt,Duplicate,DummyDuplicate) META_VMT(TYPE_FUNC,stream_vmt,Read,DummyRead) META_VMT(TYPE_FUNC,stream_vmt,ReadOneOrMore,DummyReadOneOrMore) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,DummyReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Write,DummyWrite) META_VMT(TYPE_FUNC,stream_vmt,Seek,DummySeek) META_VMT(TYPE_FUNC,stream_vmt,Blocking,DummyBlocking) META_VMT(TYPE_FUNC,stream_vmt,OpenDir,DummyOpenDir) META_VMT(TYPE_FUNC,stream_vmt,EnumDir,DummyEnumDir) META_VMT(TYPE_FUNC,stream_vmt,Wait,DummyWait) META_VMT(TYPE_FUNC,stream_vmt,Skip,DummySkip) META_VMT(TYPE_FUNC,stream_vmt,Flush,DummyFlush) META_VMT(TYPE_FUNC,stream_vmt,ResetReadTimeout,DummyResetReadTimeout) META_END_CONTINUE(MEDIA_CLASS) // STREAMPROCESS_CLASS can have NODE_EXTS META_START_CONTINUE(STREAMPROCESS_CLASS) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_PARAM(NAME,STREAMPROCESS_INPUT,T("Input")) META_PARAM(TYPE,STREAMPROCESS_INPUT,TYPE_NODE) META_PARAM(CLASS,STREAMPROCESS_INPUT,STREAM_CLASS) META_VMT(TYPE_FUNC,stream_vmt,Blocking,ProcessBlocking) META_VMT(TYPE_FUNC,stream_vmt,Wait,ProcessWait) META_END(STREAM_CLASS) stream* StreamOpen(anynode *AnyNode, const tchar_t* Path, int Flags) { stream* File = GetStream(AnyNode,Path,Flags); if (File) { err_t Err = Stream_Open(File,Path,Flags); if (Err != ERR_NONE && Err != ERR_NEED_MORE_DATA) { NodeDelete((node*)File); File = NULL; } else { stream* Buf; if ((Flags & SFLAG_BUFFERED) && (Buf = (stream*)NodeCreate(AnyNode,BUFSTREAM_CLASS)) != NULL) { Node_SET(Buf,BUFSTREAM_STREAM,&File); File = Buf; } } } return File; } void StreamClose(stream* File) { NodeDelete((node*)File); } bool_t StreamGenExts(anynode* AnyNode,array* Exts, fourcc_t ClassFilter, const tchar_t* TypeFilter) { fourcc_t* i; array List; ArrayInit(Exts); if (TypeFilter && !TypeFilter[0]) TypeFilter = NULL; NodeEnumClass(AnyNode,&List,ClassFilter); for (i=ARRAYBEGIN(List,fourcc_t);i!=ARRAYEND(List,fourcc_t);++i) { const tchar_t* s = NodeStr2(AnyNode,*i,NODE_EXTS); while (s && s[0]) { size_t n; for (n=0;s[n] && s[n]!=';' && s[n]!=':';++n) {} if (!TypeFilter || (s[n]==':' && tcschr(TypeFilter,s[n+1])!=NULL)) { while (s[n] && s[n]!=';') ++n; if (n) { if (!ARRAYEMPTY(*Exts)) ArrayAppend(Exts,T(";"),sizeof(tchar_t),64); ArrayAppend(Exts,s,n*sizeof(tchar_t),64); } } s = tcschr(s,';'); if (s) ++s; } } ArrayClear(&List); if (!ARRAYEMPTY(*Exts) && !ArrayAppend(Exts,T("\0"),sizeof(tchar_t),64)) ArrayClear(Exts); return !ARRAYEMPTY(*Exts); } char StreamExtType(anynode* AnyNode, fourcc_t ClassFilter, const tchar_t *Ext) { char Result = FTYPE_UNDEFINED; tchar_t *s; size_t i; array List; StreamGenExts(AnyNode,&List,ClassFilter,NULL); for (s=ARRAYBEGIN(List,tchar_t);s;) { for (i=0;s[i] && s[i]==Ext[i];i++) {} if (!Ext[i] && s[i] == ':') { Result = (char)s[i+1]; break; } s = tcschr(s,';'); if (s) ++s; } ArrayClear(&List); return Result; } stream* GetStream(anynode *AnyNode, const tchar_t* URL, int Flags) { tchar_t Protocol[MAXPROTOCOL]; stream* Stream = NULL; fourcc_t FourCC; GetProtocol(URL,Protocol,TSIZEOF(Protocol),NULL); FourCC = NodeEnumClassStr(AnyNode,NULL,STREAM_CLASS,NODE_PROTOCOL,Protocol); #if defined(CONFIG_STREAM_CACHE) if ((Flags & (SFLAG_NO_CACHING|SFLAG_WRONLY|SFLAG_CREATE))==0) Stream = (stream*)NodeCreate(AnyNode,NodeClass_Meta(NodeContext_FindClass(AnyNode,FourCC),STREAM_CACHE_CLASS,META_PARAM_CUSTOM)); #endif if (!Stream) Stream = (stream*)NodeCreate(AnyNode,FourCC); if (Stream && (Flags & SFLAG_NON_BLOCKING)) Stream_Blocking(Stream,0); if (!Stream && !(Flags & SFLAG_SILENT)) { tcsupr(Protocol); NodeReportError(AnyNode,NULL,ERR_ID,ERR_PROTO_NOT_FOUND,Protocol); } #if defined(CONFIG_DEBUGCHECKS) if (Stream) tcscpy_s(Stream->URL,TSIZEOF(Stream->URL),URL); #endif return Stream; } int StreamProtocolPriority(anynode *AnyNode, const tchar_t* URL) { tchar_t Protocol[MAXPROTOCOL]; GetProtocol(URL,Protocol,TSIZEOF(Protocol),NULL); if (tcsicmp(Protocol,T("file"))==0) // override for local files return PRI_MAXIMUM; return NodeClass_Priority(NodeContext_FindClass(AnyNode,NodeEnumClassStr(AnyNode,NULL,STREAM_CLASS,NODE_PROTOCOL,Protocol))); } bcmatroska2-5.3.101/corec/corec/helpers/file/streams.h000066400000000000000000000201101462133141200224560ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __STREAM_H #define __STREAM_H #include "corec/node/node.h" #define FTYPE_DIR 'D' #define FTYPE_UNDEFINED 'u' #define MEDIA_CLASS FOURCC('F','M','T','M') // anything with file extension #define STREAM_CLASS FOURCC('S','T','R','M') #define STREAM_URL 0x91 // tchar_t* #define STREAM_LENGTH 0x92 // filepos_t #define STREAM_FLAGS 0x93 // int #define STREAM_CONTENTTYPE 0x95 // tchar_t* #define STREAM_META 0x96 // metanotify #define STREAM_PRAGMA_SEND 0x97 // tchar_t* #define STREAM_PRAGMA_GET 0x98 // tchar_t* #define STREAM_ENUM_BASE 0x9A // tchar_t* #define STREAM_PLAYING 0x9B // bool_t #define STREAM_TIME 0xA0 // tick_t #define STREAM_SCOUTING 0xAA // bool_t #define STREAM_NO_PAUSE 0xAB // TODO: find a better solution... #define STREAM_KIND 0xAD // fourcc_t #define STREAM_ISTTY 0xAF // bool_t #define STREAM_FULL_URL 0x99 // tchar_t* #define STREAM_TIMEOUT 0x94 // systick_t #define STREAM_NATIVE_HANDLER 0x8F // void* #define STREAM_DATE 0x8C // datetime_t #define STREAM_USERNAME 0x88 // tchar_t* #define STREAM_PASSWORD 0x89 // tchar_t* #define STREAM_PROXY_USERNAME 0xC0 // tchar_t* #define STREAM_PROXY_PASSWORD 0xC1 // tchar_t* #define STREAM_CACHE_CLASS 0xB4 // fourcc_t #define STREAM_CACHING 0xB6 // bool_t #define STREAM_KIND_LOCAL 0 #define STREAM_KIND_NETWORK 1 #define STREAM_KIND_LIVE_FEED 2 #define SFLAG_RDONLY 0x1 #define SFLAG_WRONLY 0x2 #define SFLAG_CREATE 0x4 #define SFLAG_SILENT 0x8 #define SFLAG_BUFFERED 0x10 // used only by StreamOpen helper function #define SFLAG_REOPEN 0x20 // private inside stream #define SFLAG_NO_PRAGMA 0x40 #define SFLAG_NO_PROXY 0x80 #define SFLAG_NO_DELAY 0x100 #define SFLAG_NO_RETRY 0x200 #define SFLAG_HIDDEN 0x400 #define SFLAG_NO_CACHING 0x800 #define SFLAG_NON_BLOCKING 0x1000 // used only by StreamOpen helper function #define SFLAG_CREATE_BLOCKING 0x2000 #define SFLAG_FORCE_CACHING 0x4000 #define SFLAG_LONGTERM_CACHING 0x8000 #define SFLAG_RECONNECT 0x10000 #define MAX_NETWORK_PACKET 2048 #ifndef SEEK_SET #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 #endif #ifndef EOF #define EOF (-1) #endif #define DIR_TIMEOUT 2 // 2 s typedef struct stream { node Base; tchar_t URL[MAXPATH]; } stream; typedef struct memstream { stream Base; filepos_t VirtualOffset; const uint8_t* Ptr; size_t Pos; size_t Size; } memstream; #define STDIN_ID FOURCC('S','T','D','I') #define STDOUT_ID FOURCC('S','T','D','O') #define STDERR_ID FOURCC('S','T','D','E') typedef struct streamdir { tchar_t FileName[MAXPATH]; tchar_t DisplayName[MAXPATH]; filepos_t Size; int Type; // from Exts, FTYPE_DIR for directory datetime_t ModifiedDate; } streamdir; typedef struct streamselect streamselect; struct streamselect { err_t (*Func)(streamselect*); #ifdef TARGET_PALMOS int LibRef; #endif int Max; void* Rd; void* Wr; void* Er; tick_t Timeout; // TODO: change to systick_t stream* Selected[64]; }; typedef struct stream_vmt { node_vmt Base; err_t (*Open)(thisnode,const tchar_t* URL, int Flags); stream* (*Duplicate)(thisnode,int Flags); err_t (*Read)(thisnode,void* Data,size_t Size,size_t* Readed); err_t (*ReadOneOrMore)(thisnode,void* Data,size_t Size,size_t* Readed); err_t (*ReadBlock)(thisnode,block* Block,size_t Ofs,size_t Size,size_t* Readed); err_t (*Write)(thisnode,const void* Data,size_t Size,size_t* Written); filepos_t (*Seek)(thisnode,filepos_t Pos,int SeekMode); err_t (*OpenDir)(thisnode,const tchar_t* URL, int Flags); err_t (*EnumDir)(thisnode,const tchar_t* Exts,bool_t ExtFilter,streamdir* Item); err_t (*Blocking)(thisnode,bool_t Blocking); err_t (*Wait)(thisnode,bool_t Read, streamselect* Select); err_t (*Skip)(thisnode,intptr_t* Skip); err_t (*Flush)(thisnode); err_t (*ResetReadTimeout)(thisnode,int Secs); } stream_vmt; #define Stream_Open(p,a,b) VMT_FUNC(p,stream_vmt)->Open(p,a,b) #define Stream_Duplicate(p,a) VMT_FUNC(p,stream_vmt)->Duplicate(p,a) #define Stream_Read(p,a,b,c) VMT_FUNC(p,stream_vmt)->Read(p,a,b,c) #define Stream_ReadOneOrMore(p,a,b,c) VMT_FUNC(p,stream_vmt)->ReadOneOrMore(p,a,b,c) #define Stream_ReadBlock(p,a,b,c,d) VMT_FUNC(p,stream_vmt)->ReadBlock(p,a,b,c,d) #define Stream_Write(p,a,b,c) VMT_FUNC(p,stream_vmt)->Write(p,a,b,c) #define Stream_Seek(p,a,b) VMT_FUNC(p,stream_vmt)->Seek(p,a,b) #define Stream_OpenDir(p,a,b) VMT_FUNC(p,stream_vmt)->OpenDir(p,a,b) #define Stream_EnumDir(p,a,b,c) VMT_FUNC(p,stream_vmt)->EnumDir(p,a,b,c) #define Stream_Blocking(p,a) VMT_FUNC(p,stream_vmt)->Blocking(p,a) #define Stream_Wait(p,a,b) VMT_FUNC(p,stream_vmt)->Wait(p,a,b) #define Stream_Skip(p,a) VMT_FUNC(p,stream_vmt)->Skip(p,a) #define Stream_Flush(p) VMT_FUNC(p,stream_vmt)->Flush(p) #define Stream_ResetReadTimeout(p,a) VMT_FUNC(p,stream_vmt)->ResetReadTimeout(p,a) //-------------------------------------------------------------------------- #define STREAMPROCESS_CLASS FOURCC('S','T','R','P') #define STREAMPROCESS_INPUT 0xB0 #define STREAMPROCESS_DATAFEED 0xB1 //--------------------------------------------------------------------------- #define MEMSTREAM_CLASS FOURCC('M','E','M','S') #define MEMSTREAM_DATA 0x100 #define MEMSTREAM_PTR 0x101 #define MEMSTREAM_OFFSET 0x102 //--------------------------------------------------------------------------- #define BUFSTREAM_CLASS FOURCC('B','U','F','S') #define BUFSTREAM_STREAM 0x100 //--------------------------------------------------------------------------- #define RESOURCEDATA_ID FOURCC('R','E','S','F') #define RESOURCEDATA_SIZE 0x100 #define RESOURCEDATA_PTR 0x101 //--------------------------------------------------------------------------- FILE_DLL stream* GetStream(anynode*, const tchar_t* URL, int Flags); FILE_DLL stream* StreamOpen(anynode*, const tchar_t* URL, int Flags); FILE_DLL void StreamClose(stream*); FILE_DLL bool_t StreamGenExts(anynode*,array* Exts, fourcc_t ClassFilter, const tchar_t* TypeFilter); FILE_DLL char StreamExtType(anynode*, fourcc_t ClassFilter, const tchar_t *Ext); FILE_DLL int StreamProtocolPriority(anynode*, const tchar_t* URL); #endif bcmatroska2-5.3.101/corec/corec/helpers/file/tools.c000066400000000000000000000460311462133141200221450ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "file.h" bool_t SetFileExt(tchar_t* URL, size_t URLLen, const tchar_t* Ext) { tchar_t *p,*q,*p2; bool_t HasHost; p = (tchar_t*) GetProtocol(URL,NULL,0,&HasHost); q = p; p = tcsrchr(q,'\\'); p2 = tcsrchr(q,'/'); if (!p || (p2 && p2>p)) p=p2; if (p) q = p+1; else if (HasHost) // only hostname return 0; if (!q[0]) // no filename at all? return 0; p = tcsrchr(q,'.'); if (p) *p = 0; tcscat_s(URL,URLLen,T(".")); tcscat_s(URL,URLLen,Ext); return 1; } void AddPathDelimiter(tchar_t* Path,size_t PathLen) { size_t n = tcslen(Path); #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) bool_t HasProtocol = GetProtocol(Path,NULL,0,NULL)==Path; if (!n || (n>0 && (HasProtocol || Path[n-1] != '/') && (!HasProtocol || Path[n-1] != '\\'))) { if (HasProtocol) tcscat_s(Path,PathLen,T("\\")); else tcscat_s(Path,PathLen,T("/")); } #elif defined(TARGET_PS2SDK) if (!n || (n>0 && Path[n-1] != '/' && Path[n-1] != '\\' && Path[n-1] != ':')) tcscat_s(Path,PathLen,T("/")); #else if (!n || (n>0 && Path[n-1] != '/')) tcscat_s(Path,PathLen,T("/")); #endif } void RemovePathDelimiter(tchar_t* Path) { size_t n = tcslen(Path); const tchar_t* s = GetProtocol(Path,NULL,0,NULL); #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) bool_t HasProtocol = s==Path; if (s[0] && n>0 && ((HasProtocol && Path[n-1] == '\\') || (!HasProtocol && Path[n-1] == '/'))) #else if (s[0] && n>0 && Path[n-1] == '/' && n > 1) #endif Path[n-1] = 0; } const tchar_t* GetProtocol(const tchar_t* URL, tchar_t* Proto, int ProtoLen, bool_t* HasHost) { const tchar_t* s = tcschr(URL,':'); if (s && s[1] == '/' && s[2] == '/') { while (URLp)) p=p2; } if (!p) p = Addr+tcslen(Addr); p2 = tcschr(Addr,'@'); if (!p2 || p2>p) p2 = p; else Result = 1; if (Peer) tcsncpy_s(Peer,PeerLen,URL,p2-URL); if (Local) { if (p2p)) p=p2; if (!p) p = URL+tcslen(URL); p2 = tcschr(URL,':'); if (p2 && p20) *Host = 0; } if (Path) { if (URL[0]) { tchar_t* p; tcscpy_s(Path,PathLen,URL); for (p=Path;*p;++p) if (*p == '\\') *p = '/'; } else tcscpy_s(Path,PathLen,T("/")); } } void SplitPath(const tchar_t* URL, tchar_t* Dir, int DirLen, tchar_t* Name, int NameLen, tchar_t* Ext, int ExtLen) { const tchar_t *p,*p2,*p3; bool_t HasHost; tchar_t LocalURL[MAXPATH]; tchar_t Protocol[MAXPATH]; // mime p = GetProtocol(URL,Protocol,TSIZEOF(Protocol),&HasHost); // dir p2 = tcsrchr(p,'\\'); p3 = tcsrchr(p,'/'); if (!p2 || (p3 && p3>p2)) p2 = p3; #ifdef TARGET_PS2SDK // "host:test.elf" -> "host:" // "host:/test.elf" -> "host:/" (keeping end delimiter) if ((p2 && p2>p && p2[-1]==':') || (!p2 && (p2 = tcschr(p,':'))!=NULL)) { if (Dir) tcsncpy_s(Dir,DirLen,URL,p2-URL+1); URL = p2+1; } else #endif if (p2) { if (Dir) tcsncpy_s(Dir,DirLen,URL,p2-URL); URL = p2+1; } else if (HasHost) // no filename, only host { if (Dir) tcscpy_s(Dir,DirLen,URL); URL += tcslen(URL); } else // no directory { if (Dir) tcsncpy_s(Dir,DirLen,URL,p-URL); URL = p; } // name if (tcsicmp(Protocol,T("http"))==0 && tcsrchr(URL,T('#'))) { tchar_t *NulChar; tcscpy_s(LocalURL,TSIZEOF(LocalURL),URL); URL = LocalURL; NulChar = tcsrchr(LocalURL,T('#')); *NulChar = 0; } if (Name && Name == Ext) tcscpy_s(Name,NameLen,URL); else { p = tcsrchr(URL,'.'); if (p) { if (Name) tcsncpy_s(Name,NameLen,URL,p-URL); if (Ext) { if (p[1]) ++p; // remove '.', but only if there is a real extension tcscpy_s(Ext,ExtLen,p); } } else { if (Name) tcscpy_s(Name,NameLen,URL); if (Ext) Ext[0] = 0; } } } void RelPath(tchar_t* Rel, int RelLen, const tchar_t* Path, const tchar_t* Base) { size_t n; bool_t HasHost; const tchar_t* p = GetProtocol(Base,NULL,0,&HasHost); if (p != Base) { if (HasHost) { // include host name too tchar_t *a,*b; a = tcschr(p,'\\'); b = tcschr(p,'/'); if (!a || (b && b0 && n0 && na)) a=b; #ifdef TARGET_PS2SDK if (!a && (a = tcschr(c,':'))!=NULL) if (a[1]==0) a = NULL; #endif if (!a) { if (tcsicmp(Mime, T("smb")) == 0) { *c = 0; tcscpy_s(Last, LastLen, Path); return 1; } if (HasHost && tcsicmp(Mime, T("upnp"))!=0) return 0; a=c; if (!a[0]) // only mime left a=c=Path; } else ++a; if (Last) tcscpy_s(Last,LastLen,a); if (a==c) *a = 0; #ifdef TARGET_PS2SDK if (a>c && a[-1]==':') *a = 0; #endif while (--a>=c && (*a=='\\' || *a=='/')) *a = 0; return 1; } void AbsPath(tchar_t* Abs, int AbsLen, const tchar_t* Path, const tchar_t* Base) { if (Base && GetProtocol(Base,NULL,0,NULL)!=Base && (Path[0] == '/' || Path[0] == '\\') && (Path[1] != '/' && Path[1] != '\\')) { tchar_t* s; bool_t HasHost; tcscpy_s(Abs,AbsLen,Base); s = (tchar_t*)GetProtocol(Abs,NULL,0,&HasHost); if (!HasHost) { // keep "mime://" from Base ++Path; *s = 0; } else { // keep "mime://host" from Base tchar_t *a,*b; a = tcschr(s,'\\'); b = tcschr(s,'/'); if (!a || (b && b=AbsLen) { n=AbsLen-1; Abs[n-1]=0; } memmove(Abs+1,Abs,n*sizeof(tchar_t)); Abs[0]='\\'; } #endif #endif } } void ReduceLocalPath(tchar_t* Abs,size_t UNUSED_PARAM(AbsLen)) { tchar_t *Folder,*Back; Folder = tcsstr(Abs,T("://")); // skip the protocol if (Folder) Abs = Folder+3; #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) Back = tcsstr(Abs,T("\\\\")); #else Back = tcsstr(Abs,T("//")); #endif while (Back) { memmove(Back,Back+1,tcsbytes(Back+1)); #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) Back = tcsstr(Abs,T("\\\\")); #else Back = tcsstr(Abs,T("//")); #endif } #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) Back = tcsstr(Abs,T("\\..")); #else Back = tcsstr(Abs,T("/..")); #endif while (Back) { Folder = Back; while (--Folder >= Abs) { #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) if (*Folder == T('\\')) #else if (*Folder == T('/')) #endif { memmove(Folder,Back+3,tcsbytes(Back+3)); break; } } #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) Back = tcsstr(Abs,T("\\..")); #else Back = tcsstr(Abs,T("/..")); #endif } } int CheckExts(const tchar_t* URL, const tchar_t* Exts) { tchar_t Ext[MAXPATH]; tchar_t* Tail; intptr_t ExtLen; SplitPath(URL,NULL,0,NULL,0,Ext,TSIZEOF(Ext)); Tail = tcschr(Ext,'?'); if (Tail) *Tail = 0; ExtLen = tcslen(Ext); while (Exts) { const tchar_t* p = tcschr(Exts,':'); if (p && (ExtLen == p-Exts) && tcsnicmp(Ext,Exts,p-Exts)==0) return p[1]; // return type char Exts = tcschr(Exts,';'); if (Exts) ++Exts; } return 0; } int ScaleRound(int_fast32_t v,int_fast32_t Num,int_fast32_t Den) { int64_t i; if (!Den) return 0; i = (int64_t)v * Num; if (i<0) i-=Den/2; else i+=Den/2; i/=Den; return (int)i; } void StreamLoginInfo(node* p, tchar_t* URL, bool_t Proxy) { tchar_t LoginPass[MAXPATH]; if (SplitAddr(URL,LoginPass,TSIZEOF(LoginPass),NULL,0)) { // extract the login:pass from the URL as there seems to be one tchar_t *s,*t; if (!Proxy) { Node_SetData(p,STREAM_FULL_URL,TYPE_STRING,URL); t = (tchar_t*)GetProtocol(URL,NULL,0,NULL); s = tcschr(t,T('@')); assert(s!=NULL); ++s; memmove(t, s, tcsbytes(s)); } t = (tchar_t*)GetProtocol(LoginPass,NULL,0,NULL); s=tcschr(t,T(':')); if (s) *s++ = 0; if (Proxy) { Node_SetData(p,STREAM_PROXY_PASSWORD,TYPE_STRING,s); Node_SetData(p,STREAM_PROXY_USERNAME,TYPE_STRING,t); } else { Node_SetData(p,STREAM_PASSWORD,TYPE_STRING,s); Node_SetData(p,STREAM_USERNAME,TYPE_STRING,t); } } else Node_RemoveData(p,STREAM_FULL_URL,TYPE_STRING); } tchar_t* FirstSepar(const tchar_t *Path) { tchar_t *s1, *s2; s1 = tcschr(Path, '\\'); s2 = tcschr(Path, '/'); if (!s1 || (s2 && s2 < s1)) s1 = s2; return s1; } void SplitURLLogin(const tchar_t *URL, tchar_t *UserName, size_t UserNameLen, tchar_t *Password, size_t PasswordLen, tchar_t *URL2, size_t URL2Len) { tchar_t LoginPass[MAXPATH]; if (SplitAddr(URL, LoginPass, TSIZEOF(LoginPass), NULL, 0)) { tchar_t *s,*t; if (URL2) { tcscpy_s(URL2, URL2Len, URL); t = (tchar_t*)GetProtocol(URL2,NULL,0,NULL); s = tcschr(t,T('@')); assert(s!=NULL); ++s; memmove(t, s, tcsbytes(s)); } t = (tchar_t*)GetProtocol(LoginPass,NULL,0,NULL); s=tcschr(t,T(':')); if (s) { *s++ = 0; // missing: resolving escape sequences if (Password) tcscpy_s(Password, PasswordLen, s); } else tcsclr_s(Password, PasswordLen); if (UserName) tcscpy_s(UserName, UserNameLen, t); } else { tcsclr_s(UserName, UserNameLen); tcsclr_s(Password, PasswordLen); if (URL2) tcscpy_s(URL2, URL2Len, URL); } } void SplitShare(const tchar_t *Path, tchar_t *Share, size_t ShareLen, tchar_t *Path2, size_t Path2Len) { tchar_t *s1; s1 = FirstSepar(Path); if (s1 == Path) { Path++; s1 = FirstSepar(Path); } if (s1) { if (Share) tcsncpy_s(Share, ShareLen, Path, s1 - Path); if (Path2) tcscpy_s(Path2, Path2Len, s1); } else { if (Share) tcscpy_s(Share, ShareLen, Path); tcsclr_s(Path2, Path2Len); } } tchar_t *MergeURL(tchar_t *URL, size_t URLLen, const tchar_t *Protocol, const tchar_t *Host, int Port, const tchar_t *Path) { *URL = 0; if (Protocol && *Protocol) stcatprintf_s(URL, URLLen, T("%s://"), Protocol); if (Host && *Host) { stcatprintf_s(URL, URLLen, T("%s"), Host); if (Port > 0) stcatprintf_s(URL, URLLen, T(":%d"), Port); } if (Path && *Path) { if (FirstSepar(Path) == Path) stcatprintf_s(URL, URLLen, T("%s"), Path); else stcatprintf_s(URL, URLLen, T("/%s"), Path); } return URL; } tchar_t *GetIP(tchar_t *sIP, size_t IPLen, long IP) { stprintf_s(sIP, IPLen, T("%d.%d.%d.%d"), (IP >> 24) & 0xFF, (IP >> 16) & 0xFF, (IP >> 8) & 0xFF, IP & 0xFF); return sIP; } void SplitURLParams(const tchar_t* URL, tchar_t* URL2, int URL2Len, tchar_t* Params, int ParamsLen) { tchar_t* p; p = tcschr(URL, '?'); if (p) { if (URL2) tcsncpy_s(URL2, URL2Len, URL, p-URL); if (Params) tcscpy_s(Params, ParamsLen, p); } else { if (URL2) tcscpy_s(URL2, URL2Len, URL); if (Params) *Params = 0; } } tchar_t *AddCacheURL(tchar_t* Out, size_t Len, const tchar_t *In) { CheckRemoveCacheURL(&In); if (!In || !*In) { if (Out && Len) *Out = 0; } else stprintf_s(Out, Len, T("cache://%s"), In); return Out; } bool_t CheckRemoveCacheURL(const tchar_t** URL) { if (*URL && !tcsncmp(*URL, T("cache://"), 8)) { *URL += 8; return 1; } return 0; } bool_t RemoveURLParam(tchar_t* URL, const tchar_t* Param) { size_t l; tchar_t *s1, *s2; l = tcslen(Param); if (!l) return 0; s1 = tcschr(URL, '?'); if (!s1) s1 = tcschr(URL, ';'); while (s1) { s2 = tcschr(s1+1, '&'); if (!s2) s2 = tcschr(s1+1, ';'); if (tcsncmp(s1+1, Param, l) == 0 && s1[l+1] == '=') { if (s2) memcpy(s1+1, s2+1, (tcslen(s2)+1)*sizeof(tchar_t)); else *s1 = 0; return 1; } s1 = s2; } return 0; } err_t FileStat(nodecontext* p, const tchar_t* Path, streamdir* Item) { err_t Result; stream *s; tchar_t Dir[MAXPATH]; tchar_t NameExt[MAXPATH]; tchar_t Ext[MAXPATH+2]; size_t l; SplitPath(Path, Dir, MAXPATH, NameExt, MAXPATH, Ext, MAXPATH); if (*Ext) { if (!tcschr(NameExt,T('.'))) SetFileExt(NameExt, MAXPATH, Ext); else { tcscat_s(NameExt,TSIZEOF(NameExt),T(".")); tcscat_s(NameExt,TSIZEOF(NameExt),Ext); } } l = tcslen(Ext); Ext[l] = ':'; Ext[l + 1] = '1'; Ext[l + 2] = '\0'; s = GetStream(p, Dir, SFLAG_SILENT); if (!s) return ERR_FILE_NOT_FOUND; Result = Stream_OpenDir(s, Dir, SFLAG_SILENT); if (Result == ERR_NONE) { do { Result = Stream_EnumDir(s, Ext, 1, Item); if (Result == ERR_NONE && tcscmp(Item->FileName, NameExt) == 0) break; } while (Result == ERR_NONE); } NodeDelete((node *) s); if (Result != ERR_NONE) Result = ERR_FILE_NOT_FOUND; return Result; } bcmatroska2-5.3.101/corec/corec/helpers/helpers.proj000066400000000000000000000000241462133141200222500ustar00rootroot00000000000000#include "*/*.proj" bcmatroska2-5.3.101/corec/corec/helpers/md5/000077500000000000000000000000001462133141200204035ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/md5/md5.c000066400000000000000000000227411462133141200212420ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "md5.h" /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ #ifndef IS_BIG_ENDIAN #define byteReverse(buf, len) /* Nothing */ #else void byteReverse(uint32_t* buf, size_t longs) { uint32_t* bufend = buf+longs; for (;buf!=bufend;buf+=4) { buf[0] = SWAP32(buf[0]); buf[1] = SWAP32(buf[1]); buf[2] = SWAP32(buf[2]); buf[3] = SWAP32(buf[3]); } } #endif /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(md5_ctx* ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } static void MD5Transform(uint32_t buf[4], uint32_t in[16]); /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(md5_ctx* ctx, const uint8_t* buf, size_t len) { uint32_t t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += (uint32_t)(len >> 29); t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse((uint32_t *) ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse((uint32_t *) ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(md5_ctx* ctx, uint8_t digest[16]) { size_t count; uint8_t *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); byteReverse((uint32_t *) ctx->in, 16); MD5Transform(ctx->buf, (uint32_t *) ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count - 8); } byteReverse((uint32_t *) ctx->in, 16); /* Append length in bits and transform */ ((uint32_t *) ctx->in)[14] = ctx->bits[0]; ((uint32_t *) ctx->in)[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32_t *) ctx->in); byteReverse(ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ } /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ static void MD5Transform(uint32_t buf[4], uint32_t in[16]) { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } bcmatroska2-5.3.101/corec/corec/helpers/md5/md5.h000066400000000000000000000043011462133141200212370ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __MD5_H #define __MD5_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #if defined(MD5_EXPORTS) #define MD5_DLL DLLEXPORT #elif defined(MD5_IMPORTS) #define MD5_DLL DLLIMPORT #else #define MD5_DLL #endif typedef struct md5_ctx { uint32_t buf[4]; uint32_t bits[2]; uint8_t in[64]; } md5_ctx; MD5_DLL void MD5Init(md5_ctx* ctx); MD5_DLL void MD5Update(md5_ctx* ctx, const uint8_t* buf, size_t len); MD5_DLL void MD5Final(md5_ctx* ctx, uint8_t digest[16]); #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/helpers/md5/md5.proj000066400000000000000000000000701462133141200217610ustar00rootroot00000000000000GROUP md5 { USE corec SOURCE md5.c HEADER md5.h } bcmatroska2-5.3.101/corec/corec/helpers/parser/000077500000000000000000000000001462133141200212125ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/parser/buffer.c000066400000000000000000000064541462133141200226400ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" static size_t SizeAlign(size_t Total, size_t Align) { if (!Align) { for (Align=16;Align<16384;Align<<=1) if (Align*8 > Total) break; } --Align; return (Total + Align) & ~Align; } void BufferClear(buffer* p) { free(p->Begin); p->End = NULL; p->Begin = NULL; p->Read = NULL; p->Write = NULL; } bool_t BufferAlloc(buffer* p, size_t Total, size_t Align) { size_t Read = p->Read - p->Begin; size_t Write = p->Write - p->Begin; uint8_t* Begin; Total = SizeAlign(Total + SAFETAIL,Align); Begin = (uint8_t*)realloc(p->Begin,Total); if (!Begin) return 0; p->Begin = Begin; p->Read = Begin + Read; p->Write = Begin + Write; p->End = Begin + Total - SAFETAIL; return 1; } void BufferDrop(buffer* p) { p->Write = p->Begin; p->Read = p->Begin; } uint8_t* BufferWrite(buffer* p, const void* Ptr, size_t Length, size_t Align) { uint8_t* Write = p->Write + Length; if (Write > p->End && !BufferAlloc(p,Write-p->Begin,Align)) return 0; Write = p->Write; p->Write = Write+Length; if (Ptr) memcpy(Write,Ptr,Length); return Write; } const uint8_t* BufferRead(buffer* p, size_t Length) { uint8_t* Read = p->Read; if (p->Write < Read + Length) return NULL; p->Read = Read + Length; return Read; } void BufferPack(buffer* p, size_t Length) { uint8_t* Read = p->Read + Length; if (p->Write > Read) { if (Read != p->Begin) { // move end part to the beginning memmove(p->Begin,Read,p->Write - Read); p->Write -= Read - p->Begin; } } else p->Write = p->Begin; p->Read = p->Begin; } bcmatroska2-5.3.101/corec/corec/helpers/parser/buffer.h000066400000000000000000000042261462133141200226400ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __BUFFER_H #define __BUFFER_H typedef struct buffer { uint8_t* Begin; uint8_t* Write; uint8_t* Read; uint8_t* End; } buffer; NODE_DLL void BufferClear(buffer*); NODE_DLL void BufferDrop(buffer*); NODE_DLL bool_t BufferAlloc(buffer* p, size_t Size, size_t Align); NODE_DLL uint8_t* BufferWrite(buffer*, const void* Ptr, size_t Length, size_t Align); NODE_DLL const uint8_t* BufferRead(buffer*, size_t Length); NODE_DLL void BufferPack(buffer*, size_t Readed); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/dataheap.c000066400000000000000000000250671462133141200231370ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" // Don't use dataheap in win32 debug mode. It's easier to track down memory corruptions. #if defined(NDEBUG) || !defined(TARGET_WIN32) #define DATAHEAP_LIMIT 72 #else #define DATAHEAP_LIMIT 1 #endif #ifdef MIPS64 typedef uint64_t dataunit; #else typedef uintptr_t dataunit; #endif #define BUFFER_SIZE 1024 //in dataunit #define DATAALIGN(n) (((n)+sizeof(dataunit)-1)/sizeof(dataunit)) static INLINE size_t DataSize(dataunit* i) { return (size_t)*i & 65535; } static INLINE size_t DataNext(dataunit* i) { return (size_t)*i >> 16; } struct dataheap_free { dataheap_free* Next; }; typedef struct dataheap_block { dataunit* Data; uint16_t Count; uint16_t MaxSize; } dataheap_block; #if 0 static void DataHeap_Check(dataheap* p) { dataheap_block* i; size_t MaxSize=0; for (i=ARRAYBEGIN(p->Buffer,dataheap_block);i!=ARRAYEND(p->Buffer,dataheap_block);++i) { dataunit* a = i->Data; dataunit* b = i->Data+BUFFER_SIZE-1; size_t Count=0; assert(i->MaxSize>=MaxSize); assert(!DataSize(a)); assert(*b==0); while (a!=b) { if (i->MaxSize) { assert(DataSize(a)<=i->MaxSize); if (DataSize(a)==i->MaxSize) ++Count; } assert(DataSize(a)<=DataNext(a)); assert(a+DataNext(a)<=b); a += DataNext(a); } MaxSize = i->MaxSize; assert(!i->MaxSize || i->Count==Count); } } #else #define DataHeap_Check(p) {} #endif static void DataHeap_Write(dataheap* UNUSED_PARAM(p),void* Ptr,const void* Src,size_t Pos,size_t Size) { memcpy((uint8_t*)Ptr+Pos,Src,Size); } static void* DataHeap_Alloc(dataheap* p, size_t Size, int UNUSED_PARAM(Flags)) { dataheap_block Block; dataheap_block* i; dataunit* curr; dataunit* prev; size_t n,Count,MaxSize; if (!Size) return NULL; Size = DATAALIGN(Size); if (Size>=DATAHEAP_LIMIT) return MemHeap_Alloc(p->Heap,Size*sizeof(dataunit),0); LockEnter(p->Lock); if (Size==DATAALIGN(3*sizeof(void*))) { dataheap_free* i; if (!p->Free3) { Block.Count = 0; Block.MaxSize = 0; Block.Data = MemHeap_Alloc(p->Heap,BUFFER_SIZE*sizeof(dataunit),0); if (!Block.Data) goto failed; if (!ArrayInsert(&p->Buffer,0,&Block,sizeof(Block),256)) goto failed_array; Block.Data[0] = (BUFFER_SIZE-1)<<16; // head delimiter Block.Data[BUFFER_SIZE-1] = 0; // tail delimiter for (n=1;nNext = p->Free3; p->Free3 = i; } } i=p->Free3; p->Free3 = i->Next; LockLeave(p->Lock); return i; } DataHeap_Check(p); if (!ARRAYEMPTY(p->Buffer)) { for (;;) { i=ARRAYEND(p->Buffer,dataheap_block)-1; if (i->MaxSizeCount?i->MaxSize:0; Count=0; curr = i->Data; do { prev = curr; curr += DataNext(curr); if ((n = DataSize(curr)) >= Size) { if (n==i->MaxSize) { assert(i->Count>0); i->Count = (uint16_t)(i->Count-1); } if (n == Size) *prev += DataNext(curr) << 16; else { *prev += Size << 16; curr[Size] = (n-Size) | ((DataNext(curr)-Size)<<16); } LockLeave(p->Lock); return curr; } if (MaxSize<=n) { if (MaxSize==n) ++Count; else { MaxSize=n; Count=1; } } } while (n); assert(i->Count==0); i->Count = (uint16_t)Count; i->MaxSize = (uint16_t)MaxSize; while (i!=ARRAYBEGIN(p->Buffer,dataheap_block) && i[-1].MaxSize > i->MaxSize) { SWAPVAL(dataheap_block,i[-1],i[0]); --i; } } } Block.Data = MemHeap_Alloc(p->Heap,BUFFER_SIZE*sizeof(dataunit),0); if (!Block.Data) goto failed; if (!ArrayAppend(&p->Buffer,&Block,sizeof(Block),256)) goto failed_array; MaxSize = BUFFER_SIZE-2-Size; i = ARRAYEND(p->Buffer,dataheap_block)-1; i->Count = 1; i->MaxSize = (uint16_t)MaxSize; curr = i->Data; curr[0] = (1+Size)<<16; // head delimiter curr[1+Size] = MaxSize + (MaxSize<<16); curr[BUFFER_SIZE-1] = 0; // tail delimiter while (i!=ARRAYBEGIN(p->Buffer,dataheap_block) && i[-1].MaxSize > i->MaxSize) { SWAPVAL(dataheap_block,i[-1],i[0]); --i; } LockLeave(p->Lock); return curr+1; failed_array: MemHeap_Free(p->Heap,Block.Data,BUFFER_SIZE*sizeof(dataunit)); failed: LockLeave(p->Lock); return NULL; } static void DataHeap_Free(dataheap* p, void* Ptr, size_t Size) { if (Ptr && Size) { dataunit *curr = (dataunit*)Ptr; dataunit *next; dataunit *prev; dataheap_block* i; Size = DATAALIGN(Size); if (Size>=DATAHEAP_LIMIT) { MemHeap_Free(p->Heap,Ptr,Size*sizeof(dataunit)); return; } LockEnter(p->Lock); if (Size==3) { ((dataheap_free*)Ptr)->Next = p->Free3; p->Free3 = (dataheap_free*)Ptr; LockLeave(p->Lock); return; } for (i=ARRAYEND(p->Buffer,dataheap_block);i!=ARRAYBEGIN(p->Buffer,dataheap_block);) { --i; if (i->Data < curr && i->Data+BUFFER_SIZE > curr) { DataHeap_Check(p); next = i->Data; do { prev = next; next += DataNext(next); } while (next i->MaxSize) { i->MaxSize = (uint16_t)Size; i->Count = 1; while (++i!=ARRAYEND(p->Buffer,dataheap_block) && i[-1].MaxSize > i->MaxSize) { SWAPVAL(dataheap_block,i[-1],i[0]); } } else if (Size == i->MaxSize) i->Count = (uint16_t)(i->Count+1); DataHeap_Check(p); break; } } LockLeave(p->Lock); } } static void* DataHeap_ReAlloc(dataheap* p, void* Old, size_t OldSize, size_t NewSize) { size_t n; void* New; OldSize = DATAALIGN(OldSize)*sizeof(dataunit); NewSize = DATAALIGN(NewSize)*sizeof(dataunit); if (OldSize == NewSize) return Old; if (DATAHEAP_LIMIT*sizeof(dataunit)<=OldSize && DATAHEAP_LIMIT*sizeof(dataunit)<=NewSize) return MemHeap_ReAlloc(p->Heap,Old,OldSize,NewSize); New = DataHeap_Alloc(p,NewSize,0); if (!New && NewSize) return NULL; // failed if (Old && New) { n = min(OldSize,NewSize); memcpy(New,Old,n); } DataHeap_Free(p,Old,OldSize); return New; } void DataHeap_Init(dataheap* p,const cc_memheap* Heap) { assert(BUFFER_SIZE-2>=DATAHEAP_LIMIT); p->Base.Alloc = (memheap_alloc)DataHeap_Alloc; p->Base.ReAlloc = (memheap_realloc)DataHeap_ReAlloc; p->Base.Free = (memheap_free)DataHeap_Free; p->Base.Write = (memheap_write)DataHeap_Write; p->Base.Null.Heap = &p->Base; p->Base.Null.Size = DATA_FLAG_MEMHEAP; p->Heap = Heap; ArrayInitEx(&p->Buffer,Heap); ArrayAlloc(&p->Buffer,512,1); p->Lock = LockCreate(); p->Free3 = NULL; } void DataHeap_Done(dataheap* p) { dataheap_block* i; for (i=ARRAYBEGIN(p->Buffer,dataheap_block);i!=ARRAYEND(p->Buffer,dataheap_block);++i) MemHeap_Free(p->Heap,i->Data,BUFFER_SIZE*sizeof(dataunit)); ArrayClear(&p->Buffer); p->Free3 = NULL; LockDelete(p->Lock); p->Lock = NULL; } bcmatroska2-5.3.101/corec/corec/helpers/parser/dataheap.h000066400000000000000000000041411462133141200231320ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __DATAHEAP_H #define __DATAHEAP_H typedef struct dataheap_free dataheap_free; typedef struct dataheap { cc_memheap Base; void *Lock; const cc_memheap *Heap; array Buffer; dataheap_free* Free3; // optimize the most common sized chunk (sizeof(nodenotif) and sizeof(nodedata)+4) } dataheap; NODE_DLL void DataHeap_Init(dataheap*, const cc_memheap* Base); NODE_DLL void DataHeap_Done(dataheap*); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/hotkey.c000066400000000000000000000133411462133141200226630ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" typedef struct hotkeyname { uint32_t Key; const tchar_t* XML; } hotkeyname; static const hotkeyname HotKeyName[] = { // first the masks { HOTKEY_SHIFT, T("Shift")}, { HOTKEY_CTRL, T("Ctrl")}, { HOTKEY_ALT, T("Alt")}, { HOTKEY_WIN, T("Win")}, { HOTKEY_HOLD, T("Hold")}, { HOTKEY_MEDIA_STOP, T("Stop")}, { HOTKEY_MEDIA_PLAY, T("Play")}, { HOTKEY_MEDIA_PREV, T("Prev")}, { HOTKEY_MEDIA_NEXT, T("Next")}, { HOTKEY_MEDIA_VOLUME_UP, T("VolUp")}, { HOTKEY_MEDIA_VOLUME_DOWN, T("VolDown")}, { HOTKEY_MEDIA_MUTE, T("Mute")}, { HOTKEY_MEDIA_MOVEFWD, T("MoveFwd")}, { HOTKEY_MEDIA_MOVEBACK, T("MoveBack")}, { HOTKEY_DPAD_ACTION, T("Action")}, { HOTKEY_DPAD_LEFT, T("Left")}, { HOTKEY_DPAD_RIGHT, T("Right")}, { HOTKEY_DPAD_UP, T("Up")}, { HOTKEY_DPAD_DOWN, T("Down")}, { HOTKEY_ENTER, T("Enter")}, { HOTKEY_SPACE, T("Space")}, { HOTKEY_ESCAPE, T("Escape")}, { HOTKEY_TABNEXT, T("TabNext")}, { HOTKEY_TABPREV, T("TabPrev")}, { HOTKEY_BACKSPACE, T("BackSpace")}, { HOTKEY_DELETE, T("Delete")}, { HOTKEY_SELECT, T("Select")}, { HOTKEY_START, T("Start")}, { HOTKEY_TRIANGLE, T("Triangle")}, { HOTKEY_SQUARE, T("Square")}, { HOTKEY_CIRCLE, T("Circle")}, { HOTKEY_CROSS, T("Cross")}, {0, NULL}, // should be right after {0} { HOTKEY_APP_FIRST, T("App%d")}, }; static const tchar_t* GetHotKeyName(const hotkeyname* i, hotkeygetname GetName, void* GetNameParam) { if (GetName) return GetName(GetNameParam,i->Key); return i->XML; } void HotKeyToString(tchar_t* Out, size_t OutLen, uint32_t HotKey, hotkeygetname GetName, void* GetNameParam) { const hotkeyname* i = HotKeyName; if (!GetName) { // force # XML exporting to make import safer... stprintf_s(Out,OutLen,T("#%x"),(int)HotKey); return; } *Out = 0; for (;i->Key > HOTKEY_MASK;++i) if (HotKey & i->Key) { tcscat_s(Out,OutLen,GetHotKeyName(i,GetName,GetNameParam)); tcscat_s(Out,OutLen,T("+")); } HotKey &= HOTKEY_MASK; for (;i->Key;++i) if (HotKey == i->Key) { tcscat_s(Out,OutLen,GetHotKeyName(i,GetName,GetNameParam)); return; } if ((HotKey >= '0' && HotKey <= '9') || (HotKey >= 'A' && HotKey <= 'Z')) stcatprintf_s(Out,OutLen,T("%c"),HotKey); else if (HotKey >= HOTKEY_FUNC_FIRST && HotKey <= HOTKEY_FUNC_LAST) stcatprintf_s(Out,OutLen,T("F%d"),HotKey-HOTKEY_FUNC_FIRST+1); else if (HotKey >= HOTKEY_APP_FIRST && HotKey <= HOTKEY_APP_LAST) stcatprintf_s(Out,OutLen,GetHotKeyName(i+1,GetName,GetNameParam),HotKey-HOTKEY_APP_FIRST+1); else stcatprintf_s(Out,OutLen,T("#%02X"),HotKey); } uint32_t StringToHotKey(const tchar_t* In) { const tchar_t* m; const hotkeyname* i; uint32_t HotKey = 0; size_t n; ExprSkipSpace(&In); while ((m = tcschr(In,'+')) != NULL) { n = m-In; while (n>0 && IsSpace(In[n-1])) --n; for (i = HotKeyName;i->Key > HOTKEY_MASK;++i) if (tcsnicmp(In,i->XML,n)==0) { HotKey |= i->Key; break; } In = m+1; } if (!In[0]) return 0; for (i = HotKeyName;i->Key;++i) if (tcsisame_ascii(In,i->XML)) return HotKey | i->Key; if ((In[0] == 'f' || In[0] == 'F') && IsDigit(In[1])) return HotKey | (HOTKEY_FUNC_FIRST + StringToInt(In+1,0) - 1); if (In[0] == '#') return HotKey | StringToInt(In+1,1); n = tcslen(In); if (n>1 && IsDigit(In[n-1])) { while (n>0 && IsDigit(In[n-1])) --n; return HotKey | (HOTKEY_APP_FIRST + StringToInt(In+n,0) - 1); } return HotKey | In[0]; } bcmatroska2-5.3.101/corec/corec/helpers/parser/hotkey.h000066400000000000000000000074251462133141200226760ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __HOTKEY_H #define __HOTKEY_H #define HOTKEY_MASK 0x0000FFFF #define HOTKEY_SHIFT 0x00010000 #define HOTKEY_CTRL 0x00020000 #define HOTKEY_ALT 0x00040000 #define HOTKEY_WIN 0x00080000 #define HOTKEY_HOLD 0x00100000 #define HOTKEY_MEDIA_STOP 0x00009000 #define HOTKEY_MEDIA_PLAY 0x00009001 #define HOTKEY_MEDIA_PREV 0x00009002 #define HOTKEY_MEDIA_NEXT 0x00009003 #define HOTKEY_MEDIA_VOLUME_UP 0x00009004 #define HOTKEY_MEDIA_VOLUME_DOWN 0x00009005 #define HOTKEY_MEDIA_MUTE 0x00009006 #define HOTKEY_MEDIA_MOVEFWD 0x00009007 #define HOTKEY_MEDIA_MOVEBACK 0x00009008 #define HOTKEY_DPAD_ACTION 0x00009010 #define HOTKEY_DPAD_LEFT 0x00009011 #define HOTKEY_DPAD_RIGHT 0x00009012 #define HOTKEY_DPAD_UP 0x00009013 #define HOTKEY_DPAD_DOWN 0x00009014 #define HOTKEY_ENTER 0x00009020 #define HOTKEY_SPACE 0x00009021 #define HOTKEY_ESCAPE 0x00009022 #define HOTKEY_TABNEXT 0x00009023 #define HOTKEY_TABPREV 0x00009024 #define HOTKEY_DELETE 0x00009025 #define HOTKEY_BACKSPACE 0x00009026 #define HOTKEY_FUNC_FIRST 0x00009030 #define HOTKEY_FUNC_LAST 0x0000903F #define HOTKEY_APP_FIRST 0x00009040 #define HOTKEY_APP_LAST 0x0000904F #define HOTKEY_MOD_SHIFT 0x00009050 #define HOTKEY_MOD_CTRL 0x00009051 #define HOTKEY_MOD_ALT 0x00009052 #define HOTKEY_MOD_WIN 0x00009053 #define KEYPAD_KEY_FIRST 0x00009060 #define KEYPAD_KEY_LAST 0x0000906F #define HOTKEY_SELECT 0x00009080 #define HOTKEY_START 0x00009081 #define HOTKEY_TRIANGLE 0x00009082 #define HOTKEY_SQUARE 0x00009083 #define HOTKEY_CIRCLE 0x00009084 #define HOTKEY_CROSS 0x00009085 typedef const tchar_t* (*hotkeygetname)(void* Param,uint32_t Key); NODE_DLL void HotKeyToString(tchar_t* Out, size_t OutLen, uint32_t HotKey, hotkeygetname GetName, void* GetNameParam); NODE_DLL uint32_t StringToHotKey(const tchar_t* In); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/nodelookup.c000066400000000000000000000074071462133141200235450ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" typedef struct nodelookup { const tchar_t* Name; node* Node; } nodelookup; static intptr_t CmpLookup(const void* UNUSED_PARAM(p), const nodelookup* a, const nodelookup* b) { return tcsicmp_ascii(a->Name,b->Name); } void NodeLookup_AddSingletons(array* p, nodecontext* Context) { array List; node** i; NodeEnumSingletons(Context,&List); for (i=ARRAYBEGIN(List,node*);i!=ARRAYEND(List,node*);++i) NodeLookup_Add(p,*i,NodeParamStr(*i,NODE_ID)); ArrayClear(&List); } bool_t NodeLookup_Exists(array* p, const tchar_t* Name) { assert(Name != NULL); if (Name && Name[0]) { bool_t Found; nodelookup Lookup; Lookup.Name = Name; ArrayFind(p,nodelookup,&Lookup,(arraycmp)CmpLookup,NULL,&Found); return Found; } return 0; } node* NodeLookup_FindUnique(array* p, const tchar_t* Name) { assert(Name!=NULL); if (Name && Name[0]) { bool_t Found; size_t Pos; nodelookup Lookup; Lookup.Name = Name; Pos = ArrayFind(p,nodelookup,&Lookup,(arraycmp)CmpLookup,NULL,&Found); if (Found) return ARRAYBEGIN(*p,nodelookup)[Pos].Node; } return NULL; } bool_t NodeLookup_Add(array* p, node* Node, const tchar_t* Name) { if (Name && Name[0]) { bool_t Found; size_t Pos; nodelookup Lookup; Lookup.Name = Name; Lookup.Node = Node; Pos = ArrayFind(p,nodelookup,&Lookup,(arraycmp)CmpLookup,NULL,&Found); if (!Found) { ArrayAdd(p,nodelookup,&Lookup,(arraycmp)CmpLookup,NULL,0); return 1; } else ARRAYBEGIN(*p,nodelookup)[Pos].Node = NULL; } return 0; } void NodeLookup_Remove(array* p, node* Node, const tchar_t* Name) { if (Name && Name[0]) { bool_t Found; size_t Pos; nodelookup Lookup; Lookup.Name = Name; Lookup.Node = Node; Pos = ArrayFind(p,nodelookup,&Lookup,(arraycmp)CmpLookup,NULL,&Found); if (Found) ArrayDelete(p,Pos*sizeof(Lookup),sizeof(Lookup)); } } bcmatroska2-5.3.101/corec/corec/helpers/parser/nodelookup.h000066400000000000000000000040531462133141200235440ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODELOOKUP_H #define __NODELOOKUP_H NODE_DLL void NodeLookup_AddSingletons(array*, nodecontext*); NODE_DLL bool_t NodeLookup_Add(array*, node*, const tchar_t* Id); NODE_DLL bool_t NodeLookup_Exists(array*, const tchar_t* Id); NODE_DLL node* NodeLookup_FindUnique(array*, const tchar_t* Id); NODE_DLL void NodeLookup_Remove(array*,node*,const tchar_t *Id); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/parser.h000066400000000000000000000245271462133141200226710ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __PARSER_H #define __PARSER_H #include "corec/helpers/file/file.h" #include "corec/helpers/charconvert/charconvert.h" #ifdef __cplusplus extern "C" { #endif #include "dataheap.h" #include "strtab.h" #include "strtypes.h" #include "hotkey.h" #include "buffer.h" #include "nodelookup.h" #include "urlpart.h" #define LANG_STRINGS_ID FOURCC('L','N','G','S') #define MAXTOKEN 32 #define MAXLINE 1024 #define BIGLINE 16 * 1024 #define Parser_Context(p) ((parsercontext*)Node_Context(p)) typedef struct parsercontext { nodecontext Base; charconv* ToUTF8; charconv* FromUTF8; charconv* ToStr; charconv* FromStr; charconv* ToWcs; charconv* FromWcs; charconv* ToUtf16; charconv* FromUtf16; strtab StrTab; bool_t LowStartMemory; } parsercontext; NODE_DLL void ParserContext_Init(parsercontext* p,const nodemeta* Custom, const cc_memheap* Heap, const cc_memheap* ConstHeap); NODE_DLL void ParserContext_Done(parsercontext* p); NODE_DLL void Node_ToUTF8(anynode*, char* Out,size_t OutLen, const tchar_t*); NODE_DLL void Node_FromUTF8(anynode*, tchar_t* Out,size_t OutLen, const char*); NODE_DLL void Node_ToStr(anynode*, char* Out,size_t OutLen, const tchar_t*); NODE_DLL void Node_FromStr(anynode*, tchar_t* Out,size_t OutLen, const char*); NODE_DLL void Node_ToWcs(anynode*, wchar_t* Out,size_t OutLen, const tchar_t*); NODE_DLL void Node_FromWcs(anynode*, tchar_t* Out,size_t OutLen, const wchar_t*); NODE_DLL void Node_ToUTF16(anynode*, utf16_t* Out,size_t OutLen, const tchar_t*); NODE_DLL void Node_FromUTF16(anynode*, tchar_t* Out,size_t OutLen, const utf16_t*); typedef bool_t (*exprmacro)(void* Cookie, const tchar_t* Name, size_t NameLen, tchar_t* Out, size_t OutLen); typedef struct exprstate { nodecontext* Context; node* Base; cc_point CoordScale; fourcc_t ClassId; const tchar_t* EnumList; exprmacro MacroFunc; void* MacroCookie; array NodeLookup; } exprstate; NODE_DLL void ExprState(exprstate* State, node*, dataid Id, dataflags Flags); typedef err_t (*parserexpradd)(node* Node, const datadef* DataDef, exprstate* State, const tchar_t* Expr, bool_t Save); typedef struct parser { parsercontext *Context; stream* Stream; buffer Buffer; charconv* CC; charconv* EscapeCC; tchar_t *BigLine; boolmem_t Element; boolmem_t ElementEof; boolmem_t URL; boolmem_t OwnCC; boolmem_t Error; } parser; NODE_DLL err_t ParserStream(parser*, stream* Stream, parsercontext* Context); NODE_DLL err_t ParserStreamXML(parser*, stream* Stream, parsercontext* Context, const tchar_t* Root, bool_t NeedRootAttribs); NODE_DLL void ParserCC(parser*, charconv* CC, bool_t OwnCC); NODE_DLL void ParserBOM(parser*); NODE_DLL err_t ParserFill(parser*,size_t AdditionalNeeded); // non-blocking stream could return ERR_NEED_MORE_DATA NODE_DLL err_t ParserFillLine(parser*); // non-blocking stream could return ERR_NEED_MORE_DATA NODE_DLL void ParserDataFeed(parser* p,const void* Ptr,size_t Len); NODE_DLL err_t ParserSkip(parser*, intptr_t* Skip); NODE_DLL err_t ParserRead(parser*, void* Data, size_t Size, size_t* Readed); NODE_DLL err_t ParserReadEx(parser*, void* Data, size_t Size, size_t* Readed, bool_t Fill); NODE_DLL intptr_t ParserReadUntil(parser* p, tchar_t* Out, size_t OutLen, int Delimiter); NODE_DLL void ParserSkipAfter(parser* p, int Delimiter); NODE_DLL bool_t ParserLine(parser*, tchar_t* Out, size_t OutLen); NODE_DLL bool_t ParserBigLine(parser*); NODE_DLL bool_t ParserIsToken(parser*, const tchar_t* Token); // case insensitive, ascii NODE_DLL bool_t ParserIsFormat(parser*, const tchar_t* Name, void *Value); NODE_DLL const uint8_t* ParserPeek(parser*, size_t Len); NODE_DLL const uint8_t* ParserPeekEx(parser*, size_t Len, bool_t Fill, err_t*); NODE_DLL bool_t ParserIsRootElement(parser*, tchar_t* Root, size_t RootLen); NODE_DLL bool_t ParserIsElement(parser*, tchar_t* Name, size_t NameLen); NODE_DLL bool_t ParserIsElementNested(parser*, tchar_t* Name, size_t NameLen); NODE_DLL bool_t ParserElementContent(parser*, tchar_t* Out, size_t OutLen); NODE_DLL void ParserElementSkip(parser* p); NODE_DLL void ParserElementSkipNested(parser* p); NODE_DLL bool_t ParserIsAttrib(parser*, tchar_t* Name, size_t NameLen); NODE_DLL bool_t ParserAttribString(parser*, tchar_t* Out, size_t OutLen); NODE_DLL bool_t ParserAttrib(parser*, void* Data, size_t Size, dataflags Flags, exprstate* State); NODE_DLL bool_t ParserAttribData(parser*, node* Node, const datadef* DataDef, exprstate* State, parserexpradd ExprAdd, bool_t ExprSave); NODE_DLL bool_t ParserValueData(const tchar_t* Value, node* Node, const datadef* DataDef, exprstate* State, parserexpradd ExprAdd, bool_t ExprSave); NODE_DLL bool_t ParserAttribLangStr(parser* p, parsercontext* Context, fourcc_t Class, dataid Id); NODE_DLL void ParserAttribSkip(parser*); NODE_DLL void ParserHTMLChars(parser*,tchar_t*,size_t); NODE_DLL void ParserHTMLToURL(tchar_t*,size_t); NODE_DLL void ParserURLToHTML(tchar_t*,size_t); NODE_DLL void ParserImport(parser* Parser,node* Node); NODE_DLL void ParserImportNested(parser* Parser,node* Node); typedef struct textwriter { stream* Stream; charconv* CC; bool_t SafeFormat; // use instead of // private const tchar_t* Element; int Deep; bool_t HasChild; bool_t InsideContent; } textwriter; NODE_DLL err_t TextWrite(textwriter*, const tchar_t*); NODE_DLL err_t TextPrintf(textwriter*, const tchar_t* Msg,...) #if defined(__GNUC__) __attribute__ ((format(printf, 2, 3))) #endif ; NODE_DLL void TextElementXML(parsercontext *Context, textwriter* Text, const tchar_t* Root); NODE_DLL void TextElementBegin(textwriter* Out, textwriter* In, const tchar_t* Element); NODE_DLL void TextElementEnd(textwriter*); NODE_DLL void TextElementAppendData(textwriter* Text, const tchar_t *Value); NODE_DLL void TextElementEndData(textwriter* Text, const tchar_t *Value); NODE_DLL void TextAttrib(textwriter*, const tchar_t* Name, const void* Data, dataflags Type); NODE_DLL void TextAttribEx(textwriter*,const tchar_t* Name, const void* Data, size_t Size, dataflags Type); NODE_DLL void TextSerializeNode(textwriter* Text, node* p, uint_fast32_t Mask, uint_fast32_t Filter); NODE_DLL bool_t StringToPin(pin* Data, datadef* DataDef, exprstate* State, const tchar_t** Expr); NODE_DLL bool_t StringToNode(node** Data, exprstate* State, const tchar_t** Expr); NODE_DLL bool_t StringToData(void* Data, size_t Size, dataflags Type, exprstate* State, const tchar_t* Value); NODE_DLL bool_t DataToString(tchar_t* Value, size_t ValueLen, const void* Data, size_t Size, dataflags Type); NODE_DLL bool_t PinToString(tchar_t* Value, size_t ValueLen, const pin* Data, node* Base); NODE_DLL bool_t NodeToString(tchar_t* Value, size_t ValueLen, node* Node, node* Base); NODE_DLL void ExprSkipSpace(const tchar_t** p); NODE_DLL void ExprTrimSpace(tchar_t** p); NODE_DLL bool_t ExprCmd(const tchar_t** Expr, tchar_t* Out, size_t OutLen); NODE_DLL bool_t ExprSkipAfter(const tchar_t** p,int ch); //ch=0 for general space NODE_DLL bool_t ExprIsToken(const tchar_t** p,const tchar_t* Name); NODE_DLL bool_t ExprIsTokenEx(const tchar_t** p,const tchar_t* Name,...) #if defined(__GNUC__) __attribute__ ((format(printf, 2, 3))) #endif ; NODE_DLL bool_t ExprIsSymbol(const tchar_t** p,int ch); NODE_DLL bool_t ExprIsSymbol2(const tchar_t** p,int ch, int ch2); NODE_DLL void ExprParamEnd(const tchar_t** p); NODE_DLL bool_t ExprParamNext(const tchar_t** p); NODE_DLL bool_t ExprIsFrac(const tchar_t** p,cc_fraction*); // no space skipping! NODE_DLL bool_t ExprIsInt(const tchar_t** p,intptr_t*); // no space skipping! NODE_DLL bool_t ExprIsInt64(const tchar_t** p,int64_t*); // no space skipping! NODE_DLL bool_t ExprIsIntEx(const tchar_t** p,int size,intptr_t*); // no space skipping! NODE_DLL bool_t ExprIsInt64Ex(const tchar_t** p,int size,int64_t*); // no space skipping! NODE_DLL bool_t ExprIsHex(const tchar_t** p,intptr_t*); // no space skipping! NODE_DLL bool_t ExprIsRGB(const tchar_t** p,intptr_t*); // no space skipping! NODE_DLL bool_t ExprIsFourCC(const tchar_t** p,intptr_t*); // no space skipping! NODE_DLL bool_t ExprIsPoint(const tchar_t** p,cc_point*); NODE_DLL bool_t ExprIsName(const tchar_t** p,tchar_t* Out,size_t OutLen, const tchar_t* Delimiter); NODE_DLL size_t ExprIsBase64(const tchar_t** p,uint8_t* Out,size_t OutSize); NODE_DLL void SimplifyFrac(cc_fraction*, int64_t Num, int64_t Den); NODE_DLL void DoubleToFrac(cc_fraction*, int64_t v); NODE_DLL bool_t BufferToBase64(tchar_t *Out, size_t OutLen, const uint8_t *Buffer, size_t BufferSize); NODE_DLL uint32_t StringToIP(const tchar_t *Addr); NODE_DLL err_t Stream_Printf(stream*, const tchar_t* Msg,...) #if defined(__GNUC__) __attribute__ ((format(printf, 2, 3))) #endif ; NODE_DLL void NodeDump(nodecontext*,textwriter*); #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/parser.proj000066400000000000000000000006751462133141200234120ustar00rootroot00000000000000GROUP parser { USE file USE charconvert INCLUDE .. DEFINE COREC_PARSER SOURCE parser2.c { class LangStr_Class } HEADER parser.h SOURCE strtab.c HEADER strtab.h SOURCE strtypes.c HEADER strtypes.h SOURCE dataheap.c HEADER dataheap.h SOURCE buffer.c HEADER buffer.h SOURCE hotkey.c HEADER hotkey.h SOURCE nodelookup.c HEADER nodelookup.h SOURCE urlpart.c {class UrlPart_Class} HEADER urlpart.h } bcmatroska2-5.3.101/corec/corec/helpers/parser/parser2.c000066400000000000000000001721561462133141200227500ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" static const tchar_t* ExternalStr(nodecontext* p,fourcc_t Class,int Id) { return StrTab_Find(&((parsercontext*)p)->StrTab,Class,Id); } void ParserContext_Init(parsercontext* p,const nodemeta* Custom, const cc_memheap* Heap, const cc_memheap* ConstHeap) { NodeContext_Init(&p->Base,Custom,Heap,ConstHeap); p->Base.ExternalStr = ExternalStr; StrTab_Init(&p->StrTab,p->Base.NodeConstHeap,5120); p->ToUTF8 = CharConvOpen(NULL,CHARSET_UTF8); p->FromUTF8 = CharConvOpen(CHARSET_UTF8,NULL); p->ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); p->FromStr = CharConvOpen(CHARSET_DEFAULT,NULL); p->ToWcs = CharConvOpen(NULL,CHARSET_WCHAR); p->FromWcs = CharConvOpen(CHARSET_WCHAR,NULL); p->ToUtf16 = CharConvOpen(NULL,CHARSET_UTF16); p->FromUtf16 = CharConvOpen(CHARSET_UTF16,NULL); } void ParserContext_Done(parsercontext* p) { CharConvClose(p->ToUTF8); CharConvClose(p->FromUTF8); CharConvClose(p->ToStr); CharConvClose(p->FromStr); CharConvClose(p->ToWcs); CharConvClose(p->FromWcs); CharConvClose(p->ToUtf16); CharConvClose(p->FromUtf16); p->ToUTF8 = NULL; p->FromUTF8 = NULL; p->ToStr = NULL; p->FromStr = NULL; p->ToWcs = NULL; p->FromWcs = NULL; p->ToUtf16 = NULL; p->FromUtf16 = NULL; StrTab_Done(&p->StrTab); NodeContext_Done(&p->Base); } void Node_ToUTF8(anynode* p, char* Out,size_t OutLen, const tchar_t* In) { CharConvST(Parser_Context(p)->ToUTF8,Out,OutLen,In); } void Node_FromUTF8(anynode* p, tchar_t* Out,size_t OutLen, const char* In) { CharConvTS(Parser_Context(p)->FromUTF8,Out,OutLen,In); } void Node_ToStr(anynode* p, char* Out,size_t OutLen, const tchar_t* In) { CharConvST(Parser_Context(p)->ToStr,Out,OutLen,In); } void Node_FromStr(anynode* p, tchar_t* Out,size_t OutLen, const char* In) { CharConvTS(Parser_Context(p)->FromStr,Out,OutLen,In); } void Node_ToWcs(anynode* p, wchar_t* Out,size_t OutLen, const tchar_t* In) { CharConvWT(Parser_Context(p)->ToWcs,Out,OutLen,In); } void Node_FromWcs(anynode* p, tchar_t* Out,size_t OutLen, const wchar_t* In) { CharConvTW(Parser_Context(p)->FromWcs,Out,OutLen,In); } void Node_ToUTF16(anynode* p, utf16_t* Out,size_t OutLen, const tchar_t* In) { CharConvUT(Parser_Context(p)->ToUtf16,Out,OutLen,In); } void Node_FromUTF16(anynode* p, tchar_t* Out,size_t OutLen, const utf16_t* In) { CharConvTU(Parser_Context(p)->FromUtf16,Out,OutLen,In); } void ParserDataFeed(parser* p,const void* Ptr,size_t Len) { BufferWrite(&p->Buffer,Ptr,Len,4096); } NOINLINE err_t ParserFill(parser* p,size_t Needed) { // Needed may be zero (see http.c EnumDir()) // pack buffer if more then half is done if (p->Buffer.Read > p->Buffer.Begin + (p->Buffer.End - p->Buffer.Begin)/2) BufferPack(&p->Buffer,0); for (;;) { size_t Readed,n; err_t Err; n = p->Buffer.End - p->Buffer.Write; if (n==0 || !p->Stream) return (Needed>0)?ERR_NEED_MORE_DATA:ERR_NONE; Err = Stream_ReadOneOrMore(p->Stream,p->Buffer.Write,n,&Readed); if (!Readed) return Err; p->Buffer.Write += Readed; if (Readed >= Needed) break; Needed -= Readed; } return ERR_NONE; } NOINLINE err_t ParserFillLine(parser* p) { err_t Err; do { const uint8_t* i; for (i=p->Buffer.Read;i!=p->Buffer.Write;++i) if (*i == '\n') return ERR_NONE; Err = ParserFill(p,1); } while (Err==ERR_NONE); return Err; } void ParserBOM(parser* p) { //TODO: use BOM detection in more places (playlist,xml,...) //TODO: support 16bit LE/BE encodings const uint8_t* BOM = ParserPeek(p,3); if (BOM) { if (BOM[0]==0xEF && BOM[1]==0xBB && BOM[2]==0xBF) { intptr_t Skip = 3; ParserSkip(p,&Skip); if (p->Context) ParserCC(p,p->Context->FromUTF8,0); } } } NOINLINE void ParserCC(parser* p, charconv* CC, bool_t OwnCC) { if (p->CC && p->OwnCC) CharConvClose(p->CC); p->CC = CC; p->OwnCC = (boolmem_t)OwnCC; } err_t ParserStream(parser* p, stream* Stream, parsercontext* Context) { ParserCC(p,Context ? Context->FromStr:NULL, 0); p->Stream = Stream; p->Element = 0; p->ElementEof = 0; p->Error = 0; p->URL = 0; p->Context = Context; if (Stream) { if (!p->Buffer.Begin) if (!BufferAlloc(&p->Buffer,4096,1)) return ERR_OUT_OF_MEMORY; } else { BufferClear(&p->Buffer); if (p->BigLine) { free(p->BigLine); p->BigLine = NULL; } } return ERR_NONE; } err_t ParserSkip(parser* p, intptr_t* Skip) { intptr_t n = min(*Skip,p->Buffer.Write - p->Buffer.Read); if (n>0) { *Skip -= n; p->Buffer.Read += n; } return Stream_Skip(p->Stream,Skip); } err_t ParserReadEx(parser* p, void* Data, size_t Size, size_t* Readed, bool_t Fill) { if (!Fill) { size_t n = 0; if (p->Buffer.Write > p->Buffer.Read) { n = min(Size,(size_t)(p->Buffer.Write-p->Buffer.Read)); memcpy(Data,p->Buffer.Read,n); p->Buffer.Read += n; Size -= n; } if (Readed) *Readed = n; return !Size ? ERR_NONE:ERR_NEED_MORE_DATA; } return ParserRead(p,Data,Size,Readed); } err_t ParserRead(parser* p, void* Data, size_t Size, size_t* Readed) { if (p->Buffer.Write > p->Buffer.Read) { err_t Err = ERR_NONE; size_t n = min(Size,(size_t)(p->Buffer.Write-p->Buffer.Read)); memcpy(Data,p->Buffer.Read,n); p->Buffer.Read += n; Size -= n; if (Size>0) { Err = Stream_Read(p->Stream,(uint8_t*)Data+n,Size,&Size); n += Size; } if (Readed) *Readed = n; return Err; } return Stream_Read(p->Stream,Data,Size,Readed); } const uint8_t* ParserPeek(parser* p, size_t Len) { if (p->Buffer.Write < p->Buffer.Read+Len) { ParserFill(p,p->Buffer.Read+Len-p->Buffer.Write); if (p->Buffer.Write < p->Buffer.Read+Len) return NULL; } return p->Buffer.Read; } const uint8_t* ParserPeekEx(parser* p, size_t Len, bool_t Fill, err_t* Err) { if (p->Buffer.Write < p->Buffer.Read+Len) { if (!Fill) { *Err = ERR_NEED_MORE_DATA; return NULL; } *Err = ParserFill(p,p->Buffer.Read+Len-p->Buffer.Write); if (p->Buffer.Write < p->Buffer.Read+Len) return NULL; } *Err = ERR_NONE; return p->Buffer.Read; } #define PARSER_BEGIN(p) \ uint8_t* Read = p->Buffer.Read; \ uint8_t* Write = p->Buffer.Write; \ #define PARSER_RESTART(p) \ Read = p->Buffer.Read; \ Write = p->Buffer.Write; \ #define PARSER_SAVE(p) \ p->Buffer.Read = Read; #define PARSER_FILL(p) \ PARSER_SAVE(p) \ ParserFill(p,1); \ PARSER_RESTART(p) static bool_t SkipAfter(parser* p, int ch) { PARSER_BEGIN(p) for (;;++Read) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } if (*Read==(uint8_t)ch) break; } ++Read; PARSER_SAVE(p); return 1; } bool_t ParserIsToken(parser* p, const tchar_t* Token) { PARSER_BEGIN(p) // space skipping for (;;++Read) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } if (*Read!=' ' && *Read!=9 && *Read!=10 && *Read!=13) break; } PARSER_SAVE(p) for (;*Token;++Read,++Token) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } if (*Read!=(uint8_t)*Token) return 0; } PARSER_SAVE(p) return 1; } NOINLINE bool_t ParserIsFormat(parser* p,const tchar_t* Token, void *Value) { size_t i,j=0; tchar_t tBuffer[MAXDATA]; PARSER_BEGIN(p) if (!*Token || *Token!='%') return 0; // space skipping for (;;++Read) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } if (*Read!=' ' && *Read!=9 && *Read!=10 && *Read!=13) break; } PARSER_SAVE(p) for (;j=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } tBuffer[j] = (tchar_t)p->Buffer.Read[j++]; i=j; if (!stscanf_s(tBuffer,&i,Token,Value)) break; if (i != j) break; } if (j>1) // recover the last working config { --j; stscanf_s(tBuffer,&j,Token,Value); } PARSER_SAVE(p) return (j!=0); } static bool_t IsToken(parser* p, const tchar_t* Token) { PARSER_BEGIN(p) for (;*Token;++Read,++Token) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) return 0; } if (*Read!=(uint8_t)*Token) return 0; } PARSER_SAVE(p) return 1; } typedef struct htmlchar { uint8_t ch; tchar_t sym[6+1]; } htmlchar; static const htmlchar HTMLChar[] = { {34,T("quot")}, {38,T("amp")}, {39,T("apos")}, {60,T("lt")}, {62,T("gt")}, {160,T("nbsp")}, {161,T("iexcl")}, {162,T("cent")}, {163,T("pound")}, {164,T("curren")}, {165,T("yen")}, {166,T("brvbar")}, {167,T("sect")}, {168,T("uml")}, {169,T("copy")}, {170,T("ordf")}, {171,T("laquo")}, {172,T("not")}, {173,T("shy")}, {174,T("reg")}, {175,T("hibar")}, {176,T("deg")}, {177,T("plusmn")}, {185,T("sup1")}, {178,T("sup2")}, {179,T("sup3")}, {180,T("acute")}, {181,T("micro")}, {182,T("para")}, {183,T("middot")}, {184,T("cedil")}, {186,T("ordm")}, {187,T("raquo")}, {188,T("frac14")}, {189,T("frac12")}, {190,T("frac34")}, {191,T("iquest")}, {192,T("Agrave")}, {193,T("Aacute")}, {194,T("Acirc")}, {195,T("Atilde")}, {196,T("Auml")}, {197,T("Aring")}, {198,T("AElig")}, {199,T("Ccedil")}, {200,T("Egrave")}, {201,T("Eacute")}, {202,T("Ecirc")}, {203,T("Euml")}, {204,T("Igrave")}, {205,T("Iacute")}, {206,T("Icirc")}, {207,T("Iuml")}, {208,T("ETH")}, {209,T("Ntilde")}, {210,T("Ograve")}, {211,T("Oacute")}, {212,T("Ocirc")}, {213,T("Otilde")}, {214,T("Ouml")}, {215,T("times")}, {216,T("Oslash")}, {217,T("Ugrave")}, {218,T("Uacute")}, {219,T("Ucirc")}, {220,T("Uuml")}, {221,T("Yacute")}, {222,T("THORN")}, {223,T("szlig")}, {224,T("agrave")}, {225,T("aacute")}, {226,T("acirc")}, {227,T("atilde")}, {228,T("auml")}, {229,T("aring")}, {230,T("aelig")}, {231,T("ccedil")}, {232,T("egrave")}, {233,T("eacute")}, {234,T("ecirc")}, {235,T("euml")}, {236,T("igrave")}, {237,T("iacute")}, {238,T("icirc")}, {239,T("iuml")}, {240,T("eth")}, {241,T("ntilde")}, {242,T("ograve")}, {243,T("oacute")}, {244,T("ocirc")}, {245,T("otilde")}, {246,T("ouml")}, {247,T("divide")}, {248,T("oslash")}, {249,T("ugrave")}, {250,T("uacute")}, {251,T("ucirc")}, {252,T("uuml")}, {253,T("yacute")}, {254,T("thorn")}, {255,T("yuml")}, {0,T("")} }; void ParserHTMLChars(parser *p, tchar_t *Out, size_t OutLen) { const tchar_t* i; utf16_t ch; utf16_t UChar[2]; UChar[1] = 0; for (;*Out;++Out,--OutLen) { if (*Out==T('&') && (i=tcschr(Out,T(';')))!=NULL) { ch = 0; if (Out[1]=='#') { if (IsDigit(Out[2])) // decimal encoding { const tchar_t* s; for (s = Out+2;sch;++c) if (tcsnicmp(c->sym,Out+1,n)==0 && c->sym[n]==0) { ch = c->ch; break; } } if (ch) { size_t Index=0; UChar[0] = ch; Node_FromUTF16(p->Context,Out,OutLen,UChar); for (Index=0;Index0;++URL,--OutLen) if (URL[0]=='%' && Hex(URL[1])>=0 && Hex(URL[2])>=0) { *URL = (tchar_t)((Hex(URL[1])<<4)+Hex(URL[2])); memmove(URL+1,URL+3,sizeof(tchar_t)*(tcslen(URL+3)+1)); } } void ParserURLToHTML(tchar_t* p,size_t n) { for (;*p && n>0;++p,--n) if (*p == ' ' && n>=4) { size_t i = min(n-4,tcslen(p+1)); memmove(p+3,p+1,i*sizeof(tchar_t)); p[3+i] = 0; p[0] = '%'; p[1] = '2'; p[2] = '0'; } } void ParserSkipAfter(parser* p, int Delimiter) { tchar_t Del[2]; ParserReadUntil(p,NULL,0,Delimiter); Del[0] = (tchar_t)Delimiter; Del[1] = 0; IsToken(p,Del); } intptr_t ParserReadUntil(parser* p, tchar_t* Out, size_t OutLen, int Delimiter) { char* s = alloca(OutLen); size_t n=0; if (Delimiter == '>' || Delimiter == '=') { // ' ','\t','\n','/','>' as additional delimiters PARSER_BEGIN(p) for (;;++Read) { if (Read>=Write) { PARSER_FILL(p) if (Read>=Write) { if (!n) return -1; break; } } if (*Read<0x40) // fast prefilter { if (*Read==(uint8_t)Delimiter || *Read==' ' || *Read=='\t' || *Read=='\n' || *Read=='/' || *Read=='>') break; } if (*Read!='\r' && ++n=Write) { PARSER_FILL(p) if (Read>=Write) { if (!n) return -1; break; } } if (*Read==(uint8_t)Delimiter) { if (Delimiter == ']') { bool_t Found; PARSER_SAVE(p); Found = ParserIsToken(p,T("]]>")); PARSER_RESTART(p); if (Found) break; } else { if (Delimiter != '<') // skip delimiter (except for '<') ++Read; break; } } if (*Read!='\r' && ++n0) { if (!n) *Out = 0; else { s[min(n,OutLen-1)]=0; CharConvTS(p->CC,Out,OutLen,s); if (Delimiter != '\n') // not ParserLine ParserHTMLChars(p,Out,OutLen); if (p->URL) ParserHTMLToURL(Out,OutLen); } } return n; } bool_t ParserLine(parser* p, tchar_t* Out, size_t OutLen) { return ParserReadUntil(p,Out,OutLen,'\n')>=0; } bool_t ParserBigLine(parser* p) { if (!p->BigLine) { p->BigLine = (tchar_t *) malloc(BIGLINE * sizeof(tchar_t)); if (!p->BigLine) return 0; } return ParserLine(p, p->BigLine, BIGLINE); } NOINLINE void ParserElementSkip(parser* p) { while (ParserIsAttrib(p,NULL,0)) ParserAttribSkip(p); } NOINLINE void ParserElementSkipNested(parser* p) { ParserElementSkip(p); while (ParserIsElementNested(p,NULL,0)) ParserElementSkipNested(p); } static NOINLINE bool_t ElementStart(parser* p) { for (;;) { if (!SkipAfter(p,'<')) break; if (IsToken(p,T("!--"))) { do { if (!SkipAfter(p,'-')) return 0; } while (!IsToken(p,T("->"))); } else if (IsToken(p,T("![CDATA["))) { do { if (!SkipAfter(p,']')) return 0; } while (!IsToken(p,T("]>"))); } else return 1; } return 0; } bool_t ParserIsElementNested(parser* p, tchar_t* Name, size_t NameLen) { bool_t Start = 1; if (p->Element) ParserElementSkipNested(p); if (p->ElementEof || !(Start = ElementStart(p)) || IsToken(p,T("/"))) { if (!Start) p->Error = 1; p->ElementEof = 0; p->Element = 0; } else p->Element = (boolmem_t)(ParserReadUntil(p,Name,NameLen,'>')>0); return p->Element; } bool_t ParserIsElement(parser* p, tchar_t* Name, size_t NameLen) { ParserElementSkip(p); if (!ElementStart(p)) { p->Element = 0; } else { if (IsToken(p,T("/")) && NameLen>0) { *(Name++) = '/'; --NameLen; } p->Element = (boolmem_t)(ParserReadUntil(p,Name,NameLen,'>')>0); } return p->Element; } bool_t ParserElementContent(parser* p, tchar_t* Out, size_t OutLen) { ParserElementSkip(p); if (ParserReadUntil(p,Out,OutLen,'<')<0) return 0; if (ParserIsToken(p,T("![CDATA["))) return ParserReadUntil(p,Out,OutLen,']')>=0; return 1; } bool_t ParserIsAttrib(parser* p, tchar_t* Name, size_t NameLen) { if (!p->Element) return 0; // skip spaces by ParserIsToken p->ElementEof = (boolmem_t)ParserIsToken(p,T("/>")); if (p->ElementEof || IsToken(p,T(">")) || IsToken(p,T("?>"))) p->Element = 0; else p->Element = (boolmem_t)(ParserReadUntil(p,Name,NameLen,'=')>0); return p->Element; } bool_t ParserAttribLangStr(parser* p, parsercontext* Context, fourcc_t Class, dataid Id) { tchar_t Value[MAXDATA/sizeof(tchar_t)+64]; if (!ParserAttribString(p,Value,TSIZEOF(Value))) return 0; StrTab_Add(&Context->StrTab,1,Class,(int32_t)Id,Value); return 1; } bool_t ParserAttribString(parser* p, tchar_t* Out, size_t OutLen) { int Delimiter; // skip spaces by ParserIsToken if (!ParserIsToken(p,T("="))) return 0; // skip spaces by ParserIsToken if (ParserIsToken(p,T("\""))) Delimiter = '\"'; else if (IsToken(p,T("'"))) Delimiter = '\''; else Delimiter = '>'; return ParserReadUntil(p,Out,OutLen,Delimiter)>=0; } void ParserAttribSkip(parser* p) { ParserAttribString(p,NULL,0); } bool_t ParserIsRootElement(parser *p, tchar_t* Root, size_t RootLen) { tchar_t Token[MAXTOKEN]; while (ParserIsElement(p,Token,TSIZEOF(Token))) { if (tcsisame_ascii(Token,T("?xml"))) { while (ParserIsAttrib(p,Token,TSIZEOF(Token))) { if (tcsisame_ascii(Token,T("encoding"))) { ParserAttribString(p,Token,TSIZEOF(Token)); ParserCC(p,CharConvOpen(Token,NULL),1); } else ParserAttribSkip(p); } } else if (tcsisame_ascii(Token,T("!DOCTYPE")) || Token[0]==T('?')) { ParserElementSkip(p); } else { tcscpy_s(Root,RootLen,Token); return 1; } } return 0; } err_t ParserStreamXML(parser* p, stream* s, parsercontext* Context, const tchar_t* Root, bool_t NeedRootAttribs) { err_t Result=ERR_NONE; tchar_t FoundRoot[MAXPATH]; if (!Root || !Root[0]) return ERR_INVALID_PARAM; Result = ParserStream(p,s,Context); if (Result==ERR_NONE) { if (Context) ParserCC(p,Context->FromUTF8, 0); if (ParserIsRootElement(p, FoundRoot, TSIZEOF(FoundRoot))) { if (tcsisame_ascii(FoundRoot,Root) && !NeedRootAttribs) ParserElementSkip(p); } } return Result; } static NOINLINE bool_t IsName(int ch) { return ch== '_' || IsAlpha(ch) || IsDigit(ch); } typedef struct findpin { fourcc_t ClassId; datadef* DataDef; node* Node; const tchar_t* Expr; } findpin; static bool_t FindParam(node* Base, findpin* Find, nodecontext*); static INLINE bool_t FindChild(nodetree* i, const tchar_t* Token, findpin* Find) { nodetree* Child = NodeTree_FindChild(i,Token); if (Child && FindParam((node*)Child,Find,Node_Context(Child))) return 1; return 0; } static NOINLINE bool_t ReadName(findpin* Find, tchar_t* Token, size_t TokenLen) { size_t i=0; while (IsName((Find->Expr)[0])) { if (i+1Expr)[0]; ++(Find->Expr); } Token[i] = 0; if ((Find->Expr)[0] == '.') { ++(Find->Expr); return 1; } return 0; } static NOINLINE bool_t FindParam(node* Base, findpin* Find, nodecontext* Context) { const tchar_t* Expr0 = Find->Expr; tchar_t Token[MAXTOKEN]; if (!ReadName(Find,Token,TSIZEOF(Token))) { if (Token[0]) { // check for param if (Base && Find->DataDef && NodeFindDef(Base,Token,Find->DataDef)) { Find->Node = Base; return 1; } } else { // check for default param if (Base && Find->DataDef && NodeDataDef(Base,NODE_DEFAULT_DATA,Find->DataDef)) { Find->Node = Base; return 1; } // check for classid if (Base && Node_IsPartOf(Base,Find->ClassId)) { Find->Node = Base; return 1; } Find->Expr = Expr0; return 0; } } if (!Base) { // try singleton Base = NodeSingleton(Context,StringToFourCC(Token,1)); if (Base && FindParam(Base,Find,Context)) return 1; } else if (Node_IsPartOf(Base,NODETREE_CLASS)) { if (tcsisame_ascii(Token,T("parent"))) { // go parent Base = (node*)((nodetree*)Base)->Parent; if (Base && FindParam(Base,Find,Context)) return 1; } else if (FindChild((nodetree*)Base,Token,Find)) return 1; } Find->Expr = Expr0; return 0; } static NOINLINE bool_t FindPin(node* Base, findpin* Find, nodecontext* Context) { // Base == NULL, when only singletons are accepted while (Base) { if (FindParam(Base,Find,Context)) return 1; if (Node_IsPartOf(Base,NODETREE_CLASS)) Base = (node*)((nodetree*)Base)->Parent; else Base = NULL; } // try singleton return FindParam(NULL,Find,Context); } bool_t StringToPin(pin* Data, datadef* DataDef, exprstate* State, const tchar_t** Expr) { findpin Find; Find.ClassId = 0; Find.DataDef = DataDef; Find.Expr = *Expr; Find.Node = NULL; if (!ARRAYEMPTY(State->NodeLookup)) { tchar_t Id[MAXTOKEN]; tchar_t Token[MAXTOKEN]; node* Node; Id[0]=0; while (ReadName(&Find,Token,TSIZEOF(Token))) tcscpy_s(Id,TSIZEOF(Id),Token); Node = NodeLookup_FindUnique(&State->NodeLookup,Id); if (Node) { if (NodeFindDef(Node,Token,DataDef)) { Data->Id = DataDef->Id; Data->Node = Node; *Expr = Find.Expr; return 1; } else if (Node_IsPartOf(Node,NODETREE_CLASS) && FindChild((nodetree*)Node,Token,&Find)) { Data->Id = DataDef->Id; Data->Node = Find.Node; *Expr = Find.Expr; return 1; } else { Data->Id = 0; Data->Node = NULL; return 0; } } Find.Expr = *Expr; } if (!FindPin(State->Base,&Find,State->Context)) { if (State->Context && ARRAYEMPTY(State->NodeLookup)) { bool_t Result; NodeLookup_AddSingletons(&State->NodeLookup,State->Context); Result = StringToPin(Data,DataDef,State,Expr); ArrayClear(&State->NodeLookup); return Result; } else { Data->Id = 0; Data->Node = NULL; return 0; } } Data->Id = DataDef->Id; Data->Node = Find.Node; *Expr = Find.Expr; return 1; } bool_t StringToNode(node** Data, exprstate* State, const tchar_t** Expr) { findpin Find; Find.ClassId = State->ClassId?State->ClassId:NODE_CLASS; Find.DataDef = NULL; Find.Expr = *Expr; Find.Node = NULL; if (!ARRAYEMPTY(State->NodeLookup)) { tchar_t Id[MAXTOKEN]; node* Node; while (ReadName(&Find,Id,TSIZEOF(Id))) {} Node = NodeLookup_FindUnique(&State->NodeLookup,Id); if (Node) { if (Node_IsPartOf(Node,Find.ClassId)) { *Data = Node; *Expr = Find.Expr; return 1; } else { *Data = NULL; return 0; } } Find.Expr = *Expr; } if (!FindPin(State->Base,&Find,State->Context)) { *Data = NULL; return 0; } *Data = Find.Node; *Expr = Find.Expr; return 1; } bool_t PinToString(tchar_t* Value, size_t ValueLen, const pin* Data, node* Base) { if (NodeToString(Value,ValueLen,Data->Node,Base) && Data->Node) { size_t n; if (Value[0]) tcscat_s(Value,ValueLen,T(".")); n = tcslen(Value); NodeParamName(Data->Node,Data->Id,Value+n,ValueLen-n); } return 1; } bool_t NodeToString(tchar_t* Value, size_t ValueLen, node* Node, node* UNUSED_PARAM(Base)) { Value[0]=0; if (Node) { if (NodeClassFlags(Node) & CFLAG_SINGLETON) FourCCToString(Value,ValueLen,Node_ClassId(Node)); else { //TODO: use Base... (maybe NULL) if (Node_Get(Node,NODE_ID,Value,ValueLen*sizeof(tchar_t))!=ERR_NONE) Value[0] = 0; } } return 1; } static NOINLINE int StringToIntEx(const tchar_t* Value, dataflags Flags, exprstate* State) { int v; if (State && State->EnumList) { v = StrListIndex(Value,State->EnumList); if (v>=0) return v; } v = StringToInt(Value,-1); if (State) { switch (Flags & TUNIT_MASK) { case TUNIT_XCOORD: if (State->CoordScale.x) v = (v*State->CoordScale.x+(1<<15)) >> 16; break; case TUNIT_YCOORD: if (State->CoordScale.y) v = (v*State->CoordScale.y+(1<<15)) >> 16; break; } } return v; } NOINLINE bool_t ExprToData(void* Data, size_t* Size, dataflags Flags, exprstate* State, const tchar_t** Expr) { cc_point v; switch (Flags & TYPE_MASK) { case TYPE_POINT: if (State && ExprIsPoint(Expr,&v) && *Size>=sizeof(cc_point)) { *(cc_point*)Data = v; *Size = sizeof(cc_point); return 1; } case TYPE_POINT16: if (State && ExprIsPoint(Expr,&v) && *Size>=sizeof(cc_point16)) { if ((Flags & TUNIT_MASK)==TUNIT_COORD) { if (State->CoordScale.x) v.x = (v.x*State->CoordScale.x+(1<<15)) >> 16; if (State->CoordScale.y) v.y = (v.y*State->CoordScale.y+(1<<15)) >> 16; } ((cc_point16*)Data)->x = (int16_t)v.x; ((cc_point16*)Data)->y = (int16_t)v.y; *Size = sizeof(cc_point16); return 1; } break; } return 0; } NOINLINE bool_t StringToData(void* Data, size_t Size, dataflags Flags, exprstate* State, const tchar_t* Value) { datadef DataDef; cc_fraction f; size_t i; int a,b; switch (Flags & TYPE_MASK) { case TYPE_STRING: tcscpy_s(Data,Size/sizeof(tchar_t),Value); break; case TYPE_BINARY: for (i=0;i=0 && (b=Hex(Value[i*2+1]))>=0;++i) ((uint8_t*)Data)[i] = (uint8_t)(a*16+b); break; case TYPE_RGB: *(rgbval_t*)Data = StringToRGB(Value); break; case TYPE_TICK: *(tick_t*)Data = StringToTick(Value); break; case TYPE_SIZE: *(size_t*)Data = StringToIntEx(Value,Flags,State); break; case TYPE_INT: if ((Flags & TUNIT_MASK)==TUNIT_PERCENT) { cc_fraction f; StringToFraction(Value,&f,1); *(int*)Data = ScaleRound(PERCENT_ONE,f.Num,f.Den); } else if ((Flags & TUNIT_MASK)==TUNIT_HOTKEY) *(int*)Data = StringToHotKey(Value); else *(int*)Data = StringToIntEx(Value,Flags,State); break; case TYPE_INT8: *(uint8_t*)Data = (uint8_t)StringToIntEx(Value,Flags,State); break; case TYPE_INT16: *(uint16_t*)Data = (uint16_t)StringToIntEx(Value,Flags,State); break; case TYPE_GUID: StringToGUID(Value,(cc_guid*)Data); break; case TYPE_DBNO: //TODO: support for 64 bits case TYPE_DATETIME: case TYPE_INT32: *(int32_t*)Data = (int32_t)StringToIntEx(Value,Flags,State); break; case TYPE_INT64: *(int64_t*)Data = StringToInt64(Value); break; case TYPE_BOOL_BIT: case TYPE_BOOLEAN: *(bool_t*)Data = StringToInt(Value,-1); break; case TYPE_FOURCC: *(fourcc_t*)Data = StringToFourCC(Value,(Flags & TUNIT_MASK)==TUNIT_UPPER); break; case TYPE_FIX16: StringToFraction(Value,&f,0); *(int*)Data = Scale32(FIX16_UNIT,f.Num,f.Den); break; case TYPE_FRACTION: ((cc_fraction*)Data)->Num = 0; ((cc_fraction*)Data)->Den = 0; if (tcschr(Value,':')) { stscanf(Value,T("%d:%d"),&a,&b); ((cc_fraction*)Data)->Num = a; ((cc_fraction*)Data)->Den = b; } else StringToFraction(Value,(cc_fraction*)Data,(Flags & TUNIT_MASK)==TUNIT_PERCENT); break; case TYPE_NODE: if (!State) return 0; return StringToNode((node**)Data,State,&Value); case TYPE_PIN: if (!State) return 0; return StringToPin((pin*)Data,&DataDef,State,&Value); case TYPE_POINT: case TYPE_POINT16: return ExprToData(Data,&Size,Flags,State,&Value); default: return 0; } return 1; } NOINLINE bool_t ParserAttrib(parser* p, void* Data, size_t Size, dataflags Flags, exprstate* State) { tchar_t Value[MAXDATA+64]; if (!ParserAttribString(p,Value,TSIZEOF(Value))) return 0; return StringToData(Data,Size,Flags,State,Value); } void ExprState(exprstate* State, node* Node, dataid Id, dataflags Flags) { if (Flags & TFLAG_ENUM) State->EnumList = (const tchar_t*)Node_Meta(Node,Id,META_PARAM_ENUMNAME); else State->EnumList = NULL; if ((Flags & TYPE_MASK) == TYPE_NODE) State->ClassId = (fourcc_t)Node_Meta(Node,Id,META_PARAM_CLASS); } bool_t ParserValueData(const tchar_t* Value, node* Node, const datadef* DataDef, exprstate* State, parserexpradd ExprAdd, bool_t ExprSave) { uint8_t Data[MAXDATA]; size_t Size = Node_MaxDataSize(Node,DataDef->Id,DataDef->Flags,META_PARAM_SET); datatype Type = DataDef->Flags & TYPE_MASK; State->Context = Node_Context(Node); ExprState(State,Node,DataDef->Id,DataDef->Flags); if (Type == TYPE_ARRAY) { bool_t Result; array Array; const tchar_t* Expr = Value; dataflags Flags = (dataflags)Node_Meta(Node,DataDef->Id,META_PARAM_ARRAY_TYPE); ArrayInit(&Array); for (;;) { size_t Size = sizeof(Data); if (!ExprToData(Data,&Size,Flags,State,&Expr)) break; if (!ArrayAppend(&Array,Data,Size,0)) break; ExprIsSymbol(&Expr,','); } Result = Node_SET(Node,DataDef->Id,&Array) == ERR_NONE; ArrayClear(&Array); return Result; } if (ExprAdd && !State->EnumList && (Type == TYPE_INT || Type == TYPE_STRING || Type == TYPE_FRACTION || Type == TYPE_FIX16 || Type == TYPE_RGB || Type == TYPE_BOOLEAN || Type == TYPE_BOOL_BIT || Type == TYPE_FOURCC || Type == TYPE_DBNO || Type == TYPE_TICK || Type == TYPE_SIZE || Type == TYPE_PIN || Type == TYPE_EXPR)) { // try to detect constants to skip expression evaluation... const tchar_t* s = Value; if (Type != TYPE_STRING && Type != TYPE_EXPR && Type != TYPE_FOURCC) { if (*s=='-' || *s=='+') ++s; for (;*s;++s) if (IsAlpha(*s) || tcschr(T("+-<>()=*/!%"),*s)!=NULL) break; } if (*s) return ExprAdd(Node,DataDef,State,Value,ExprSave) == ERR_NONE; } if (!StringToData(Data,sizeof(Data),DataDef->Flags,State,Value)) { // try reference resolving if (Type == TYPE_NODE && ExprAdd) return ExprAdd(Node,DataDef,State,Value,ExprSave) == ERR_NONE; // save for later return ExprAdd && ExprSave && ExprAdd(Node,DataDef,NULL,Value,1) == ERR_NONE; } return Node_Set(Node,DataDef->Id,Data,Size) == ERR_NONE; } bool_t ParserAttribData(parser* p, node* Node, const datadef* DataDef, exprstate* State, parserexpradd ExprAdd, bool_t ExprSave) { tchar_t Value[MAXDATA+64]; if (!ParserAttribString(p,Value,TSIZEOF(Value))) return 0; return ParserValueData(Value,Node,DataDef,State,ExprAdd,ExprSave); } err_t TextPrintf(textwriter* p, const tchar_t* Msg,...) { tchar_t s[MAXLINE]; va_list Arg; va_start(Arg,Msg); vstprintf_s(s,TSIZEOF(s),Msg,Arg); va_end(Arg); return TextWrite(p,s); } err_t Stream_Printf(stream* Stream, const tchar_t* Msg,...) { tchar_t s[MAXLINE]; va_list Arg; textwriter p; if (!Stream) return ERR_INVALID_PARAM; p.Stream = Stream; p.CC = Parser_Context(Stream)->ToUTF8; va_start(Arg,Msg); vstprintf_s(s,TSIZEOF(s),Msg,Arg); va_end(Arg); return TextWrite(&p,s); } err_t TextWrite(textwriter* p, const tchar_t* Msg) { size_t i; char s[MAXLINE]; CharConvST(p->CC,s,sizeof(s),Msg); i = strlen(s); #if defined(TARGET_WIN) || defined(TARGET_SYMBIAN) { char* nl = s; while (i+1Stream,s,i,NULL); } static NOINLINE void DumpPtr(textwriter* Text, const tchar_t* Name, node* Node, dataid Id, tchar_t* Value, size_t ValueLen) { TextAttrib(Text,Name,&Node,TYPE_PTR); if (Node) { fourcc_t ClassId = Node_ClassId(Node); tcscpy_s(Value,ValueLen,Name); tcscat_s(Value,ValueLen,T("_Class")); TextAttrib(Text,Value,&ClassId,TYPE_FOURCC); } if (Id) { int i = (int)Id; tcscpy_s(Value,ValueLen,Name); tcscat_s(Value,ValueLen,T("_Id")); TextAttrib(Text,Value,&i,TYPE_INT); } } NOINLINE bool_t DataToString(tchar_t* Value, size_t ValueLen, const void* Data, size_t Size, dataflags Type) { cc_fraction f; size_t i; bool_t Display = (Type & TFLAG_DISPLAY)!=0; if (!Size) Size = NodeTypeSize(Type); if (Type & TFLAG_DEFAULT) { if ((Type & TYPE_MASK) == TYPE_STRING) { if (((const tchar_t*)Data)[0]==0) return 0; } else { for (i=0;i 0xFFFFFFFF Int64ToString(Value,ValueLen,*(size_t*)Data,0); #else IntToString(Value,ValueLen,*(size_t*)Data,0); #endif break; case TYPE_INT: if ((Type & TUNIT_MASK)==TUNIT_PERCENT) { cc_fraction f; f.Num = *(int*)Data; f.Den = PERCENT_ONE; FractionToString(Value,ValueLen,&f,-1,1); } else if ((Type & TUNIT_MASK)==TUNIT_HOTKEY) HotKeyToString(Value,ValueLen,*(int*)Data,NULL,NULL); else if (Display && (Type & TUNIT_MASK)==TUNIT_BYTERATE) ByteRateToString(Value,ValueLen,*(int*)Data); else { IntToString(Value,ValueLen,*(int*)Data,0); if (Display && (Type & TUNIT_MASK)==TUNIT_KBYTE) tcscat_s(Value,ValueLen,T(" KB")); } break; case TYPE_INT8: IntToString(Value,ValueLen,*(uint8_t*)Data,0); break; case TYPE_INT16: IntToString(Value,ValueLen,*(int16_t*)Data,0); break; case TYPE_GUID: GUIDToString(Value,ValueLen,(const cc_guid*)Data); break; case TYPE_DBNO: //TODO: support for 64 bits case TYPE_DATETIME: case TYPE_INT32: IntToString(Value,ValueLen,*(int32_t*)Data,(Type & TUNIT_MASK)==TUNIT_HEX); break; case TYPE_INT64: Int64ToString(Value,ValueLen,*(int64_t*)Data,(Type & TUNIT_MASK)==TUNIT_HEX); break; case TYPE_BOOL_BIT: case TYPE_BOOLEAN: IntToString(Value,ValueLen,(int32_t)*(bool_t*)Data,0); break; case TYPE_FOURCC: FourCCToString(Value,ValueLen,*(fourcc_t*)Data); break; case TYPE_POINT: stprintf_s(Value,ValueLen,T("%d,%d"),((cc_point*)Data)->x,((cc_point*)Data)->y); break; case TYPE_RECT: stprintf_s(Value,ValueLen,T("%d,%d,%d,%d"),((cc_rect*)Data)->x,((cc_rect*)Data)->y,((cc_rect*)Data)->Width,((cc_rect*)Data)->Height); break; case TYPE_FIX16: f.Num = *(int*)Data; f.Den = FIX16_UNIT; FractionToString(Value,ValueLen,&f,0,3); break; case TYPE_FRACTION: if ((Type & TUNIT_MASK)==TUNIT_PERCENT) FractionToString(Value,ValueLen,(cc_fraction*)Data,Display?1:-1,2); else if (Display) FractionToString(Value,ValueLen,(cc_fraction*)Data,0,3); //fps needs 3 decimal else stprintf_s(Value,ValueLen,T("%d:%d"),((cc_fraction*)Data)->Num,((cc_fraction*)Data)->Den); break; case TYPE_PIN: PinToString(Value,ValueLen,(pin*)Data,NULL); break; case TYPE_NODE: NodeToString(Value,ValueLen,*(node**)Data,NULL); break; case TYPE_STRING: tcscpy_s(Value,ValueLen,(tchar_t*)Data); break; } return 1; } void TextAttribEx(textwriter* Text, const tchar_t* Name, const void* Data, size_t Size, dataflags Type) { tchar_t Value[MAXDATA+64]; tchar_t *c; size_t i; if (DataToString(Value,TSIZEOF(Value),Data,Size,Type)) { switch (Type & TYPE_MASK) { case TYPE_PIN: case TYPE_PACKET: DumpPtr(Text,Name,((pin*)Data)->Node,((pin*)Data)->Id,Value,TSIZEOF(Value)); return; case TYPE_NODE: DumpPtr(Text,Name,*(node**)Data,0,Value,TSIZEOF(Value)); return; case TYPE_STRING: for (i=0,c=(tchar_t*)Data;*c && i': s = T(">"); break; default: s = NULL; break; } if (s) { tcscpy_s(Value+i,TSIZEOF(Value)-i,s); i += tcslen(Value+i); } else Value[i++] = *c; } assert(iTSIZEOF(Value)-1) i=TSIZEOF(Value)-1; Value[i] = 0; break; case TYPE_PTR: stprintf_s(Value,TSIZEOF(Value),T("%08x"),*(uint32_t*)Data); break; } TextPrintf(Text,T(" %s=\"%s\""),Name,Value); } } void TextAttrib(textwriter* Text, const tchar_t* Name, const void* Data, dataflags Type) { TextAttribEx(Text,Name,Data,0,Type); } void TextElementBegin(textwriter* Out, textwriter* In, const tchar_t* Element) { if (!In->HasChild) { In->HasChild = 1; if (In->InsideContent) TextWrite(In,T(">")); else TextWrite(In,T(">\n")); } Out->CC = In->CC; Out->Stream = In->Stream; Out->HasChild = 0; Out->SafeFormat = In->SafeFormat; Out->InsideContent = In->Deep==0; Out->Deep = In->InsideContent ? 0 : In->Deep+2; Out->Element = Element; TextPrintf(Out,T("%*c%s"),In->Deep?Out->Deep:0, '<',Element); } void TextElementEnd(textwriter* Text) { if (Text->HasChild) { if (Text->InsideContent) TextPrintf(Text,T(" "),Text->Element); else TextPrintf(Text,T("%*c/%s>\n"),Text->Deep,'<',Text->Element); } else { if (Text->SafeFormat) TextPrintf(Text,T(">"),Text->Element); else TextWrite(Text,T("/>")); if (!Text->InsideContent) TextWrite(Text,T("\n")); } } void TextElementEndData(textwriter* Text, const tchar_t *Value) { if (Text->HasChild) TextPrintf(Text,T("%s%*c/%s>\n"),Value, Text->Deep,'<',Text->Element); else TextPrintf(Text,T(">%s\n"), Value, Text->Element); } void TextElementAppendData(textwriter* Text, const tchar_t *Value) { if (Text->Deep==1 && tcsisame_ascii(Value,T(" "))) return; // root element if (Text->HasChild) TextWrite(Text,Value); else { TextPrintf(Text,T(">%s"), Value); Text->HasChild = 1; Text->Deep = 0; } } void TextElementXML(parsercontext *Context, textwriter* Text, const tchar_t* Root) { assert(Text->Stream); Text->CC = Context->ToUTF8; Text->Element = Root; Text->Deep = 1; Text->HasChild = 0; Text->InsideContent = 0; Text->SafeFormat = 0; TextPrintf(Text,T("\n<%s"),Root); } NOINLINE bool_t ExprSkipAfter(const tchar_t** p,int ch) { const tchar_t* s = *p; for (;*s;++s) if ((ch && *s == ch) || (!ch && IsSpace(*s))) { *p = s+1; if (!ch) ExprSkipSpace(p); // skip other spaces too return 1; } *p = s; return 0; } NOINLINE void ExprSkipSpace(const tchar_t** p) { const tchar_t* s = *p; while (IsSpace(*s)) ++s; *p = s; } NOINLINE void ExprTrimSpace(tchar_t** p) { if (*p[0]) { tchar_t* s = *p+tcslen(*p)-1; while (s>=*p && IsSpace(*s)) { *s = 0; s--; } } } NOINLINE bool_t ExprCmd(const tchar_t** Expr, tchar_t* Out, size_t OutLen) { const tchar_t* s; bool_t Quote=0; ExprSkipSpace(Expr); s = *Expr; if (*s == '\0') return 0; assert(*s && (Quote || !IsSpace(*s))); for (;*s && (Quote || !IsSpace(*s));++s) { if (*s == '"') { Quote = !Quote; continue; } if (OutLen>1) { *(Out++) = *s; --OutLen; } } *Expr = s; if (OutLen>0) *Out=0; return 1; } static NOINLINE bool_t ReadHex(const tchar_t** p,intptr_t* Out,bool_t RGB, bool_t Neg); NOINLINE bool_t ExprIsTokenEx(const tchar_t** p,const tchar_t* Name,...) { const tchar_t* s = *p; bool_t Long = 0; va_list Arg; va_start(Arg, Name); if (!*Name) return 0; ExprSkipSpace(&s); while (*Name && *s) { if (*Name == ' ') { ExprSkipSpace(&s); ++Name; } else if (*Name == '%') { int IntSize = 0; ++Name; if (IsDigit(*Name)) { IntSize = *Name - '0'; ++Name; } while (*Name == 'l') { Long=1; ++Name; // long } if (*Name=='I' && *(Name+1)=='6' && *(Name+2)=='4') { Long=1; Name += 3; } if (*Name == 'd') { if (Long) { if ((!IntSize && !ExprIsInt64(&s,va_arg(Arg,int64_t*)))||(IntSize && !ExprIsInt64Ex(&s,IntSize,va_arg(Arg,int64_t*)))) break; } else { if ((!IntSize && !ExprIsInt(&s,va_arg(Arg,intptr_t*)))||(IntSize && !ExprIsIntEx(&s,IntSize,va_arg(Arg,intptr_t*)))) break; } ++Name; } if (*Name == 'x') { if (!ReadHex(&s,va_arg(Arg,intptr_t*),0,0)) break; ++Name; } else if (*Name == 's') { tchar_t *Out = va_arg(Arg,tchar_t*); size_t OutLen = va_arg(Arg,size_t); ++Name; while (OutLen>1 && *s && (*s != *Name && (*Name || *s != ' '))) { *Out++ = *s++; OutLen--; } *Out = 0; } else if (*Name == '%') { if (*s == '%') { ++s; ++Name; } } } else { size_t n; for (n=1;Name[n] && Name[n]!=' ' && Name[n]!='%';++n) {} if (tcsnicmp_ascii(s,Name,n)!=0) break; Name += n; s += n; } } va_end(Arg); if (*Name==0 && (!IsAlpha(Name[-1]) || !IsAlpha(*s))) { *p = s; return 1; } return 0; } NOINLINE bool_t ExprIsToken(const tchar_t** p,const tchar_t* Name) { return ExprIsTokenEx(p,"%s",Name); } uint32_t StringToIP(const tchar_t *Address) { uint32_t Result = 0; tchar_t *s; while ((s = tcschr(Address,T('.')))!=NULL) { *s++ = 0; Result <<= 8; Result |= StringToInt(Address,0); Address = s; } Result <<= 8; Result |= StringToInt(Address,0); return Result; } static const uint8_t Base64[] = { 0x3e,0x80,0x80,0x80,0x3f,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x80, 0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, 0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19, 0x80,0x80,0x80,0x80,0x80,0x80,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23, 0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33 }; static tchar_t Base64Char(int Value) { if (Value < 26) return (tchar_t)(Value + 'A'); if (Value < 52) return (tchar_t)(Value - 26 + 'a'); if (Value < 62) return (tchar_t)(Value - 52 + '0'); if (Value == 62) return '+'; assert(Value == 63); return '/'; } bool_t BufferToBase64(tchar_t *Out, size_t OutLen, const uint8_t *Buffer, size_t BufferSize) { while (BufferSize >= 3 && OutLen > 4) // treat packets of 3 bytes at once { Out[0] = Base64Char(Buffer[0] >> 2); Out[1] = Base64Char(((Buffer[0]&0x03)<<4) | (Buffer[1]>>4)); Out[2] = Base64Char(((Buffer[1]&0x0F)<<2) | (Buffer[2]>>6)); Out[3] = Base64Char(Buffer[2]&0x3F); BufferSize -= 3; Buffer += 3; OutLen -= 4; Out += 4; } if (BufferSize--) { if (OutLen < 5) return 0; // not enough room in the output buffer Out[0] = Base64Char(Buffer[0] >> 2); if (BufferSize--) Out[1] = Base64Char(((Buffer[0]&0x03)<<4) | (Buffer[1]>>4)); else Out[1] = Base64Char((Buffer[0]&0x03)<<4); if (BufferSize == (size_t)-1) Out[2] = '='; else if (BufferSize--) Out[2] = Base64Char(((Buffer[1]&0x0F)<<2) | (Buffer[2]>>6)); else Out[2] = Base64Char((Buffer[1]&0x0F)<<2); if (BufferSize == (size_t)-1) Out[3] = '='; else Out[3] = Base64Char(Buffer[2]&0x3F); Out += 4; } Out[0] = 0; return 1; } NOINLINE size_t ExprIsBase64(const tchar_t** p,uint8_t* Out,size_t OutSize) { size_t n; size_t v=0; uint8_t* Out0 = Out; ExprSkipSpace(p); for (n=0;**p;++n,++(*p)) { if (**p == '=') { while (**p == '=') ++(*p); break; } if (**p < 43 || **p >= 43+sizeof(Base64) || Base64[**p-43] == 0x80) break; v = (v<<6) + Base64[**p-43]; if ((n & 3) && OutSize>0) { --OutSize; *(Out++) = (uint8_t)(v >> (6 - (n & 3)*2)); } } return Out-Out0; } NOINLINE bool_t ExprIsName(const tchar_t** p,tchar_t* Out,size_t OutLen, const tchar_t* Delimiter) { bool_t Found = 0; ExprSkipSpace(p); for (;**p && !IsSpace(**p) && tcschr(Delimiter,**p)==NULL;++(*p)) if (OutLen>1) { --OutLen; *(Out++) = **p; Found = 1; } if (OutLen) *Out = 0; return Found; } NOINLINE bool_t ExprIsSymbol(const tchar_t** p,int ch) { if (**p) { ExprSkipSpace(p); if (**p == ch) { ++(*p); return 1; } } return 0; } NOINLINE bool_t ExprIsSymbol2(const tchar_t** p,int ch, int ch2) { ExprSkipSpace(p); if ((*p)[0] == ch && (*p)[1]==ch2) { (*p)+=2; return 1; } return 0; } NOINLINE void ExprParamEnd(const tchar_t** p) { ExprIsSymbol(p,')'); } NOINLINE bool_t ExprParamNext(const tchar_t** p) { if (ExprIsSymbol(p,',')) return 1; ExprParamEnd(p); return 0; } static NOINLINE bool_t ReadHex(const tchar_t** p,intptr_t* Out,bool_t RGB, bool_t Neg) { const tchar_t* s = *p; intptr_t v = 0; intptr_t w; size_t n = 0; if ((w = Hex(*s))<0) return 0; do { ++n; v = v*16+w; } while ((w = Hex(*(++s)))>=0); if (RGB) { if (n<=6) v <<= 8; v = INT32BE(v); } if (Neg) v = -v; *Out = v; *p = s; return 1; } NOINLINE bool_t ExprIsHex(const tchar_t** p,intptr_t* Out) { const tchar_t* s = *p; bool_t Pos = *s == '+'; bool_t Neg = *s == '-'; if (Neg || Pos) ++s; if (s[0]=='0' && s[1]=='x') { s += 2; if (ReadHex(&s,Out,0,Neg)) { *p = s; return 1; } } return 0; } NOINLINE bool_t ExprIsRGB(const tchar_t** p,intptr_t* Out) { const tchar_t* s = *p; if (*(s++) == '#' && ReadHex(&s,Out,1,0)) { *p = s; return 1; } return 0; } NOINLINE bool_t ExprIsFourCC(const tchar_t** p,intptr_t* Out) { const tchar_t* s = *p; if (*(s++) == '@' && *(s++) == '\'' && ExprSkipAfter(&s,'\'') && (s <= *p+7)) { tchar_t v[16]; tcsncpy_s(v,TSIZEOF(v),*p+2,s-*p-3); *Out = StringToFourCC(v,0); *p = s; return 1; } return 0; } NOINLINE bool_t ExprIsIntEx(const tchar_t** p,int Size,intptr_t* Out) { const tchar_t* s = *p; intptr_t v = 0; bool_t Pos = *s == '+'; bool_t Neg = *s == '-'; if (Neg || Pos) ++s; if (!IsDigit(*s)) return 0; do { v = v*10 + (*s-'0'); } while (--Size && IsDigit(*(++s))); if (Size!=0) return 0; if (Neg) v = -v; *Out = v; *p = s+1; return 1; } NOINLINE bool_t ExprIsInt64Ex(const tchar_t** p,int Size,int64_t* Out) { const tchar_t* s = *p; int64_t v = 0; bool_t Pos = *s == '+'; bool_t Neg = *s == '-'; if (Neg || Pos) ++s; if (!IsDigit(*s)) return 0; do { v = v*10 + (*s-'0'); } while (--Size && IsDigit(*(++s))); if (Size!=0) return 0; if (Neg) v = -v; *Out = v; *p = s+1; return 1; } NOINLINE bool_t ExprIsInt(const tchar_t** p,intptr_t* Out) { const tchar_t* s = *p; intptr_t v = 0; bool_t Pos = *s == '+'; bool_t Neg = *s == '-'; if (Neg || Pos) ++s; if (!IsDigit(*s)) return 0; do { v = v*10 + (*s-'0'); } while (IsDigit(*(++s))); if (Neg) v = -v; *Out = v; *p = s; return 1; } NOINLINE bool_t ExprIsInt64(const tchar_t** p,int64_t* Out) { const tchar_t* s = *p; int64_t v = 0; bool_t Pos = *s == '+'; bool_t Neg = *s == '-'; if (Neg || Pos) ++s; if (!IsDigit(*s)) return 0; do { v = v*10 + (*s-'0'); } while (IsDigit(*(++s))); if (Neg) v = -v; *Out = v; *p = s; return 1; } NOINLINE bool_t ExprIsFrac(const tchar_t** p,cc_fraction* Out) { int64_t Num,Den; intptr_t v; if (!ExprIsInt(p,&v)) return 0; Num = v; Den = 1; if (**p == '.' || **p == ',') { ++(*p); for (;IsDigit(**p);++(*p)) { Num = Num*10 + (**p-'0'); Den *= 10; } } SimplifyFrac(Out,Num,Den); return 1; } bool_t ExprIsPoint(const tchar_t** p, cc_point* Out) { intptr_t x,y; if (ExprIsTokenEx(p,T("{ %d , %d }"),&x,&y)) { Out->x = (int)x; Out->y = (int)y; return 1; } return 0; } #define MAX_GCD_ITER 128 void SimplifyFrac(cc_fraction* f, int64_t Num, int64_t Den) { bool_t Sign = (Num<0) != (Den<0); Num = _abs(Num); Den = _abs(Den); if (Num>INT_MAX || Den>INT_MAX) { int64_t a = Num; int64_t b = Den; size_t n; for (n=0;n0 && b>0;++n) { int64_t c = a; a = b % a; b = c; } if (n1) { Num /= b; Den /= b; } while (Num>INT_MAX || Den>INT_MAX) { Num >>= 1; Den >>= 1; } } f->Num = (int)(Sign?-Num:Num); f->Den = (int)Den; } void DoubleToFrac(cc_fraction* f,int64_t v) { if (!v) { f->Num = 0; f->Den = 1; } else { int e = (int)(((v >> 52) & 0xFFF) - 1023); SimplifyFrac(f,(v & LL(0xFFFFFFFFFFFFF))|LL(0x10000000000000),LL(1)<<(52-e)); if (v<0) f->Num = -f->Num; } } void NodeParamName(node* p, dataid Id, tchar_t* Name, size_t NameLen) { const tchar_t* ShortName = (const tchar_t*)Node_Meta(p,Id,META_PARAM_NAME); if (ShortName) tcscpy_s(Name,NameLen,ShortName); else if (Id>(1<<24)) FourCCToString(Name,NameLen,(fourcc_t)Id); else if (Node_Get(p,Id|DATA_DYNNAME,Name,NameLen*sizeof(tchar_t))!=ERR_NONE) stprintf_s(Name,NameLen,T("_%04x"),Id); } static bool_t CheckHex(const tchar_t* s) { for (;*s;++s) if (Hex(*s)<0) return 0; return 1; } bool_t NodeFindDef(node* p,const tchar_t* Token,datadef* DataDef) { dataid Id; if (Token[0]=='_' && CheckHex(Token+1)) Id = StringToInt(Token+1,1); else { Id = Node_FindParam(p,Token); if (!Id) Id = StringToFourCC(Token,0); } return NodeDataDef(p,Id,DataDef); } void TextSerializeNode(textwriter* Text, node* p, uint_fast32_t Mask, uint_fast32_t Filter) { array List; datadef* i; NodeEnumDef(p,&List); for (i=ARRAYBEGIN(List,datadef);i!=ARRAYEND(List,datadef);++i) if ((i->Flags & Mask)==Filter) { tchar_t Name[32]; uint8_t Data[MAXDATA]; size_t Size = Node_MaxDataSize(p,i->Id,i->Flags,META_PARAM_GET); assert((i->Id & ~DATA_ENUM)==i->Id); assert(Size <= sizeof(Data)); if (Size) { err_t Result = Node_Get(p,i->Id,Data,Size); if (Result == ERR_NONE || Result == ERR_NOT_SUPPORTED) // ERR_NOT_SUPPORTED for subclasses that don't support a param of the main class { NodeParamName(p,i->Id,Name,TSIZEOF(Name)); TextAttribEx(Text,Name,Data,Size,i->Flags); /* TODO: support dumping packetformat information (example for crash.txt) if ((i->Flags & TYPE_MASK) == TYPE_PACKET && Node_Get(p,i->Id|PIN_FORMAT,Data,sizeof(packetformat)) == ERR_NONE) { tcscat_s(Name,TSIZEOF(Name),T("_Format")); TextAttrib(Text,Name,Data,TYPE_PACKETFORMAT); } */ } } } ArrayClear(&List); } void ParserImport(parser* Parser,node* Node) { tchar_t Token[MAXTOKEN]; exprstate State; memset(&State,0,sizeof(State)); while (ParserIsAttrib(Parser,Token,MAXTOKEN)) { datadef DataDef; if (NodeFindDef(Node,Token,&DataDef)) ParserAttribData(Parser,Node,&DataDef,&State,NULL,0); else ParserAttribSkip(Parser); } } void ParserImportNested(parser* Parser,node* Node) { if (Node) ParserImport(Parser,Node); if (Node && Node_IsPartOf(Node,NODETREE_CLASS)) { tchar_t Token[MAXTOKEN]; while (ParserIsElementNested(Parser,Token,MAXTOKEN)) { node* Child = NodeCreate(Node,StringToFourCC(Token,0)); ParserImportNested(Parser,Child); if (Child) NodeTree_SetParent(Child,Node,NULL); } } else ParserElementSkipNested(Parser); } #define LANG_STRINGS_OFFSET 0x100 static err_t GetStr(node* p,dataid Id, tchar_t *Data, size_t Size) { if (Id-LANG_STRINGS_OFFSET < DATA_ENUM) tcscpy_s(Data,Size/sizeof(tchar_t),StrTab_GetPos(&Parser_Context(p)->StrTab,Id-LANG_STRINGS_OFFSET)); else if ((Id-LANG_STRINGS_OFFSET) & DATA_DYNNAME) StrTab_GetPosName(&Parser_Context(p)->StrTab,(Id-LANG_STRINGS_OFFSET) & ~DATA_DYNNAME, Data, Size/sizeof(tchar_t)); else return ERR_INVALID_PARAM; return ERR_NONE; } static uintptr_t MetaStr(node* p,dataid Id,datameta Meta) { if (Meta==META_PARAM_TYPE) return TYPE_STRING|TFLAG_RDONLY; else if (Meta == META_PARAM_NAME) return 0; // get it with Id|DATA_DYNNAME return INHERITED(p,node_vmt,LANG_STRINGS_ID)->Meta(p,Id-LANG_STRINGS_OFFSET,Meta); } static dataid FindStrParam(node* p,const tchar_t* Token) { fourcc_t ClassId; int No; if (tcslen(Token)!=8) return 0; ClassId = StringToFourCC(Token,0); No = StringToInt(Token+4,1); return (dataid)StrTab_Pos(&Parser_Context(p)->StrTab,ClassId,No) + LANG_STRINGS_OFFSET; } static void EnumStr(node *p,array* List) { dataid Id,*i; size_t StrSize = ArraySize(&Parser_Context(p)->StrTab.Table); StrSize /= STRTAB_ITEMSIZE; ArrayInit(List); ArrayResize(List,StrSize*sizeof(dataid),0); i = ARRAYBEGIN(*List,dataid); for (Id = 0;Id < StrSize;++Id,++i) *i = Id+LANG_STRINGS_OFFSET; } static void NodeDumpObject(node* p,textwriter* Text) { textwriter Level; array Children; tchar_t Element[8]; node** i; TRY_BEGIN if (!(NodeClassFlags(p) & CFLAG_LOCAL)) // example skin UI stuff { FourCCToString(Element,TSIZEOF(Element),Node_ClassId(p)); TextElementBegin(&Level,Text,Element); TextAttrib(&Level,T("Addr"),&p,TYPE_PTR); TextSerializeNode(&Level,p,TFLAG_NODUMP,0); ArrayInit(&Children); if (Node_GET(p,NODE_CHILDREN,&Children)==ERR_NONE) for (i=ARRAYBEGIN(Children,node*);i!=ARRAYEND(Children,node*);++i) NodeDumpObject(*i,&Level); ArrayClear(&Children); TextElementEnd(&Level); } TRY_END } void NodeDump(nodecontext* p,textwriter* Text) { //no NodeLock, because may be stayed locked when dumping after crash node **i; for (i=ARRAYBEGIN(p->NodeSingleton,node*);i!=ARRAYEND(p->NodeSingleton,node*);++i) if (*i) NodeDumpObject(*i,Text); } META_START(LangStr_Class,LANG_STRINGS_ID) META_CLASS(FLAGS,CFLAG_SINGLETON|CFLAG_LOCAL) META_PARAM(STRING,NODE_ID,T("LangStr")) META_VMT(TYPE_FUNC,node_vmt,Get,GetStr) META_VMT(TYPE_FUNC,node_vmt,Meta,MetaStr) META_VMT(TYPE_FUNC,node_vmt,Enum,EnumStr) META_VMT(TYPE_FUNC,node_vmt,FindParam,FindStrParam) META_END(NODE_CLASS) bcmatroska2-5.3.101/corec/corec/helpers/parser/strtab.c000066400000000000000000000133521462133141200226610ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" #define TABLEALIGN 1024 typedef struct stringdef { fourcc_t Class; int32_t Id; // tchar_t s[] } stringdef; void StrTab_Init(strtab* p, const cc_memheap* Heap, size_t Alloc) { assert(STRTAB_ITEMSIZE == sizeof(stringdef)); p->Heap = Heap; ArrayInit(&p->Table); // not using Heap, because we need direct write acess ArrayAlloc(&p->Table,Alloc,TABLEALIGN); p->Lock = LockCreate(); } NOINLINE void StrTab_Clear(strtab* p) { stringdef **i; LockEnter(p->Lock); for (i=ARRAYBEGIN(p->Table,stringdef*);i!=ARRAYEND(p->Table,stringdef*);++i) MemHeap_Free(p->Heap,*i,sizeof(stringdef)+tcsbytes((tchar_t*)(*i+1))); ArrayClear(&p->Table); LockLeave(p->Lock); } void StrTab_Done(strtab* p) { StrTab_Clear(p); LockDelete(p->Lock); p->Lock = NULL; } static int CmpDef(const void* UNUSED_PARAM(p), const stringdef* const* pa, const stringdef* const* pb) { const stringdef* a = *pa; const stringdef* b = *pb; if (a->Class < b->Class || (a->Class == b->Class && a->Id < b->Id)) return -1; if (a->Class > b->Class || a->Id > b->Id) return 1; return 0; } void StrTab_Add(strtab* p, bool_t Secondary, fourcc_t Class, int32_t Id, const tchar_t* s) { size_t Pos; bool_t Found; stringdef Def; stringdef* Ptr = &Def; Def.Class = Class; Def.Id = Id; if (s && !*s) s = NULL; LockEnter(p->Lock); // already the same? Pos = ArrayFind(&p->Table,stringdef*,&Ptr,(arraycmp)CmpDef,NULL,&Found); if (Found) { Ptr = ARRAYBEGIN(p->Table,stringdef*)[Pos]; if (Secondary || (s && tcscmp(s,(tchar_t*)(Ptr+1))==0)) s = NULL; // keep old else { MemHeap_Free(p->Heap,Ptr,sizeof(stringdef)+tcsbytes((tchar_t*)(Ptr+1))); ArrayDelete(&p->Table,Pos*sizeof(stringdef*),sizeof(stringdef*)); } } if (s) { size_t Size = tcsbytes(s); Ptr = MemHeap_Alloc(p->Heap,sizeof(stringdef)+Size,0); if (Ptr) { MemHeap_Write(p->Heap,Ptr,&Def,0,sizeof(stringdef)); MemHeap_Write(p->Heap,Ptr,s,sizeof(stringdef),Size); ArrayAdd(&p->Table,stringdef*,&Ptr,(arraycmp)CmpDef,NULL,TABLEALIGN); } } LockLeave(p->Lock); } int StrTab_Enum(strtab* p, fourcc_t Class, size_t Count) { int Result = -1; stringdef **i; LockEnter(p->Lock); for (i=ARRAYBEGIN(p->Table,stringdef*);i!=ARRAYEND(p->Table,stringdef*);++i) if ((*i)->Class==Class && Count--==0) { Result = (*i)->Id; break; } LockLeave(p->Lock); return Result; } static NOINLINE size_t FindPos(strtab *p, fourcc_t Class, int Id) { size_t Pos; bool_t Found; stringdef Def; stringdef* Ptr = &Def; Def.Class = Class; Def.Id = Id; Pos = ArrayFind(&p->Table,stringdef*,&Ptr,(arraycmp)CmpDef,NULL,&Found); if (!Found) Pos = STRTAB_INVALID_POS; return Pos; } static NOINLINE const tchar_t *GetPos(strtab *p, size_t Pos) { if (Pos==STRTAB_INVALID_POS || Pos>=ARRAYCOUNT(p->Table,stringdef*)) return T(""); return (const tchar_t*)(ARRAYBEGIN(p->Table,stringdef*)[Pos]+1); } size_t StrTab_Pos(strtab *p, fourcc_t Class, int Id) { size_t Pos; LockEnter(p->Lock); Pos = FindPos(p,Class,Id); LockLeave(p->Lock); return Pos; } const tchar_t *StrTab_GetPos(strtab *p, size_t Pos) { const tchar_t *s; LockEnter(p->Lock); s = GetPos(p,Pos); LockLeave(p->Lock); return s; } const tchar_t* StrTab_Find(strtab* p, fourcc_t Class, int Id) { const tchar_t *s; LockEnter(p->Lock); s = GetPos(p,FindPos(p,Class,Id)); LockLeave(p->Lock); return s; } bool_t StrTab_Get(strtab* p, fourcc_t Class, int Id, tchar_t* Out, size_t OutLen) { size_t Pos; LockEnter(p->Lock); Pos = FindPos(p,Class,Id); tcscpy_s(Out,OutLen,GetPos(p,Pos)); LockLeave(p->Lock); return (Pos!=STRTAB_INVALID_POS); } void StrTab_GetPosName(strtab *p, size_t Pos, tchar_t *Out, size_t OutLen) { *Out = 0; if (Pos < ARRAYCOUNT(p->Table,stringdef*)) { stringdef *i = ARRAYBEGIN(p->Table,stringdef*)[Pos]; FourCCToString(Out,OutLen,i->Class); stprintf_s(Out+4,OutLen-4,T("%04X"),i->Id); } } bcmatroska2-5.3.101/corec/corec/helpers/parser/strtab.h000066400000000000000000000047341462133141200226720ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __STRTAB_H #define __STRTAB_H typedef struct strtab { const cc_memheap* Heap; array Table; void* Lock; } strtab; #define STRTAB_INVALID_POS ((size_t)-1) #define STRTAB_ITEMSIZE 8 void StrTab_Init(strtab*, const cc_memheap* Heap, size_t Alloc); void StrTab_Done(strtab*); void StrTab_Clear(strtab*); void StrTab_Add(strtab*, bool_t Secondary, fourcc_t Class, int32_t Id, const tchar_t* s); NODE_DLL int StrTab_Enum(strtab*, fourcc_t Class, size_t No); const tchar_t* StrTab_Find(strtab*, fourcc_t Class, int Id); bool_t StrTab_Get(strtab*, fourcc_t Class, int Id, tchar_t* Out, size_t OutLen); size_t StrTab_Pos(strtab*, fourcc_t Class, int Id); const tchar_t* StrTab_GetPos(strtab*, size_t Pos); void StrTab_GetPosName(strtab *, size_t Pos, tchar_t *Out, size_t OutLen); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/strtypes.c000066400000000000000000000456031462133141200232630ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" fourcc_t StringToFourCC(const tchar_t* In, bool_t Upper) { tchar_t s[4+1]; size_t i; if (!In[0]) return 0; tcscpy_s(s,TSIZEOF(s),In); if (Upper) tcsupr(s); for (i=1;i<4;++i) if (!s[i]) for (;i<4;++i) s[i] = '_'; return FOURCC((uint8_t)s[0],(uint8_t)s[1],(uint8_t)s[2],(uint8_t)s[3]); } size_t FourCCToString(tchar_t* Out, size_t OutLen, fourcc_t FourCC) { size_t i=0; if (OutLen) { union { fourcc_t d; uint8_t a[4]; } s; s.d = FourCC; for (i=0;i<4 && i0 && Out[i-1]=='_') --i; Out[i] = 0; } return i; } void GUIDToString(tchar_t* Out, size_t OutLen, const cc_guid* p) { stprintf_s(Out,OutLen,T("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x"), (int)p->v1,p->v2,p->v3,p->v4[0],p->v4[1],p->v4[2],p->v4[3], p->v4[4],p->v4[5],p->v4[6],p->v4[7]); } bool_t StringToGUID(const tchar_t* In, cc_guid* p) { int i,v[10]; if (In[0]=='{') ++In; if (stscanf(In,T("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x"), &p->v1,v+0,v+1,v+2,v+3,v+4,v+5,v+6,v+7,v+8,v+9) < 11) { memset(p,0,sizeof(cc_guid)); return 0; } p->v2 = (uint16_t)v[0]; p->v3 = (uint16_t)v[1]; for (i=0;i<8;++i) p->v4[i] = (uint8_t)v[2+i]; return 1; } // gcc 2.97 bug... static const tchar_t mask_d[] = T("%d"); static const tchar_t mask_dd[] = T("%d%d"); static const tchar_t mask_X[] = T("%X"); static const tchar_t mask_02X[] = T("%02X"); static const tchar_t mask_0x08X[] = T("0x%08X"); static const tchar_t mask_0x08Xx08X[] = T("0x%08X%08X"); static const tchar_t mask_rgb[] = T("#%08X"); void FractionToString(tchar_t* Out, size_t OutLen, const cc_fraction* p, int Percent, int Decimal) { int a,b,i; int_fast32_t Num = p->Num; int_fast32_t Den = p->Den; if (Percent) { while (_abs(Num) > INT_MAX/100) { Num >>= 1; Den >>= 1; } Num *= 100; } if (Den) { if (Den<0) { Num = -Num; Den = -Den; } for (i=0,b=1;i0) { // rounding int_fast32_t r = Den/(2*b); if (Num < INT_MAX-r) Num += r; else Num = INT_MAX; } a=(int)(Num/Den); Num -= a*Den; b=(int)(((int64_t)Num*b)/Den); } else a=b=0; if (Decimal) stprintf_s(Out,OutLen,T("%d.%0*d"),a,Decimal,b); else stprintf_s(Out,OutLen,mask_d,a); if (Percent>0) tcscat_s(Out,OutLen,T("%")); } void StringToFraction(const tchar_t* In, cc_fraction* Out, bool_t Percent) { ExprSkipSpace(&In); if (!ExprIsFrac(&In,Out)) { Out->Num=0; Out->Den=0; } if (Percent) Out->Den *= 100; } int StringToInt(const tchar_t* In, int Hex) { int v=0; if (Hex<0) { ExprSkipSpace(&In); Hex = In[0]=='0' && In[1]=='x'; if (Hex) In+=2; } stscanf(In,Hex ? mask_X:mask_d,&v); return v; } int64_t StringToInt64(const tchar_t* In) { int hi=0,lo=0; stscanf(In,T("0x%8x%8x"),&hi,&lo); return (((uint64_t)hi)<<32)+lo; } void Int64ToString(tchar_t* Out, size_t OutLen, int64_t p, bool_t Hex) { if (!Hex && (p & 0xFFFFFFFF)==p) stprintf_s(Out,OutLen,mask_d,(int32_t)p); else stprintf_s(Out,OutLen,Hex ? mask_0x08Xx08X:mask_dd,(uint32_t)(((uint64_t)p)>>32),(uint32_t)p); } void IntToString(tchar_t* Out, size_t OutLen, int32_t p, bool_t Hex) { stprintf_s(Out,OutLen,Hex ? mask_0x08X:mask_d,p); } void RGBToString(tchar_t* Out, size_t OutLen, rgbval_t RGB) { stprintf_s(Out,OutLen,mask_rgb,(int)INT32BE(RGB)); if (tcslen(Out)>=1+8 && Out[7]=='0' && Out[8]=='0') Out[7] = 0; } rgbval_t StringToRGB(const tchar_t* In) { int v; if (*In=='#') ++In; v = StringToInt(In,1); if (tcslen(In)<=6) v <<= 8; return INT32BE(v); } tick_t StringToTick(const tchar_t* In) { // hour:min:sec.msec bool_t Sign = 0; tick_t Tick = 0; int Hour,Min,Sec; int n; if (*In=='-') { Sign = 1; ++In; } else if (*In=='+') ++In; n = stscanf(In,T("%d:%d:%d"),&Hour,&Min,&Sec); if (n>0) { Tick = Hour; if (n>1) { Tick *= 60; Tick += Min; if (n>2) { Tick *= 60; Tick += Sec; } } Tick *= TICKSPERSEC; } In = tcschr(In,T('.')); if (In) { int64_t Num = 0; int64_t Den = 1; ++In; for (;IsDigit(*In);++In) { Num = Num*10 + (*In-'0'); Den *= 10; } Tick += (tick_t)((Num*TICKSPERSEC+Den/2)/Den); } if (Sign) Tick = -Tick; return Tick; } systick_t StringToSysTick(const tchar_t* In) { // hour:min:sec.msec bool_t Sign = 0; systick_t Tick = 0; int Hour,Min,Sec; int n; if (*In=='-') { Sign = 1; ++In; } else if (*In=='+') ++In; n = stscanf(In,T("%d:%d:%d"),&Hour,&Min,&Sec); if (n>0) { Tick = Hour; if (n>1) { Tick *= 60; Tick += Min; if (n>2) { Tick *= 60; Tick += Sec; } } Tick *= GetTimeFreq(); } In = tcschr(In,T('.')); if (In) { int64_t Num = 0; int64_t Den = 1; ++In; for (;IsDigit(*In);++In) { Num = Num*10 + (*In-'0'); Den *= 10; } Tick += (systick_t)((Num*GetTimeFreq()+Den/2)/Den); } if (Sign) Tick = -Tick; return Tick; } void TickToString(tchar_t* Out, size_t OutLen, tick_t Tick, bool_t MS, bool_t Extended, bool_t Fix) { tchar_t Sign[2] = {0}; if (Tick<0) { Sign[0] = '-'; Tick = -Tick; } if (!MS) { int Hour,Min,Sec; Tick += TICKSPERSEC/2000; Hour = (int)(Tick / 3600 / TICKSPERSEC); Tick -= Hour * 3600 * TICKSPERSEC; Min = (int)(Tick / 60 / TICKSPERSEC); Tick -= Min * 60 * TICKSPERSEC; Sec = (int)(Tick / TICKSPERSEC); Tick -= Sec * TICKSPERSEC; if (!Hour && !Min && !Fix && Extended) stprintf_s(Out,OutLen,T("%s%d"),Sign,Sec); else { if (Hour) stprintf_s(Out,OutLen,T("%s%d:%02d"),Sign,Hour,Min); else stprintf_s(Out,OutLen,Fix?T("%s%02d"):T("%s%d"),Sign,Min); stcatprintf_s(Out,OutLen,T(":%02d"),Sec); } if (Extended) stcatprintf_s(Out,OutLen,T(".%03d"),(int)((Tick*1000)/TICKSPERSEC)); } else { int i = Scale32(Tick,100000,TICKSPERSEC); stprintf_s(Out,OutLen,T("%s%d.%02d%s"),Sign,i/100,i%100,Extended?T(" ms"):T("")); } } void SysTickToString(tchar_t* Out, size_t OutLen, systick_t Tick, bool_t MS, bool_t Extended, bool_t Fix) { tchar_t Sign[2] = {0}; if (Tick<0) { Sign[0] = '-'; Tick = -Tick; } if (!MS) { int Hour,Min,Sec; //Tick += GetTimeFreq()/2000; Hour = (int)(Tick / 3600 / GetTimeFreq()); Tick -= Hour * 3600 * GetTimeFreq(); Min = (int)(Tick / 60 / GetTimeFreq()); Tick -= Min * 60 * GetTimeFreq(); Sec = (int)(Tick / GetTimeFreq()); Tick -= Sec * GetTimeFreq(); if (!Hour && !Min && !Fix && Extended) stprintf_s(Out,OutLen,T("%s%d"),Sign,Sec); else { if (Hour) stprintf_s(Out,OutLen,T("%s%d:%02d"),Sign,Hour,Min); else stprintf_s(Out,OutLen,Fix?T("%s%02d"):T("%s%d"),Sign,Min); stcatprintf_s(Out,OutLen,T(":%02d"),Sec); } if (Extended) stcatprintf_s(Out,OutLen,T(".%03d"),(int)((Tick*1000)/GetTimeFreq())); } else { int i = Scale32(Tick,1000,GetTimeFreq()); stprintf_s(Out,OutLen,T("%s%d%s"),Sign,i,Extended?T(" ms"):T("")); } } void URLToString(tchar_t* Title, size_t TitleLen, const tchar_t* URL) { const tchar_t *i; tchar_t *j; assert(TitleLen>0); // replace %20 and '_' with space for (j=Title,i=URL;*i && TitleLen>1;++i,--TitleLen) { if (*i=='_') *j++ = ' '; else if (i[0]=='%' && Hex(i[1])>=0 && Hex(i[2])>=0) { *j++ = (tchar_t)((Hex(i[1])<<4) + Hex(i[2])); i += 2; } else *j++ = *i; } *j=0; } static bool_t IsUrlSafe(tchar_t i) { return (i == T('$') || i == T('-') || i == T('_') || i == T('.') || i == T('+')); } void StringToURL(anynode* AnyNode, tchar_t* Out, size_t OutLen, const tchar_t *URL) { size_t Utf8Len = max(2*tcslen(URL),OutLen); // try to estimate char *Utf8 = malloc(Utf8Len); assert(OutLen>0); if (Utf8) { const char *i; Node_ToUTF8(AnyNode,Utf8,Utf8Len,URL); for (i=Utf8;*i && OutLen>1;++i) { if (IsDigit(*i) || IsAlpha(*i) || IsUrlSafe(*i)) { OutLen--; *Out++ = *i; } else if (OutLen>3) { OutLen--; *Out++ = T('%'); stprintf_s(Out,OutLen,mask_02X,*i & 0xFF); OutLen -= tcslen(Out); Out += tcslen(Out); } } free(Utf8); } *Out = 0; } void LangToIso639_1(tchar_t *Out, size_t OutLen, fourcc_t Lang) { FourCCToString(Out,OutLen,Lang); tcslwr(Out); } void ByteRateToString(tchar_t* Out, size_t OutLen, int ByteRate) { int KB = Scale32(ByteRate,8,1000); if (KB>=1000) { cc_fraction f; f.Num = KB; f.Den = 1000; FractionToString(Out,OutLen,&f,0,2); tcscat_s(Out,OutLen,T(" Mbit/s")); } else { IntToString(Out,OutLen,KB,0); tcscat_s(Out,OutLen,T(" kbit/s")); } } datetime_t RFC822ToRel(const tchar_t *Date) { datetime_t Result; datepack_t ResultPacked = {0}; intptr_t Offset=0; const tchar_t *s = tcschr(Date,T(',')); const tchar_t* const Token[12] = { T("Jan"), T("Feb"), T("Mar"), T("Apr"), T("May"), T("Jun"), T("Jul"), T("Aug"), T("Sep"), T("Oct"), T("Nov"), T("Dec") }; const tchar_t* const TokenLong[12] = { T("January"), T("February"), T("March"), T("April"), T("May"), T("June"), T("July"), T("August"), T("September"), T("October"), T("November"), T("December") }; if (s) s++; else s = Date; ExprSkipSpace(&s); if (!ExprIsTokenEx(&s,T("%d "),&ResultPacked.Day)) return INVALID_DATETIME_T; ExprSkipSpace(&s); for (ResultPacked.Month=0;ResultPacked.Month<12;++ResultPacked.Month) if (ExprIsToken(&s,Token[ResultPacked.Month])) break; if (ResultPacked.Month==12) for (ResultPacked.Month=0;ResultPacked.Month<12;++ResultPacked.Month) if (ExprIsToken(&s,TokenLong[ResultPacked.Month])) break; if (ResultPacked.Month==12) return INVALID_DATETIME_T; ResultPacked.Month++; ExprSkipSpace(&s); if (!ExprIsTokenEx(&s,T("%d %d:%d:%d"),&ResultPacked.Year,&ResultPacked.Hour,&ResultPacked.Minute,&ResultPacked.Second) && !ExprIsTokenEx(&s,T("%d %d:%d"),&ResultPacked.Year,&ResultPacked.Hour,&ResultPacked.Minute)) return INVALID_DATETIME_T; if (ResultPacked.Year < 100) ResultPacked.Year += 2000; ExprSkipSpace(&s); if (ExprIsTokenEx(&s,T("+%d"),&Offset)) Offset = -Offset; else if (ExprIsTokenEx(&s,T("-%d"),&Offset)) {} else if (ExprIsToken(&s,T("EDT"))) Offset = 400; else if (ExprIsToken(&s,T("EST"))) Offset = 500; else if (ExprIsToken(&s,T("CST"))) Offset = 600; else if (ExprIsToken(&s,T("CDT"))) Offset = 500; else if (ExprIsToken(&s,T("MST"))) Offset = 600; else if (ExprIsToken(&s,T("MDT"))) Offset = 500; else if (ExprIsToken(&s,T("PST"))) Offset = 600; else if (ExprIsToken(&s,T("PDT"))) Offset = 500; Result = TimePackToRel(&ResultPacked,0); if (Result != INVALID_DATETIME_T) Result += (datetime_t)(((Offset/100)*60)+(Offset%100))*60; return Result; } datetime_t ISO8601ToRel(const tchar_t *InDate) { tchar_t Time[32],Date[32]; datetime_t Result; datepack_t ResultPacked = {0}; intptr_t Offset=0; const tchar_t *s; tchar_t *t; s = InDate; ExprSkipSpace(&s); tcscpy_s(Date,TSIZEOF(Date),s); s = Date; // split the time and date parts Time[0] = 0; t = tcsrchr(s,T('T')); if (!t) t = tcsrchr(s,T(' ')); if (t) { tcscpy_s(Time,TSIZEOF(Time),t+1); t[0] = 0; } if (!*Time) { t = tcsrchr(s,T('Z')); if (t && t[1] == 0) { // assume HHMMSS for the time if (tcslen(Date)>=13) { tcscpy_s(Time,TSIZEOF(Time),max(t-6,s)); Time[6] = 0; t[-6]=0; } } } if (!ExprIsTokenEx(&s,T("%d-%d-%d"),&ResultPacked.Year,&ResultPacked.Month,&ResultPacked.Day) && !ExprIsTokenEx(&s,T("%d:%d:%d"),&ResultPacked.Year,&ResultPacked.Month,&ResultPacked.Day) && !ExprIsTokenEx(&s,T("%4d%2d%2d"),&ResultPacked.Year,&ResultPacked.Month,&ResultPacked.Day) && !ExprIsTokenEx(&s,T("%2d%2d%2d"),&ResultPacked.Year,&ResultPacked.Month,&ResultPacked.Day)) return INVALID_DATETIME_T; if (ResultPacked.Year < 50) ResultPacked.Year += 2000; else if (ResultPacked.Year < 100) ResultPacked.Year += 1900; if (*Time) { s = Time; if (ExprIsTokenEx(&s,T("%d:%d:%d"),&ResultPacked.Hour,&ResultPacked.Minute,&ResultPacked.Second) || ExprIsTokenEx(&s,T("%2d%2d%2d"),&ResultPacked.Hour,&ResultPacked.Minute,&ResultPacked.Second)) { intptr_t MilliSeconds; ExprIsTokenEx(&s,T(".%d"),&MilliSeconds); if (s[0]) { const tchar_t *o=s + 1; intptr_t OffsetH,OffsetM=0; if (ExprIsTokenEx(&o,T("%d:%d"),&OffsetH,&OffsetM) || ExprIsTokenEx(&o,T("%2d%2d"),&OffsetH,&OffsetM) || ExprIsTokenEx(&o,T("%2d"),&OffsetH)) { Offset = (OffsetH*60 + OffsetM)*60; } if (s[0] == T('+')) Offset = -Offset; } } } Result = TimePackToRel(&ResultPacked,0); if (Result != INVALID_DATETIME_T) Result += (datetime_t)Offset; return Result; } #define BUFLEN 30 static void ZPad(tchar_t* Out, size_t Len, intptr_t v) { Out[Len] = '\0'; while (Len--) { Out[Len] = (tchar_t) ('0' + v % 10); v = v / 10; } } size_t StrFTime(tchar_t* Out, size_t OutLen, const tchar_t *Format, datepack_t *dp) { const tchar_t* const Month[12] = { T("Jan"), T("Feb"), T("Mar"), T("Apr"), T("May"), T("Jun"), T("Jul"), T("Aug"), T("Sep"), T("Oct"), T("Nov"), T("Dec") }; const tchar_t* const MonthLong[12] = { T("January"), T("February"), T("March"), T("April"), T("May"), T("June"), T("July"), T("August"), T("September"), T("October"), T("November"), T("December") }; const tchar_t* const WeekDay[7] = { T("Sun"), T("Mon"), T("Tue"), T("Wed"), T("Thu"), T("Fri"), T("Sat") }; const tchar_t* const WeekDayLong[7] = { T("Sunday"), T("Monday"), T("Tuesday"), T("Wednesday"), T("Thursday"), T("Friday"), T("Saturday") }; const tchar_t* const AMPM[2] = { T("am"), T("pm") }; const tchar_t* const DateTimeFormat[3] = { T("%y/%m/%d"), T("%H:%M:%S"), T("%a %b %d %H:%M:%S %Y") }; tchar_t buf[BUFLEN]; tchar_t *p, *q; const tchar_t *r; p = Out; q = Out + OutLen - 1; while ((*Format != '\0')) { if (*Format++ == '%') { r = buf; switch (*Format++) { case '%' : buf[0] = '%'; buf[1] = '\0'; break; case 'a' : r = WeekDay[dp->WeekDay-1]; break; case 'A' : r = WeekDayLong[dp->WeekDay-1]; break; case 'b' : r = Month[dp->Month-1]; break; case 'B' : r = MonthLong[dp->Month-1]; break; case 'c' : StrFTime(buf, BUFLEN, DateTimeFormat[2], dp); break; case 'd' : ZPad(buf, 2, dp->Day); break; case 'H' : ZPad(buf, 2, dp->Hour); break; case 'I' : ZPad(buf, 2, dp->Hour==12 ? 12 : dp->Hour%12); break; case 'm' : ZPad(buf, 2, dp->Month); break; case 'M' : ZPad(buf, 2, dp->Minute); break; case 'p' : r = AMPM[dp->Hour/12]; break; case 'S' : ZPad(buf, 2, dp->Second); break; case 'w' : ZPad(buf, 1, dp->WeekDay-1); break; case 'x' : StrFTime(buf, BUFLEN, DateTimeFormat[0], dp); break; case 'X' : StrFTime(buf, BUFLEN, DateTimeFormat[1], dp); break; case 'y' : ZPad(buf, 2, dp->Year % 100); break; case 'Y' : ZPad(buf, 4, dp->Year); break; default: buf[0] = '%'; buf[1] = Format[-1]; buf[2] = '\0'; if (buf[1] == 0) Format--; } while (*r) { if (p == q) { *q = '\0'; return 0; } *p++ = *r++; } } else { if (p == q) { *q = '\0'; return 0; } *p++ = Format[-1]; } } *p = '\0'; return p - Out; } bcmatroska2-5.3.101/corec/corec/helpers/parser/strtypes.h000066400000000000000000000066261462133141200232720ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __STRTYPES_H #define __STRTYPES_H NODE_DLL size_t FourCCToString(tchar_t* Out, size_t OutLen, fourcc_t FourCC); NODE_DLL fourcc_t StringToFourCC(const tchar_t* In, bool_t Upper); NODE_DLL void FractionToString(tchar_t* Out, size_t OutLen, const cc_fraction* Fraction, int Percent, int Decimal); NODE_DLL void StringToFraction(const tchar_t* In, cc_fraction* Out, bool_t Percent); NODE_DLL int StringToInt(const tchar_t* In, int Hex); NODE_DLL int64_t StringToInt64(const tchar_t* In); NODE_DLL void IntToString(tchar_t* Out, size_t OutLen, int32_t Int, bool_t Hex); NODE_DLL void Int64ToString(tchar_t* Out, size_t OutLen, int64_t Int, bool_t Hex); NODE_DLL void TickToString(tchar_t* Out, size_t OutLen, tick_t Tick, bool_t MS, bool_t Extended, bool_t Fix); NODE_DLL void SysTickToString(tchar_t* Out, size_t OutLen, systick_t Tick, bool_t MS, bool_t Extended, bool_t Fix); NODE_DLL tick_t StringToTick(const tchar_t* In); NODE_DLL systick_t StringToSysTick(const tchar_t* In); NODE_DLL void RGBToString(tchar_t* Out, size_t OutLen, rgbval_t RGB); NODE_DLL rgbval_t StringToRGB(const tchar_t* In); NODE_DLL void GUIDToString(tchar_t* Out, size_t OutLen, const cc_guid*); NODE_DLL bool_t StringToGUID(const tchar_t* In, cc_guid*); NODE_DLL void StringToURL(anynode* AnyNode, tchar_t* Out, size_t OutLen, const tchar_t *URL); NODE_DLL void URLToString(tchar_t* Out, size_t OutLen, const tchar_t *URL); NODE_DLL void LangToIso639_1(tchar_t *Out, size_t OutLen, fourcc_t Lang); NODE_DLL void ByteRateToString(tchar_t* Out, size_t OutLen, int ByteRate); NODE_DLL datetime_t RFC822ToRel(const tchar_t *); NODE_DLL datetime_t ISO8601ToRel(const tchar_t *); NODE_DLL size_t StrFTime(tchar_t* Out, size_t OutLen, const tchar_t *Format, datepack_t *dp); #endif bcmatroska2-5.3.101/corec/corec/helpers/parser/urlpart.c000066400000000000000000000202321462133141200230460ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "parser.h" #define URLPART_ID FOURCC('U','P','A','T') #define URLPART_URL 0x100 #define URLPART_MIME 0x101 #define URLPART_SEPARATOR T("$") #define URLPART_SEP_CHAR T('$') #define URLPART_SEP_ESCAPE T("$$") typedef struct urlpart { stream Base; stream *Input; filepos_t Pos; size_t Length; bool_t Blocking; } urlpart; err_t CreateUrlPart(nodecontext *Context, tchar_t *Out, size_t OutLen, const tchar_t *URL, filepos_t Offset, size_t Length, const tchar_t *Mime) { datetime_t FileDate; if (!URL || !URL[0]) return ERR_INVALID_DATA; stprintf_s(Out,OutLen,T("urlpart://%s"),URL); tcsreplace(Out,OutLen,URLPART_SEPARATOR,URLPART_SEP_ESCAPE); tcscat_s(Out,OutLen,URLPART_SEPARATOR); if (Offset > 0) stcatprintf_s(Out,OutLen,T("ofs=%d#"),(int)Offset); // TODO: support 64 bits offset if (Length > 0) stcatprintf_s(Out,OutLen,T("len=%d#"),(int)Length); if (Mime) stcatprintf_s(Out,OutLen,T("mime=%s#"),Mime); FileDate = FileDateTime(Context,URL); if (FileDate != INVALID_DATETIME_T) stcatprintf_s(Out,OutLen,T("date=%d#"),(int)FileDate); return ERR_NONE; } static void Clear(urlpart* p) { Node_RemoveData((node*)p,STREAM_URL,TYPE_STRING); Node_RemoveData((node*)p,URLPART_URL,TYPE_STRING); Node_RemoveData((node*)p,URLPART_MIME,TYPE_STRING); p->Length = (size_t)-1; p->Pos = INVALID_FILEPOS_T; p->Input = 0; } static err_t Get(urlpart* p,dataid Id, void* Data, size_t Size) { if (!p->Input) return ERR_INVALID_DATA; switch (Id) { case STREAM_LENGTH: (*(filepos_t*)Data)=p->Length; return ERR_NONE; case STREAM_URL: return INHERITED(p,node_vmt,URLPART_ID)->Get(p,Id,Data,Size); case STREAM_CONTENTTYPE: { tchar_t *Mime = Node_GetData((node*)p,URLPART_MIME,TYPE_STRING); if (Mime) { tcscpy_s(Data,Size/sizeof(tchar_t),Mime); return ERR_NONE; } } } return Node_Get(p->Input,Id,Data,Size); } static err_t Set(urlpart* p,dataid Id, const void* Data, size_t Size) { if (!p->Input) return ERR_INVALID_DATA; return Node_Set(p->Input,Id,Data,Size); } static err_t Open(urlpart* p, const tchar_t* URL, int Flags) { err_t Result; const tchar_t *String, *Equal; tchar_t Value[MAXPATHFULL]; datetime_t Date = INVALID_DATETIME_T; String = tcsrchr(URL,URLPART_SEP_CHAR); if (!String) return ERR_INVALID_DATA; Clear(p); Node_SetData((node*)p,STREAM_URL,TYPE_STRING,URL); Equal = GetProtocol(URL,NULL,0,NULL); tcsncpy_s(Value,TSIZEOF(Value),Equal,String-Equal); tcsreplace(Value,TSIZEOF(Value),URLPART_SEP_ESCAPE,URLPART_SEPARATOR); Node_SetData((node*)p,URLPART_URL,TYPE_STRING,Value); while (String++ && *String) { Equal = tcschr(String,T('=')); if (Equal) { tchar_t *Sep = tcschr(Equal,T('#')); if (Sep) tcsncpy_s(Value,TSIZEOF(Value),Equal+1,Sep-Equal-1); else tcscpy_s(Value,TSIZEOF(Value),Equal+1); if (tcsncmp(String,T("ofs"),Equal-String)==0) p->Pos = StringToInt(Value,0); else if (tcsncmp(String,T("len"),Equal-String)==0) p->Length = StringToInt(Value,0); else if (tcsncmp(String,T("mime"),Equal-String)==0) Node_SetData((node*)p,URLPART_MIME,TYPE_STRING,Value); else if (tcsncmp(String,T("date"),Equal-String)==0) Date = StringToInt(Value,0); } String = tcschr(String,'#'); } if (Date!=INVALID_DATETIME_T && Date != FileDateTime(Node_Context(p),Node_GetDataStr((node*)p,URLPART_URL))) return ERR_INVALID_DATA; p->Input = GetStream(p,Node_GetDataStr((node*)p,URLPART_URL),Flags); if (!p->Input) return ERR_NOT_SUPPORTED; Stream_Blocking(p->Input,p->Blocking); Result = Stream_Open(p->Input,Node_GetDataStr((node*)p,URLPART_URL),Flags); if (Result == ERR_NONE && p->Pos!=INVALID_FILEPOS_T) // TODO: support asynchronous stream opening { if (Stream_Seek(p->Input,p->Pos,SEEK_SET)!=p->Pos) return ERR_INVALID_DATA; } return Result; } static filepos_t Seek(urlpart* p,filepos_t Pos,int SeekMode) { if (!p->Input) return INVALID_FILEPOS_T; switch (SeekMode) { case SEEK_SET: Pos = min(Pos,(filepos_t)p->Length); assert(p->Pos!=INVALID_FILEPOS_T); return Stream_Seek(p->Input,Pos+p->Pos,SeekMode); case SEEK_CUR: return Stream_Seek(p->Input,Pos,SeekMode); case SEEK_END: Pos = max(Pos,-(filepos_t)p->Length); assert(p->Pos!=INVALID_FILEPOS_T); return Stream_Seek(p->Input,Pos+p->Pos+p->Length,SeekMode); } return INVALID_FILEPOS_T; } static err_t Read(urlpart* p,void* Data,size_t Size,size_t* Readed) { if (!p->Input) { if (Readed) *Readed=0; return ERR_INVALID_DATA; } return Stream_Read(p->Input,Data,Size,Readed); } static err_t ReadBlock(urlpart* p,block* Block,size_t Ofs,size_t Size,size_t* Readed) { if (!p->Input) { if (Readed) *Readed=0; return ERR_INVALID_DATA; } return Stream_ReadBlock(p->Input,Block,Ofs,Size,Readed); } static err_t Blocking(urlpart* p,bool_t Blocking) { p->Blocking = Blocking; if (p->Input) return Stream_Blocking(p->Input,Blocking); return Blocking ? ERR_NONE : ERR_NOT_SUPPORTED; } static err_t WaitStream(urlpart* p,bool_t Read, streamselect* Select) { if (!p->Input) return ERR_NOT_SUPPORTED; return Stream_Wait(p->Input,Read,Select); } static err_t SkipStream(urlpart* p,intptr_t* Skip) { if (!p->Input) return ERR_NOT_SUPPORTED; return Stream_Skip(p->Input,Skip); } static err_t Create(urlpart* p) { p->Blocking = 1; return ERR_NONE; } static void Delete(urlpart* p) { if (p->Input) Node_Release(p->Input); Clear(p); } META_START(UrlPart_Class,URLPART_ID) META_CLASS(SIZE,sizeof(urlpart)) META_PARAM(STRING,NODE_PROTOCOL,T("urlpart")) META_CLASS(CREATE,Create) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,node_vmt,Get,Get) META_VMT(TYPE_FUNC,node_vmt,Set,Set) META_VMT(TYPE_FUNC,stream_vmt,Blocking,Blocking) META_VMT(TYPE_FUNC,stream_vmt,Open,Open) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_VMT(TYPE_FUNC,stream_vmt,ReadBlock,ReadBlock) META_VMT(TYPE_FUNC,stream_vmt,Wait,WaitStream) META_VMT(TYPE_FUNC,stream_vmt,Skip,SkipStream) META_DYNAMIC(TYPE_STRING,STREAM_URL) META_END(STREAM_CLASS) bcmatroska2-5.3.101/corec/corec/helpers/parser/urlpart.h000066400000000000000000000036221462133141200230570ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __URLPART_H #define __URLPART_H NODE_DLL err_t CreateUrlPart(nodecontext *Context, tchar_t *Out, size_t OutLen, const tchar_t *URL, filepos_t Offset, size_t Length, const tchar_t *Mime); #endif /* __URLPART_H */ bcmatroska2-5.3.101/corec/corec/helpers/system/000077500000000000000000000000001462133141200212425ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/system/ccsystem.h000066400000000000000000000041371462133141200232520ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2010, Steve Lhomme * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef COREC_SYSTEM_H #define COREC_SYSTEM_H #include "corec/node/node.h" #ifdef __cplusplus extern "C" { #endif #if defined(CCSYSTEM_EXPORTS) #define CCSYSTEM_DLL DLLEXPORT #elif defined(CCSYSTEM_IMPORTS) #define CCSYSTEM_DLL DLLIMPORT #else #define CCSYSTEM_DLL #endif CCSYSTEM_DLL int RunCommand(anynode *, const tchar_t *Cmd, const tchar_t *CmdParams, bool_t Silent); #ifdef __cplusplus } #endif #endif /* COREC_SYSTEM_H */ bcmatroska2-5.3.101/corec/corec/helpers/system/ccsystem_posix.c000066400000000000000000000043711462133141200244670ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2010, Steve Lhomme * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "ccsystem.h" #include "corec/helpers/parser/parser.h" #include int RunCommand(anynode *p, const tchar_t *Cmd, const tchar_t *CmdParams, bool_t Silent) { char Command[2048]; Node_ToUTF8(p, Command,sizeof(Command), Cmd); if (CmdParams && CmdParams[0]) { size_t len = strlen(Command) + 1; strcat(Command," "); Node_ToUTF8(p, Command+len,sizeof(Command)-len, CmdParams); if (Silent) strcat(Command," > /dev/null 2>/dev/null"); } return system(Command); } bcmatroska2-5.3.101/corec/corec/helpers/system/ccsystem_win32.c000066400000000000000000000056741462133141200242760ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2010, Steve Lhomme * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "ccsystem.h" #include "corec/helpers/parser/parser.h" #include #if defined(__MINGW32__) || !defined(WINAPI_FAMILY_PARTITION) || !defined(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_FAMILY_PARTITION) #if defined(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_PARTITION_PHONE_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #define WINDOWS_PHONE 1 #elif defined(WINAPI_PARTITION_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define WINDOWS_UNIVERSAL 1 #endif #endif int RunCommand(anynode *p, const tchar_t *Cmd, const tchar_t *CmdParams, bool_t Silent) { #ifdef WINDOWS_DESKTOP STARTUPINFO si; PROCESS_INFORMATION pi; DWORD returnCode; tchar_t Command[4096]; int Flags = Silent ? CREATE_NO_WINDOW : 0; stprintf_s(Command,TSIZEOF(Command),T("%s %s"),Cmd, CmdParams); ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if (!CreateProcess(NULL,Command,NULL,NULL,FALSE,Flags,NULL,NULL,&si,&pi)) return -1; while (GetExitCodeProcess(pi.hProcess, &returnCode) && returnCode==STILL_ACTIVE) Sleep(100); return (int)returnCode; #else return 0; #endif } bcmatroska2-5.3.101/corec/corec/helpers/system/system.proj000066400000000000000000000002001462133141200234520ustar00rootroot00000000000000GROUP ccsystem { USE corec SOURCE(TARGET_WIN) ccsystem_win32.c SOURCE(!TARGET_WIN) ccsystem_posix.c HEADER ccsystem.h } bcmatroska2-5.3.101/corec/corec/helpers/zlib/000077500000000000000000000000001462133141200206565ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/ChangeLog000066400000000000000000001714631462133141200224440ustar00rootroot00000000000000 ChangeLog file for zlib Changes in 1.2.5 (19 Apr 2010) - Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] - Default to libdir as sharedlibdir in configure [Nieder] - Update copyright dates on modified source files - Update trees.c to be able to generate modified trees.h - Exit configure for MinGW, suggesting win32/Makefile.gcc Changes in 1.2.4.5 (18 Apr 2010) - Set sharedlibdir in configure [Torok] - Set LDFLAGS in Makefile.in [Bar-Lev] - Avoid mkdir objs race condition in Makefile.in [Bowler] - Add ZLIB_INTERNAL in front of internal inter-module functions and arrays - Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C - Don't use hidden attribute when it is a warning generator (e.g. Solaris) Changes in 1.2.4.4 (18 Apr 2010) - Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] - Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty - Try to use bash or ksh regardless of functionality of /bin/sh - Fix configure incompatibility with NetBSD sh - Remove attempt to run under bash or ksh since have better NetBSD fix - Fix win32/Makefile.gcc for MinGW [Bar-Lev] - Add diagnostic messages when using CROSS_PREFIX in configure - Added --sharedlibdir option to configure [Weigelt] - Use hidden visibility attribute when available [Frysinger] Changes in 1.2.4.3 (10 Apr 2010) - Only use CROSS_PREFIX in configure for ar and ranlib if they exist - Use CROSS_PREFIX for nm [Bar-Lev] - Assume _LARGEFILE64_SOURCE defined is equivalent to true - Avoid use of undefined symbols in #if with && and || - Make *64 prototypes in gzguts.h consistent with functions - Add -shared load option for MinGW in configure [Bowler] - Move z_off64_t to public interface, use instead of off64_t - Remove ! from shell test in configure (not portable to Solaris) - Change +0 macro tests to -0 for possibly increased portability Changes in 1.2.4.2 (9 Apr 2010) - Add consistent carriage returns to readme.txt's in masmx86 and masmx64 - Really provide prototypes for *64 functions when building without LFS - Only define unlink() in minigzip.c if unistd.h not included - Update README to point to contrib/vstudio project files - Move projects/vc6 to old/ and remove projects/ - Include stdlib.h in minigzip.c for setmode() definition under WinCE - Clean up assembler builds in win32/Makefile.msc [Rowe] - Include sys/types.h for Microsoft for off_t definition - Fix memory leak on error in gz_open() - Symbolize nm as $NM in configure [Weigelt] - Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] - Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined - Fix bug in gzeof() to take into account unused input data - Avoid initialization of structures with variables in puff.c - Updated win32/README-WIN32.txt [Rowe] Changes in 1.2.4.1 (28 Mar 2010) - Remove the use of [a-z] constructs for sed in configure [gentoo 310225] - Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] - Restore "for debugging" comment on sprintf() in gzlib.c - Remove fdopen for MVS from gzguts.h - Put new README-WIN32.txt in win32 [Rowe] - Add check for shell to configure and invoke another shell if needed - Fix big fat stinking bug in gzseek() on uncompressed files - Remove vestigial F_OPEN64 define in zutil.h - Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE - Avoid errors on non-LFS systems when applications define LFS macros - Set EXE to ".exe" in configure for MINGW [Kahle] - Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] - Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] - Add DLL install in win32/makefile.gcc [Bar-Lev] - Allow Linux* or linux* from uname in configure [Bar-Lev] - Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] - Add cross-compilation prefixes to configure [Bar-Lev] - Match type exactly in gz_load() invocation in gzread.c - Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func - Provide prototypes for *64 functions when building zlib without LFS - Don't use -lc when linking shared library on MinGW - Remove errno.h check in configure and vestigial errno code in zutil.h Changes in 1.2.4 (14 Mar 2010) - Fix VER3 extraction in configure for no fourth subversion - Update zlib.3, add docs to Makefile.in to make .pdf out of it - Add zlib.3.pdf to distribution - Don't set error code in gzerror() if passed pointer is NULL - Apply destination directory fixes to CMakeLists.txt [Lowman] - Move #cmakedefine's to a new zconf.in.cmakein - Restore zconf.h for builds that don't use configure or cmake - Add distclean to dummy Makefile for convenience - Update and improve INDEX, README, and FAQ - Update CMakeLists.txt for the return of zconf.h [Lowman] - Update contrib/vstudio/vc9 and vc10 [Vollant] - Change libz.dll.a back to libzdll.a in win32/Makefile.gcc - Apply license and readme changes to contrib/asm686 [Raiter] - Check file name lengths and add -c option in minigzip.c [Li] - Update contrib/amd64 and contrib/masmx86/ [Vollant] - Avoid use of "eof" parameter in trees.c to not shadow library variable - Update make_vms.com for removal of zlibdefs.h [Zinser] - Update assembler code and vstudio projects in contrib [Vollant] - Remove outdated assembler code contrib/masm686 and contrib/asm586 - Remove old vc7 and vc8 from contrib/vstudio - Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] - Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() - Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] - Remove *64 functions from win32/zlib.def (they're not 64-bit yet) - Fix bug in void-returning vsprintf() case in gzwrite.c - Fix name change from inflate.h in contrib/inflate86/inffas86.c - Check if temporary file exists before removing in make_vms.com [Zinser] - Fix make install and uninstall for --static option - Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] - Update readme.txt in contrib/masmx64 and masmx86 to assemble Changes in 1.2.3.9 (21 Feb 2010) - Expunge gzio.c - Move as400 build information to old - Fix updates in contrib/minizip and contrib/vstudio - Add const to vsnprintf test in configure to avoid warnings [Weigelt] - Delete zconf.h (made by configure) [Weigelt] - Change zconf.in.h to zconf.h.in per convention [Weigelt] - Check for NULL buf in gzgets() - Return empty string for gzgets() with len == 1 (like fgets()) - Fix description of gzgets() in zlib.h for end-of-file, NULL return - Update minizip to 1.1 [Vollant] - Avoid MSVC loss of data warnings in gzread.c, gzwrite.c - Note in zlib.h that gzerror() should be used to distinguish from EOF - Remove use of snprintf() from gzlib.c - Fix bug in gzseek() - Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] - Fix zconf.h generation in CMakeLists.txt [Lowman] - Improve comments in zconf.h where modified by configure Changes in 1.2.3.8 (13 Feb 2010) - Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] - Use z_off64_t in gz_zero() and gz_skip() to match state->skip - Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) - Revert to Makefile.in from 1.2.3.6 (live with the clutter) - Fix missing error return in gzflush(), add zlib.h note - Add *64 functions to zlib.map [Levin] - Fix signed/unsigned comparison in gz_comp() - Use SFLAGS when testing shared linking in configure - Add --64 option to ./configure to use -m64 with gcc - Fix ./configure --help to correctly name options - Have make fail if a test fails [Levin] - Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] - Remove assembler object files from contrib Changes in 1.2.3.7 (24 Jan 2010) - Always gzopen() with O_LARGEFILE if available - Fix gzdirect() to work immediately after gzopen() or gzdopen() - Make gzdirect() more precise when the state changes while reading - Improve zlib.h documentation in many places - Catch memory allocation failure in gz_open() - Complete close operation if seek forward in gzclose_w() fails - Return Z_ERRNO from gzclose_r() if close() fails - Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL - Return zero for gzwrite() errors to match zlib.h description - Return -1 on gzputs() error to match zlib.h description - Add zconf.in.h to allow recovery from configure modification [Weigelt] - Fix static library permissions in Makefile.in [Weigelt] - Avoid warnings in configure tests that hide functionality [Weigelt] - Add *BSD and DragonFly to Linux case in configure [gentoo 123571] - Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] - Avoid access of uninitialized data for first inflateReset2 call [Gomes] - Keep object files in subdirectories to reduce the clutter somewhat - Remove default Makefile and zlibdefs.h, add dummy Makefile - Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ - Remove zlibdefs.h completely -- modify zconf.h instead Changes in 1.2.3.6 (17 Jan 2010) - Avoid void * arithmetic in gzread.c and gzwrite.c - Make compilers happier with const char * for gz_error message - Avoid unused parameter warning in inflate.c - Avoid signed-unsigned comparison warning in inflate.c - Indent #pragma's for traditional C - Fix usage of strwinerror() in glib.c, change to gz_strwinerror() - Correct email address in configure for system options - Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] - Update zlib.map [Brown] - Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] - Apply various fixes to CMakeLists.txt [Lowman] - Add checks on len in gzread() and gzwrite() - Add error message for no more room for gzungetc() - Remove zlib version check in gzwrite() - Defer compression of gzprintf() result until need to - Use snprintf() in gzdopen() if available - Remove USE_MMAP configuration determination (only used by minigzip) - Remove examples/pigz.c (available separately) - Update examples/gun.c to 1.6 Changes in 1.2.3.5 (8 Jan 2010) - Add space after #if in zutil.h for some compilers - Fix relatively harmless bug in deflate_fast() [Exarevsky] - Fix same problem in deflate_slow() - Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] - Add deflate_rle() for faster Z_RLE strategy run-length encoding - Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding - Change name of "write" variable in inffast.c to avoid library collisions - Fix premature EOF from gzread() in gzio.c [Brown] - Use zlib header window size if windowBits is 0 in inflateInit2() - Remove compressBound() call in deflate.c to avoid linking compress.o - Replace use of errno in gz* with functions, support WinCE [Alves] - Provide alternative to perror() in minigzip.c for WinCE [Alves] - Don't use _vsnprintf on later versions of MSVC [Lowman] - Add CMake build script and input file [Lowman] - Update contrib/minizip to 1.1 [Svensson, Vollant] - Moved nintendods directory from contrib to . - Replace gzio.c with a new set of routines with the same functionality - Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above - Update contrib/minizip to 1.1b - Change gzeof() to return 0 on error instead of -1 to agree with zlib.h Changes in 1.2.3.4 (21 Dec 2009) - Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility - Update comments in configure and Makefile.in for default --shared - Fix test -z's in configure [Marquess] - Build examplesh and minigzipsh when not testing - Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h - Import LDFLAGS from the environment in configure - Fix configure to populate SFLAGS with discovered CFLAGS options - Adapt make_vms.com to the new Makefile.in [Zinser] - Add zlib2ansi script for C++ compilation [Marquess] - Add _FILE_OFFSET_BITS=64 test to make test (when applicable) - Add AMD64 assembler code for longest match to contrib [Teterin] - Include options from $SFLAGS when doing $LDSHARED - Simplify 64-bit file support by introducing z_off64_t type - Make shared object files in objs directory to work around old Sun cc - Use only three-part version number for Darwin shared compiles - Add rc option to ar in Makefile.in for when ./configure not run - Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* - Set LD_LIBRARYN32_PATH for SGI IRIX shared compile - Protect against _FILE_OFFSET_BITS being defined when compiling zlib - Rename Makefile.in targets allstatic to static and allshared to shared - Fix static and shared Makefile.in targets to be independent - Correct error return bug in gz_open() by setting state [Brown] - Put spaces before ;;'s in configure for better sh compatibility - Add pigz.c (parallel implementation of gzip) to examples/ - Correct constant in crc32.c to UL [Leventhal] - Reject negative lengths in crc32_combine() - Add inflateReset2() function to work like inflateEnd()/inflateInit2() - Include sys/types.h for _LARGEFILE64_SOURCE [Brown] - Correct typo in doc/algorithm.txt [Janik] - Fix bug in adler32_combine() [Zhu] - Catch missing-end-of-block-code error in all inflates and in puff Assures that random input to inflate eventually results in an error - Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ - Update ENOUGH and its usage to reflect discovered bounds - Fix gzerror() error report on empty input file [Brown] - Add ush casts in trees.c to avoid pedantic runtime errors - Fix typo in zlib.h uncompress() description [Reiss] - Correct inflate() comments with regard to automatic header detection - Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) - Put new version of gzlog (2.0) in examples with interruption recovery - Add puff compile option to permit invalid distance-too-far streams - Add puff TEST command options, ability to read piped input - Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but _LARGEFILE64_SOURCE not defined - Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart - Fix deflateSetDictionary() to use all 32K for output consistency - Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) - Clear bytes after deflate lookahead to avoid use of uninitialized data - Change a limit in inftrees.c to be more transparent to Coverity Prevent - Update win32/zlib.def with exported symbols from zlib.h - Correct spelling error in zlib.h [Willem] - Allow Z_BLOCK for deflate() to force a new block - Allow negative bits in inflatePrime() to delete existing bit buffer - Add Z_TREES flush option to inflate() to return at end of trees - Add inflateMark() to return current state information for random access - Add Makefile for NintendoDS to contrib [Costa] - Add -w in configure compile tests to avoid spurious warnings [Beucler] - Fix typos in zlib.h comments for deflateSetDictionary() - Fix EOF detection in transparent gzread() [Maier] Changes in 1.2.3.3 (2 October 2006) - Make --shared the default for configure, add a --static option - Add compile option to permit invalid distance-too-far streams - Add inflateUndermine() function which is required to enable above - Remove use of "this" variable name for C++ compatibility [Marquess] - Add testing of shared library in make test, if shared library built - Use ftello() and fseeko() if available instead of ftell() and fseek() - Provide two versions of all functions that use the z_off_t type for binary compatibility -- a normal version and a 64-bit offset version, per the Large File Support Extension when _LARGEFILE64_SOURCE is defined; use the 64-bit versions by default when _FILE_OFFSET_BITS is defined to be 64 - Add a --uname= option to configure to perhaps help with cross-compiling Changes in 1.2.3.2 (3 September 2006) - Turn off silly Borland warnings [Hay] - Use off64_t and define _LARGEFILE64_SOURCE when present - Fix missing dependency on inffixed.h in Makefile.in - Rig configure --shared to build both shared and static [Teredesai, Truta] - Remove zconf.in.h and instead create a new zlibdefs.h file - Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] - Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] Changes in 1.2.3.1 (16 August 2006) - Add watcom directory with OpenWatcom make files [Daniel] - Remove #undef of FAR in zconf.in.h for MVS [Fedtke] - Update make_vms.com [Zinser] - Use -fPIC for shared build in configure [Teredesai, Nicholson] - Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] - Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck] - Add some FAQ entries about the contrib directory - Update the MVS question in the FAQ - Avoid extraneous reads after EOF in gzio.c [Brown] - Correct spelling of "successfully" in gzio.c [Randers-Pehrson] - Add comments to zlib.h about gzerror() usage [Brown] - Set extra flags in gzip header in gzopen() like deflate() does - Make configure options more compatible with double-dash conventions [Weigelt] - Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] - Fix uninstall target in Makefile.in [Truta] - Add pkgconfig support [Weigelt] - Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] - Replace set_data_type() with a more accurate detect_data_type() in trees.c, according to the txtvsbin.txt document [Truta] - Swap the order of #include and #include "zlib.h" in gzio.c, example.c and minigzip.c [Truta] - Shut up annoying VS2005 warnings about standard C deprecation [Rowe, Truta] (where?) - Fix target "clean" from win32/Makefile.bor [Truta] - Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] - Update zlib www home address in win32/DLL_FAQ.txt [Truta] - Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] - Enable browse info in the "Debug" and "ASM Debug" configurations in the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] - Add pkgconfig support [Weigelt] - Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, for use in win32/zlib1.rc [Polushin, Rowe, Truta] - Add a document that explains the new text detection scheme to doc/txtvsbin.txt [Truta] - Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] - Move algorithm.txt into doc/ [Truta] - Synchronize FAQ with website - Fix compressBound(), was low for some pathological cases [Fearnley] - Take into account wrapper variations in deflateBound() - Set examples/zpipe.c input and output to binary mode for Windows - Update examples/zlib_how.html with new zpipe.c (also web site) - Fix some warnings in examples/gzlog.c and examples/zran.c (it seems that gcc became pickier in 4.0) - Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain un-versioned, the patch adds versioning only for symbols introduced in zlib-1.2.0 or later. It also declares as local those symbols which are not designed to be exported." [Levin] - Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure - Do not initialize global static by default in trees.c, add a response NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] - Don't use strerror() in gzio.c under WinCE [Yakimov] - Don't use errno.h in zutil.h under WinCE [Yakimov] - Move arguments for AR to its usage to allow replacing ar [Marot] - Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] - Improve inflateInit() and inflateInit2() documentation - Fix structure size comment in inflate.h - Change configure help option from --h* to --help [Santos] Changes in 1.2.3 (18 July 2005) - Apply security vulnerability fixes to contrib/infback9 as well - Clean up some text files (carriage returns, trailing space) - Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] Changes in 1.2.2.4 (11 July 2005) - Add inflatePrime() function for starting inflation at bit boundary - Avoid some Visual C warnings in deflate.c - Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit compile - Fix some spelling errors in comments [Betts] - Correct inflateInit2() error return documentation in zlib.h - Add zran.c example of compressed data random access to examples directory, shows use of inflatePrime() - Fix cast for assignments to strm->state in inflate.c and infback.c - Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] - Move declarations of gf2 functions to right place in crc32.c [Oberhumer] - Add cast in trees.c t avoid a warning [Oberhumer] - Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] - Update make_vms.com [Zinser] - Initialize state->write in inflateReset() since copied in inflate_fast() - Be more strict on incomplete code sets in inflate_table() and increase ENOUGH and MAXD -- this repairs a possible security vulnerability for invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for discovering the vulnerability and providing test cases. - Add ia64 support to configure for HP-UX [Smith] - Add error return to gzread() for format or i/o error [Levin] - Use malloc.h for OS/2 [Necasek] Changes in 1.2.2.3 (27 May 2005) - Replace 1U constants in inflate.c and inftrees.c for 64-bit compile - Typecast fread() return values in gzio.c [Vollant] - Remove trailing space in minigzip.c outmode (VC++ can't deal with it) - Fix crc check bug in gzread() after gzungetc() [Heiner] - Add the deflateTune() function to adjust internal compression parameters - Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) - Remove an incorrect assertion in examples/zpipe.c - Add C++ wrapper in infback9.h [Donais] - Fix bug in inflateCopy() when decoding fixed codes - Note in zlib.h how much deflateSetDictionary() actually uses - Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) - Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] - Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] - Add gzdirect() function to indicate transparent reads - Update contrib/minizip [Vollant] - Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] - Add casts in crc32.c to avoid warnings [Oberhumer] - Add contrib/masmx64 [Vollant] - Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] Changes in 1.2.2.2 (30 December 2004) - Replace structure assignments in deflate.c and inflate.c with zmemcpy to avoid implicit memcpy calls (portability for no-library compilation) - Increase sprintf() buffer size in gzdopen() to allow for large numbers - Add INFLATE_STRICT to check distances against zlib header - Improve WinCE errno handling and comments [Chang] - Remove comment about no gzip header processing in FAQ - Add Z_FIXED strategy option to deflateInit2() to force fixed trees - Add updated make_vms.com [Coghlan], update README - Create a new "examples" directory, move gzappend.c there, add zpipe.c, fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. - Add FAQ entry and comments in deflate.c on uninitialized memory access - Add Solaris 9 make options in configure [Gilbert] - Allow strerror() usage in gzio.c for STDC - Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] - Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] - Use z_off_t for adler32_combine() and crc32_combine() lengths - Make adler32() much faster for small len - Use OS_CODE in deflate() default gzip header Changes in 1.2.2.1 (31 October 2004) - Allow inflateSetDictionary() call for raw inflate - Fix inflate header crc check bug for file names and comments - Add deflateSetHeader() and gz_header structure for custom gzip headers - Add inflateGetheader() to retrieve gzip headers - Add crc32_combine() and adler32_combine() functions - Add alloc_func, free_func, in_func, out_func to Z_PREFIX list - Use zstreamp consistently in zlib.h (inflate_back functions) - Remove GUNZIP condition from definition of inflate_mode in inflate.h and in contrib/inflate86/inffast.S [Truta, Anderson] - Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] - Update projects/README.projects and projects/visualc6 [Truta] - Update win32/DLL_FAQ.txt [Truta] - Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] - Deprecate Z_ASCII; use Z_TEXT instead [Truta] - Use a new algorithm for setting strm->data_type in trees.c [Truta] - Do not define an exit() prototype in zutil.c unless DEBUG defined - Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] - Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() - Fix Darwin build version identification [Peterson] Changes in 1.2.2 (3 October 2004) - Update zlib.h comments on gzip in-memory processing - Set adler to 1 in inflateReset() to support Java test suite [Walles] - Add contrib/dotzlib [Ravn] - Update win32/DLL_FAQ.txt [Truta] - Update contrib/minizip [Vollant] - Move contrib/visual-basic.txt to old/ [Truta] - Fix assembler builds in projects/visualc6/ [Truta] Changes in 1.2.1.2 (9 September 2004) - Update INDEX file - Fix trees.c to update strm->data_type (no one ever noticed!) - Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] - Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) - Add limited multitasking protection to DYNAMIC_CRC_TABLE - Add NO_vsnprintf for VMS in zutil.h [Mozilla] - Don't declare strerror() under VMS [Mozilla] - Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize - Update contrib/ada [Anisimkov] - Update contrib/minizip [Vollant] - Fix configure to not hardcode directories for Darwin [Peterson] - Fix gzio.c to not return error on empty files [Brown] - Fix indentation; update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas [Truta] - Update mkasm.bat in contrib/masmx86 [Truta] - Update contrib/untgz [Truta] - Add projects/README.projects [Truta] - Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] - Update win32/DLL_FAQ.txt [Truta] - Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] - Remove an unnecessary assignment to curr in inftrees.c [Truta] - Add OS/2 to exe builds in configure [Poltorak] - Remove err dummy parameter in zlib.h [Kientzle] Changes in 1.2.1.1 (9 January 2004) - Update email address in README - Several FAQ updates - Fix a big fat bug in inftrees.c that prevented decoding valid dynamic blocks with only literals and no distance codes -- Thanks to "Hot Emu" for the bug report and sample file - Add a note to puff.c on no distance codes case. Changes in 1.2.1 (17 November 2003) - Remove a tab in contrib/gzappend/gzappend.c - Update some interfaces in contrib for new zlib functions - Update zlib version number in some contrib entries - Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] - Support shared libraries on Hurd and KFreeBSD [Brown] - Fix error in NO_DIVIDE option of adler32.c Changes in 1.2.0.8 (4 November 2003) - Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas - Add experimental NO_DIVIDE #define in adler32.c - Possibly faster on some processors (let me know if it is) - Correct Z_BLOCK to not return on first inflate call if no wrap - Fix strm->data_type on inflate() return to correctly indicate EOB - Add deflatePrime() function for appending in the middle of a byte - Add contrib/gzappend for an example of appending to a stream - Update win32/DLL_FAQ.txt [Truta] - Delete Turbo C comment in README [Truta] - Improve some indentation in zconf.h [Truta] - Fix infinite loop on bad input in configure script [Church] - Fix gzeof() for concatenated gzip files [Johnson] - Add example to contrib/visual-basic.txt [Michael B.] - Add -p to mkdir's in Makefile.in [vda] - Fix configure to properly detect presence or lack of printf functions - Add AS400 support [Monnerat] - Add a little Cygwin support [Wilson] Changes in 1.2.0.7 (21 September 2003) - Correct some debug formats in contrib/infback9 - Cast a type in a debug statement in trees.c - Change search and replace delimiter in configure from % to # [Beebe] - Update contrib/untgz to 0.2 with various fixes [Truta] - Add build support for Amiga [Nikl] - Remove some directories in old that have been updated to 1.2 - Add dylib building for Mac OS X in configure and Makefile.in - Remove old distribution stuff from Makefile - Update README to point to DLL_FAQ.txt, and add comment on Mac OS X - Update links in README Changes in 1.2.0.6 (13 September 2003) - Minor FAQ updates - Update contrib/minizip to 1.00 [Vollant] - Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] - Update POSTINC comment for 68060 [Nikl] - Add contrib/infback9 with deflate64 decoding (unsupported) - For MVS define NO_vsnprintf and undefine FAR [van Burik] - Add pragma for fdopen on MVS [van Burik] Changes in 1.2.0.5 (8 September 2003) - Add OF to inflateBackEnd() declaration in zlib.h - Remember start when using gzdopen in the middle of a file - Use internal off_t counters in gz* functions to properly handle seeks - Perform more rigorous check for distance-too-far in inffast.c - Add Z_BLOCK flush option to return from inflate at block boundary - Set strm->data_type on return from inflate - Indicate bits unused, if at block boundary, and if in last block - Replace size_t with ptrdiff_t in crc32.c, and check for correct size - Add condition so old NO_DEFLATE define still works for compatibility - FAQ update regarding the Windows DLL [Truta] - INDEX update: add qnx entry, remove aix entry [Truta] - Install zlib.3 into mandir [Wilson] - Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] - Adapt the zlib interface to the new DLL convention guidelines [Truta] - Introduce ZLIB_WINAPI macro to allow the export of functions using the WINAPI calling convention, for Visual Basic [Vollant, Truta] - Update msdos and win32 scripts and makefiles [Truta] - Export symbols by name, not by ordinal, in win32/zlib.def [Truta] - Add contrib/ada [Anisimkov] - Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] - Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] - Add contrib/masm686 [Truta] - Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm [Truta, Vollant] - Update contrib/delphi; rename to contrib/pascal; add example [Truta] - Remove contrib/delphi2; add a new contrib/delphi [Truta] - Avoid inclusion of the nonstandard in contrib/iostream, and fix some method prototypes [Truta] - Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip [Truta] - Avoid the use of backslash (\) in contrib/minizip [Vollant] - Fix file time handling in contrib/untgz; update makefiles [Truta] - Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines [Vollant] - Remove contrib/vstudio/vc15_16 [Vollant] - Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] - Update README.contrib [Truta] - Invert the assignment order of match_head and s->prev[...] in INSERT_STRING [Truta] - Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings [Truta] - Compare function pointers with 0, not with NULL or Z_NULL [Truta] - Fix prototype of syncsearch in inflate.c [Truta] - Introduce ASMINF macro to be enabled when using an ASM implementation of inflate_fast [Truta] - Change NO_DEFLATE to NO_GZCOMPRESS [Truta] - Modify test_gzio in example.c to take a single file name as a parameter [Truta] - Exit the example.c program if gzopen fails [Truta] - Add type casts around strlen in example.c [Truta] - Remove casting to sizeof in minigzip.c; give a proper type to the variable compared with SUFFIX_LEN [Truta] - Update definitions of STDC and STDC99 in zconf.h [Truta] - Synchronize zconf.h with the new Windows DLL interface [Truta] - Use SYS16BIT instead of __32BIT__ to distinguish between 16- and 32-bit platforms [Truta] - Use far memory allocators in small 16-bit memory models for Turbo C [Truta] - Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in zlibCompileFlags [Truta] - Cygwin has vsnprintf [Wilson] - In Windows16, OS_CODE is 0, as in MSDOS [Truta] - In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] Changes in 1.2.0.4 (10 August 2003) - Minor FAQ updates - Be more strict when checking inflateInit2's windowBits parameter - Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well - Add gzip wrapper option to deflateInit2 using windowBits - Add updated QNX rule in configure and qnx directory [Bonnefoy] - Make inflate distance-too-far checks more rigorous - Clean up FAR usage in inflate - Add casting to sizeof() in gzio.c and minigzip.c Changes in 1.2.0.3 (19 July 2003) - Fix silly error in gzungetc() implementation [Vollant] - Update contrib/minizip and contrib/vstudio [Vollant] - Fix printf format in example.c - Correct cdecl support in zconf.in.h [Anisimkov] - Minor FAQ updates Changes in 1.2.0.2 (13 July 2003) - Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons - Attempt to avoid warnings in crc32.c for pointer-int conversion - Add AIX to configure, remove aix directory [Bakker] - Add some casts to minigzip.c - Improve checking after insecure sprintf() or vsprintf() calls - Remove #elif's from crc32.c - Change leave label to inf_leave in inflate.c and infback.c to avoid library conflicts - Remove inflate gzip decoding by default--only enable gzip decoding by special request for stricter backward compatibility - Add zlibCompileFlags() function to return compilation information - More typecasting in deflate.c to avoid warnings - Remove leading underscore from _Capital #defines [Truta] - Fix configure to link shared library when testing - Add some Windows CE target adjustments [Mai] - Remove #define ZLIB_DLL in zconf.h [Vollant] - Add zlib.3 [Rodgers] - Update RFC URL in deflate.c and algorithm.txt [Mai] - Add zlib_dll_FAQ.txt to contrib [Truta] - Add UL to some constants [Truta] - Update minizip and vstudio [Vollant] - Remove vestigial NEED_DUMMY_RETURN from zconf.in.h - Expand use of NO_DUMMY_DECL to avoid all dummy structures - Added iostream3 to contrib [Schwardt] - Replace rewind() with fseek() for WinCE [Truta] - Improve setting of zlib format compression level flags - Report 0 for huffman and rle strategies and for level == 0 or 1 - Report 2 only for level == 6 - Only deal with 64K limit when necessary at compile time [Truta] - Allow TOO_FAR check to be turned off at compile time [Truta] - Add gzclearerr() function [Souza] - Add gzungetc() function Changes in 1.2.0.1 (17 March 2003) - Add Z_RLE strategy for run-length encoding [Truta] - When Z_RLE requested, restrict matches to distance one - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE - Correct FASTEST compilation to allow level == 0 - Clean up what gets compiled for FASTEST - Incorporate changes to zconf.in.h [Vollant] - Refine detection of Turbo C need for dummy returns - Refine ZLIB_DLL compilation - Include additional header file on VMS for off_t typedef - Try to use _vsnprintf where it supplants vsprintf [Vollant] - Add some casts in inffast.c - Enchance comments in zlib.h on what happens if gzprintf() tries to write more than 4095 bytes before compression - Remove unused state from inflateBackEnd() - Remove exit(0) from minigzip.c, example.c - Get rid of all those darn tabs - Add "check" target to Makefile.in that does the same thing as "test" - Add "mostlyclean" and "maintainer-clean" targets to Makefile.in - Update contrib/inflate86 [Anderson] - Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] - Add msdos and win32 directories with makefiles [Truta] - More additions and improvements to the FAQ Changes in 1.2.0 (9 March 2003) - New and improved inflate code - About 20% faster - Does not allocate 32K window unless and until needed - Automatically detects and decompresses gzip streams - Raw inflate no longer needs an extra dummy byte at end - Added inflateBack functions using a callback interface--even faster than inflate, useful for file utilities (gzip, zip) - Added inflateCopy() function to record state for random access on externally generated deflate streams (e.g. in gzip files) - More readable code (I hope) - New and improved crc32() - About 50% faster, thanks to suggestions from Rodney Brown - Add deflateBound() and compressBound() functions - Fix memory leak in deflateInit2() - Permit setting dictionary for raw deflate (for parallel deflate) - Fix const declaration for gzwrite() - Check for some malloc() failures in gzio.c - Fix bug in gzopen() on single-byte file 0x1f - Fix bug in gzread() on concatenated file with 0x1f at end of buffer and next buffer doesn't start with 0x8b - Fix uncompress() to return Z_DATA_ERROR on truncated input - Free memory at end of example.c - Remove MAX #define in trees.c (conflicted with some libraries) - Fix static const's in deflate.c, gzio.c, and zutil.[ch] - Declare malloc() and free() in gzio.c if STDC not defined - Use malloc() instead of calloc() in zutil.c if int big enough - Define STDC for AIX - Add aix/ with approach for compiling shared library on AIX - Add HP-UX support for shared libraries in configure - Add OpenUNIX support for shared libraries in configure - Use $cc instead of gcc to build shared library - Make prefix directory if needed when installing - Correct Macintosh avoidance of typedef Byte in zconf.h - Correct Turbo C memory allocation when under Linux - Use libz.a instead of -lz in Makefile (assure use of compiled library) - Update configure to check for snprintf or vsnprintf functions and their return value, warn during make if using an insecure function - Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that is lost when library is used--resolution is to build new zconf.h - Documentation improvements (in zlib.h): - Document raw deflate and inflate - Update RFCs URL - Point out that zlib and gzip formats are different - Note that Z_BUF_ERROR is not fatal - Document string limit for gzprintf() and possible buffer overflow - Note requirement on avail_out when flushing - Note permitted values of flush parameter of inflate() - Add some FAQs (and even answers) to the FAQ - Add contrib/inflate86/ for x86 faster inflate - Add contrib/blast/ for PKWare Data Compression Library decompression - Add contrib/puff/ simple inflate for deflate format description Changes in 1.1.4 (11 March 2002) - ZFREE was repeated on same allocation on some error conditions. This creates a security problem described in http://www.zlib.org/advisory-2002-03-11.txt - Returned incorrect error (Z_MEM_ERROR) on some invalid data - Avoid accesses before window for invalid distances with inflate window less than 32K. - force windowBits > 8 to avoid a bug in the encoder for a window size of 256 bytes. (A complete fix will be available in 1.1.5). Changes in 1.1.3 (9 July 1998) - fix "an inflate input buffer bug that shows up on rare but persistent occasions" (Mark) - fix gzread and gztell for concatenated .gz files (Didier Le Botlan) - fix gzseek(..., SEEK_SET) in write mode - fix crc check after a gzeek (Frank Faubert) - fix miniunzip when the last entry in a zip file is itself a zip file (J Lillge) - add contrib/asm586 and contrib/asm686 (Brian Raiter) See http://www.muppetlabs.com/~breadbox/software/assembly.html - add support for Delphi 3 in contrib/delphi (Bob Dellaca) - add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) - do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) - use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) - added a FAQ file - Support gzdopen on Mac with Metrowerks (Jason Linhart) - Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) - define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) - avoid some warnings with Borland C (Tom Tanner) - fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) - emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) - allow several arguments to configure (Tim Mooney, Frodo Looijaard) - use libdir and includedir in Makefile.in (Tim Mooney) - support shared libraries on OSF1 V4 (Tim Mooney) - remove so_locations in "make clean" (Tim Mooney) - fix maketree.c compilation error (Glenn, Mark) - Python interface to zlib now in Python 1.5 (Jeremy Hylton) - new Makefile.riscos (Rich Walker) - initialize static descriptors in trees.c for embedded targets (Nick Smith) - use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) - add the OS/2 files in Makefile.in too (Andrew Zabolotny) - fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) - fix maketree.c to allow clean compilation of inffixed.h (Mark) - fix parameter check in deflateCopy (Gunther Nikl) - cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) - Many portability patches by Christian Spieler: . zutil.c, zutil.h: added "const" for zmem* . Make_vms.com: fixed some typos . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists . msdos/Makefile.msc: remove "default rtl link library" info from obj files . msdos/Makefile.*: use model-dependent name for the built zlib library . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) - use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) - replace __far with _far for better portability (Christian Spieler, Tom Lane) - fix test for errno.h in configure (Tim Newsham) Changes in 1.1.2 (19 March 98) - added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) See http://www.winimage.com/zLibDll/unzip.html - preinitialize the inflate tables for fixed codes, to make the code completely thread safe (Mark) - some simplifications and slight speed-up to the inflate code (Mark) - fix gzeof on non-compressed files (Allan Schrum) - add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) - use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) - added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) - add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) - do not wrap extern "C" around system includes (Tom Lane) - mention zlib binding for TCL in README (Andreas Kupries) - added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) - allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) - allow "configure --prefix $HOME" (Tim Mooney) - remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) - move Makefile.sas to amiga/Makefile.sas Changes in 1.1.1 (27 Feb 98) - fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) - remove block truncation heuristic which had very marginal effect for zlib (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the compression ratio on some files. This also allows inlining _tr_tally for matches in deflate_slow. - added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) Changes in 1.1.0 (24 Feb 98) - do not return STREAM_END prematurely in inflate (John Bowler) - revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) - compile with -DFASTEST to get compression code optimized for speed only - in minigzip, try mmap'ing the input file first (Miguel Albrecht) - increase size of I/O buffers in minigzip.c and gzio.c (not a big gain on Sun but significant on HP) - add a pointer to experimental unzip library in README (Gilles Vollant) - initialize variable gcc in configure (Chris Herborth) Changes in 1.0.9 (17 Feb 1998) - added gzputs and gzgets functions - do not clear eof flag in gzseek (Mark Diekhans) - fix gzseek for files in transparent mode (Mark Diekhans) - do not assume that vsprintf returns the number of bytes written (Jens Krinke) - replace EXPORT with ZEXPORT to avoid conflict with other programs - added compress2 in zconf.h, zlib.def, zlib.dnt - new asm code from Gilles Vollant in contrib/asm386 - simplify the inflate code (Mark): . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() . ZALLOC the length list in inflate_trees_fixed() instead of using stack . ZALLOC the value area for huft_build() instead of using stack . Simplify Z_FINISH check in inflate() - Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 - in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) - in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with the declaration of FAR (Gilles VOllant) - install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) - read_buf buf parameter of type Bytef* instead of charf* - zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) - do not redeclare unlink in minigzip.c for WIN32 (John Bowler) - fix check for presence of directories in "make install" (Ian Willis) Changes in 1.0.8 (27 Jan 1998) - fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) - fix gzgetc and gzputc for big endian systems (Markus Oberhumer) - added compress2() to allow setting the compression level - include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) - use constant arrays for the static trees in trees.c instead of computing them at run time (thanks to Ken Raeburn for this suggestion). To create trees.h, compile with GEN_TREES_H and run "make test". - check return code of example in "make test" and display result - pass minigzip command line options to file_compress - simplifying code of inflateSync to avoid gcc 2.8 bug - support CC="gcc -Wall" in configure -s (QingLong) - avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) - fix test for shared library support to avoid compiler warnings - zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) - check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) - do not use fdopen for Metrowerks on Mac (Brad Pettit)) - add checks for gzputc and gzputc in example.c - avoid warnings in gzio.c and deflate.c (Andreas Kleinert) - use const for the CRC table (Ken Raeburn) - fixed "make uninstall" for shared libraries - use Tracev instead of Trace in infblock.c - in example.c use correct compressed length for test_sync - suppress +vnocompatwarnings in configure for HPUX (not always supported) Changes in 1.0.7 (20 Jan 1998) - fix gzseek which was broken in write mode - return error for gzseek to negative absolute position - fix configure for Linux (Chun-Chung Chen) - increase stack space for MSC (Tim Wegner) - get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) - define EXPORTVA for gzprintf (Gilles Vollant) - added man page zlib.3 (Rick Rodgers) - for contrib/untgz, fix makedir() and improve Makefile - check gzseek in write mode in example.c - allocate extra buffer for seeks only if gzseek is actually called - avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) - add inflateSyncPoint in zconf.h - fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def Changes in 1.0.6 (19 Jan 1998) - add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) - Fix a deflate bug occurring only with compression level 0 (thanks to Andy Buckler for finding this one). - In minigzip, pass transparently also the first byte for .Z files. - return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() - check Z_FINISH in inflate (thanks to Marc Schluper) - Implement deflateCopy (thanks to Adam Costello) - make static libraries by default in configure, add --shared option. - move MSDOS or Windows specific files to directory msdos - suppress the notion of partial flush to simplify the interface (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) - suppress history buffer provided by application to simplify the interface (this feature was not implemented anyway in 1.0.4) - next_in and avail_in must be initialized before calling inflateInit or inflateInit2 - add EXPORT in all exported functions (for Windows DLL) - added Makefile.nt (thanks to Stephen Williams) - added the unsupported "contrib" directory: contrib/asm386/ by Gilles Vollant 386 asm code replacing longest_match(). contrib/iostream/ by Kevin Ruland A C++ I/O streams interface to the zlib gz* functions contrib/iostream2/ by Tyge Løvset Another C++ I/O streams interface contrib/untgz/ by "Pedro A. Aranda Guti\irrez" A very simple tar.gz file extractor using zlib contrib/visual-basic.txt by Carlos Rios How to use compress(), uncompress() and the gz* functions from VB. - pass params -f (filtered data), -h (huffman only), -1 to -9 (compression level) in minigzip (thanks to Tom Lane) - use const for rommable constants in deflate - added test for gzseek and gztell in example.c - add undocumented function inflateSyncPoint() (hack for Paul Mackerras) - add undocumented function zError to convert error code to string (for Tim Smithers) - Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. - Use default memcpy for Symantec MSDOS compiler. - Add EXPORT keyword for check_func (needed for Windows DLL) - add current directory to LD_LIBRARY_PATH for "make test" - create also a link for libz.so.1 - added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) - use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) - added -soname for Linux in configure (Chun-Chung Chen, - assign numbers to the exported functions in zlib.def (for Windows DLL) - add advice in zlib.h for best usage of deflateSetDictionary - work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) - allow compilation with ANSI keywords only enabled for TurboC in large model - avoid "versionString"[0] (Borland bug) - add NEED_DUMMY_RETURN for Borland - use variable z_verbose for tracing in debug mode (L. Peter Deutsch). - allow compilation with CC - defined STDC for OS/2 (David Charlap) - limit external names to 8 chars for MVS (Thomas Lund) - in minigzip.c, use static buffers only for 16-bit systems - fix suffix check for "minigzip -d foo.gz" - do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) - use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) - added makelcc.bat for lcc-win32 (Tom St Denis) - in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) - Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. - check for unistd.h in configure (for off_t) - remove useless check parameter in inflate_blocks_free - avoid useless assignment of s->check to itself in inflate_blocks_new - do not flush twice in gzclose (thanks to Ken Raeburn) - rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h - use NO_ERRNO_H instead of enumeration of operating systems with errno.h - work around buggy fclose on pipes for HP/UX - support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) - fix configure if CC is already equal to gcc Changes in 1.0.5 (3 Jan 98) - Fix inflate to terminate gracefully when fed corrupted or invalid data - Use const for rommable constants in inflate - Eliminate memory leaks on error conditions in inflate - Removed some vestigial code in inflate - Update web address in README Changes in 1.0.4 (24 Jul 96) - In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF bit, so the decompressor could decompress all the correct data but went on to attempt decompressing extra garbage data. This affected minigzip too. - zlibVersion and gzerror return const char* (needed for DLL) - port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) - use z_error only for DEBUG (avoid problem with DLLs) Changes in 1.0.3 (2 Jul 96) - use z_streamp instead of z_stream *, which is now a far pointer in MSDOS small and medium models; this makes the library incompatible with previous versions for these models. (No effect in large model or on other systems.) - return OK instead of BUF_ERROR if previous deflate call returned with avail_out as zero but there is nothing to do - added memcmp for non STDC compilers - define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) - define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) - better check for 16-bit mode MSC (avoids problem with Symantec) Changes in 1.0.2 (23 May 96) - added Windows DLL support - added a function zlibVersion (for the DLL support) - fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) - Bytef is define's instead of typedef'd only for Borland C - avoid reading uninitialized memory in example.c - mention in README that the zlib format is now RFC1950 - updated Makefile.dj2 - added algorithm.doc Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] - fix array overlay in deflate.c which sometimes caused bad compressed data - fix inflate bug with empty stored block - fix MSDOS medium model which was broken in 0.99 - fix deflateParams() which could generated bad compressed data. - Bytef is define'd instead of typedef'ed (work around Borland bug) - added an INDEX file - new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) - speed up adler32 for modern machines without auto-increment - added -ansi for IRIX in configure - static_init_done in trees.c is an int - define unlink as delete for VMS - fix configure for QNX - add configure branch for SCO and HPUX - avoid many warnings (unused variables, dead assignments, etc...) - no fdopen for BeOS - fix the Watcom fix for 32 bit mode (define FAR as empty) - removed redefinition of Byte for MKWERKS - work around an MWKERKS bug (incorrect merge of all .h files) Changes in 0.99 (27 Jan 96) - allow preset dictionary shared between compressor and decompressor - allow compression level 0 (no compression) - add deflateParams in zlib.h: allow dynamic change of compression level and compression strategy. - test large buffers and deflateParams in example.c - add optional "configure" to build zlib as a shared library - suppress Makefile.qnx, use configure instead - fixed deflate for 64-bit systems (detected on Cray) - fixed inflate_blocks for 64-bit systems (detected on Alpha) - declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) - always return Z_BUF_ERROR when deflate() has nothing to do - deflateInit and inflateInit are now macros to allow version checking - prefix all global functions and types with z_ with -DZ_PREFIX - make falloc completely reentrant (inftrees.c) - fixed very unlikely race condition in ct_static_init - free in reverse order of allocation to help memory manager - use zlib-1.0/* instead of zlib/* inside the tar.gz - make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion -Wstrict-prototypes -Wmissing-prototypes" - allow gzread on concatenated .gz files - deflateEnd now returns Z_DATA_ERROR if it was premature - deflate is finally (?) fully deterministic (no matches beyond end of input) - Document Z_SYNC_FLUSH - add uninstall in Makefile - Check for __cpluplus in zlib.h - Better test in ct_align for partial flush - avoid harmless warnings for Borland C++ - initialize hash_head in deflate.c - avoid warning on fdopen (gzio.c) for HP cc -Aa - include stdlib.h for STDC compilers - include errno.h for Cray - ignore error if ranlib doesn't exist - call ranlib twice for NeXTSTEP - use exec_prefix instead of prefix for libz.a - renamed ct_* as _tr_* to avoid conflict with applications - clear z->msg in inflateInit2 before any error return - initialize opaque in example.c, gzio.c, deflate.c and inflate.c - fixed typo in zconf.h (_GNUC__ => __GNUC__) - check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) - fix typo in Make_vms.com (f$trnlnm -> f$getsyi) - in fcalloc, normalize pointer if size > 65520 bytes - don't use special fcalloc for 32 bit Borland C++ - use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... - use Z_BINARY instead of BINARY - document that gzclose after gzdopen will close the file - allow "a" as mode in gzopen. - fix error checking in gzread - allow skipping .gz extra-field on pipes - added reference to Perl interface in README - put the crc table in FAR data (I dislike more and more the medium model :) - added get_crc_table - added a dimension to all arrays (Borland C can't count). - workaround Borland C bug in declaration of inflate_codes_new & inflate_fast - guard against multiple inclusion of *.h (for precompiled header on Mac) - Watcom C pretends to be Microsoft C small model even in 32 bit mode. - don't use unsized arrays to avoid silly warnings by Visual C++: warning C4746: 'inflate_mask' : unsized array treated as '__far' (what's wrong with far data in far model?). - define enum out of inflate_blocks_state to allow compilation with C++ Changes in 0.95 (16 Aug 95) - fix MSDOS small and medium model (now easier to adapt to any compiler) - inlined send_bits - fix the final (:-) bug for deflate with flush (output was correct but not completely flushed in rare occasions). - default window size is same for compression and decompression (it's now sufficient to set MAX_WBITS in zconf.h). - voidp -> voidpf and voidnp -> voidp (for consistency with other typedefs and because voidnp was not near in large model). Changes in 0.94 (13 Aug 95) - support MSDOS medium model - fix deflate with flush (could sometimes generate bad output) - fix deflateReset (zlib header was incorrectly suppressed) - added support for VMS - allow a compression level in gzopen() - gzflush now calls fflush - For deflate with flush, flush even if no more input is provided. - rename libgz.a as libz.a - avoid complex expression in infcodes.c triggering Turbo C bug - work around a problem with gcc on Alpha (in INSERT_STRING) - don't use inline functions (problem with some gcc versions) - allow renaming of Byte, uInt, etc... with #define. - avoid warning about (unused) pointer before start of array in deflate.c - avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c - avoid reserved word 'new' in trees.c Changes in 0.93 (25 June 95) - temporarily disable inline functions - make deflate deterministic - give enough lookahead for PARTIAL_FLUSH - Set binary mode for stdin/stdout in minigzip.c for OS/2 - don't even use signed char in inflate (not portable enough) - fix inflate memory leak for segmented architectures Changes in 0.92 (3 May 95) - don't assume that char is signed (problem on SGI) - Clear bit buffer when starting a stored block - no memcpy on Pyramid - suppressed inftest.c - optimized fill_window, put longest_match inline for gcc - optimized inflate on stored blocks. - untabify all sources to simplify patches Changes in 0.91 (2 May 95) - Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h - Document the memory requirements in zconf.h - added "make install" - fix sync search logic in inflateSync - deflate(Z_FULL_FLUSH) now works even if output buffer too short - after inflateSync, don't scare people with just "lo world" - added support for DJGPP Changes in 0.9 (1 May 95) - don't assume that zalloc clears the allocated memory (the TurboC bug was Mark's bug after all :) - let again gzread copy uncompressed data unchanged (was working in 0.71) - deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented - added a test of inflateSync in example.c - moved MAX_WBITS to zconf.h because users might want to change that. - document explicitly that zalloc(64K) on MSDOS must return a normalized pointer (zero offset) - added Makefiles for Microsoft C, Turbo C, Borland C++ - faster crc32() Changes in 0.8 (29 April 95) - added fast inflate (inffast.c) - deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this is incompatible with previous versions of zlib which returned Z_OK. - work around a TurboC compiler bug (bad code for b << 0, see infutil.h) (actually that was not a compiler bug, see 0.81 above) - gzread no longer reads one extra byte in certain cases - In gzio destroy(), don't reference a freed structure - avoid many warnings for MSDOS - avoid the ERROR symbol which is used by MS Windows Changes in 0.71 (14 April 95) - Fixed more MSDOS compilation problems :( There is still a bug with TurboC large model. Changes in 0.7 (14 April 95) - Added full inflate support. - Simplified the crc32() interface. The pre- and post-conditioning (one's complement) is now done inside crc32(). WARNING: this is incompatible with previous versions; see zlib.h for the new usage. Changes in 0.61 (12 April 95) - workaround for a bug in TurboC. example and minigzip now work on MSDOS. Changes in 0.6 (11 April 95) - added minigzip.c - added gzdopen to reopen a file descriptor as gzFile - added transparent reading of non-gziped files in gzread. - fixed bug in gzread (don't read crc as data) - fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). - don't allocate big arrays in the stack (for MSDOS) - fix some MSDOS compilation problems Changes in 0.5: - do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but not yet Z_FULL_FLUSH. - support decompression but only in a single step (forced Z_FINISH) - added opaque object for zalloc and zfree. - added deflateReset and inflateReset - added a variable zlib_version for consistency checking. - renamed the 'filter' parameter of deflateInit2 as 'strategy'. Added Z_FILTERED and Z_HUFFMAN_ONLY constants. Changes in 0.4: - avoid "zip" everywhere, use zlib instead of ziplib. - suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush if compression method == 8. - added adler32 and crc32 - renamed deflateOptions as deflateInit2, call one or the other but not both - added the method parameter for deflateInit2. - added inflateInit2 - simplied considerably deflateInit and inflateInit by not supporting user-provided history buffer. This is supported only in deflateInit2 and inflateInit2. Changes in 0.3: - prefix all macro names with Z_ - use Z_FINISH instead of deflateEnd to finish compression. - added Z_HUFFMAN_ONLY - added gzerror() bcmatroska2-5.3.101/corec/corec/helpers/zlib/FAQ000066400000000000000000000401521462133141200212120ustar00rootroot00000000000000 Frequently Asked Questions about zlib If your question is not there, please check the zlib home page http://zlib.net/ which may have more recent information. The lastest zlib FAQ is at http://zlib.net/zlib_faq.html 1. Is zlib Y2K-compliant? Yes. zlib doesn't handle dates. 2. Where can I get a Windows DLL version? The zlib sources can be compiled without change to produce a DLL. See the file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the precompiled DLL are found in the zlib web site at http://zlib.net/ . 3. Where can I get a Visual Basic interface to zlib? See * http://marknelson.us/1997/01/01/zlib-engine/ * win32/DLL_FAQ.txt in the zlib distribution 4. compress() returns Z_BUF_ERROR. Make sure that before the call of compress(), the length of the compressed buffer is equal to the available size of the compressed buffer and not zero. For Visual Basic, check that this parameter is passed by reference ("as any"), not by value ("as long"). 5. deflate() or inflate() returns Z_BUF_ERROR. Before making the call, make sure that avail_in and avail_out are not zero. When setting the parameter flush equal to Z_FINISH, also make sure that avail_out is big enough to allow processing all pending input. Note that a Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be made with more input or output space. A Z_BUF_ERROR may in fact be unavoidable depending on how the functions are used, since it is not possible to tell whether or not there is more output pending when strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a heavily annotated example. 6. Where's the zlib documentation (man pages, etc.)? It's in zlib.h . Examples of zlib usage are in the files example.c and minigzip.c, with more in examples/ . 7. Why don't you use GNU autoconf or libtool or ...? Because we would like to keep zlib as a very small and simple package. zlib is rather portable and doesn't need much configuration. 8. I found a bug in zlib. Most of the time, such problems are due to an incorrect usage of zlib. Please try to reproduce the problem with a small program and send the corresponding source to us at zlib@gzip.org . Do not send multi-megabyte data files without prior agreement. 9. Why do I get "undefined reference to gzputc"? If "make test" produces something like example.o(.text+0x154): undefined reference to `gzputc' check that you don't have old files libz.* in /usr/lib, /usr/local/lib or /usr/X11R6/lib. Remove any old versions, then do "make install". 10. I need a Delphi interface to zlib. See the contrib/delphi directory in the zlib distribution. 11. Can zlib handle .zip archives? Not by itself, no. See the directory contrib/minizip in the zlib distribution. 12. Can zlib handle .Z files? No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt the code of uncompress on your own. 13. How can I make a Unix shared library? make clean ./configure -s make 14. How do I install a shared zlib library on Unix? After the above, then: make install However, many flavors of Unix come with a shared zlib already installed. Before going to the trouble of compiling a shared version of zlib and trying to install it, you may want to check if it's already there! If you can #include , it's there. The -lz option will probably link to it. You can check the version at the top of zlib.h or with the ZLIB_VERSION symbol defined in zlib.h . 15. I have a question about OttoPDF. We are not the authors of OttoPDF. The real author is on the OttoPDF web site: Joel Hainley, jhainley@myndkryme.com. 16. Can zlib decode Flate data in an Adobe PDF file? Yes. See http://www.pdflib.com/ . To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ . 17. Why am I getting this "register_frame_info not found" error on Solaris? After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib generates an error such as: ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: symbol __register_frame_info: referenced symbol not found The symbol __register_frame_info is not part of zlib, it is generated by the C compiler (cc or gcc). You must recompile applications using zlib which have this problem. This problem is specific to Solaris. See http://www.sunfreeware.com for Solaris versions of zlib and applications using zlib. 18. Why does gzip give an error on a file I make with compress/deflate? The compress and deflate functions produce data in the zlib format, which is different and incompatible with the gzip format. The gz* functions in zlib on the other hand use the gzip format. Both the zlib and gzip formats use the same compressed data format internally, but have different headers and trailers around the compressed data. 19. Ok, so why are there two different formats? The gzip format was designed to retain the directory information about a single file, such as the name and last modification date. The zlib format on the other hand was designed for in-memory and communication channel applications, and has a much more compact header and trailer and uses a faster integrity check than gzip. 20. Well that's nice, but how do I make a gzip file in memory? You can request that deflate write the gzip format instead of the zlib format using deflateInit2(). You can also request that inflate decode the gzip format using inflateInit2(). Read zlib.h for more details. 21. Is zlib thread-safe? Yes. However any library routines that zlib uses and any application- provided memory allocation routines must also be thread-safe. zlib's gz* functions use stdio library routines, and most of zlib's functions use the library memory allocation routines by default. zlib's *Init* functions allow for the application to provide custom memory allocation routines. Of course, you should only operate on any given zlib or gzip stream from a single thread at a time. 22. Can I use zlib in my commercial application? Yes. Please read the license in zlib.h. 23. Is zlib under the GNU license? No. Please read the license in zlib.h. 24. The license says that altered source versions must be "plainly marked". So what exactly do I need to do to meet that requirement? You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In particular, the final version number needs to be changed to "f", and an identification string should be appended to ZLIB_VERSION. Version numbers x.x.x.f are reserved for modifications to zlib by others than the zlib maintainers. For example, if the version of the base zlib you are altering is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also update the version strings in deflate.c and inftrees.c. For altered source distributions, you should also note the origin and nature of the changes in zlib.h, as well as in ChangeLog and README, along with the dates of the alterations. The origin should include at least your name (or your company's name), and an email address to contact for help or issues with the library. Note that distributing a compiled zlib library along with zlib.h and zconf.h is also a source distribution, and so you should change ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes in zlib.h as you would for a full source distribution. 25. Will zlib work on a big-endian or little-endian architecture, and can I exchange compressed data between them? Yes and yes. 26. Will zlib work on a 64-bit machine? Yes. It has been tested on 64-bit machines, and has no dependence on any data types being limited to 32-bits in length. If you have any difficulties, please provide a complete problem report to zlib@gzip.org 27. Will zlib decompress data from the PKWare Data Compression Library? No. The PKWare DCL uses a completely different compressed data format than does PKZIP and zlib. However, you can look in zlib's contrib/blast directory for a possible solution to your problem. 28. Can I access data randomly in a compressed stream? No, not without some preparation. If when compressing you periodically use Z_FULL_FLUSH, carefully write all the pending data at those points, and keep an index of those locations, then you can start decompression at those points. You have to be careful to not use Z_FULL_FLUSH too often, since it can significantly degrade compression. Alternatively, you can scan a deflate stream once to generate an index, and then use that index for random access. See examples/zran.c . 29. Does zlib work on MVS, OS/390, CICS, etc.? It has in the past, but we have not heard of any recent evidence. There were working ports of zlib 1.1.4 to MVS, but those links no longer work. If you know of recent, successful applications of zlib on these operating systems, please let us know. Thanks. 30. Is there some simpler, easier to read version of inflate I can look at to understand the deflate format? First off, you should read RFC 1951. Second, yes. Look in zlib's contrib/puff directory. 31. Does zlib infringe on any patents? As far as we know, no. In fact, that was originally the whole point behind zlib. Look here for some more information: http://www.gzip.org/#faq11 32. Can zlib work with greater than 4 GB of data? Yes. inflate() and deflate() will process any amount of data correctly. Each call of inflate() or deflate() is limited to input and output chunks of the maximum value that can be stored in the compiler's "unsigned int" type, but there is no limit to the number of chunks. Note however that the strm.total_in and strm_total_out counters may be limited to 4 GB. These counters are provided as a convenience and are not used internally by inflate() or deflate(). The application can easily set up its own counters updated after each call of inflate() or deflate() to count beyond 4 GB. compress() and uncompress() may be limited to 4 GB, since they operate in a single call. gzseek() and gztell() may be limited to 4 GB depending on how zlib is compiled. See the zlibCompileFlags() function in zlib.h. The word "may" appears several times above since there is a 4 GB limit only if the compiler's "long" type is 32 bits. If the compiler's "long" type is 64 bits, then the limit is 16 exabytes. 33. Does zlib have any security vulnerabilities? The only one that we are aware of is potentially in gzprintf(). If zlib is compiled to use sprintf() or vsprintf(), then there is no protection against a buffer overflow of an 8K string space (or other value as set by gzbuffer()), other than the caller of gzprintf() assuring that the output will not exceed 8K. On the other hand, if zlib is compiled to use snprintf() or vsnprintf(), which should normally be the case, then there is no vulnerability. The ./configure script will display warnings if an insecure variation of sprintf() will be used by gzprintf(). Also the zlibCompileFlags() function will return information on what variant of sprintf() is used by gzprintf(). If you don't have snprintf() or vsnprintf() and would like one, you can find a portable implementation here: http://www.ijs.si/software/snprintf/ Note that you should be using the most recent version of zlib. Versions 1.1.3 and before were subject to a double-free vulnerability, and versions 1.2.1 and 1.2.2 were subject to an access exception when decompressing invalid compressed data. 34. Is there a Java version of zlib? Probably what you want is to use zlib in Java. zlib is already included as part of the Java SDK in the java.util.zip package. If you really want a version of zlib written in the Java language, look on the zlib home page for links: http://zlib.net/ . 35. I get this or that compiler or source-code scanner warning when I crank it up to maximally-pedantic. Can't you guys write proper code? Many years ago, we gave up attempting to avoid warnings on every compiler in the universe. It just got to be a waste of time, and some compilers were downright silly as well as contradicted each other. So now, we simply make sure that the code always works. 36. Valgrind (or some similar memory access checker) says that deflate is performing a conditional jump that depends on an uninitialized value. Isn't that a bug? No. That is intentional for performance reasons, and the output of deflate is not affected. This only started showing up recently since zlib 1.2.x uses malloc() by default for allocations, whereas earlier versions used calloc(), which zeros out the allocated memory. Even though the code was correct, versions 1.2.4 and later was changed to not stimulate these checkers. 37. Will zlib read the (insert any ancient or arcane format here) compressed data format? Probably not. Look in the comp.compression FAQ for pointers to various formats and associated software. 38. How can I encrypt/decrypt zip files with zlib? zlib doesn't support encryption. The original PKZIP encryption is very weak and can be broken with freely available programs. To get strong encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib compression. For PKZIP compatible "encryption", look at http://www.info-zip.org/ 39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? "gzip" is the gzip format, and "deflate" is the zlib format. They should probably have called the second one "zlib" instead to avoid confusion with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 correctly points to the zlib specification in RFC 1950 for the "deflate" transfer encoding, there have been reports of servers and browsers that incorrectly produce or expect raw deflate data per the deflate specficiation in RFC 1951, most notably Microsoft. So even though the "deflate" transfer encoding using the zlib format would be the more efficient approach (and in fact exactly what the zlib format was designed for), using the "gzip" transfer encoding is probably more reliable due to an unfortunate choice of name on the part of the HTTP 1.1 authors. Bottom line: use the gzip format for HTTP 1.1 encoding. 40. Does zlib support the new "Deflate64" format introduced by PKWare? No. PKWare has apparently decided to keep that format proprietary, since they have not documented it as they have previous compression formats. In any case, the compression improvements are so modest compared to other more modern approaches, that it's not worth the effort to implement. 41. I'm having a problem with the zip functions in zlib, can you help? There are no zip functions in zlib. You are probably using minizip by Giles Vollant, which is found in the contrib directory of zlib. It is not part of zlib. In fact none of the stuff in contrib is part of zlib. The files in there are not supported by the zlib authors. You need to contact the authors of the respective contribution for help. 42. The match.asm code in contrib is under the GNU General Public License. Since it's part of zlib, doesn't that mean that all of zlib falls under the GNU GPL? No. The files in contrib are not part of zlib. They were contributed by other authors and are provided as a convenience to the user within the zlib distribution. Each item in contrib has its own license. 43. Is zlib subject to export controls? What is its ECCN? zlib is not subject to export controls, and so is classified as EAR99. 44. Can you please sign these lengthy legal documents and fax them back to us so that we can use your software in our product? No. Go away. Shoo. bcmatroska2-5.3.101/corec/corec/helpers/zlib/README000066400000000000000000000121201462133141200215320ustar00rootroot00000000000000ZLIB DATA COMPRESSION LIBRARY zlib 1.2.5 is a general purpose data compression library. All the code is thread safe. The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). All functions of the compression library are documented in the file zlib.h (volunteer to write man pages welcome, contact zlib@gzip.org). A usage example of the library is given in the file example.c which also tests that the library is working correctly. Another example is given in the file minigzip.c. The compression library itself is composed of all source files except example.c and minigzip.c. To compile all files and run the test program, follow the instructions given at the top of Makefile.in. In short "./configure; make test", and if that goes well, "make install" should work for most flavors of Unix. For Windows, use one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use make_vms.com. Questions about zlib should be sent to , or to Gilles Vollant for the Windows DLL version. The zlib home page is http://zlib.net/ . Before reporting a problem, please check this site to verify that you have the latest version of zlib; otherwise get the latest version and check whether the problem still exists or not. PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. Mark Nelson wrote an article about zlib for the Jan. 1997 issue of Dr. Dobb's Journal; a copy of the article is available at http://marknelson.us/1997/01/01/zlib-engine/ . The changes made in version 1.2.5 are documented in the file ChangeLog. Unsupported third party contributions are provided in directory contrib/ . zlib is available in Java using the java.util.zip package, documented at http://java.sun.com/developer/technicalArticles/Programming/compression/ . A Perl interface to zlib written by Paul Marquess is available at CPAN (Comprehensive Perl Archive Network) sites, including http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . A Python interface to zlib written by A.M. Kuchling is available in Python 1.5 and later versions, see http://www.python.org/doc/lib/module-zlib.html . zlib is built into tcl: http://wiki.tcl.tk/4610 . An experimental package to read and write files in .zip format, written on top of zlib by Gilles Vollant , is available in the contrib/minizip directory of zlib. Notes for some targets: - For Windows DLL versions, please see win32/DLL_FAQ.txt - For 64-bit Irix, deflate.c must be compiled without any optimization. With -O, one libpng test fails. The test works in 32 bit mode (with the -n32 compiler flag). The compiler bug has been reported to SGI. - zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works when compiled with cc. - On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is necessary to get gzprintf working correctly. This is done by configure. - zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with other compilers. Use "make test" to check your compiler. - gzdopen is not supported on RISCOS or BEOS. - For PalmOs, see http://palmzlib.sourceforge.net/ Acknowledgments: The deflate format used by zlib was defined by Phil Katz. The deflate and zlib specifications were written by L. Peter Deutsch. Thanks to all the people who reported problems and suggested various improvements in zlib; they are too numerous to cite here. Copyright notice: (C) 1995-2010 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu If you use the zlib library in a product, we would appreciate *not* receiving lengthy legal documents to sign. The sources are provided for free but without warranty of any kind. The library has been entirely written by Jean-loup Gailly and Mark Adler; it does not include third-party code. If you redistribute modified sources, we would appreciate that you include in the file ChangeLog history information documenting your changes. Please read the FAQ for more information on the distribution of modified source versions. bcmatroska2-5.3.101/corec/corec/helpers/zlib/adler32.c000066400000000000000000000116701462133141200222630ustar00rootroot00000000000000/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2007 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" #define local static local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* use NO_DIVIDE if your processor does not do division in hardware */ #ifdef NO_DIVIDE # define MOD(a) \ do { \ if (a >= (BASE << 16)) a -= (BASE << 16); \ if (a >= (BASE << 15)) a -= (BASE << 15); \ if (a >= (BASE << 14)) a -= (BASE << 14); \ if (a >= (BASE << 13)) a -= (BASE << 13); \ if (a >= (BASE << 12)) a -= (BASE << 12); \ if (a >= (BASE << 11)) a -= (BASE << 11); \ if (a >= (BASE << 10)) a -= (BASE << 10); \ if (a >= (BASE << 9)) a -= (BASE << 9); \ if (a >= (BASE << 8)) a -= (BASE << 8); \ if (a >= (BASE << 7)) a -= (BASE << 7); \ if (a >= (BASE << 6)) a -= (BASE << 6); \ if (a >= (BASE << 5)) a -= (BASE << 5); \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) # define MOD4(a) \ do { \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE # define MOD4(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long sum2; unsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD4(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /* ========================================================================= */ local uLong adler32_combine_(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { unsigned long sum1; unsigned long sum2; unsigned rem; /* the derivation of this formula is left as an exercise for the reader */ rem = (unsigned)(len2 % BASE); sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); sum1 += (adler2 & 0xffff) + BASE - 1; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; if (sum1 >= BASE) sum1 -= BASE; if (sum1 >= BASE) sum1 -= BASE; if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); if (sum2 >= BASE) sum2 -= BASE; return sum1 | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32_combine(adler1, adler2, len2) uLong adler1; uLong adler2; z_off_t len2; { return adler32_combine_(adler1, adler2, len2); } uLong ZEXPORT adler32_combine64(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { return adler32_combine_(adler1, adler2, len2); } bcmatroska2-5.3.101/corec/corec/helpers/zlib/compress.c000066400000000000000000000047301462133141200226610ustar00rootroot00000000000000/* compress.c -- compress a memory buffer * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; int level; { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; #ifdef MAXSEG_64K /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; #endif stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; err = deflateInit(&stream, level); if (err != Z_OK) return err; err = deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { deflateEnd(&stream); return err == Z_OK ? Z_BUF_ERROR : err; } *destLen = stream.total_out; err = deflateEnd(&stream); return err; } /* =========================================================================== */ int ZEXPORT compress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); } /* =========================================================================== If the default memLevel or windowBits for deflateInit() is changed, then this function needs to be updated. */ uLong ZEXPORT compressBound (sourceLen) uLong sourceLen; { return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/000077500000000000000000000000001462133141200223165ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/amd64/000077500000000000000000000000001462133141200232315ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/amd64/amd64-match.S000066400000000000000000000302021462133141200253570ustar00rootroot00000000000000/* * match.S -- optimized version of longest_match() * based on the similar work by Gilles Vollant, and Brian Raiter, written 1998 * * This is free software; you can redistribute it and/or modify it * under the terms of the BSD License. Use by owners of Che Guevarra * parafernalia is prohibited, where possible, and highly discouraged * elsewhere. */ #ifndef NO_UNDERLINE # define match_init _match_init # define longest_match _longest_match #endif #define scanend ebx #define scanendw bx #define chainlenwmask edx /* high word: current chain len low word: s->wmask */ #define curmatch rsi #define curmatchd esi #define windowbestlen r8 #define scanalign r9 #define scanalignd r9d #define window r10 #define bestlen r11 #define bestlend r11d #define scanstart r12d #define scanstartw r12w #define scan r13 #define nicematch r14d #define limit r15 #define limitd r15d #define prev rcx /* * The 258 is a "magic number, not a parameter -- changing it * breaks the hell loose */ #define MAX_MATCH (258) #define MIN_MATCH (3) #define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) #define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) /* stack frame offsets */ #define LocalVarsSize (112) #define _chainlenwmask ( 8-LocalVarsSize)(%rsp) #define _windowbestlen (16-LocalVarsSize)(%rsp) #define save_r14 (24-LocalVarsSize)(%rsp) #define save_rsi (32-LocalVarsSize)(%rsp) #define save_rbx (40-LocalVarsSize)(%rsp) #define save_r12 (56-LocalVarsSize)(%rsp) #define save_r13 (64-LocalVarsSize)(%rsp) #define save_r15 (80-LocalVarsSize)(%rsp) .globl match_init, longest_match /* * On AMD64 the first argument of a function (in our case -- the pointer to * deflate_state structure) is passed in %rdi, hence our offsets below are * all off of that. */ /* you can check the structure offset by running #include #include #include "deflate.h" void print_depl() { deflate_state ds; deflate_state *s=&ds; printf("size pointer=%u\n",(int)sizeof(void*)); printf("#define dsWSize (%3u)(%%rdi)\n",(int)(((char*)&(s->w_size))-((char*)s))); printf("#define dsWMask (%3u)(%%rdi)\n",(int)(((char*)&(s->w_mask))-((char*)s))); printf("#define dsWindow (%3u)(%%rdi)\n",(int)(((char*)&(s->window))-((char*)s))); printf("#define dsPrev (%3u)(%%rdi)\n",(int)(((char*)&(s->prev))-((char*)s))); printf("#define dsMatchLen (%3u)(%%rdi)\n",(int)(((char*)&(s->match_length))-((char*)s))); printf("#define dsPrevMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_match))-((char*)s))); printf("#define dsStrStart (%3u)(%%rdi)\n",(int)(((char*)&(s->strstart))-((char*)s))); printf("#define dsMatchStart (%3u)(%%rdi)\n",(int)(((char*)&(s->match_start))-((char*)s))); printf("#define dsLookahead (%3u)(%%rdi)\n",(int)(((char*)&(s->lookahead))-((char*)s))); printf("#define dsPrevLen (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_length))-((char*)s))); printf("#define dsMaxChainLen (%3u)(%%rdi)\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); printf("#define dsGoodMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->good_match))-((char*)s))); printf("#define dsNiceMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->nice_match))-((char*)s))); } */ /* to compile for XCode 3.2 on MacOSX x86_64 - run "gcc -g -c -DXCODE_MAC_X64_STRUCTURE amd64-match.S" */ #ifndef CURRENT_LINX_XCODE_MAC_X64_STRUCTURE #define dsWSize ( 68)(%rdi) #define dsWMask ( 76)(%rdi) #define dsWindow ( 80)(%rdi) #define dsPrev ( 96)(%rdi) #define dsMatchLen (144)(%rdi) #define dsPrevMatch (148)(%rdi) #define dsStrStart (156)(%rdi) #define dsMatchStart (160)(%rdi) #define dsLookahead (164)(%rdi) #define dsPrevLen (168)(%rdi) #define dsMaxChainLen (172)(%rdi) #define dsGoodMatch (188)(%rdi) #define dsNiceMatch (192)(%rdi) #else #ifndef STRUCT_OFFSET # define STRUCT_OFFSET (0) #endif #define dsWSize ( 56 + STRUCT_OFFSET)(%rdi) #define dsWMask ( 64 + STRUCT_OFFSET)(%rdi) #define dsWindow ( 72 + STRUCT_OFFSET)(%rdi) #define dsPrev ( 88 + STRUCT_OFFSET)(%rdi) #define dsMatchLen (136 + STRUCT_OFFSET)(%rdi) #define dsPrevMatch (140 + STRUCT_OFFSET)(%rdi) #define dsStrStart (148 + STRUCT_OFFSET)(%rdi) #define dsMatchStart (152 + STRUCT_OFFSET)(%rdi) #define dsLookahead (156 + STRUCT_OFFSET)(%rdi) #define dsPrevLen (160 + STRUCT_OFFSET)(%rdi) #define dsMaxChainLen (164 + STRUCT_OFFSET)(%rdi) #define dsGoodMatch (180 + STRUCT_OFFSET)(%rdi) #define dsNiceMatch (184 + STRUCT_OFFSET)(%rdi) #endif .text /* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ longest_match: /* * Retrieve the function arguments. %curmatch will hold cur_match * throughout the entire function (passed via rsi on amd64). * rdi will hold the pointer to the deflate_state (first arg on amd64) */ mov %rsi, save_rsi mov %rbx, save_rbx mov %r12, save_r12 mov %r13, save_r13 mov %r14, save_r14 mov %r15, save_r15 /* uInt wmask = s->w_mask; */ /* unsigned chain_length = s->max_chain_length; */ /* if (s->prev_length >= s->good_match) { */ /* chain_length >>= 2; */ /* } */ movl dsPrevLen, %eax movl dsGoodMatch, %ebx cmpl %ebx, %eax movl dsWMask, %eax movl dsMaxChainLen, %chainlenwmask jl LastMatchGood shrl $2, %chainlenwmask LastMatchGood: /* chainlen is decremented once beforehand so that the function can */ /* use the sign flag instead of the zero flag for the exit test. */ /* It is then shifted into the high word, to make room for the wmask */ /* value, which it will always accompany. */ decl %chainlenwmask shll $16, %chainlenwmask orl %eax, %chainlenwmask /* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ movl dsNiceMatch, %eax movl dsLookahead, %ebx cmpl %eax, %ebx jl LookaheadLess movl %eax, %ebx LookaheadLess: movl %ebx, %nicematch /* register Bytef *scan = s->window + s->strstart; */ mov dsWindow, %window movl dsStrStart, %limitd lea (%limit, %window), %scan /* Determine how many bytes the scan ptr is off from being */ /* dword-aligned. */ mov %scan, %scanalign negl %scanalignd andl $3, %scanalignd /* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ /* s->strstart - (IPos)MAX_DIST(s) : NIL; */ movl dsWSize, %eax subl $MIN_LOOKAHEAD, %eax xorl %ecx, %ecx subl %eax, %limitd cmovng %ecx, %limitd /* int best_len = s->prev_length; */ movl dsPrevLen, %bestlend /* Store the sum of s->window + best_len in %windowbestlen locally, and in memory. */ lea (%window, %bestlen), %windowbestlen mov %windowbestlen, _windowbestlen /* register ush scan_start = *(ushf*)scan; */ /* register ush scan_end = *(ushf*)(scan+best_len-1); */ /* Posf *prev = s->prev; */ movzwl (%scan), %scanstart movzwl -1(%scan, %bestlen), %scanend mov dsPrev, %prev /* Jump into the main loop. */ movl %chainlenwmask, _chainlenwmask jmp LoopEntry .balign 16 /* do { * match = s->window + cur_match; * if (*(ushf*)(match+best_len-1) != scan_end || * *(ushf*)match != scan_start) continue; * [...] * } while ((cur_match = prev[cur_match & wmask]) > limit * && --chain_length != 0); * * Here is the inner loop of the function. The function will spend the * majority of its time in this loop, and majority of that time will * be spent in the first ten instructions. */ LookupLoop: andl %chainlenwmask, %curmatchd movzwl (%prev, %curmatch, 2), %curmatchd cmpl %limitd, %curmatchd jbe LeaveNow subl $0x00010000, %chainlenwmask js LeaveNow LoopEntry: cmpw -1(%windowbestlen, %curmatch), %scanendw jne LookupLoop cmpw %scanstartw, (%window, %curmatch) jne LookupLoop /* Store the current value of chainlen. */ movl %chainlenwmask, _chainlenwmask /* %scan is the string under scrutiny, and %prev to the string we */ /* are hoping to match it up with. In actuality, %esi and %edi are */ /* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ /* initialized to -(MAX_MATCH_8 - scanalign). */ mov $(-MAX_MATCH_8), %rdx lea (%curmatch, %window), %windowbestlen lea MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen lea MAX_MATCH_8(%scan, %scanalign), %prev /* the prefetching below makes very little difference... */ prefetcht1 (%windowbestlen, %rdx) prefetcht1 (%prev, %rdx) /* * Test the strings for equality, 8 bytes at a time. At the end, * adjust %rdx so that it is offset to the exact byte that mismatched. * * It should be confessed that this loop usually does not represent * much of the total running time. Replacing it with a more * straightforward "rep cmpsb" would not drastically degrade * performance -- unrolling it, for example, makes no difference. */ #undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */ LoopCmps: #ifdef USE_SSE /* Preload the SSE registers */ movdqu (%windowbestlen, %rdx), %xmm1 movdqu (%prev, %rdx), %xmm2 pcmpeqb %xmm2, %xmm1 movdqu 16(%windowbestlen, %rdx), %xmm3 movdqu 16(%prev, %rdx), %xmm4 pcmpeqb %xmm4, %xmm3 movdqu 32(%windowbestlen, %rdx), %xmm5 movdqu 32(%prev, %rdx), %xmm6 pcmpeqb %xmm6, %xmm5 movdqu 48(%windowbestlen, %rdx), %xmm7 movdqu 48(%prev, %rdx), %xmm8 pcmpeqb %xmm8, %xmm7 /* Check the comparisions' results */ pmovmskb %xmm1, %rax notw %ax bsfw %ax, %ax jnz LeaveLoopCmps /* this is the only iteration of the loop with a possibility of having incremented rdx by 0x108 (each loop iteration add 16*4 = 0x40 and (0x40*4)+8=0x108 */ add $8, %rdx jz LenMaximum add $8, %rdx pmovmskb %xmm3, %rax notw %ax bsfw %ax, %ax jnz LeaveLoopCmps add $16, %rdx pmovmskb %xmm5, %rax notw %ax bsfw %ax, %ax jnz LeaveLoopCmps add $16, %rdx pmovmskb %xmm7, %rax notw %ax bsfw %ax, %ax jnz LeaveLoopCmps add $16, %rdx jmp LoopCmps LeaveLoopCmps: add %rax, %rdx #else mov (%windowbestlen, %rdx), %rax xor (%prev, %rdx), %rax jnz LeaveLoopCmps mov 8(%windowbestlen, %rdx), %rax xor 8(%prev, %rdx), %rax jnz LeaveLoopCmps8 mov 16(%windowbestlen, %rdx), %rax xor 16(%prev, %rdx), %rax jnz LeaveLoopCmps16 add $24, %rdx jnz LoopCmps jmp LenMaximum # if 0 /* * This three-liner is tantalizingly simple, but bsf is a slow instruction, * and the complicated alternative down below is quite a bit faster. Sad... */ LeaveLoopCmps: bsf %rax, %rax /* find the first non-zero bit */ shrl $3, %eax /* divide by 8 to get the byte */ add %rax, %rdx # else LeaveLoopCmps16: add $8, %rdx LeaveLoopCmps8: add $8, %rdx LeaveLoopCmps: testl $0xFFFFFFFF, %eax /* Check the first 4 bytes */ jnz Check16 add $4, %rdx shr $32, %rax Check16: testw $0xFFFF, %ax jnz LenLower add $2, %rdx shrl $16, %eax LenLower: subb $1, %al adc $0, %rdx # endif #endif /* Calculate the length of the match. If it is longer than MAX_MATCH, */ /* then automatically accept it as the best possible match and leave. */ lea (%prev, %rdx), %rax sub %scan, %rax cmpl $MAX_MATCH, %eax jge LenMaximum /* If the length of the match is not longer than the best match we */ /* have so far, then forget it and return to the lookup loop. */ cmpl %bestlend, %eax jg LongerMatch mov _windowbestlen, %windowbestlen mov dsPrev, %prev movl _chainlenwmask, %edx jmp LookupLoop /* s->match_start = cur_match; */ /* best_len = len; */ /* if (len >= nice_match) break; */ /* scan_end = *(ushf*)(scan+best_len-1); */ LongerMatch: movl %eax, %bestlend movl %curmatchd, dsMatchStart cmpl %nicematch, %eax jge LeaveNow lea (%window, %bestlen), %windowbestlen mov %windowbestlen, _windowbestlen movzwl -1(%scan, %rax), %scanend mov dsPrev, %prev movl _chainlenwmask, %chainlenwmask jmp LookupLoop /* Accept the current string, with the maximum possible length. */ LenMaximum: movl $MAX_MATCH, %bestlend movl %curmatchd, dsMatchStart /* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ /* return s->lookahead; */ LeaveNow: movl dsLookahead, %eax cmpl %eax, %bestlend cmovngl %bestlend, %eax LookaheadRet: /* Restore the registers and return from whence we came. */ mov save_rsi, %rsi mov save_rbx, %rbx mov save_r12, %r12 mov save_r13, %r13 mov save_r14, %r14 mov save_r15, %r15 ret match_init: ret bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/asm686/000077500000000000000000000000001462133141200233425ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/asm686/README.686000066400000000000000000000031261462133141200245460ustar00rootroot00000000000000This is a patched version of zlib, modified to use Pentium-Pro-optimized assembly code in the deflation algorithm. The files changed/added by this patch are: README.686 match.S The speedup that this patch provides varies, depending on whether the compiler used to build the original version of zlib falls afoul of the PPro's speed traps. My own tests show a speedup of around 10-20% at the default compression level, and 20-30% using -9, against a version compiled using gcc 2.7.2.3. Your mileage may vary. Note that this code has been tailored for the PPro/PII in particular, and will not perform particuarly well on a Pentium. If you are using an assembler other than GNU as, you will have to translate match.S to use your assembler's syntax. (Have fun.) Brian Raiter breadbox@muppetlabs.com April, 1998 Added for zlib 1.1.3: The patches come from http://www.muppetlabs.com/~breadbox/software/assembly.html To compile zlib with this asm file, copy match.S to the zlib directory then do: CFLAGS="-O3 -DASMV" ./configure make OBJA=match.o Update: I've been ignoring these assembly routines for years, believing that gcc's generated code had caught up with it sometime around gcc 2.95 and the major rearchitecting of the Pentium 4. However, I recently learned that, despite what I believed, this code still has some life in it. On the Pentium 4 and AMD64 chips, it continues to run about 8% faster than the code produced by gcc 4.1. In acknowledgement of its continuing usefulness, I've altered the license to match that of the rest of zlib. Share and Enjoy! Brian Raiter breadbox@muppetlabs.com April, 2007 bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/asm686/match.S000066400000000000000000000234521462133141200245700ustar00rootroot00000000000000/* match.S -- x86 assembly version of the zlib longest_match() function. * Optimized for the Intel 686 chips (PPro and later). * * Copyright (C) 1998, 2007 Brian Raiter * * This software is provided 'as-is', without any express or implied * warranty. In no event will the author be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef NO_UNDERLINE #define match_init _match_init #define longest_match _longest_match #endif #define MAX_MATCH (258) #define MIN_MATCH (3) #define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) #define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) /* stack frame offsets */ #define chainlenwmask 0 /* high word: current chain len */ /* low word: s->wmask */ #define window 4 /* local copy of s->window */ #define windowbestlen 8 /* s->window + bestlen */ #define scanstart 16 /* first two bytes of string */ #define scanend 12 /* last two bytes of string */ #define scanalign 20 /* dword-misalignment of string */ #define nicematch 24 /* a good enough match size */ #define bestlen 28 /* size of best match so far */ #define scan 32 /* ptr to string wanting match */ #define LocalVarsSize (36) /* saved ebx 36 */ /* saved edi 40 */ /* saved esi 44 */ /* saved ebp 48 */ /* return address 52 */ #define deflatestate 56 /* the function arguments */ #define curmatch 60 /* All the +zlib1222add offsets are due to the addition of fields * in zlib in the deflate_state structure since the asm code was first written * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). */ #define zlib1222add (8) #define dsWSize (36+zlib1222add) #define dsWMask (44+zlib1222add) #define dsWindow (48+zlib1222add) #define dsPrev (56+zlib1222add) #define dsMatchLen (88+zlib1222add) #define dsPrevMatch (92+zlib1222add) #define dsStrStart (100+zlib1222add) #define dsMatchStart (104+zlib1222add) #define dsLookahead (108+zlib1222add) #define dsPrevLen (112+zlib1222add) #define dsMaxChainLen (116+zlib1222add) #define dsGoodMatch (132+zlib1222add) #define dsNiceMatch (136+zlib1222add) .file "match.S" .globl match_init, longest_match .text /* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ longest_match: /* Save registers that the compiler may be using, and adjust %esp to */ /* make room for our stack frame. */ pushl %ebp pushl %edi pushl %esi pushl %ebx subl $LocalVarsSize, %esp /* Retrieve the function arguments. %ecx will hold cur_match */ /* throughout the entire function. %edx will hold the pointer to the */ /* deflate_state structure during the function's setup (before */ /* entering the main loop). */ movl deflatestate(%esp), %edx movl curmatch(%esp), %ecx /* uInt wmask = s->w_mask; */ /* unsigned chain_length = s->max_chain_length; */ /* if (s->prev_length >= s->good_match) { */ /* chain_length >>= 2; */ /* } */ movl dsPrevLen(%edx), %eax movl dsGoodMatch(%edx), %ebx cmpl %ebx, %eax movl dsWMask(%edx), %eax movl dsMaxChainLen(%edx), %ebx jl LastMatchGood shrl $2, %ebx LastMatchGood: /* chainlen is decremented once beforehand so that the function can */ /* use the sign flag instead of the zero flag for the exit test. */ /* It is then shifted into the high word, to make room for the wmask */ /* value, which it will always accompany. */ decl %ebx shll $16, %ebx orl %eax, %ebx movl %ebx, chainlenwmask(%esp) /* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ movl dsNiceMatch(%edx), %eax movl dsLookahead(%edx), %ebx cmpl %eax, %ebx jl LookaheadLess movl %eax, %ebx LookaheadLess: movl %ebx, nicematch(%esp) /* register Bytef *scan = s->window + s->strstart; */ movl dsWindow(%edx), %esi movl %esi, window(%esp) movl dsStrStart(%edx), %ebp lea (%esi,%ebp), %edi movl %edi, scan(%esp) /* Determine how many bytes the scan ptr is off from being */ /* dword-aligned. */ movl %edi, %eax negl %eax andl $3, %eax movl %eax, scanalign(%esp) /* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ /* s->strstart - (IPos)MAX_DIST(s) : NIL; */ movl dsWSize(%edx), %eax subl $MIN_LOOKAHEAD, %eax subl %eax, %ebp jg LimitPositive xorl %ebp, %ebp LimitPositive: /* int best_len = s->prev_length; */ movl dsPrevLen(%edx), %eax movl %eax, bestlen(%esp) /* Store the sum of s->window + best_len in %esi locally, and in %esi. */ addl %eax, %esi movl %esi, windowbestlen(%esp) /* register ush scan_start = *(ushf*)scan; */ /* register ush scan_end = *(ushf*)(scan+best_len-1); */ /* Posf *prev = s->prev; */ movzwl (%edi), %ebx movl %ebx, scanstart(%esp) movzwl -1(%edi,%eax), %ebx movl %ebx, scanend(%esp) movl dsPrev(%edx), %edi /* Jump into the main loop. */ movl chainlenwmask(%esp), %edx jmp LoopEntry .balign 16 /* do { * match = s->window + cur_match; * if (*(ushf*)(match+best_len-1) != scan_end || * *(ushf*)match != scan_start) continue; * [...] * } while ((cur_match = prev[cur_match & wmask]) > limit * && --chain_length != 0); * * Here is the inner loop of the function. The function will spend the * majority of its time in this loop, and majority of that time will * be spent in the first ten instructions. * * Within this loop: * %ebx = scanend * %ecx = curmatch * %edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) * %esi = windowbestlen - i.e., (window + bestlen) * %edi = prev * %ebp = limit */ LookupLoop: andl %edx, %ecx movzwl (%edi,%ecx,2), %ecx cmpl %ebp, %ecx jbe LeaveNow subl $0x00010000, %edx js LeaveNow LoopEntry: movzwl -1(%esi,%ecx), %eax cmpl %ebx, %eax jnz LookupLoop movl window(%esp), %eax movzwl (%eax,%ecx), %eax cmpl scanstart(%esp), %eax jnz LookupLoop /* Store the current value of chainlen. */ movl %edx, chainlenwmask(%esp) /* Point %edi to the string under scrutiny, and %esi to the string we */ /* are hoping to match it up with. In actuality, %esi and %edi are */ /* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ /* initialized to -(MAX_MATCH_8 - scanalign). */ movl window(%esp), %esi movl scan(%esp), %edi addl %ecx, %esi movl scanalign(%esp), %eax movl $(-MAX_MATCH_8), %edx lea MAX_MATCH_8(%edi,%eax), %edi lea MAX_MATCH_8(%esi,%eax), %esi /* Test the strings for equality, 8 bytes at a time. At the end, * adjust %edx so that it is offset to the exact byte that mismatched. * * We already know at this point that the first three bytes of the * strings match each other, and they can be safely passed over before * starting the compare loop. So what this code does is skip over 0-3 * bytes, as much as necessary in order to dword-align the %edi * pointer. (%esi will still be misaligned three times out of four.) * * It should be confessed that this loop usually does not represent * much of the total running time. Replacing it with a more * straightforward "rep cmpsb" would not drastically degrade * performance. */ LoopCmps: movl (%esi,%edx), %eax xorl (%edi,%edx), %eax jnz LeaveLoopCmps movl 4(%esi,%edx), %eax xorl 4(%edi,%edx), %eax jnz LeaveLoopCmps4 addl $8, %edx jnz LoopCmps jmp LenMaximum LeaveLoopCmps4: addl $4, %edx LeaveLoopCmps: testl $0x0000FFFF, %eax jnz LenLower addl $2, %edx shrl $16, %eax LenLower: subb $1, %al adcl $0, %edx /* Calculate the length of the match. If it is longer than MAX_MATCH, */ /* then automatically accept it as the best possible match and leave. */ lea (%edi,%edx), %eax movl scan(%esp), %edi subl %edi, %eax cmpl $MAX_MATCH, %eax jge LenMaximum /* If the length of the match is not longer than the best match we */ /* have so far, then forget it and return to the lookup loop. */ movl deflatestate(%esp), %edx movl bestlen(%esp), %ebx cmpl %ebx, %eax jg LongerMatch movl windowbestlen(%esp), %esi movl dsPrev(%edx), %edi movl scanend(%esp), %ebx movl chainlenwmask(%esp), %edx jmp LookupLoop /* s->match_start = cur_match; */ /* best_len = len; */ /* if (len >= nice_match) break; */ /* scan_end = *(ushf*)(scan+best_len-1); */ LongerMatch: movl nicematch(%esp), %ebx movl %eax, bestlen(%esp) movl %ecx, dsMatchStart(%edx) cmpl %ebx, %eax jge LeaveNow movl window(%esp), %esi addl %eax, %esi movl %esi, windowbestlen(%esp) movzwl -1(%edi,%eax), %ebx movl dsPrev(%edx), %edi movl %ebx, scanend(%esp) movl chainlenwmask(%esp), %edx jmp LookupLoop /* Accept the current string, with the maximum possible length. */ LenMaximum: movl deflatestate(%esp), %edx movl $MAX_MATCH, bestlen(%esp) movl %ecx, dsMatchStart(%edx) /* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ /* return s->lookahead; */ LeaveNow: movl deflatestate(%esp), %edx movl bestlen(%esp), %ebx movl dsLookahead(%edx), %eax cmpl %eax, %ebx jg LookaheadRet movl %ebx, %eax LookaheadRet: /* Restore the stack and return from whence we came. */ addl $LocalVarsSize, %esp popl %ebx popl %esi popl %edi popl %ebp match_init: ret bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/gcc_gvmat64/000077500000000000000000000000001462133141200244225ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/gcc_gvmat64/gvmat64.S000066400000000000000000000367371462133141200260560ustar00rootroot00000000000000/* ;uInt longest_match_x64( ; deflate_state *s, ; IPos cur_match); // current match ; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64 ; (AMD64 on Athlon 64, Opteron, Phenom ; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) ; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode) ; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. ; ; File written by Gilles Vollant, by converting to assembly the longest_match ; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. ; and by taking inspiration on asm686 with masm, optimised assembly code ; from Brian Raiter, written 1998 ; ; This software is provided 'as-is', without any express or implied ; warranty. In no event will the authors be held liable for any damages ; arising from the use of this software. ; ; Permission is granted to anyone to use this software for any purpose, ; including commercial applications, and to alter it and redistribute it ; freely, subject to the following restrictions: ; ; 1. The origin of this software must not be misrepresented; you must not ; claim that you wrote the original software. If you use this software ; in a product, an acknowledgment in the product documentation would be ; appreciated but is not required. ; 2. Altered source versions must be plainly marked as such, and must not be ; misrepresented as being the original software ; 3. This notice may not be removed or altered from any source distribution. ; ; http://www.zlib.net ; http://www.winimage.com/zLibDll ; http://www.muppetlabs.com/~breadbox/software/assembly.html ; ; to compile this file for zLib, I use option: ; gcc -c -arch x86_64 gvmat64.S ;uInt longest_match(s, cur_match) ; deflate_state *s; ; IPos cur_match; // current match / ; ; with XCode for Mac, I had strange error with some jump on intel syntax ; this is why BEFORE_JMP and AFTER_JMP are used */ #define BEFORE_JMP .att_syntax #define AFTER_JMP .intel_syntax noprefix #ifndef NO_UNDERLINE # define match_init _match_init # define longest_match _longest_match #endif .intel_syntax noprefix .globl match_init, longest_match .text longest_match: #define LocalVarsSize 96 /* ; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 ; free register : r14,r15 ; register can be saved : rsp */ #define chainlenwmask (rsp + 8 - LocalVarsSize) #define nicematch (rsp + 16 - LocalVarsSize) #define save_rdi (rsp + 24 - LocalVarsSize) #define save_rsi (rsp + 32 - LocalVarsSize) #define save_rbx (rsp + 40 - LocalVarsSize) #define save_rbp (rsp + 48 - LocalVarsSize) #define save_r12 (rsp + 56 - LocalVarsSize) #define save_r13 (rsp + 64 - LocalVarsSize) #define save_r14 (rsp + 72 - LocalVarsSize) #define save_r15 (rsp + 80 - LocalVarsSize) /* ; all the +4 offsets are due to the addition of pending_buf_size (in zlib ; in the deflate_state structure since the asm code was first written ; (if you compile with zlib 1.0.4 or older, remove the +4). ; Note : these value are good with a 8 bytes boundary pack structure */ #define MAX_MATCH 258 #define MIN_MATCH 3 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* ;;; Offsets for fields in the deflate_state structure. These numbers ;;; are calculated from the definition of deflate_state, with the ;;; assumption that the compiler will dword-align the fields. (Thus, ;;; changing the definition of deflate_state could easily cause this ;;; program to crash horribly, without so much as a warning at ;;; compile time. Sigh.) ; all the +zlib1222add offsets are due to the addition of fields ; in zlib in the deflate_state structure since the asm code was first written ; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). ; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). ; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). */ /* you can check the structure offset by running #include #include #include "deflate.h" void print_depl() { deflate_state ds; deflate_state *s=&ds; printf("size pointer=%u\n",(int)sizeof(void*)); printf("#define dsWSize %u\n",(int)(((char*)&(s->w_size))-((char*)s))); printf("#define dsWMask %u\n",(int)(((char*)&(s->w_mask))-((char*)s))); printf("#define dsWindow %u\n",(int)(((char*)&(s->window))-((char*)s))); printf("#define dsPrev %u\n",(int)(((char*)&(s->prev))-((char*)s))); printf("#define dsMatchLen %u\n",(int)(((char*)&(s->match_length))-((char*)s))); printf("#define dsPrevMatch %u\n",(int)(((char*)&(s->prev_match))-((char*)s))); printf("#define dsStrStart %u\n",(int)(((char*)&(s->strstart))-((char*)s))); printf("#define dsMatchStart %u\n",(int)(((char*)&(s->match_start))-((char*)s))); printf("#define dsLookahead %u\n",(int)(((char*)&(s->lookahead))-((char*)s))); printf("#define dsPrevLen %u\n",(int)(((char*)&(s->prev_length))-((char*)s))); printf("#define dsMaxChainLen %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); printf("#define dsGoodMatch %u\n",(int)(((char*)&(s->good_match))-((char*)s))); printf("#define dsNiceMatch %u\n",(int)(((char*)&(s->nice_match))-((char*)s))); } */ #define dsWSize 68 #define dsWMask 76 #define dsWindow 80 #define dsPrev 96 #define dsMatchLen 144 #define dsPrevMatch 148 #define dsStrStart 156 #define dsMatchStart 160 #define dsLookahead 164 #define dsPrevLen 168 #define dsMaxChainLen 172 #define dsGoodMatch 188 #define dsNiceMatch 192 #define window_size [ rcx + dsWSize] #define WMask [ rcx + dsWMask] #define window_ad [ rcx + dsWindow] #define prev_ad [ rcx + dsPrev] #define strstart [ rcx + dsStrStart] #define match_start [ rcx + dsMatchStart] #define Lookahead [ rcx + dsLookahead] //; 0ffffffffh on infozip #define prev_length [ rcx + dsPrevLen] #define max_chain_length [ rcx + dsMaxChainLen] #define good_match [ rcx + dsGoodMatch] #define nice_match [ rcx + dsNiceMatch] /* ; windows: ; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match) ; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and ; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp ; ; All registers must be preserved across the call, except for ; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. ; ; gcc on macosx-linux: ; see http://www.x86-64.org/documentation/abi-0.99.pdf ; param 1 in rdi, param 2 in rsi ; rbx, rsp, rbp, r12 to r15 must be preserved ;;; Save registers that the compiler may be using, and adjust esp to ;;; make room for our stack frame. ;;; Retrieve the function arguments. r8d will hold cur_match ;;; throughout the entire function. edx will hold the pointer to the ;;; deflate_state structure during the function's setup (before ;;; entering the main loop. ; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) ; mac: param 1 in rdi, param 2 rsi ; this clear high 32 bits of r8, which can be garbage in both r8 and rdx */ mov [save_rbx],rbx mov [save_rbp],rbp mov rcx,rdi mov r8d,esi mov [save_r12],r12 mov [save_r13],r13 mov [save_r14],r14 mov [save_r15],r15 //;;; uInt wmask = s->w_mask; //;;; unsigned chain_length = s->max_chain_length; //;;; if (s->prev_length >= s->good_match) { //;;; chain_length >>= 2; //;;; } mov edi, prev_length mov esi, good_match mov eax, WMask mov ebx, max_chain_length cmp edi, esi jl LastMatchGood shr ebx, 2 LastMatchGood: //;;; chainlen is decremented once beforehand so that the function can //;;; use the sign flag instead of the zero flag for the exit test. //;;; It is then shifted into the high word, to make room for the wmask //;;; value, which it will always accompany. dec ebx shl ebx, 16 or ebx, eax //;;; on zlib only //;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; mov eax, nice_match mov [chainlenwmask], ebx mov r10d, Lookahead cmp r10d, eax cmovnl r10d, eax mov [nicematch],r10d //;;; register Bytef *scan = s->window + s->strstart; mov r10, window_ad mov ebp, strstart lea r13, [r10 + rbp] //;;; Determine how many bytes the scan ptr is off from being //;;; dword-aligned. mov r9,r13 neg r13 and r13,3 //;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? //;;; s->strstart - (IPos)MAX_DIST(s) : NIL; mov eax, window_size sub eax, MIN_LOOKAHEAD xor edi,edi sub ebp, eax mov r11d, prev_length cmovng ebp,edi //;;; int best_len = s->prev_length; //;;; Store the sum of s->window + best_len in esi locally, and in esi. lea rsi,[r10+r11] //;;; register ush scan_start = *(ushf*)scan; //;;; register ush scan_end = *(ushf*)(scan+best_len-1); //;;; Posf *prev = s->prev; movzx r12d,word ptr [r9] movzx ebx, word ptr [r9 + r11 - 1] mov rdi, prev_ad //;;; Jump into the main loop. mov edx, [chainlenwmask] cmp bx,word ptr [rsi + r8 - 1] jz LookupLoopIsZero LookupLoop1: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp jbe LeaveNow sub edx, 0x00010000 BEFORE_JMP js LeaveNow AFTER_JMP LoopEntry1: cmp bx,word ptr [rsi + r8 - 1] BEFORE_JMP jz LookupLoopIsZero AFTER_JMP LookupLoop2: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp BEFORE_JMP jbe LeaveNow AFTER_JMP sub edx, 0x00010000 BEFORE_JMP js LeaveNow AFTER_JMP LoopEntry2: cmp bx,word ptr [rsi + r8 - 1] BEFORE_JMP jz LookupLoopIsZero AFTER_JMP LookupLoop4: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp BEFORE_JMP jbe LeaveNow AFTER_JMP sub edx, 0x00010000 BEFORE_JMP js LeaveNow AFTER_JMP LoopEntry4: cmp bx,word ptr [rsi + r8 - 1] BEFORE_JMP jnz LookupLoop1 jmp LookupLoopIsZero AFTER_JMP /* ;;; do { ;;; match = s->window + cur_match; ;;; if (*(ushf*)(match+best_len-1) != scan_end || ;;; *(ushf*)match != scan_start) continue; ;;; [...] ;;; } while ((cur_match = prev[cur_match & wmask]) > limit ;;; && --chain_length != 0); ;;; ;;; Here is the inner loop of the function. The function will spend the ;;; majority of its time in this loop, and majority of that time will ;;; be spent in the first ten instructions. ;;; ;;; Within this loop: ;;; ebx = scanend ;;; r8d = curmatch ;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) ;;; esi = windowbestlen - i.e., (window + bestlen) ;;; edi = prev ;;; ebp = limit */ .balign 16 LookupLoop: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp BEFORE_JMP jbe LeaveNow AFTER_JMP sub edx, 0x00010000 BEFORE_JMP js LeaveNow AFTER_JMP LoopEntry: cmp bx,word ptr [rsi + r8 - 1] BEFORE_JMP jnz LookupLoop1 AFTER_JMP LookupLoopIsZero: cmp r12w, word ptr [r10 + r8] BEFORE_JMP jnz LookupLoop1 AFTER_JMP //;;; Store the current value of chainlen. mov [chainlenwmask], edx /* ;;; Point edi to the string under scrutiny, and esi to the string we ;;; are hoping to match it up with. In actuality, esi and edi are ;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is ;;; initialized to -(MAX_MATCH_8 - scanalign). */ lea rsi,[r8+r10] mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8) lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8] lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8] prefetcht1 [rsi+rdx] prefetcht1 [rdi+rdx] /* ;;; Test the strings for equality, 8 bytes at a time. At the end, ;;; adjust rdx so that it is offset to the exact byte that mismatched. ;;; ;;; We already know at this point that the first three bytes of the ;;; strings match each other, and they can be safely passed over before ;;; starting the compare loop. So what this code does is skip over 0-3 ;;; bytes, as much as necessary in order to dword-align the edi ;;; pointer. (rsi will still be misaligned three times out of four.) ;;; ;;; It should be confessed that this loop usually does not represent ;;; much of the total running time. Replacing it with a more ;;; straightforward "rep cmpsb" would not drastically degrade ;;; performance. */ LoopCmps: mov rax, [rsi + rdx] xor rax, [rdi + rdx] jnz LeaveLoopCmps mov rax, [rsi + rdx + 8] xor rax, [rdi + rdx + 8] jnz LeaveLoopCmps8 mov rax, [rsi + rdx + 8+8] xor rax, [rdi + rdx + 8+8] jnz LeaveLoopCmps16 add rdx,8+8+8 BEFORE_JMP jnz LoopCmps jmp LenMaximum AFTER_JMP LeaveLoopCmps16: add rdx,8 LeaveLoopCmps8: add rdx,8 LeaveLoopCmps: test eax, 0x0000FFFF jnz LenLower test eax,0xffffffff jnz LenLower32 add rdx,4 shr rax,32 or ax,ax BEFORE_JMP jnz LenLower AFTER_JMP LenLower32: shr eax,16 add rdx,2 LenLower: sub al, 1 adc rdx, 0 //;;; Calculate the length of the match. If it is longer than MAX_MATCH, //;;; then automatically accept it as the best possible match and leave. lea rax, [rdi + rdx] sub rax, r9 cmp eax, MAX_MATCH BEFORE_JMP jge LenMaximum AFTER_JMP /* ;;; If the length of the match is not longer than the best match we ;;; have so far, then forget it and return to the lookup loop. ;/////////////////////////////////// */ cmp eax, r11d jg LongerMatch lea rsi,[r10+r11] mov rdi, prev_ad mov edx, [chainlenwmask] BEFORE_JMP jmp LookupLoop AFTER_JMP /* ;;; s->match_start = cur_match; ;;; best_len = len; ;;; if (len >= nice_match) break; ;;; scan_end = *(ushf*)(scan+best_len-1); */ LongerMatch: mov r11d, eax mov match_start, r8d cmp eax, [nicematch] BEFORE_JMP jge LeaveNow AFTER_JMP lea rsi,[r10+rax] movzx ebx, word ptr [r9 + rax - 1] mov rdi, prev_ad mov edx, [chainlenwmask] BEFORE_JMP jmp LookupLoop AFTER_JMP //;;; Accept the current string, with the maximum possible length. LenMaximum: mov r11d,MAX_MATCH mov match_start, r8d //;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; //;;; return s->lookahead; LeaveNow: mov eax, Lookahead cmp r11d, eax cmovng eax, r11d //;;; Restore the stack and return from whence we came. // mov rsi,[save_rsi] // mov rdi,[save_rdi] mov rbx,[save_rbx] mov rbp,[save_rbp] mov r12,[save_r12] mov r13,[save_r13] mov r14,[save_r14] mov r15,[save_r15] ret 0 //; please don't remove this string ! //; Your can freely use gvmat64 in any free or commercial app //; but it is far better don't remove the string in the binary! // db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 match_init: ret 0 bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/inflate86/000077500000000000000000000000001462133141200241165ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/inflate86/inffas86.c000066400000000000000000001172401462133141200257130ustar00rootroot00000000000000/* inffas86.c is a hand tuned assembler version of * * inffast.c -- fast decoding * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Copyright (C) 2003 Chris Anderson * Please use the copyright conditions above. * * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also * slightly quicker on x86 systems because, instead of using rep movsb to copy * data, it uses rep movsw, which moves data in 2-byte chunks instead of single * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates * from http://fedora.linux.duke.edu/fc1_x86_64 * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, * when decompressing mozilla-source-1.3.tar.gz. * * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at * the moment. I have successfully compiled and tested this code with gcc2.96, * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX * enabled. I will attempt to merge the MMX code into this version. Newer * versions of this and inffast.S can be found at * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* Mark Adler's comments from inffast.c: */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state->mode == LEN strm->avail_in >= 6 strm->avail_out >= 258 start >= strm->avail_out state->bits < 8 On return, state->mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ void inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { struct inflate_state FAR *state; struct inffast_ar { /* 64 32 x86 x86_64 */ /* ar offset register */ /* 0 0 */ void *esp; /* esp save */ /* 8 4 */ void *ebp; /* ebp save */ /* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ /* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ /* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ /* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ /* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ /* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ /* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ /* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ /* 80 40 */ unsigned long hold; /* edx rdx local strm->hold */ /* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ /* 92 48 */ unsigned wsize; /* window size */ /* 96 52 */ unsigned write; /* window write index */ /*100 56 */ unsigned lmask; /* r12 mask for lcode */ /*104 60 */ unsigned dmask; /* r13 mask for dcode */ /*108 64 */ unsigned len; /* r14 match length */ /*112 68 */ unsigned dist; /* r15 match distance */ /*116 72 */ unsigned status; /* set when state chng*/ } ar; #if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) #define PAD_AVAIL_IN 6 #define PAD_AVAIL_OUT 258 #else #define PAD_AVAIL_IN 5 #define PAD_AVAIL_OUT 257 #endif /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; ar.in = strm->next_in; ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); ar.out = strm->next_out; ar.beg = ar.out - (start - strm->avail_out); ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); ar.wsize = state->wsize; ar.write = state->wnext; ar.window = state->window; ar.hold = state->hold; ar.bits = state->bits; ar.lcode = state->lencode; ar.dcode = state->distcode; ar.lmask = (1U << state->lenbits) - 1; ar.dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ /* align in on 1/2 hold size boundary */ while (((unsigned long)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { ar.hold += (unsigned long)*ar.in++ << ar.bits; ar.bits += 8; } #if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) __asm__ __volatile__ ( " leaq %0, %%rax\n" " movq %%rbp, 8(%%rax)\n" /* save regs rbp and rsp */ " movq %%rsp, (%%rax)\n" " movq %%rax, %%rsp\n" /* make rsp point to &ar */ " movq 16(%%rsp), %%rsi\n" /* rsi = in */ " movq 32(%%rsp), %%rdi\n" /* rdi = out */ " movq 24(%%rsp), %%r9\n" /* r9 = last */ " movq 48(%%rsp), %%r10\n" /* r10 = end */ " movq 64(%%rsp), %%rbp\n" /* rbp = lcode */ " movq 72(%%rsp), %%r11\n" /* r11 = dcode */ " movq 80(%%rsp), %%rdx\n" /* rdx = hold */ " movl 88(%%rsp), %%ebx\n" /* ebx = bits */ " movl 100(%%rsp), %%r12d\n" /* r12d = lmask */ " movl 104(%%rsp), %%r13d\n" /* r13d = dmask */ /* r14d = len */ /* r15d = dist */ " cld\n" " cmpq %%rdi, %%r10\n" " je .L_one_time\n" /* if only one decode left */ " cmpq %%rsi, %%r9\n" " je .L_one_time\n" " jmp .L_do_loop\n" ".L_one_time:\n" " movq %%r12, %%r8\n" /* r8 = lmask */ " cmpb $32, %%bl\n" " ja .L_get_length_code_one_time\n" " lodsl\n" /* eax = *(uint *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $32, %%bl\n" /* bits += 32 */ " shlq %%cl, %%rax\n" " orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ " jmp .L_get_length_code_one_time\n" ".align 32,0x90\n" ".L_while_test:\n" " cmpq %%rdi, %%r10\n" " jbe .L_break_loop\n" " cmpq %%rsi, %%r9\n" " jbe .L_break_loop\n" ".L_do_loop:\n" " movq %%r12, %%r8\n" /* r8 = lmask */ " cmpb $32, %%bl\n" " ja .L_get_length_code\n" /* if (32 < bits) */ " lodsl\n" /* eax = *(uint *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $32, %%bl\n" /* bits += 32 */ " shlq %%cl, %%rax\n" " orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ ".L_get_length_code:\n" " andq %%rdx, %%r8\n" /* r8 &= hold */ " movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ " movb %%ah, %%cl\n" /* cl = this.bits */ " subb %%ah, %%bl\n" /* bits -= this.bits */ " shrq %%cl, %%rdx\n" /* hold >>= this.bits */ " testb %%al, %%al\n" " jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ " movq %%r12, %%r8\n" /* r8 = lmask */ " shrl $16, %%eax\n" /* output this.val char */ " stosb\n" ".L_get_length_code_one_time:\n" " andq %%rdx, %%r8\n" /* r8 &= hold */ " movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ ".L_dolen:\n" " movb %%ah, %%cl\n" /* cl = this.bits */ " subb %%ah, %%bl\n" /* bits -= this.bits */ " shrq %%cl, %%rdx\n" /* hold >>= this.bits */ " testb %%al, %%al\n" " jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ " shrl $16, %%eax\n" /* output this.val char */ " stosb\n" " jmp .L_while_test\n" ".align 32,0x90\n" ".L_test_for_length_base:\n" " movl %%eax, %%r14d\n" /* len = this */ " shrl $16, %%r14d\n" /* len = this.val */ " movb %%al, %%cl\n" " testb $16, %%al\n" " jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ " andb $15, %%cl\n" /* op &= 15 */ " jz .L_decode_distance\n" /* if (!op) */ ".L_add_bits_to_len:\n" " subb %%cl, %%bl\n" " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " shrq %%cl, %%rdx\n" " addl %%eax, %%r14d\n" /* len += hold & mask[op] */ ".L_decode_distance:\n" " movq %%r13, %%r8\n" /* r8 = dmask */ " cmpb $32, %%bl\n" " ja .L_get_distance_code\n" /* if (32 < bits) */ " lodsl\n" /* eax = *(uint *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $32, %%bl\n" /* bits += 32 */ " shlq %%cl, %%rax\n" " orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ ".L_get_distance_code:\n" " andq %%rdx, %%r8\n" /* r8 &= hold */ " movl (%%r11,%%r8,4), %%eax\n" /* eax = dcode[hold & dmask] */ ".L_dodist:\n" " movl %%eax, %%r15d\n" /* dist = this */ " shrl $16, %%r15d\n" /* dist = this.val */ " movb %%ah, %%cl\n" " subb %%ah, %%bl\n" /* bits -= this.bits */ " shrq %%cl, %%rdx\n" /* hold >>= this.bits */ " movb %%al, %%cl\n" /* cl = this.op */ " testb $16, %%al\n" /* if ((op & 16) == 0) */ " jz .L_test_for_second_level_dist\n" " andb $15, %%cl\n" /* op &= 15 */ " jz .L_check_dist_one\n" ".L_add_bits_to_dist:\n" " subb %%cl, %%bl\n" " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" /* (1 << op) - 1 */ " andl %%edx, %%eax\n" /* eax &= hold */ " shrq %%cl, %%rdx\n" " addl %%eax, %%r15d\n" /* dist += hold & ((1 << op) - 1) */ ".L_check_window:\n" " movq %%rsi, %%r8\n" /* save in so from can use it's reg */ " movq %%rdi, %%rax\n" " subq 40(%%rsp), %%rax\n" /* nbytes = out - beg */ " cmpl %%r15d, %%eax\n" " jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ " movl %%r14d, %%ecx\n" /* ecx = len */ " movq %%rdi, %%rsi\n" " subq %%r15, %%rsi\n" /* from = out - dist */ " sarl %%ecx\n" " jnc .L_copy_two\n" /* if len % 2 == 0 */ " rep movsw\n" " movb (%%rsi), %%al\n" " movb %%al, (%%rdi)\n" " incq %%rdi\n" " movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ " jmp .L_while_test\n" ".L_copy_two:\n" " rep movsw\n" " movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ " jmp .L_while_test\n" ".align 32,0x90\n" ".L_check_dist_one:\n" " cmpl $1, %%r15d\n" /* if dist 1, is a memset */ " jne .L_check_window\n" " cmpq %%rdi, 40(%%rsp)\n" /* if out == beg, outside window */ " je .L_check_window\n" " movl %%r14d, %%ecx\n" /* ecx = len */ " movb -1(%%rdi), %%al\n" " movb %%al, %%ah\n" " sarl %%ecx\n" " jnc .L_set_two\n" " movb %%al, (%%rdi)\n" " incq %%rdi\n" ".L_set_two:\n" " rep stosw\n" " jmp .L_while_test\n" ".align 32,0x90\n" ".L_test_for_second_level_length:\n" " testb $64, %%al\n" " jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " addl %%r14d, %%eax\n" /* eax += len */ " movl (%%rbp,%%rax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ " jmp .L_dolen\n" ".align 32,0x90\n" ".L_test_for_second_level_dist:\n" " testb $64, %%al\n" " jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " addl %%r15d, %%eax\n" /* eax += dist */ " movl (%%r11,%%rax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ " jmp .L_dodist\n" ".align 32,0x90\n" ".L_clip_window:\n" " movl %%eax, %%ecx\n" /* ecx = nbytes */ " movl 92(%%rsp), %%eax\n" /* eax = wsize, prepare for dist cmp */ " negl %%ecx\n" /* nbytes = -nbytes */ " cmpl %%r15d, %%eax\n" " jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ " addl %%r15d, %%ecx\n" /* nbytes = dist - nbytes */ " cmpl $0, 96(%%rsp)\n" " jne .L_wrap_around_window\n" /* if (write != 0) */ " movq 56(%%rsp), %%rsi\n" /* from = window */ " subl %%ecx, %%eax\n" /* eax -= nbytes */ " addq %%rax, %%rsi\n" /* from += wsize - nbytes */ " movl %%r14d, %%eax\n" /* eax = len */ " cmpl %%ecx, %%r14d\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* eax -= nbytes */ " rep movsb\n" " movq %%rdi, %%rsi\n" " subq %%r15, %%rsi\n" /* from = &out[ -dist ] */ " jmp .L_do_copy\n" ".align 32,0x90\n" ".L_wrap_around_window:\n" " movl 96(%%rsp), %%eax\n" /* eax = write */ " cmpl %%eax, %%ecx\n" " jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ " movl 92(%%rsp), %%esi\n" /* from = wsize */ " addq 56(%%rsp), %%rsi\n" /* from += window */ " addq %%rax, %%rsi\n" /* from += write */ " subq %%rcx, %%rsi\n" /* from -= nbytes */ " subl %%eax, %%ecx\n" /* nbytes -= write */ " movl %%r14d, %%eax\n" /* eax = len */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movq 56(%%rsp), %%rsi\n" /* from = window */ " movl 96(%%rsp), %%ecx\n" /* nbytes = write */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movq %%rdi, %%rsi\n" " subq %%r15, %%rsi\n" /* from = out - dist */ " jmp .L_do_copy\n" ".align 32,0x90\n" ".L_contiguous_in_window:\n" " movq 56(%%rsp), %%rsi\n" /* rsi = window */ " addq %%rax, %%rsi\n" " subq %%rcx, %%rsi\n" /* from += write - nbytes */ " movl %%r14d, %%eax\n" /* eax = len */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movq %%rdi, %%rsi\n" " subq %%r15, %%rsi\n" /* from = out - dist */ " jmp .L_do_copy\n" /* if (nbytes >= len) */ ".align 32,0x90\n" ".L_do_copy:\n" " movl %%eax, %%ecx\n" /* ecx = len */ " rep movsb\n" " movq %%r8, %%rsi\n" /* move in back to %esi, toss from */ " jmp .L_while_test\n" ".L_test_for_end_of_block:\n" " testb $32, %%al\n" " jz .L_invalid_literal_length_code\n" " movl $1, 116(%%rsp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_literal_length_code:\n" " movl $2, 116(%%rsp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_distance_code:\n" " movl $3, 116(%%rsp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_distance_too_far:\n" " movl $4, 116(%%rsp)\n" " jmp .L_break_loop_with_status\n" ".L_break_loop:\n" " movl $0, 116(%%rsp)\n" ".L_break_loop_with_status:\n" /* put in, out, bits, and hold back into ar and pop esp */ " movq %%rsi, 16(%%rsp)\n" /* in */ " movq %%rdi, 32(%%rsp)\n" /* out */ " movl %%ebx, 88(%%rsp)\n" /* bits */ " movq %%rdx, 80(%%rsp)\n" /* hold */ " movq (%%rsp), %%rax\n" /* restore rbp and rsp */ " movq 8(%%rsp), %%rbp\n" " movq %%rax, %%rsp\n" : : "m" (ar) : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" ); #elif ( defined( __GNUC__ ) || defined( __ICC ) ) && defined( __i386 ) __asm__ __volatile__ ( " leal %0, %%eax\n" " movl %%esp, (%%eax)\n" /* save esp, ebp */ " movl %%ebp, 4(%%eax)\n" " movl %%eax, %%esp\n" " movl 8(%%esp), %%esi\n" /* esi = in */ " movl 16(%%esp), %%edi\n" /* edi = out */ " movl 40(%%esp), %%edx\n" /* edx = hold */ " movl 44(%%esp), %%ebx\n" /* ebx = bits */ " movl 32(%%esp), %%ebp\n" /* ebp = lcode */ " cld\n" " jmp .L_do_loop\n" ".align 32,0x90\n" ".L_while_test:\n" " cmpl %%edi, 24(%%esp)\n" /* out < end */ " jbe .L_break_loop\n" " cmpl %%esi, 12(%%esp)\n" /* in < last */ " jbe .L_break_loop\n" ".L_do_loop:\n" " cmpb $15, %%bl\n" " ja .L_get_length_code\n" /* if (15 < bits) */ " xorl %%eax, %%eax\n" " lodsw\n" /* al = *(ushort *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $16, %%bl\n" /* bits += 16 */ " shll %%cl, %%eax\n" " orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ ".L_get_length_code:\n" " movl 56(%%esp), %%eax\n" /* eax = lmask */ " andl %%edx, %%eax\n" /* eax &= hold */ " movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[hold & lmask] */ ".L_dolen:\n" " movb %%ah, %%cl\n" /* cl = this.bits */ " subb %%ah, %%bl\n" /* bits -= this.bits */ " shrl %%cl, %%edx\n" /* hold >>= this.bits */ " testb %%al, %%al\n" " jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ " shrl $16, %%eax\n" /* output this.val char */ " stosb\n" " jmp .L_while_test\n" ".align 32,0x90\n" ".L_test_for_length_base:\n" " movl %%eax, %%ecx\n" /* len = this */ " shrl $16, %%ecx\n" /* len = this.val */ " movl %%ecx, 64(%%esp)\n" /* save len */ " movb %%al, %%cl\n" " testb $16, %%al\n" " jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ " andb $15, %%cl\n" /* op &= 15 */ " jz .L_decode_distance\n" /* if (!op) */ " cmpb %%cl, %%bl\n" " jae .L_add_bits_to_len\n" /* if (op <= bits) */ " movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ " xorl %%eax, %%eax\n" " lodsw\n" /* al = *(ushort *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $16, %%bl\n" /* bits += 16 */ " shll %%cl, %%eax\n" " orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ " movb %%ch, %%cl\n" /* move op back to ecx */ ".L_add_bits_to_len:\n" " subb %%cl, %%bl\n" " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " shrl %%cl, %%edx\n" " addl %%eax, 64(%%esp)\n" /* len += hold & mask[op] */ ".L_decode_distance:\n" " cmpb $15, %%bl\n" " ja .L_get_distance_code\n" /* if (15 < bits) */ " xorl %%eax, %%eax\n" " lodsw\n" /* al = *(ushort *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $16, %%bl\n" /* bits += 16 */ " shll %%cl, %%eax\n" " orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ ".L_get_distance_code:\n" " movl 60(%%esp), %%eax\n" /* eax = dmask */ " movl 36(%%esp), %%ecx\n" /* ecx = dcode */ " andl %%edx, %%eax\n" /* eax &= hold */ " movl (%%ecx,%%eax,4), %%eax\n"/* eax = dcode[hold & dmask] */ ".L_dodist:\n" " movl %%eax, %%ebp\n" /* dist = this */ " shrl $16, %%ebp\n" /* dist = this.val */ " movb %%ah, %%cl\n" " subb %%ah, %%bl\n" /* bits -= this.bits */ " shrl %%cl, %%edx\n" /* hold >>= this.bits */ " movb %%al, %%cl\n" /* cl = this.op */ " testb $16, %%al\n" /* if ((op & 16) == 0) */ " jz .L_test_for_second_level_dist\n" " andb $15, %%cl\n" /* op &= 15 */ " jz .L_check_dist_one\n" " cmpb %%cl, %%bl\n" " jae .L_add_bits_to_dist\n" /* if (op <= bits) 97.6% */ " movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ " xorl %%eax, %%eax\n" " lodsw\n" /* al = *(ushort *)in++ */ " movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ " addb $16, %%bl\n" /* bits += 16 */ " shll %%cl, %%eax\n" " orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ " movb %%ch, %%cl\n" /* move op back to ecx */ ".L_add_bits_to_dist:\n" " subb %%cl, %%bl\n" " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" /* (1 << op) - 1 */ " andl %%edx, %%eax\n" /* eax &= hold */ " shrl %%cl, %%edx\n" " addl %%eax, %%ebp\n" /* dist += hold & ((1 << op) - 1) */ ".L_check_window:\n" " movl %%esi, 8(%%esp)\n" /* save in so from can use it's reg */ " movl %%edi, %%eax\n" " subl 20(%%esp), %%eax\n" /* nbytes = out - beg */ " cmpl %%ebp, %%eax\n" " jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ " movl 64(%%esp), %%ecx\n" /* ecx = len */ " movl %%edi, %%esi\n" " subl %%ebp, %%esi\n" /* from = out - dist */ " sarl %%ecx\n" " jnc .L_copy_two\n" /* if len % 2 == 0 */ " rep movsw\n" " movb (%%esi), %%al\n" " movb %%al, (%%edi)\n" " incl %%edi\n" " movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ " movl 32(%%esp), %%ebp\n" /* ebp = lcode */ " jmp .L_while_test\n" ".L_copy_two:\n" " rep movsw\n" " movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ " movl 32(%%esp), %%ebp\n" /* ebp = lcode */ " jmp .L_while_test\n" ".align 32,0x90\n" ".L_check_dist_one:\n" " cmpl $1, %%ebp\n" /* if dist 1, is a memset */ " jne .L_check_window\n" " cmpl %%edi, 20(%%esp)\n" " je .L_check_window\n" /* out == beg, if outside window */ " movl 64(%%esp), %%ecx\n" /* ecx = len */ " movb -1(%%edi), %%al\n" " movb %%al, %%ah\n" " sarl %%ecx\n" " jnc .L_set_two\n" " movb %%al, (%%edi)\n" " incl %%edi\n" ".L_set_two:\n" " rep stosw\n" " movl 32(%%esp), %%ebp\n" /* ebp = lcode */ " jmp .L_while_test\n" ".align 32,0x90\n" ".L_test_for_second_level_length:\n" " testb $64, %%al\n" " jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " addl 64(%%esp), %%eax\n" /* eax += len */ " movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ " jmp .L_dolen\n" ".align 32,0x90\n" ".L_test_for_second_level_dist:\n" " testb $64, %%al\n" " jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ " xorl %%eax, %%eax\n" " incl %%eax\n" " shll %%cl, %%eax\n" " decl %%eax\n" " andl %%edx, %%eax\n" /* eax &= hold */ " addl %%ebp, %%eax\n" /* eax += dist */ " movl 36(%%esp), %%ecx\n" /* ecx = dcode */ " movl (%%ecx,%%eax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ " jmp .L_dodist\n" ".align 32,0x90\n" ".L_clip_window:\n" " movl %%eax, %%ecx\n" " movl 48(%%esp), %%eax\n" /* eax = wsize */ " negl %%ecx\n" /* nbytes = -nbytes */ " movl 28(%%esp), %%esi\n" /* from = window */ " cmpl %%ebp, %%eax\n" " jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ " addl %%ebp, %%ecx\n" /* nbytes = dist - nbytes */ " cmpl $0, 52(%%esp)\n" " jne .L_wrap_around_window\n" /* if (write != 0) */ " subl %%ecx, %%eax\n" " addl %%eax, %%esi\n" /* from += wsize - nbytes */ " movl 64(%%esp), %%eax\n" /* eax = len */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movl %%edi, %%esi\n" " subl %%ebp, %%esi\n" /* from = out - dist */ " jmp .L_do_copy\n" ".align 32,0x90\n" ".L_wrap_around_window:\n" " movl 52(%%esp), %%eax\n" /* eax = write */ " cmpl %%eax, %%ecx\n" " jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ " addl 48(%%esp), %%esi\n" /* from += wsize */ " addl %%eax, %%esi\n" /* from += write */ " subl %%ecx, %%esi\n" /* from -= nbytes */ " subl %%eax, %%ecx\n" /* nbytes -= write */ " movl 64(%%esp), %%eax\n" /* eax = len */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movl 28(%%esp), %%esi\n" /* from = window */ " movl 52(%%esp), %%ecx\n" /* nbytes = write */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movl %%edi, %%esi\n" " subl %%ebp, %%esi\n" /* from = out - dist */ " jmp .L_do_copy\n" ".align 32,0x90\n" ".L_contiguous_in_window:\n" " addl %%eax, %%esi\n" " subl %%ecx, %%esi\n" /* from += write - nbytes */ " movl 64(%%esp), %%eax\n" /* eax = len */ " cmpl %%ecx, %%eax\n" " jbe .L_do_copy\n" /* if (nbytes >= len) */ " subl %%ecx, %%eax\n" /* len -= nbytes */ " rep movsb\n" " movl %%edi, %%esi\n" " subl %%ebp, %%esi\n" /* from = out - dist */ " jmp .L_do_copy\n" /* if (nbytes >= len) */ ".align 32,0x90\n" ".L_do_copy:\n" " movl %%eax, %%ecx\n" " rep movsb\n" " movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ " movl 32(%%esp), %%ebp\n" /* ebp = lcode */ " jmp .L_while_test\n" ".L_test_for_end_of_block:\n" " testb $32, %%al\n" " jz .L_invalid_literal_length_code\n" " movl $1, 72(%%esp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_literal_length_code:\n" " movl $2, 72(%%esp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_distance_code:\n" " movl $3, 72(%%esp)\n" " jmp .L_break_loop_with_status\n" ".L_invalid_distance_too_far:\n" " movl 8(%%esp), %%esi\n" " movl $4, 72(%%esp)\n" " jmp .L_break_loop_with_status\n" ".L_break_loop:\n" " movl $0, 72(%%esp)\n" ".L_break_loop_with_status:\n" /* put in, out, bits, and hold back into ar and pop esp */ " movl %%esi, 8(%%esp)\n" /* save in */ " movl %%edi, 16(%%esp)\n" /* save out */ " movl %%ebx, 44(%%esp)\n" /* save bits */ " movl %%edx, 40(%%esp)\n" /* save hold */ " movl 4(%%esp), %%ebp\n" /* restore esp, ebp */ " movl (%%esp), %%esp\n" : : "m" (ar) : "memory", "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi" ); #elif defined( _MSC_VER ) && ! defined( _M_AMD64 ) __asm { lea eax, ar mov [eax], esp /* save esp, ebp */ mov [eax+4], ebp mov esp, eax mov esi, [esp+8] /* esi = in */ mov edi, [esp+16] /* edi = out */ mov edx, [esp+40] /* edx = hold */ mov ebx, [esp+44] /* ebx = bits */ mov ebp, [esp+32] /* ebp = lcode */ cld jmp L_do_loop ALIGN 4 L_while_test: cmp [esp+24], edi jbe L_break_loop cmp [esp+12], esi jbe L_break_loop L_do_loop: cmp bl, 15 ja L_get_length_code /* if (15 < bits) */ xor eax, eax lodsw /* al = *(ushort *)in++ */ mov cl, bl /* cl = bits, needs it for shifting */ add bl, 16 /* bits += 16 */ shl eax, cl or edx, eax /* hold |= *((ushort *)in)++ << bits */ L_get_length_code: mov eax, [esp+56] /* eax = lmask */ and eax, edx /* eax &= hold */ mov eax, [ebp+eax*4] /* eax = lcode[hold & lmask] */ L_dolen: mov cl, ah /* cl = this.bits */ sub bl, ah /* bits -= this.bits */ shr edx, cl /* hold >>= this.bits */ test al, al jnz L_test_for_length_base /* if (op != 0) 45.7% */ shr eax, 16 /* output this.val char */ stosb jmp L_while_test ALIGN 4 L_test_for_length_base: mov ecx, eax /* len = this */ shr ecx, 16 /* len = this.val */ mov [esp+64], ecx /* save len */ mov cl, al test al, 16 jz L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ and cl, 15 /* op &= 15 */ jz L_decode_distance /* if (!op) */ cmp bl, cl jae L_add_bits_to_len /* if (op <= bits) */ mov ch, cl /* stash op in ch, freeing cl */ xor eax, eax lodsw /* al = *(ushort *)in++ */ mov cl, bl /* cl = bits, needs it for shifting */ add bl, 16 /* bits += 16 */ shl eax, cl or edx, eax /* hold |= *((ushort *)in)++ << bits */ mov cl, ch /* move op back to ecx */ L_add_bits_to_len: sub bl, cl xor eax, eax inc eax shl eax, cl dec eax and eax, edx /* eax &= hold */ shr edx, cl add [esp+64], eax /* len += hold & mask[op] */ L_decode_distance: cmp bl, 15 ja L_get_distance_code /* if (15 < bits) */ xor eax, eax lodsw /* al = *(ushort *)in++ */ mov cl, bl /* cl = bits, needs it for shifting */ add bl, 16 /* bits += 16 */ shl eax, cl or edx, eax /* hold |= *((ushort *)in)++ << bits */ L_get_distance_code: mov eax, [esp+60] /* eax = dmask */ mov ecx, [esp+36] /* ecx = dcode */ and eax, edx /* eax &= hold */ mov eax, [ecx+eax*4]/* eax = dcode[hold & dmask] */ L_dodist: mov ebp, eax /* dist = this */ shr ebp, 16 /* dist = this.val */ mov cl, ah sub bl, ah /* bits -= this.bits */ shr edx, cl /* hold >>= this.bits */ mov cl, al /* cl = this.op */ test al, 16 /* if ((op & 16) == 0) */ jz L_test_for_second_level_dist and cl, 15 /* op &= 15 */ jz L_check_dist_one cmp bl, cl jae L_add_bits_to_dist /* if (op <= bits) 97.6% */ mov ch, cl /* stash op in ch, freeing cl */ xor eax, eax lodsw /* al = *(ushort *)in++ */ mov cl, bl /* cl = bits, needs it for shifting */ add bl, 16 /* bits += 16 */ shl eax, cl or edx, eax /* hold |= *((ushort *)in)++ << bits */ mov cl, ch /* move op back to ecx */ L_add_bits_to_dist: sub bl, cl xor eax, eax inc eax shl eax, cl dec eax /* (1 << op) - 1 */ and eax, edx /* eax &= hold */ shr edx, cl add ebp, eax /* dist += hold & ((1 << op) - 1) */ L_check_window: mov [esp+8], esi /* save in so from can use it's reg */ mov eax, edi sub eax, [esp+20] /* nbytes = out - beg */ cmp eax, ebp jb L_clip_window /* if (dist > nbytes) 4.2% */ mov ecx, [esp+64] /* ecx = len */ mov esi, edi sub esi, ebp /* from = out - dist */ sar ecx, 1 jnc L_copy_two rep movsw mov al, [esi] mov [edi], al inc edi mov esi, [esp+8] /* move in back to %esi, toss from */ mov ebp, [esp+32] /* ebp = lcode */ jmp L_while_test L_copy_two: rep movsw mov esi, [esp+8] /* move in back to %esi, toss from */ mov ebp, [esp+32] /* ebp = lcode */ jmp L_while_test ALIGN 4 L_check_dist_one: cmp ebp, 1 /* if dist 1, is a memset */ jne L_check_window cmp [esp+20], edi je L_check_window /* out == beg, if outside window */ mov ecx, [esp+64] /* ecx = len */ mov al, [edi-1] mov ah, al sar ecx, 1 jnc L_set_two mov [edi], al /* memset out with from[-1] */ inc edi L_set_two: rep stosw mov ebp, [esp+32] /* ebp = lcode */ jmp L_while_test ALIGN 4 L_test_for_second_level_length: test al, 64 jnz L_test_for_end_of_block /* if ((op & 64) != 0) */ xor eax, eax inc eax shl eax, cl dec eax and eax, edx /* eax &= hold */ add eax, [esp+64] /* eax += len */ mov eax, [ebp+eax*4] /* eax = lcode[val+(hold&mask[op])]*/ jmp L_dolen ALIGN 4 L_test_for_second_level_dist: test al, 64 jnz L_invalid_distance_code /* if ((op & 64) != 0) */ xor eax, eax inc eax shl eax, cl dec eax and eax, edx /* eax &= hold */ add eax, ebp /* eax += dist */ mov ecx, [esp+36] /* ecx = dcode */ mov eax, [ecx+eax*4] /* eax = dcode[val+(hold&mask[op])]*/ jmp L_dodist ALIGN 4 L_clip_window: mov ecx, eax mov eax, [esp+48] /* eax = wsize */ neg ecx /* nbytes = -nbytes */ mov esi, [esp+28] /* from = window */ cmp eax, ebp jb L_invalid_distance_too_far /* if (dist > wsize) */ add ecx, ebp /* nbytes = dist - nbytes */ cmp dword ptr [esp+52], 0 jne L_wrap_around_window /* if (write != 0) */ sub eax, ecx add esi, eax /* from += wsize - nbytes */ mov eax, [esp+64] /* eax = len */ cmp eax, ecx jbe L_do_copy /* if (nbytes >= len) */ sub eax, ecx /* len -= nbytes */ rep movsb mov esi, edi sub esi, ebp /* from = out - dist */ jmp L_do_copy ALIGN 4 L_wrap_around_window: mov eax, [esp+52] /* eax = write */ cmp ecx, eax jbe L_contiguous_in_window /* if (write >= nbytes) */ add esi, [esp+48] /* from += wsize */ add esi, eax /* from += write */ sub esi, ecx /* from -= nbytes */ sub ecx, eax /* nbytes -= write */ mov eax, [esp+64] /* eax = len */ cmp eax, ecx jbe L_do_copy /* if (nbytes >= len) */ sub eax, ecx /* len -= nbytes */ rep movsb mov esi, [esp+28] /* from = window */ mov ecx, [esp+52] /* nbytes = write */ cmp eax, ecx jbe L_do_copy /* if (nbytes >= len) */ sub eax, ecx /* len -= nbytes */ rep movsb mov esi, edi sub esi, ebp /* from = out - dist */ jmp L_do_copy ALIGN 4 L_contiguous_in_window: add esi, eax sub esi, ecx /* from += write - nbytes */ mov eax, [esp+64] /* eax = len */ cmp eax, ecx jbe L_do_copy /* if (nbytes >= len) */ sub eax, ecx /* len -= nbytes */ rep movsb mov esi, edi sub esi, ebp /* from = out - dist */ jmp L_do_copy ALIGN 4 L_do_copy: mov ecx, eax rep movsb mov esi, [esp+8] /* move in back to %esi, toss from */ mov ebp, [esp+32] /* ebp = lcode */ jmp L_while_test L_test_for_end_of_block: test al, 32 jz L_invalid_literal_length_code mov dword ptr [esp+72], 1 jmp L_break_loop_with_status L_invalid_literal_length_code: mov dword ptr [esp+72], 2 jmp L_break_loop_with_status L_invalid_distance_code: mov dword ptr [esp+72], 3 jmp L_break_loop_with_status L_invalid_distance_too_far: mov esi, [esp+4] mov dword ptr [esp+72], 4 jmp L_break_loop_with_status L_break_loop: mov dword ptr [esp+72], 0 L_break_loop_with_status: /* put in, out, bits, and hold back into ar and pop esp */ mov [esp+8], esi /* save in */ mov [esp+16], edi /* save out */ mov [esp+44], ebx /* save bits */ mov [esp+40], edx /* save hold */ mov ebp, [esp+4] /* restore esp, ebp */ mov esp, [esp] } #else #error "x86 architecture not defined" #endif if (ar.status > 1) { if (ar.status == 2) strm->msg = "invalid literal/length code"; else if (ar.status == 3) strm->msg = "invalid distance code"; else strm->msg = "invalid distance too far back"; state->mode = BAD; } else if ( ar.status == 1 ) { state->mode = TYPE; } /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ ar.len = ar.bits >> 3; ar.in -= ar.len; ar.bits -= ar.len << 3; ar.hold &= (1U << ar.bits) - 1; /* update state and return */ strm->next_in = ar.in; strm->next_out = ar.out; strm->avail_in = (unsigned)(ar.in < ar.last ? PAD_AVAIL_IN + (ar.last - ar.in) : PAD_AVAIL_IN - (ar.in - ar.last)); strm->avail_out = (unsigned)(ar.out < ar.end ? PAD_AVAIL_OUT + (ar.end - ar.out) : PAD_AVAIL_OUT - (ar.out - ar.end)); state->hold = ar.hold; state->bits = ar.bits; return; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/inflate86/inffast.S000066400000000000000000001235321462133141200257020ustar00rootroot00000000000000/* * inffast.S is a hand tuned assembler version of: * * inffast.c -- fast decoding * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Copyright (C) 2003 Chris Anderson * Please use the copyright conditions above. * * This version (Jan-23-2003) of inflate_fast was coded and tested under * GNU/Linux on a pentium 3, using the gcc-3.2 compiler distribution. On that * machine, I found that gzip style archives decompressed about 20% faster than * the gcc-3.2 -O3 -fomit-frame-pointer compiled version. Your results will * depend on how large of a buffer is used for z_stream.next_in & next_out * (8K-32K worked best for my 256K cpu cache) and how much overhead there is in * stream processing I/O and crc32/addler32. In my case, this routine used * 70% of the cpu time and crc32 used 20%. * * I am confident that this version will work in the general case, but I have * not tested a wide variety of datasets or a wide variety of platforms. * * Jan-24-2003 -- Added -DUSE_MMX define for slightly faster inflating. * It should be a runtime flag instead of compile time flag... * * Jan-26-2003 -- Added runtime check for MMX support with cpuid instruction. * With -DUSE_MMX, only MMX code is compiled. With -DNO_MMX, only non-MMX code * is compiled. Without either option, runtime detection is enabled. Runtime * detection should work on all modern cpus and the recomended algorithm (flip * ID bit on eflags and then use the cpuid instruction) is used in many * multimedia applications. Tested under win2k with gcc-2.95 and gas-2.12 * distributed with cygwin3. Compiling with gcc-2.95 -c inffast.S -o * inffast.obj generates a COFF object which can then be linked with MSVC++ * compiled code. Tested under FreeBSD 4.7 with gcc-2.95. * * Jan-28-2003 -- Tested Athlon XP... MMX mode is slower than no MMX (and * slower than compiler generated code). Adjusted cpuid check to use the MMX * code only for Pentiums < P4 until I have more data on the P4. Speed * improvment is only about 15% on the Athlon when compared with code generated * with MSVC++. Not sure yet, but I think the P4 will also be slower using the * MMX mode because many of it's x86 ALU instructions execute in .5 cycles and * have less latency than MMX ops. Added code to buffer the last 11 bytes of * the input stream since the MMX code grabs bits in chunks of 32, which * differs from the inffast.c algorithm. I don't think there would have been * read overruns where a page boundary was crossed (a segfault), but there * could have been overruns when next_in ends on unaligned memory (unintialized * memory read). * * Mar-13-2003 -- P4 MMX is slightly slower than P4 NO_MMX. I created a C * version of the non-MMX code so that it doesn't depend on zstrm and zstate * structure offsets which are hard coded in this file. This was last tested * with zlib-1.2.0 which is currently in beta testing, newer versions of this * and inffas86.c can be found at http://www.eetbeetee.com/zlib/ and * http://www.charm.net/~christop/zlib/ */ /* * if you have underscore linking problems (_inflate_fast undefined), try * using -DGAS_COFF */ #if ! defined( GAS_COFF ) && ! defined( GAS_ELF ) #if defined( WIN32 ) || defined( __CYGWIN__ ) #define GAS_COFF /* windows object format */ #else #define GAS_ELF #endif #endif /* ! GAS_COFF && ! GAS_ELF */ #if defined( GAS_COFF ) /* coff externals have underscores */ #define inflate_fast _inflate_fast #define inflate_fast_use_mmx _inflate_fast_use_mmx #endif /* GAS_COFF */ .file "inffast.S" .globl inflate_fast .text .align 4,0 .L_invalid_literal_length_code_msg: .string "invalid literal/length code" .align 4,0 .L_invalid_distance_code_msg: .string "invalid distance code" .align 4,0 .L_invalid_distance_too_far_msg: .string "invalid distance too far back" #if ! defined( NO_MMX ) .align 4,0 .L_mask: /* mask[N] = ( 1 << N ) - 1 */ .long 0 .long 1 .long 3 .long 7 .long 15 .long 31 .long 63 .long 127 .long 255 .long 511 .long 1023 .long 2047 .long 4095 .long 8191 .long 16383 .long 32767 .long 65535 .long 131071 .long 262143 .long 524287 .long 1048575 .long 2097151 .long 4194303 .long 8388607 .long 16777215 .long 33554431 .long 67108863 .long 134217727 .long 268435455 .long 536870911 .long 1073741823 .long 2147483647 .long 4294967295 #endif /* NO_MMX */ .text /* * struct z_stream offsets, in zlib.h */ #define next_in_strm 0 /* strm->next_in */ #define avail_in_strm 4 /* strm->avail_in */ #define next_out_strm 12 /* strm->next_out */ #define avail_out_strm 16 /* strm->avail_out */ #define msg_strm 24 /* strm->msg */ #define state_strm 28 /* strm->state */ /* * struct inflate_state offsets, in inflate.h */ #define mode_state 0 /* state->mode */ #define wsize_state 32 /* state->wsize */ #define write_state 40 /* state->write */ #define window_state 44 /* state->window */ #define hold_state 48 /* state->hold */ #define bits_state 52 /* state->bits */ #define lencode_state 68 /* state->lencode */ #define distcode_state 72 /* state->distcode */ #define lenbits_state 76 /* state->lenbits */ #define distbits_state 80 /* state->distbits */ /* * inflate_fast's activation record */ #define local_var_size 64 /* how much local space for vars */ #define strm_sp 88 /* first arg: z_stream * (local_var_size + 24) */ #define start_sp 92 /* second arg: unsigned int (local_var_size + 28) */ /* * offsets for local vars on stack */ #define out 60 /* unsigned char* */ #define window 56 /* unsigned char* */ #define wsize 52 /* unsigned int */ #define write 48 /* unsigned int */ #define in 44 /* unsigned char* */ #define beg 40 /* unsigned char* */ #define buf 28 /* char[ 12 ] */ #define len 24 /* unsigned int */ #define last 20 /* unsigned char* */ #define end 16 /* unsigned char* */ #define dcode 12 /* code* */ #define lcode 8 /* code* */ #define dmask 4 /* unsigned int */ #define lmask 0 /* unsigned int */ /* * typedef enum inflate_mode consts, in inflate.h */ #define INFLATE_MODE_TYPE 11 /* state->mode flags enum-ed in inflate.h */ #define INFLATE_MODE_BAD 26 #if ! defined( USE_MMX ) && ! defined( NO_MMX ) #define RUN_TIME_MMX #define CHECK_MMX 1 #define DO_USE_MMX 2 #define DONT_USE_MMX 3 .globl inflate_fast_use_mmx .data .align 4,0 inflate_fast_use_mmx: /* integer flag for run time control 1=check,2=mmx,3=no */ .long CHECK_MMX #if defined( GAS_ELF ) /* elf info */ .type inflate_fast_use_mmx,@object .size inflate_fast_use_mmx,4 #endif #endif /* RUN_TIME_MMX */ #if defined( GAS_COFF ) /* coff info: scl 2 = extern, type 32 = function */ .def inflate_fast; .scl 2; .type 32; .endef #endif .text .align 32,0x90 inflate_fast: pushl %edi pushl %esi pushl %ebp pushl %ebx pushf /* save eflags (strm_sp, state_sp assumes this is 32 bits) */ subl $local_var_size, %esp cld #define strm_r %esi #define state_r %edi movl strm_sp(%esp), strm_r movl state_strm(strm_r), state_r /* in = strm->next_in; * out = strm->next_out; * last = in + strm->avail_in - 11; * beg = out - (start - strm->avail_out); * end = out + (strm->avail_out - 257); */ movl avail_in_strm(strm_r), %edx movl next_in_strm(strm_r), %eax addl %eax, %edx /* avail_in += next_in */ subl $11, %edx /* avail_in -= 11 */ movl %eax, in(%esp) movl %edx, last(%esp) movl start_sp(%esp), %ebp movl avail_out_strm(strm_r), %ecx movl next_out_strm(strm_r), %ebx subl %ecx, %ebp /* start -= avail_out */ negl %ebp /* start = -start */ addl %ebx, %ebp /* start += next_out */ subl $257, %ecx /* avail_out -= 257 */ addl %ebx, %ecx /* avail_out += out */ movl %ebx, out(%esp) movl %ebp, beg(%esp) movl %ecx, end(%esp) /* wsize = state->wsize; * write = state->write; * window = state->window; * hold = state->hold; * bits = state->bits; * lcode = state->lencode; * dcode = state->distcode; * lmask = ( 1 << state->lenbits ) - 1; * dmask = ( 1 << state->distbits ) - 1; */ movl lencode_state(state_r), %eax movl distcode_state(state_r), %ecx movl %eax, lcode(%esp) movl %ecx, dcode(%esp) movl $1, %eax movl lenbits_state(state_r), %ecx shll %cl, %eax decl %eax movl %eax, lmask(%esp) movl $1, %eax movl distbits_state(state_r), %ecx shll %cl, %eax decl %eax movl %eax, dmask(%esp) movl wsize_state(state_r), %eax movl write_state(state_r), %ecx movl window_state(state_r), %edx movl %eax, wsize(%esp) movl %ecx, write(%esp) movl %edx, window(%esp) movl hold_state(state_r), %ebp movl bits_state(state_r), %ebx #undef strm_r #undef state_r #define in_r %esi #define from_r %esi #define out_r %edi movl in(%esp), in_r movl last(%esp), %ecx cmpl in_r, %ecx ja .L_align_long /* if in < last */ addl $11, %ecx /* ecx = &in[ avail_in ] */ subl in_r, %ecx /* ecx = avail_in */ movl $12, %eax subl %ecx, %eax /* eax = 12 - avail_in */ leal buf(%esp), %edi rep movsb /* memcpy( buf, in, avail_in ) */ movl %eax, %ecx xorl %eax, %eax rep stosb /* memset( &buf[ avail_in ], 0, 12 - avail_in ) */ leal buf(%esp), in_r /* in = buf */ movl in_r, last(%esp) /* last = in, do just one iteration */ jmp .L_is_aligned /* align in_r on long boundary */ .L_align_long: testl $3, in_r jz .L_is_aligned xorl %eax, %eax movb (in_r), %al incl in_r movl %ebx, %ecx addl $8, %ebx shll %cl, %eax orl %eax, %ebp jmp .L_align_long .L_is_aligned: movl out(%esp), out_r #if defined( NO_MMX ) jmp .L_do_loop #endif #if defined( USE_MMX ) jmp .L_init_mmx #endif /*** Runtime MMX check ***/ #if defined( RUN_TIME_MMX ) .L_check_mmx: cmpl $DO_USE_MMX, inflate_fast_use_mmx je .L_init_mmx ja .L_do_loop /* > 2 */ pushl %eax pushl %ebx pushl %ecx pushl %edx pushf movl (%esp), %eax /* copy eflags to eax */ xorl $0x200000, (%esp) /* try toggling ID bit of eflags (bit 21) * to see if cpu supports cpuid... * ID bit method not supported by NexGen but * bios may load a cpuid instruction and * cpuid may be disabled on Cyrix 5-6x86 */ popf pushf popl %edx /* copy new eflags to edx */ xorl %eax, %edx /* test if ID bit is flipped */ jz .L_dont_use_mmx /* not flipped if zero */ xorl %eax, %eax cpuid cmpl $0x756e6547, %ebx /* check for GenuineIntel in ebx,ecx,edx */ jne .L_dont_use_mmx cmpl $0x6c65746e, %ecx jne .L_dont_use_mmx cmpl $0x49656e69, %edx jne .L_dont_use_mmx movl $1, %eax cpuid /* get cpu features */ shrl $8, %eax andl $15, %eax cmpl $6, %eax /* check for Pentium family, is 0xf for P4 */ jne .L_dont_use_mmx testl $0x800000, %edx /* test if MMX feature is set (bit 23) */ jnz .L_use_mmx jmp .L_dont_use_mmx .L_use_mmx: movl $DO_USE_MMX, inflate_fast_use_mmx jmp .L_check_mmx_pop .L_dont_use_mmx: movl $DONT_USE_MMX, inflate_fast_use_mmx .L_check_mmx_pop: popl %edx popl %ecx popl %ebx popl %eax jmp .L_check_mmx #endif /*** Non-MMX code ***/ #if defined ( NO_MMX ) || defined( RUN_TIME_MMX ) #define hold_r %ebp #define bits_r %bl #define bitslong_r %ebx .align 32,0x90 .L_while_test: /* while (in < last && out < end) */ cmpl out_r, end(%esp) jbe .L_break_loop /* if (out >= end) */ cmpl in_r, last(%esp) jbe .L_break_loop .L_do_loop: /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out * * do { * if (bits < 15) { * hold |= *((unsigned short *)in)++ << bits; * bits += 16 * } * this = lcode[hold & lmask] */ cmpb $15, bits_r ja .L_get_length_code /* if (15 < bits) */ xorl %eax, %eax lodsw /* al = *(ushort *)in++ */ movb bits_r, %cl /* cl = bits, needs it for shifting */ addb $16, bits_r /* bits += 16 */ shll %cl, %eax orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ .L_get_length_code: movl lmask(%esp), %edx /* edx = lmask */ movl lcode(%esp), %ecx /* ecx = lcode */ andl hold_r, %edx /* edx &= hold */ movl (%ecx,%edx,4), %eax /* eax = lcode[hold & lmask] */ .L_dolen: /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out * * dolen: * bits -= this.bits; * hold >>= this.bits */ movb %ah, %cl /* cl = this.bits */ subb %ah, bits_r /* bits -= this.bits */ shrl %cl, hold_r /* hold >>= this.bits */ /* check if op is a literal * if (op == 0) { * PUP(out) = this.val; * } */ testb %al, %al jnz .L_test_for_length_base /* if (op != 0) 45.7% */ shrl $16, %eax /* output this.val char */ stosb jmp .L_while_test .L_test_for_length_base: /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = len * * else if (op & 16) { * len = this.val * op &= 15 * if (op) { * if (op > bits) { * hold |= *((unsigned short *)in)++ << bits; * bits += 16 * } * len += hold & mask[op]; * bits -= op; * hold >>= op; * } */ #define len_r %edx movl %eax, len_r /* len = this */ shrl $16, len_r /* len = this.val */ movb %al, %cl testb $16, %al jz .L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ andb $15, %cl /* op &= 15 */ jz .L_save_len /* if (!op) */ cmpb %cl, bits_r jae .L_add_bits_to_len /* if (op <= bits) */ movb %cl, %ch /* stash op in ch, freeing cl */ xorl %eax, %eax lodsw /* al = *(ushort *)in++ */ movb bits_r, %cl /* cl = bits, needs it for shifting */ addb $16, bits_r /* bits += 16 */ shll %cl, %eax orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ movb %ch, %cl /* move op back to ecx */ .L_add_bits_to_len: movl $1, %eax shll %cl, %eax decl %eax subb %cl, bits_r andl hold_r, %eax /* eax &= hold */ shrl %cl, hold_r addl %eax, len_r /* len += hold & mask[op] */ .L_save_len: movl len_r, len(%esp) /* save len */ #undef len_r .L_decode_distance: /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = dist * * if (bits < 15) { * hold |= *((unsigned short *)in)++ << bits; * bits += 16 * } * this = dcode[hold & dmask]; * dodist: * bits -= this.bits; * hold >>= this.bits; * op = this.op; */ cmpb $15, bits_r ja .L_get_distance_code /* if (15 < bits) */ xorl %eax, %eax lodsw /* al = *(ushort *)in++ */ movb bits_r, %cl /* cl = bits, needs it for shifting */ addb $16, bits_r /* bits += 16 */ shll %cl, %eax orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ .L_get_distance_code: movl dmask(%esp), %edx /* edx = dmask */ movl dcode(%esp), %ecx /* ecx = dcode */ andl hold_r, %edx /* edx &= hold */ movl (%ecx,%edx,4), %eax /* eax = dcode[hold & dmask] */ #define dist_r %edx .L_dodist: movl %eax, dist_r /* dist = this */ shrl $16, dist_r /* dist = this.val */ movb %ah, %cl subb %ah, bits_r /* bits -= this.bits */ shrl %cl, hold_r /* hold >>= this.bits */ /* if (op & 16) { * dist = this.val * op &= 15 * if (op > bits) { * hold |= *((unsigned short *)in)++ << bits; * bits += 16 * } * dist += hold & mask[op]; * bits -= op; * hold >>= op; */ movb %al, %cl /* cl = this.op */ testb $16, %al /* if ((op & 16) == 0) */ jz .L_test_for_second_level_dist andb $15, %cl /* op &= 15 */ jz .L_check_dist_one cmpb %cl, bits_r jae .L_add_bits_to_dist /* if (op <= bits) 97.6% */ movb %cl, %ch /* stash op in ch, freeing cl */ xorl %eax, %eax lodsw /* al = *(ushort *)in++ */ movb bits_r, %cl /* cl = bits, needs it for shifting */ addb $16, bits_r /* bits += 16 */ shll %cl, %eax orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ movb %ch, %cl /* move op back to ecx */ .L_add_bits_to_dist: movl $1, %eax shll %cl, %eax decl %eax /* (1 << op) - 1 */ subb %cl, bits_r andl hold_r, %eax /* eax &= hold */ shrl %cl, hold_r addl %eax, dist_r /* dist += hold & ((1 << op) - 1) */ jmp .L_check_window .L_check_window: /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist * %ecx = nbytes * * nbytes = out - beg; * if (dist <= nbytes) { * from = out - dist; * do { * PUP(out) = PUP(from); * } while (--len > 0) { * } */ movl in_r, in(%esp) /* save in so from can use it's reg */ movl out_r, %eax subl beg(%esp), %eax /* nbytes = out - beg */ cmpl dist_r, %eax jb .L_clip_window /* if (dist > nbytes) 4.2% */ movl len(%esp), %ecx movl out_r, from_r subl dist_r, from_r /* from = out - dist */ subl $3, %ecx movb (from_r), %al movb %al, (out_r) movb 1(from_r), %al movb 2(from_r), %dl addl $3, from_r movb %al, 1(out_r) movb %dl, 2(out_r) addl $3, out_r rep movsb movl in(%esp), in_r /* move in back to %esi, toss from */ jmp .L_while_test .align 16,0x90 .L_check_dist_one: cmpl $1, dist_r jne .L_check_window cmpl out_r, beg(%esp) je .L_check_window decl out_r movl len(%esp), %ecx movb (out_r), %al subl $3, %ecx movb %al, 1(out_r) movb %al, 2(out_r) movb %al, 3(out_r) addl $4, out_r rep stosb jmp .L_while_test .align 16,0x90 .L_test_for_second_level_length: /* else if ((op & 64) == 0) { * this = lcode[this.val + (hold & mask[op])]; * } */ testb $64, %al jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ movl $1, %eax shll %cl, %eax decl %eax andl hold_r, %eax /* eax &= hold */ addl %edx, %eax /* eax += this.val */ movl lcode(%esp), %edx /* edx = lcode */ movl (%edx,%eax,4), %eax /* eax = lcode[val + (hold&mask[op])] */ jmp .L_dolen .align 16,0x90 .L_test_for_second_level_dist: /* else if ((op & 64) == 0) { * this = dcode[this.val + (hold & mask[op])]; * } */ testb $64, %al jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ movl $1, %eax shll %cl, %eax decl %eax andl hold_r, %eax /* eax &= hold */ addl %edx, %eax /* eax += this.val */ movl dcode(%esp), %edx /* edx = dcode */ movl (%edx,%eax,4), %eax /* eax = dcode[val + (hold&mask[op])] */ jmp .L_dodist .align 16,0x90 .L_clip_window: /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist * %ecx = nbytes * * else { * if (dist > wsize) { * invalid distance * } * from = window; * nbytes = dist - nbytes; * if (write == 0) { * from += wsize - nbytes; */ #define nbytes_r %ecx movl %eax, nbytes_r movl wsize(%esp), %eax /* prepare for dist compare */ negl nbytes_r /* nbytes = -nbytes */ movl window(%esp), from_r /* from = window */ cmpl dist_r, %eax jb .L_invalid_distance_too_far /* if (dist > wsize) */ addl dist_r, nbytes_r /* nbytes = dist - nbytes */ cmpl $0, write(%esp) jne .L_wrap_around_window /* if (write != 0) */ subl nbytes_r, %eax addl %eax, from_r /* from += wsize - nbytes */ /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist * %ecx = nbytes, %eax = len * * if (nbytes < len) { * len -= nbytes; * do { * PUP(out) = PUP(from); * } while (--nbytes); * from = out - dist; * } * } */ #define len_r %eax movl len(%esp), len_r cmpl nbytes_r, len_r jbe .L_do_copy1 /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1 cmpl nbytes_r, len_r jbe .L_do_copy1 /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1 .L_wrap_around_window: /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist * %ecx = nbytes, %eax = write, %eax = len * * else if (write < nbytes) { * from += wsize + write - nbytes; * nbytes -= write; * if (nbytes < len) { * len -= nbytes; * do { * PUP(out) = PUP(from); * } while (--nbytes); * from = window; * nbytes = write; * if (nbytes < len) { * len -= nbytes; * do { * PUP(out) = PUP(from); * } while(--nbytes); * from = out - dist; * } * } * } */ #define write_r %eax movl write(%esp), write_r cmpl write_r, nbytes_r jbe .L_contiguous_in_window /* if (write >= nbytes) */ addl wsize(%esp), from_r addl write_r, from_r subl nbytes_r, from_r /* from += wsize + write - nbytes */ subl write_r, nbytes_r /* nbytes -= write */ #undef write_r movl len(%esp), len_r cmpl nbytes_r, len_r jbe .L_do_copy1 /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl window(%esp), from_r /* from = window */ movl write(%esp), nbytes_r /* nbytes = write */ cmpl nbytes_r, len_r jbe .L_do_copy1 /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1 .L_contiguous_in_window: /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist * %ecx = nbytes, %eax = write, %eax = len * * else { * from += write - nbytes; * if (nbytes < len) { * len -= nbytes; * do { * PUP(out) = PUP(from); * } while (--nbytes); * from = out - dist; * } * } */ #define write_r %eax addl write_r, from_r subl nbytes_r, from_r /* from += write - nbytes */ #undef write_r movl len(%esp), len_r cmpl nbytes_r, len_r jbe .L_do_copy1 /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ .L_do_copy1: /* regs: %esi = from, %esi = in, %ebp = hold, %bl = bits, %edi = out * %eax = len * * while (len > 0) { * PUP(out) = PUP(from); * len--; * } * } * } while (in < last && out < end); */ #undef nbytes_r #define in_r %esi movl len_r, %ecx rep movsb movl in(%esp), in_r /* move in back to %esi, toss from */ jmp .L_while_test #undef len_r #undef dist_r #endif /* NO_MMX || RUN_TIME_MMX */ /*** MMX code ***/ #if defined( USE_MMX ) || defined( RUN_TIME_MMX ) .align 32,0x90 .L_init_mmx: emms #undef bits_r #undef bitslong_r #define bitslong_r %ebp #define hold_mm %mm0 movd %ebp, hold_mm movl %ebx, bitslong_r #define used_mm %mm1 #define dmask2_mm %mm2 #define lmask2_mm %mm3 #define lmask_mm %mm4 #define dmask_mm %mm5 #define tmp_mm %mm6 movd lmask(%esp), lmask_mm movq lmask_mm, lmask2_mm movd dmask(%esp), dmask_mm movq dmask_mm, dmask2_mm pxor used_mm, used_mm movl lcode(%esp), %ebx /* ebx = lcode */ jmp .L_do_loop_mmx .align 32,0x90 .L_while_test_mmx: /* while (in < last && out < end) */ cmpl out_r, end(%esp) jbe .L_break_loop /* if (out >= end) */ cmpl in_r, last(%esp) jbe .L_break_loop .L_do_loop_mmx: psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ cmpl $32, bitslong_r ja .L_get_length_code_mmx /* if (32 < bits) */ movd bitslong_r, tmp_mm movd (in_r), %mm7 addl $4, in_r psllq tmp_mm, %mm7 addl $32, bitslong_r por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ .L_get_length_code_mmx: pand hold_mm, lmask_mm movd lmask_mm, %eax movq lmask2_mm, lmask_mm movl (%ebx,%eax,4), %eax /* eax = lcode[hold & lmask] */ .L_dolen_mmx: movzbl %ah, %ecx /* ecx = this.bits */ movd %ecx, used_mm subl %ecx, bitslong_r /* bits -= this.bits */ testb %al, %al jnz .L_test_for_length_base_mmx /* if (op != 0) 45.7% */ shrl $16, %eax /* output this.val char */ stosb jmp .L_while_test_mmx .L_test_for_length_base_mmx: #define len_r %edx movl %eax, len_r /* len = this */ shrl $16, len_r /* len = this.val */ testb $16, %al jz .L_test_for_second_level_length_mmx /* if ((op & 16) == 0) 8% */ andl $15, %eax /* op &= 15 */ jz .L_decode_distance_mmx /* if (!op) */ psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ movd %eax, used_mm movd hold_mm, %ecx subl %eax, bitslong_r andl .L_mask(,%eax,4), %ecx addl %ecx, len_r /* len += hold & mask[op] */ .L_decode_distance_mmx: psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ cmpl $32, bitslong_r ja .L_get_dist_code_mmx /* if (32 < bits) */ movd bitslong_r, tmp_mm movd (in_r), %mm7 addl $4, in_r psllq tmp_mm, %mm7 addl $32, bitslong_r por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ .L_get_dist_code_mmx: movl dcode(%esp), %ebx /* ebx = dcode */ pand hold_mm, dmask_mm movd dmask_mm, %eax movq dmask2_mm, dmask_mm movl (%ebx,%eax,4), %eax /* eax = dcode[hold & lmask] */ .L_dodist_mmx: #define dist_r %ebx movzbl %ah, %ecx /* ecx = this.bits */ movl %eax, dist_r shrl $16, dist_r /* dist = this.val */ subl %ecx, bitslong_r /* bits -= this.bits */ movd %ecx, used_mm testb $16, %al /* if ((op & 16) == 0) */ jz .L_test_for_second_level_dist_mmx andl $15, %eax /* op &= 15 */ jz .L_check_dist_one_mmx .L_add_bits_to_dist_mmx: psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ movd %eax, used_mm /* save bit length of current op */ movd hold_mm, %ecx /* get the next bits on input stream */ subl %eax, bitslong_r /* bits -= op bits */ andl .L_mask(,%eax,4), %ecx /* ecx = hold & mask[op] */ addl %ecx, dist_r /* dist += hold & mask[op] */ .L_check_window_mmx: movl in_r, in(%esp) /* save in so from can use it's reg */ movl out_r, %eax subl beg(%esp), %eax /* nbytes = out - beg */ cmpl dist_r, %eax jb .L_clip_window_mmx /* if (dist > nbytes) 4.2% */ movl len_r, %ecx movl out_r, from_r subl dist_r, from_r /* from = out - dist */ subl $3, %ecx movb (from_r), %al movb %al, (out_r) movb 1(from_r), %al movb 2(from_r), %dl addl $3, from_r movb %al, 1(out_r) movb %dl, 2(out_r) addl $3, out_r rep movsb movl in(%esp), in_r /* move in back to %esi, toss from */ movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ jmp .L_while_test_mmx .align 16,0x90 .L_check_dist_one_mmx: cmpl $1, dist_r jne .L_check_window_mmx cmpl out_r, beg(%esp) je .L_check_window_mmx decl out_r movl len_r, %ecx movb (out_r), %al subl $3, %ecx movb %al, 1(out_r) movb %al, 2(out_r) movb %al, 3(out_r) addl $4, out_r rep stosb movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ jmp .L_while_test_mmx .align 16,0x90 .L_test_for_second_level_length_mmx: testb $64, %al jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ andl $15, %eax psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ movd hold_mm, %ecx andl .L_mask(,%eax,4), %ecx addl len_r, %ecx movl (%ebx,%ecx,4), %eax /* eax = lcode[hold & lmask] */ jmp .L_dolen_mmx .align 16,0x90 .L_test_for_second_level_dist_mmx: testb $64, %al jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ andl $15, %eax psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ movd hold_mm, %ecx andl .L_mask(,%eax,4), %ecx movl dcode(%esp), %eax /* ecx = dcode */ addl dist_r, %ecx movl (%eax,%ecx,4), %eax /* eax = lcode[hold & lmask] */ jmp .L_dodist_mmx .align 16,0x90 .L_clip_window_mmx: #define nbytes_r %ecx movl %eax, nbytes_r movl wsize(%esp), %eax /* prepare for dist compare */ negl nbytes_r /* nbytes = -nbytes */ movl window(%esp), from_r /* from = window */ cmpl dist_r, %eax jb .L_invalid_distance_too_far /* if (dist > wsize) */ addl dist_r, nbytes_r /* nbytes = dist - nbytes */ cmpl $0, write(%esp) jne .L_wrap_around_window_mmx /* if (write != 0) */ subl nbytes_r, %eax addl %eax, from_r /* from += wsize - nbytes */ cmpl nbytes_r, len_r jbe .L_do_copy1_mmx /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1_mmx cmpl nbytes_r, len_r jbe .L_do_copy1_mmx /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1_mmx .L_wrap_around_window_mmx: #define write_r %eax movl write(%esp), write_r cmpl write_r, nbytes_r jbe .L_contiguous_in_window_mmx /* if (write >= nbytes) */ addl wsize(%esp), from_r addl write_r, from_r subl nbytes_r, from_r /* from += wsize + write - nbytes */ subl write_r, nbytes_r /* nbytes -= write */ #undef write_r cmpl nbytes_r, len_r jbe .L_do_copy1_mmx /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl window(%esp), from_r /* from = window */ movl write(%esp), nbytes_r /* nbytes = write */ cmpl nbytes_r, len_r jbe .L_do_copy1_mmx /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ jmp .L_do_copy1_mmx .L_contiguous_in_window_mmx: #define write_r %eax addl write_r, from_r subl nbytes_r, from_r /* from += write - nbytes */ #undef write_r cmpl nbytes_r, len_r jbe .L_do_copy1_mmx /* if (nbytes >= len) */ subl nbytes_r, len_r /* len -= nbytes */ rep movsb movl out_r, from_r subl dist_r, from_r /* from = out - dist */ .L_do_copy1_mmx: #undef nbytes_r #define in_r %esi movl len_r, %ecx rep movsb movl in(%esp), in_r /* move in back to %esi, toss from */ movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ jmp .L_while_test_mmx #undef hold_r #undef bitslong_r #endif /* USE_MMX || RUN_TIME_MMX */ /*** USE_MMX, NO_MMX, and RUNTIME_MMX from here on ***/ .L_invalid_distance_code: /* else { * strm->msg = "invalid distance code"; * state->mode = BAD; * } */ movl $.L_invalid_distance_code_msg, %ecx movl $INFLATE_MODE_BAD, %edx jmp .L_update_stream_state .L_test_for_end_of_block: /* else if (op & 32) { * state->mode = TYPE; * break; * } */ testb $32, %al jz .L_invalid_literal_length_code /* if ((op & 32) == 0) */ movl $0, %ecx movl $INFLATE_MODE_TYPE, %edx jmp .L_update_stream_state .L_invalid_literal_length_code: /* else { * strm->msg = "invalid literal/length code"; * state->mode = BAD; * } */ movl $.L_invalid_literal_length_code_msg, %ecx movl $INFLATE_MODE_BAD, %edx jmp .L_update_stream_state .L_invalid_distance_too_far: /* strm->msg = "invalid distance too far back"; * state->mode = BAD; */ movl in(%esp), in_r /* from_r has in's reg, put in back */ movl $.L_invalid_distance_too_far_msg, %ecx movl $INFLATE_MODE_BAD, %edx jmp .L_update_stream_state .L_update_stream_state: /* set strm->msg = %ecx, strm->state->mode = %edx */ movl strm_sp(%esp), %eax testl %ecx, %ecx /* if (msg != NULL) */ jz .L_skip_msg movl %ecx, msg_strm(%eax) /* strm->msg = msg */ .L_skip_msg: movl state_strm(%eax), %eax /* state = strm->state */ movl %edx, mode_state(%eax) /* state->mode = edx (BAD | TYPE) */ jmp .L_break_loop .align 32,0x90 .L_break_loop: /* * Regs: * * bits = %ebp when mmx, and in %ebx when non-mmx * hold = %hold_mm when mmx, and in %ebp when non-mmx * in = %esi * out = %edi */ #if defined( USE_MMX ) || defined( RUN_TIME_MMX ) #if defined( RUN_TIME_MMX ) cmpl $DO_USE_MMX, inflate_fast_use_mmx jne .L_update_next_in #endif /* RUN_TIME_MMX */ movl %ebp, %ebx .L_update_next_in: #endif #define strm_r %eax #define state_r %edx /* len = bits >> 3; * in -= len; * bits -= len << 3; * hold &= (1U << bits) - 1; * state->hold = hold; * state->bits = bits; * strm->next_in = in; * strm->next_out = out; */ movl strm_sp(%esp), strm_r movl %ebx, %ecx movl state_strm(strm_r), state_r shrl $3, %ecx subl %ecx, in_r shll $3, %ecx subl %ecx, %ebx movl out_r, next_out_strm(strm_r) movl %ebx, bits_state(state_r) movl %ebx, %ecx leal buf(%esp), %ebx cmpl %ebx, last(%esp) jne .L_buf_not_used /* if buf != last */ subl %ebx, in_r /* in -= buf */ movl next_in_strm(strm_r), %ebx movl %ebx, last(%esp) /* last = strm->next_in */ addl %ebx, in_r /* in += strm->next_in */ movl avail_in_strm(strm_r), %ebx subl $11, %ebx addl %ebx, last(%esp) /* last = &strm->next_in[ avail_in - 11 ] */ .L_buf_not_used: movl in_r, next_in_strm(strm_r) movl $1, %ebx shll %cl, %ebx decl %ebx #if defined( USE_MMX ) || defined( RUN_TIME_MMX ) #if defined( RUN_TIME_MMX ) cmpl $DO_USE_MMX, inflate_fast_use_mmx jne .L_update_hold #endif /* RUN_TIME_MMX */ psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ movd hold_mm, %ebp emms .L_update_hold: #endif /* USE_MMX || RUN_TIME_MMX */ andl %ebx, %ebp movl %ebp, hold_state(state_r) #define last_r %ebx /* strm->avail_in = in < last ? 11 + (last - in) : 11 - (in - last) */ movl last(%esp), last_r cmpl in_r, last_r jbe .L_last_is_smaller /* if (in >= last) */ subl in_r, last_r /* last -= in */ addl $11, last_r /* last += 11 */ movl last_r, avail_in_strm(strm_r) jmp .L_fixup_out .L_last_is_smaller: subl last_r, in_r /* in -= last */ negl in_r /* in = -in */ addl $11, in_r /* in += 11 */ movl in_r, avail_in_strm(strm_r) #undef last_r #define end_r %ebx .L_fixup_out: /* strm->avail_out = out < end ? 257 + (end - out) : 257 - (out - end)*/ movl end(%esp), end_r cmpl out_r, end_r jbe .L_end_is_smaller /* if (out >= end) */ subl out_r, end_r /* end -= out */ addl $257, end_r /* end += 257 */ movl end_r, avail_out_strm(strm_r) jmp .L_done .L_end_is_smaller: subl end_r, out_r /* out -= end */ negl out_r /* out = -out */ addl $257, out_r /* out += 257 */ movl out_r, avail_out_strm(strm_r) #undef end_r #undef strm_r #undef state_r .L_done: addl $local_var_size, %esp popf popl %ebx popl %ebp popl %esi popl %edi ret #if defined( GAS_ELF ) /* elf info */ .type inflate_fast,@function .size inflate_fast,.-inflate_fast #endif bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/000077500000000000000000000000001462133141200236155ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/bld_ml64.bat000066400000000000000000000001241462133141200257050ustar00rootroot00000000000000ml64.exe /Flinffasx64 /c /Zi inffasx64.asm ml64.exe /Flgvmat64 /c /Zi gvmat64.asm bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/gvmat64.asm000066400000000000000000000370221462133141200256130ustar00rootroot00000000000000;uInt longest_match_x64( ; deflate_state *s, ; IPos cur_match); /* current match */ ; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64 ; (AMD64 on Athlon 64, Opteron, Phenom ; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) ; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. ; ; File written by Gilles Vollant, by converting to assembly the longest_match ; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. ; ; and by taking inspiration on asm686 with masm, optimised assembly code ; from Brian Raiter, written 1998 ; ; This software is provided 'as-is', without any express or implied ; warranty. In no event will the authors be held liable for any damages ; arising from the use of this software. ; ; Permission is granted to anyone to use this software for any purpose, ; including commercial applications, and to alter it and redistribute it ; freely, subject to the following restrictions: ; ; 1. The origin of this software must not be misrepresented; you must not ; claim that you wrote the original software. If you use this software ; in a product, an acknowledgment in the product documentation would be ; appreciated but is not required. ; 2. Altered source versions must be plainly marked as such, and must not be ; misrepresented as being the original software ; 3. This notice may not be removed or altered from any source distribution. ; ; ; ; http://www.zlib.net ; http://www.winimage.com/zLibDll ; http://www.muppetlabs.com/~breadbox/software/assembly.html ; ; to compile this file for infozip Zip, I use option: ; ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm ; ; to compile this file for zLib, I use option: ; ml64.exe /Flgvmat64 /c /Zi gvmat64.asm ; Be carrefull to adapt zlib1222add below to your version of zLib ; (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change ; value of zlib1222add later) ; ; This file compile with Microsoft Macro Assembler (x64) for AMD64 ; ; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK ; ; (you can get Windows WDK with ml64 for AMD64 from ; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) ; ;uInt longest_match(s, cur_match) ; deflate_state *s; ; IPos cur_match; /* current match */ .code longest_match PROC ;LocalVarsSize equ 88 LocalVarsSize equ 72 ; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 ; free register : r14,r15 ; register can be saved : rsp chainlenwmask equ rsp + 8 - LocalVarsSize ; high word: current chain len ; low word: s->wmask ;window equ rsp + xx - LocalVarsSize ; local copy of s->window ; stored in r10 ;windowbestlen equ rsp + xx - LocalVarsSize ; s->window + bestlen , use r10+r11 ;scanstart equ rsp + xx - LocalVarsSize ; first two bytes of string ; stored in r12w ;scanend equ rsp + xx - LocalVarsSize ; last two bytes of string use ebx ;scanalign equ rsp + xx - LocalVarsSize ; dword-misalignment of string r13 ;bestlen equ rsp + xx - LocalVarsSize ; size of best match so far -> r11d ;scan equ rsp + xx - LocalVarsSize ; ptr to string wanting match -> r9 IFDEF INFOZIP ELSE nicematch equ (rsp + 16 - LocalVarsSize) ; a good enough match size ENDIF save_rdi equ rsp + 24 - LocalVarsSize save_rsi equ rsp + 32 - LocalVarsSize save_rbx equ rsp + 40 - LocalVarsSize save_rbp equ rsp + 48 - LocalVarsSize save_r12 equ rsp + 56 - LocalVarsSize save_r13 equ rsp + 64 - LocalVarsSize ;save_r14 equ rsp + 72 - LocalVarsSize ;save_r15 equ rsp + 80 - LocalVarsSize ; summary of register usage ; scanend ebx ; scanendw bx ; chainlenwmask edx ; curmatch rsi ; curmatchd esi ; windowbestlen r8 ; scanalign r9 ; scanalignd r9d ; window r10 ; bestlen r11 ; bestlend r11d ; scanstart r12d ; scanstartw r12w ; scan r13 ; nicematch r14d ; limit r15 ; limitd r15d ; prev rcx ; all the +4 offsets are due to the addition of pending_buf_size (in zlib ; in the deflate_state structure since the asm code was first written ; (if you compile with zlib 1.0.4 or older, remove the +4). ; Note : these value are good with a 8 bytes boundary pack structure MAX_MATCH equ 258 MIN_MATCH equ 3 MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) ;;; Offsets for fields in the deflate_state structure. These numbers ;;; are calculated from the definition of deflate_state, with the ;;; assumption that the compiler will dword-align the fields. (Thus, ;;; changing the definition of deflate_state could easily cause this ;;; program to crash horribly, without so much as a warning at ;;; compile time. Sigh.) ; all the +zlib1222add offsets are due to the addition of fields ; in zlib in the deflate_state structure since the asm code was first written ; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). ; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). ; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). IFDEF INFOZIP _DATA SEGMENT COMM window_size:DWORD ; WMask ; 7fff COMM window:BYTE:010040H COMM prev:WORD:08000H ; MatchLen : unused ; PrevMatch : unused COMM strstart:DWORD COMM match_start:DWORD ; Lookahead : ignore COMM prev_length:DWORD ; PrevLen COMM max_chain_length:DWORD COMM good_match:DWORD COMM nice_match:DWORD prev_ad equ OFFSET prev window_ad equ OFFSET window nicematch equ nice_match _DATA ENDS WMask equ 07fffh ELSE IFNDEF zlib1222add zlib1222add equ 8 ENDIF dsWSize equ 56+zlib1222add+(zlib1222add/2) dsWMask equ 64+zlib1222add+(zlib1222add/2) dsWindow equ 72+zlib1222add dsPrev equ 88+zlib1222add dsMatchLen equ 128+zlib1222add dsPrevMatch equ 132+zlib1222add dsStrStart equ 140+zlib1222add dsMatchStart equ 144+zlib1222add dsLookahead equ 148+zlib1222add dsPrevLen equ 152+zlib1222add dsMaxChainLen equ 156+zlib1222add dsGoodMatch equ 172+zlib1222add dsNiceMatch equ 176+zlib1222add window_size equ [ rcx + dsWSize] WMask equ [ rcx + dsWMask] window_ad equ [ rcx + dsWindow] prev_ad equ [ rcx + dsPrev] strstart equ [ rcx + dsStrStart] match_start equ [ rcx + dsMatchStart] Lookahead equ [ rcx + dsLookahead] ; 0ffffffffh on infozip prev_length equ [ rcx + dsPrevLen] max_chain_length equ [ rcx + dsMaxChainLen] good_match equ [ rcx + dsGoodMatch] nice_match equ [ rcx + dsNiceMatch] ENDIF ; parameter 1 in r8(deflate state s), param 2 in rdx (cur match) ; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and ; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp ; ; All registers must be preserved across the call, except for ; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. ;;; Save registers that the compiler may be using, and adjust esp to ;;; make room for our stack frame. ;;; Retrieve the function arguments. r8d will hold cur_match ;;; throughout the entire function. edx will hold the pointer to the ;;; deflate_state structure during the function's setup (before ;;; entering the main loop. ; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) ; this clear high 32 bits of r8, which can be garbage in both r8 and rdx mov [save_rdi],rdi mov [save_rsi],rsi mov [save_rbx],rbx mov [save_rbp],rbp IFDEF INFOZIP mov r8d,ecx ELSE mov r8d,edx ENDIF mov [save_r12],r12 mov [save_r13],r13 ; mov [save_r14],r14 ; mov [save_r15],r15 ;;; uInt wmask = s->w_mask; ;;; unsigned chain_length = s->max_chain_length; ;;; if (s->prev_length >= s->good_match) { ;;; chain_length >>= 2; ;;; } mov edi, prev_length mov esi, good_match mov eax, WMask mov ebx, max_chain_length cmp edi, esi jl LastMatchGood shr ebx, 2 LastMatchGood: ;;; chainlen is decremented once beforehand so that the function can ;;; use the sign flag instead of the zero flag for the exit test. ;;; It is then shifted into the high word, to make room for the wmask ;;; value, which it will always accompany. dec ebx shl ebx, 16 or ebx, eax ;;; on zlib only ;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; IFDEF INFOZIP mov [chainlenwmask], ebx ; on infozip nice_match = [nice_match] ELSE mov eax, nice_match mov [chainlenwmask], ebx mov r10d, Lookahead cmp r10d, eax cmovnl r10d, eax mov [nicematch],r10d ENDIF ;;; register Bytef *scan = s->window + s->strstart; mov r10, window_ad mov ebp, strstart lea r13, [r10 + rbp] ;;; Determine how many bytes the scan ptr is off from being ;;; dword-aligned. mov r9,r13 neg r13 and r13,3 ;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? ;;; s->strstart - (IPos)MAX_DIST(s) : NIL; IFDEF INFOZIP mov eax,07efah ; MAX_DIST = (WSIZE-MIN_LOOKAHEAD) (0x8000-(3+8+1)) ELSE mov eax, window_size sub eax, MIN_LOOKAHEAD ENDIF xor edi,edi sub ebp, eax mov r11d, prev_length cmovng ebp,edi ;;; int best_len = s->prev_length; ;;; Store the sum of s->window + best_len in esi locally, and in esi. lea rsi,[r10+r11] ;;; register ush scan_start = *(ushf*)scan; ;;; register ush scan_end = *(ushf*)(scan+best_len-1); ;;; Posf *prev = s->prev; movzx r12d,word ptr [r9] movzx ebx, word ptr [r9 + r11 - 1] mov rdi, prev_ad ;;; Jump into the main loop. mov edx, [chainlenwmask] cmp bx,word ptr [rsi + r8 - 1] jz LookupLoopIsZero LookupLoop1: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp jbe LeaveNow sub edx, 00010000h js LeaveNow LoopEntry1: cmp bx,word ptr [rsi + r8 - 1] jz LookupLoopIsZero LookupLoop2: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp jbe LeaveNow sub edx, 00010000h js LeaveNow LoopEntry2: cmp bx,word ptr [rsi + r8 - 1] jz LookupLoopIsZero LookupLoop4: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp jbe LeaveNow sub edx, 00010000h js LeaveNow LoopEntry4: cmp bx,word ptr [rsi + r8 - 1] jnz LookupLoop1 jmp LookupLoopIsZero ;;; do { ;;; match = s->window + cur_match; ;;; if (*(ushf*)(match+best_len-1) != scan_end || ;;; *(ushf*)match != scan_start) continue; ;;; [...] ;;; } while ((cur_match = prev[cur_match & wmask]) > limit ;;; && --chain_length != 0); ;;; ;;; Here is the inner loop of the function. The function will spend the ;;; majority of its time in this loop, and majority of that time will ;;; be spent in the first ten instructions. ;;; ;;; Within this loop: ;;; ebx = scanend ;;; r8d = curmatch ;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) ;;; esi = windowbestlen - i.e., (window + bestlen) ;;; edi = prev ;;; ebp = limit LookupLoop: and r8d, edx movzx r8d, word ptr [rdi + r8*2] cmp r8d, ebp jbe LeaveNow sub edx, 00010000h js LeaveNow LoopEntry: cmp bx,word ptr [rsi + r8 - 1] jnz LookupLoop1 LookupLoopIsZero: cmp r12w, word ptr [r10 + r8] jnz LookupLoop1 ;;; Store the current value of chainlen. mov [chainlenwmask], edx ;;; Point edi to the string under scrutiny, and esi to the string we ;;; are hoping to match it up with. In actuality, esi and edi are ;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is ;;; initialized to -(MAX_MATCH_8 - scanalign). lea rsi,[r8+r10] mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8) lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8] lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8] prefetcht1 [rsi+rdx] prefetcht1 [rdi+rdx] ;;; Test the strings for equality, 8 bytes at a time. At the end, ;;; adjust rdx so that it is offset to the exact byte that mismatched. ;;; ;;; We already know at this point that the first three bytes of the ;;; strings match each other, and they can be safely passed over before ;;; starting the compare loop. So what this code does is skip over 0-3 ;;; bytes, as much as necessary in order to dword-align the edi ;;; pointer. (rsi will still be misaligned three times out of four.) ;;; ;;; It should be confessed that this loop usually does not represent ;;; much of the total running time. Replacing it with a more ;;; straightforward "rep cmpsb" would not drastically degrade ;;; performance. LoopCmps: mov rax, [rsi + rdx] xor rax, [rdi + rdx] jnz LeaveLoopCmps mov rax, [rsi + rdx + 8] xor rax, [rdi + rdx + 8] jnz LeaveLoopCmps8 mov rax, [rsi + rdx + 8+8] xor rax, [rdi + rdx + 8+8] jnz LeaveLoopCmps16 add rdx,8+8+8 jnz short LoopCmps jmp short LenMaximum LeaveLoopCmps16: add rdx,8 LeaveLoopCmps8: add rdx,8 LeaveLoopCmps: test eax, 0000FFFFh jnz LenLower test eax,0ffffffffh jnz LenLower32 add rdx,4 shr rax,32 or ax,ax jnz LenLower LenLower32: shr eax,16 add rdx,2 LenLower: sub al, 1 adc rdx, 0 ;;; Calculate the length of the match. If it is longer than MAX_MATCH, ;;; then automatically accept it as the best possible match and leave. lea rax, [rdi + rdx] sub rax, r9 cmp eax, MAX_MATCH jge LenMaximum ;;; If the length of the match is not longer than the best match we ;;; have so far, then forget it and return to the lookup loop. ;/////////////////////////////////// cmp eax, r11d jg LongerMatch lea rsi,[r10+r11] mov rdi, prev_ad mov edx, [chainlenwmask] jmp LookupLoop ;;; s->match_start = cur_match; ;;; best_len = len; ;;; if (len >= nice_match) break; ;;; scan_end = *(ushf*)(scan+best_len-1); LongerMatch: mov r11d, eax mov match_start, r8d cmp eax, [nicematch] jge LeaveNow lea rsi,[r10+rax] movzx ebx, word ptr [r9 + rax - 1] mov rdi, prev_ad mov edx, [chainlenwmask] jmp LookupLoop ;;; Accept the current string, with the maximum possible length. LenMaximum: mov r11d,MAX_MATCH mov match_start, r8d ;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; ;;; return s->lookahead; LeaveNow: IFDEF INFOZIP mov eax,r11d ELSE mov eax, Lookahead cmp r11d, eax cmovng eax, r11d ENDIF ;;; Restore the stack and return from whence we came. mov rsi,[save_rsi] mov rdi,[save_rdi] mov rbx,[save_rbx] mov rbp,[save_rbp] mov r12,[save_r12] mov r13,[save_r13] ; mov r14,[save_r14] ; mov r15,[save_r15] ret 0 ; please don't remove this string ! ; Your can freely use gvmat64 in any free or commercial app ; but it is far better don't remove the string in the binary! db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 longest_match ENDP match_init PROC ret 0 match_init ENDP END bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/inffas8664.c000066400000000000000000000163371462133141200255710ustar00rootroot00000000000000/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding * version for AMD64 on Windows using Microsoft C compiler * * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Copyright (C) 2003 Chris Anderson * Please use the copyright conditions above. * * 2005 - Adaptation to Microsoft C Compiler for AMD64 by Gilles Vollant * * inffas8664.c call function inffas8664fnc in inffasx64.asm * inffasx64.asm is automatically convert from AMD64 portion of inffas86.c * * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also * slightly quicker on x86 systems because, instead of using rep movsb to copy * data, it uses rep movsw, which moves data in 2-byte chunks instead of single * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates * from http://fedora.linux.duke.edu/fc1_x86_64 * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, * when decompressing mozilla-source-1.3.tar.gz. * * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at * the moment. I have successfully compiled and tested this code with gcc2.96, * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX * enabled. I will attempt to merge the MMX code into this version. Newer * versions of this and inffast.S can be found at * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ * */ #include #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* Mark Adler's comments from inffast.c: */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state->mode == LEN strm->avail_in >= 6 strm->avail_out >= 258 start >= strm->avail_out state->bits < 8 On return, state->mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ typedef struct inffast_ar { /* 64 32 x86 x86_64 */ /* ar offset register */ /* 0 0 */ void *esp; /* esp save */ /* 8 4 */ void *ebp; /* ebp save */ /* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ /* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ /* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ /* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ /* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ /* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ /* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ /* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ /* 80 40 */ size_t /*unsigned long */hold; /* edx rdx local strm->hold */ /* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ /* 92 48 */ unsigned wsize; /* window size */ /* 96 52 */ unsigned write; /* window write index */ /*100 56 */ unsigned lmask; /* r12 mask for lcode */ /*104 60 */ unsigned dmask; /* r13 mask for dcode */ /*108 64 */ unsigned len; /* r14 match length */ /*112 68 */ unsigned dist; /* r15 match distance */ /*116 72 */ unsigned status; /* set when state chng*/ } type_ar; #ifdef ASMINF void inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { struct inflate_state FAR *state; type_ar ar; void inffas8664fnc(struct inffast_ar * par); #if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) #define PAD_AVAIL_IN 6 #define PAD_AVAIL_OUT 258 #else #define PAD_AVAIL_IN 5 #define PAD_AVAIL_OUT 257 #endif /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; ar.in = strm->next_in; ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); ar.out = strm->next_out; ar.beg = ar.out - (start - strm->avail_out); ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); ar.wsize = state->wsize; ar.write = state->wnext; ar.window = state->window; ar.hold = state->hold; ar.bits = state->bits; ar.lcode = state->lencode; ar.dcode = state->distcode; ar.lmask = (1U << state->lenbits) - 1; ar.dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ /* align in on 1/2 hold size boundary */ while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { ar.hold += (unsigned long)*ar.in++ << ar.bits; ar.bits += 8; } inffas8664fnc(&ar); if (ar.status > 1) { if (ar.status == 2) strm->msg = "invalid literal/length code"; else if (ar.status == 3) strm->msg = "invalid distance code"; else strm->msg = "invalid distance too far back"; state->mode = BAD; } else if ( ar.status == 1 ) { state->mode = TYPE; } /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ ar.len = ar.bits >> 3; ar.in -= ar.len; ar.bits -= ar.len << 3; ar.hold &= (1U << ar.bits) - 1; /* update state and return */ strm->next_in = ar.in; strm->next_out = ar.out; strm->avail_in = (unsigned)(ar.in < ar.last ? PAD_AVAIL_IN + (ar.last - ar.in) : PAD_AVAIL_IN - (ar.in - ar.last)); strm->avail_out = (unsigned)(ar.out < ar.end ? PAD_AVAIL_OUT + (ar.end - ar.out) : PAD_AVAIL_OUT - (ar.out - ar.end)); state->hold = (unsigned long)ar.hold; state->bits = ar.bits; return; } #endif bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/inffasx64.asm000066400000000000000000000237131462133141200261350ustar00rootroot00000000000000; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding ; version for AMD64 on Windows using Microsoft C compiler ; ; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c ; inffasx64.asm is called by inffas8664.c, which contain more info. ; to compile this file, I use option ; ml64.exe /Flinffasx64 /c /Zi inffasx64.asm ; with Microsoft Macro Assembler (x64) for AMD64 ; ; This file compile with Microsoft Macro Assembler (x64) for AMD64 ; ; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK ; ; (you can get Windows WDK with ml64 for AMD64 from ; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) ; .code inffas8664fnc PROC ; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and ; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp ; ; All registers must be preserved across the call, except for ; rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch. mov [rsp-8],rsi mov [rsp-16],rdi mov [rsp-24],r12 mov [rsp-32],r13 mov [rsp-40],r14 mov [rsp-48],r15 mov [rsp-56],rbx mov rax,rcx mov [rax+8], rbp ; /* save regs rbp and rsp */ mov [rax], rsp mov rsp, rax ; /* make rsp point to &ar */ mov rsi, [rsp+16] ; /* rsi = in */ mov rdi, [rsp+32] ; /* rdi = out */ mov r9, [rsp+24] ; /* r9 = last */ mov r10, [rsp+48] ; /* r10 = end */ mov rbp, [rsp+64] ; /* rbp = lcode */ mov r11, [rsp+72] ; /* r11 = dcode */ mov rdx, [rsp+80] ; /* rdx = hold */ mov ebx, [rsp+88] ; /* ebx = bits */ mov r12d, [rsp+100] ; /* r12d = lmask */ mov r13d, [rsp+104] ; /* r13d = dmask */ ; /* r14d = len */ ; /* r15d = dist */ cld cmp r10, rdi je L_one_time ; /* if only one decode left */ cmp r9, rsi jne L_do_loop L_one_time: mov r8, r12 ; /* r8 = lmask */ cmp bl, 32 ja L_get_length_code_one_time lodsd ; /* eax = *(uint *)in++ */ mov cl, bl ; /* cl = bits, needs it for shifting */ add bl, 32 ; /* bits += 32 */ shl rax, cl or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ jmp L_get_length_code_one_time ALIGN 4 L_while_test: cmp r10, rdi jbe L_break_loop cmp r9, rsi jbe L_break_loop L_do_loop: mov r8, r12 ; /* r8 = lmask */ cmp bl, 32 ja L_get_length_code ; /* if (32 < bits) */ lodsd ; /* eax = *(uint *)in++ */ mov cl, bl ; /* cl = bits, needs it for shifting */ add bl, 32 ; /* bits += 32 */ shl rax, cl or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ L_get_length_code: and r8, rdx ; /* r8 &= hold */ mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ mov cl, ah ; /* cl = this.bits */ sub bl, ah ; /* bits -= this.bits */ shr rdx, cl ; /* hold >>= this.bits */ test al, al jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ mov r8, r12 ; /* r8 = lmask */ shr eax, 16 ; /* output this.val char */ stosb L_get_length_code_one_time: and r8, rdx ; /* r8 &= hold */ mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ L_dolen: mov cl, ah ; /* cl = this.bits */ sub bl, ah ; /* bits -= this.bits */ shr rdx, cl ; /* hold >>= this.bits */ test al, al jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ shr eax, 16 ; /* output this.val char */ stosb jmp L_while_test ALIGN 4 L_test_for_length_base: mov r14d, eax ; /* len = this */ shr r14d, 16 ; /* len = this.val */ mov cl, al test al, 16 jz L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */ and cl, 15 ; /* op &= 15 */ jz L_decode_distance ; /* if (!op) */ L_add_bits_to_len: sub bl, cl xor eax, eax inc eax shl eax, cl dec eax and eax, edx ; /* eax &= hold */ shr rdx, cl add r14d, eax ; /* len += hold & mask[op] */ L_decode_distance: mov r8, r13 ; /* r8 = dmask */ cmp bl, 32 ja L_get_distance_code ; /* if (32 < bits) */ lodsd ; /* eax = *(uint *)in++ */ mov cl, bl ; /* cl = bits, needs it for shifting */ add bl, 32 ; /* bits += 32 */ shl rax, cl or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ L_get_distance_code: and r8, rdx ; /* r8 &= hold */ mov eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */ L_dodist: mov r15d, eax ; /* dist = this */ shr r15d, 16 ; /* dist = this.val */ mov cl, ah sub bl, ah ; /* bits -= this.bits */ shr rdx, cl ; /* hold >>= this.bits */ mov cl, al ; /* cl = this.op */ test al, 16 ; /* if ((op & 16) == 0) */ jz L_test_for_second_level_dist and cl, 15 ; /* op &= 15 */ jz L_check_dist_one L_add_bits_to_dist: sub bl, cl xor eax, eax inc eax shl eax, cl dec eax ; /* (1 << op) - 1 */ and eax, edx ; /* eax &= hold */ shr rdx, cl add r15d, eax ; /* dist += hold & ((1 << op) - 1) */ L_check_window: mov r8, rsi ; /* save in so from can use it's reg */ mov rax, rdi sub rax, [rsp+40] ; /* nbytes = out - beg */ cmp eax, r15d jb L_clip_window ; /* if (dist > nbytes) 4.2% */ mov ecx, r14d ; /* ecx = len */ mov rsi, rdi sub rsi, r15 ; /* from = out - dist */ sar ecx, 1 jnc L_copy_two ; /* if len % 2 == 0 */ rep movsw mov al, [rsi] mov [rdi], al inc rdi mov rsi, r8 ; /* move in back to %rsi, toss from */ jmp L_while_test L_copy_two: rep movsw mov rsi, r8 ; /* move in back to %rsi, toss from */ jmp L_while_test ALIGN 4 L_check_dist_one: cmp r15d, 1 ; /* if dist 1, is a memset */ jne L_check_window cmp [rsp+40], rdi ; /* if out == beg, outside window */ je L_check_window mov ecx, r14d ; /* ecx = len */ mov al, [rdi-1] mov ah, al sar ecx, 1 jnc L_set_two mov [rdi], al inc rdi L_set_two: rep stosw jmp L_while_test ALIGN 4 L_test_for_second_level_length: test al, 64 jnz L_test_for_end_of_block ; /* if ((op & 64) != 0) */ xor eax, eax inc eax shl eax, cl dec eax and eax, edx ; /* eax &= hold */ add eax, r14d ; /* eax += len */ mov eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/ jmp L_dolen ALIGN 4 L_test_for_second_level_dist: test al, 64 jnz L_invalid_distance_code ; /* if ((op & 64) != 0) */ xor eax, eax inc eax shl eax, cl dec eax and eax, edx ; /* eax &= hold */ add eax, r15d ; /* eax += dist */ mov eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/ jmp L_dodist ALIGN 4 L_clip_window: mov ecx, eax ; /* ecx = nbytes */ mov eax, [rsp+92] ; /* eax = wsize, prepare for dist cmp */ neg ecx ; /* nbytes = -nbytes */ cmp eax, r15d jb L_invalid_distance_too_far ; /* if (dist > wsize) */ add ecx, r15d ; /* nbytes = dist - nbytes */ cmp dword ptr [rsp+96], 0 jne L_wrap_around_window ; /* if (write != 0) */ mov rsi, [rsp+56] ; /* from = window */ sub eax, ecx ; /* eax -= nbytes */ add rsi, rax ; /* from += wsize - nbytes */ mov eax, r14d ; /* eax = len */ cmp r14d, ecx jbe L_do_copy ; /* if (nbytes >= len) */ sub eax, ecx ; /* eax -= nbytes */ rep movsb mov rsi, rdi sub rsi, r15 ; /* from = &out[ -dist ] */ jmp L_do_copy ALIGN 4 L_wrap_around_window: mov eax, [rsp+96] ; /* eax = write */ cmp ecx, eax jbe L_contiguous_in_window ; /* if (write >= nbytes) */ mov esi, [rsp+92] ; /* from = wsize */ add rsi, [rsp+56] ; /* from += window */ add rsi, rax ; /* from += write */ sub rsi, rcx ; /* from -= nbytes */ sub ecx, eax ; /* nbytes -= write */ mov eax, r14d ; /* eax = len */ cmp eax, ecx jbe L_do_copy ; /* if (nbytes >= len) */ sub eax, ecx ; /* len -= nbytes */ rep movsb mov rsi, [rsp+56] ; /* from = window */ mov ecx, [rsp+96] ; /* nbytes = write */ cmp eax, ecx jbe L_do_copy ; /* if (nbytes >= len) */ sub eax, ecx ; /* len -= nbytes */ rep movsb mov rsi, rdi sub rsi, r15 ; /* from = out - dist */ jmp L_do_copy ALIGN 4 L_contiguous_in_window: mov rsi, [rsp+56] ; /* rsi = window */ add rsi, rax sub rsi, rcx ; /* from += write - nbytes */ mov eax, r14d ; /* eax = len */ cmp eax, ecx jbe L_do_copy ; /* if (nbytes >= len) */ sub eax, ecx ; /* len -= nbytes */ rep movsb mov rsi, rdi sub rsi, r15 ; /* from = out - dist */ jmp L_do_copy ; /* if (nbytes >= len) */ ALIGN 4 L_do_copy: mov ecx, eax ; /* ecx = len */ rep movsb mov rsi, r8 ; /* move in back to %esi, toss from */ jmp L_while_test L_test_for_end_of_block: test al, 32 jz L_invalid_literal_length_code mov dword ptr [rsp+116], 1 jmp L_break_loop_with_status L_invalid_literal_length_code: mov dword ptr [rsp+116], 2 jmp L_break_loop_with_status L_invalid_distance_code: mov dword ptr [rsp+116], 3 jmp L_break_loop_with_status L_invalid_distance_too_far: mov dword ptr [rsp+116], 4 jmp L_break_loop_with_status L_break_loop: mov dword ptr [rsp+116], 0 L_break_loop_with_status: ; /* put in, out, bits, and hold back into ar and pop esp */ mov [rsp+16], rsi ; /* in */ mov [rsp+32], rdi ; /* out */ mov [rsp+88], ebx ; /* bits */ mov [rsp+80], rdx ; /* hold */ mov rax, [rsp] ; /* restore rbp and rsp */ mov rbp, [rsp+8] mov rsp, rax mov rsi,[rsp-8] mov rdi,[rsp-16] mov r12,[rsp-24] mov r13,[rsp-32] mov r14,[rsp-40] mov r15,[rsp-48] mov rbx,[rsp-56] ret 0 ; : ; : "m" (ar) ; : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", ; "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" ; ); inffas8664fnc ENDP ;_TEXT ENDS END bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx64/readme.txt000066400000000000000000000022661462133141200256210ustar00rootroot00000000000000Summary ------- This directory contains ASM implementations of the functions longest_match() and inflate_fast(), for 64 bits x86 (both AMD64 and Intel EM64t), for use with Microsoft Macro Assembler (x64) for AMD64 and Microsoft C++ 64 bits. gvmat64.asm is written by Gilles Vollant (2005), by using Brian Raiter 686/32 bits assembly optimized version from Jean-loup Gailly original longest_match function inffasx64.asm and inffas8664.c were written by Chris Anderson, by optimizing original function from Mark Adler Use instructions ---------------- Assemble the .asm files using MASM and put the object files into the zlib source directory. You can also get object files here: http://www.winimage.com/zLibDll/zlib124_masm_obj.zip define ASMV and ASMINF in your project. Include inffas8664.c in your source tree, and inffasx64.obj and gvmat64.obj as object to link. Build instructions ------------------ run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe) ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK You can get Windows 2003 server DDK with ml64 and cl for AMD64 from http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx86/000077500000000000000000000000001462133141200236215ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx86/bld_ml32.bat000066400000000000000000000001321462133141200257030ustar00rootroot00000000000000ml /coff /Zi /c /Flmatch686.lst match686.asm ml /coff /Zi /c /Flinffas32.lst inffas32.asm bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx86/inffas32.asm000066400000000000000000000357451462133141200257540ustar00rootroot00000000000000;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding ; * ; * inffas32.asm is derivated from inffas86.c, with translation of assembly code ; * ; * Copyright (C) 1995-2003 Mark Adler ; * For conditions of distribution and use, see copyright notice in zlib.h ; * ; * Copyright (C) 2003 Chris Anderson ; * Please use the copyright conditions above. ; * ; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from ; * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at ; * the moment. I have successfully compiled and tested this code with gcc2.96, ; * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S ; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX ; * enabled. I will attempt to merge the MMX code into this version. Newer ; * versions of this and inffast.S can be found at ; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ ; * ; * 2005 : modification by Gilles Vollant ; */ ; For Visual C++ 4.x and higher and ML 6.x and higher ; ml.exe is in directory \MASM611C of Win95 DDK ; ml.exe is also distributed in http://www.masm32.com/masmdl.htm ; and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/ ; ; ; compile with command line option ; ml /coff /Zi /c /Flinffas32.lst inffas32.asm ; if you define NO_GZIP (see inflate.h), compile with ; ml /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm ; zlib122sup is 0 fort zlib 1.2.2.1 and lower ; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head ; in inflate_state in inflate.h) zlib1222sup equ 8 IFDEF GUNZIP INFLATE_MODE_TYPE equ 11 INFLATE_MODE_BAD equ 26 ELSE IFNDEF NO_GUNZIP INFLATE_MODE_TYPE equ 11 INFLATE_MODE_BAD equ 26 ELSE INFLATE_MODE_TYPE equ 3 INFLATE_MODE_BAD equ 17 ENDIF ENDIF ; 75 "inffast.S" ;FILE "inffast.S" ;;;GLOBAL _inflate_fast ;;;SECTION .text .586p .mmx name inflate_fast_x86 .MODEL FLAT _DATA segment inflate_fast_use_mmx: dd 1 _TEXT segment PUBLIC _inflate_fast ALIGN 4 _inflate_fast: jmp inflate_fast_entry ALIGN 4 db 'Fast decoding Code from Chris Anderson' db 0 ALIGN 4 invalid_literal_length_code_msg: db 'invalid literal/length code' db 0 ALIGN 4 invalid_distance_code_msg: db 'invalid distance code' db 0 ALIGN 4 invalid_distance_too_far_msg: db 'invalid distance too far back' db 0 ALIGN 4 inflate_fast_mask: dd 0 dd 1 dd 3 dd 7 dd 15 dd 31 dd 63 dd 127 dd 255 dd 511 dd 1023 dd 2047 dd 4095 dd 8191 dd 16383 dd 32767 dd 65535 dd 131071 dd 262143 dd 524287 dd 1048575 dd 2097151 dd 4194303 dd 8388607 dd 16777215 dd 33554431 dd 67108863 dd 134217727 dd 268435455 dd 536870911 dd 1073741823 dd 2147483647 dd 4294967295 mode_state equ 0 ;/* state->mode */ wsize_state equ (32+zlib1222sup) ;/* state->wsize */ write_state equ (36+4+zlib1222sup) ;/* state->write */ window_state equ (40+4+zlib1222sup) ;/* state->window */ hold_state equ (44+4+zlib1222sup) ;/* state->hold */ bits_state equ (48+4+zlib1222sup) ;/* state->bits */ lencode_state equ (64+4+zlib1222sup) ;/* state->lencode */ distcode_state equ (68+4+zlib1222sup) ;/* state->distcode */ lenbits_state equ (72+4+zlib1222sup) ;/* state->lenbits */ distbits_state equ (76+4+zlib1222sup) ;/* state->distbits */ ;;SECTION .text ; 205 "inffast.S" ;GLOBAL inflate_fast_use_mmx ;SECTION .data ; GLOBAL inflate_fast_use_mmx:object ;.size inflate_fast_use_mmx, 4 ; 226 "inffast.S" ;SECTION .text ALIGN 4 inflate_fast_entry: push edi push esi push ebp push ebx pushfd sub esp,64 cld mov esi, [esp+88] mov edi, [esi+28] mov edx, [esi+4] mov eax, [esi+0] add edx,eax sub edx,11 mov [esp+44],eax mov [esp+20],edx mov ebp, [esp+92] mov ecx, [esi+16] mov ebx, [esi+12] sub ebp,ecx neg ebp add ebp,ebx sub ecx,257 add ecx,ebx mov [esp+60],ebx mov [esp+40],ebp mov [esp+16],ecx ; 285 "inffast.S" mov eax, [edi+lencode_state] mov ecx, [edi+distcode_state] mov [esp+8],eax mov [esp+12],ecx mov eax,1 mov ecx, [edi+lenbits_state] shl eax,cl dec eax mov [esp+0],eax mov eax,1 mov ecx, [edi+distbits_state] shl eax,cl dec eax mov [esp+4],eax mov eax, [edi+wsize_state] mov ecx, [edi+write_state] mov edx, [edi+window_state] mov [esp+52],eax mov [esp+48],ecx mov [esp+56],edx mov ebp, [edi+hold_state] mov ebx, [edi+bits_state] ; 321 "inffast.S" mov esi, [esp+44] mov ecx, [esp+20] cmp ecx,esi ja L_align_long add ecx,11 sub ecx,esi mov eax,12 sub eax,ecx lea edi, [esp+28] rep movsb mov ecx,eax xor eax,eax rep stosb lea esi, [esp+28] mov [esp+20],esi jmp L_is_aligned L_align_long: test esi,3 jz L_is_aligned xor eax,eax mov al, [esi] inc esi mov ecx,ebx add ebx,8 shl eax,cl or ebp,eax jmp L_align_long L_is_aligned: mov edi, [esp+60] ; 366 "inffast.S" L_check_mmx: cmp dword ptr [inflate_fast_use_mmx],2 je L_init_mmx ja L_do_loop push eax push ebx push ecx push edx pushfd mov eax, [esp] xor dword ptr [esp],0200000h popfd pushfd pop edx xor edx,eax jz L_dont_use_mmx xor eax,eax cpuid cmp ebx,0756e6547h jne L_dont_use_mmx cmp ecx,06c65746eh jne L_dont_use_mmx cmp edx,049656e69h jne L_dont_use_mmx mov eax,1 cpuid shr eax,8 and eax,15 cmp eax,6 jne L_dont_use_mmx test edx,0800000h jnz L_use_mmx jmp L_dont_use_mmx L_use_mmx: mov dword ptr [inflate_fast_use_mmx],2 jmp L_check_mmx_pop L_dont_use_mmx: mov dword ptr [inflate_fast_use_mmx],3 L_check_mmx_pop: pop edx pop ecx pop ebx pop eax jmp L_check_mmx ; 426 "inffast.S" ALIGN 4 L_do_loop: ; 437 "inffast.S" cmp bl,15 ja L_get_length_code xor eax,eax lodsw mov cl,bl add bl,16 shl eax,cl or ebp,eax L_get_length_code: mov edx, [esp+0] mov ecx, [esp+8] and edx,ebp mov eax, [ecx+edx*4] L_dolen: mov cl,ah sub bl,ah shr ebp,cl test al,al jnz L_test_for_length_base shr eax,16 stosb L_while_test: cmp [esp+16],edi jbe L_break_loop cmp [esp+20],esi ja L_do_loop jmp L_break_loop L_test_for_length_base: ; 502 "inffast.S" mov edx,eax shr edx,16 mov cl,al test al,16 jz L_test_for_second_level_length and cl,15 jz L_save_len cmp bl,cl jae L_add_bits_to_len mov ch,cl xor eax,eax lodsw mov cl,bl add bl,16 shl eax,cl or ebp,eax mov cl,ch L_add_bits_to_len: mov eax,1 shl eax,cl dec eax sub bl,cl and eax,ebp shr ebp,cl add edx,eax L_save_len: mov [esp+24],edx L_decode_distance: ; 549 "inffast.S" cmp bl,15 ja L_get_distance_code xor eax,eax lodsw mov cl,bl add bl,16 shl eax,cl or ebp,eax L_get_distance_code: mov edx, [esp+4] mov ecx, [esp+12] and edx,ebp mov eax, [ecx+edx*4] L_dodist: mov edx,eax shr edx,16 mov cl,ah sub bl,ah shr ebp,cl ; 584 "inffast.S" mov cl,al test al,16 jz L_test_for_second_level_dist and cl,15 jz L_check_dist_one cmp bl,cl jae L_add_bits_to_dist mov ch,cl xor eax,eax lodsw mov cl,bl add bl,16 shl eax,cl or ebp,eax mov cl,ch L_add_bits_to_dist: mov eax,1 shl eax,cl dec eax sub bl,cl and eax,ebp shr ebp,cl add edx,eax jmp L_check_window L_check_window: ; 625 "inffast.S" mov [esp+44],esi mov eax,edi sub eax, [esp+40] cmp eax,edx jb L_clip_window mov ecx, [esp+24] mov esi,edi sub esi,edx sub ecx,3 mov al, [esi] mov [edi],al mov al, [esi+1] mov dl, [esi+2] add esi,3 mov [edi+1],al mov [edi+2],dl add edi,3 rep movsb mov esi, [esp+44] jmp L_while_test ALIGN 4 L_check_dist_one: cmp edx,1 jne L_check_window cmp [esp+40],edi je L_check_window dec edi mov ecx, [esp+24] mov al, [edi] sub ecx,3 mov [edi+1],al mov [edi+2],al mov [edi+3],al add edi,4 rep stosb jmp L_while_test ALIGN 4 L_test_for_second_level_length: test al,64 jnz L_test_for_end_of_block mov eax,1 shl eax,cl dec eax and eax,ebp add eax,edx mov edx, [esp+8] mov eax, [edx+eax*4] jmp L_dolen ALIGN 4 L_test_for_second_level_dist: test al,64 jnz L_invalid_distance_code mov eax,1 shl eax,cl dec eax and eax,ebp add eax,edx mov edx, [esp+12] mov eax, [edx+eax*4] jmp L_dodist ALIGN 4 L_clip_window: ; 721 "inffast.S" mov ecx,eax mov eax, [esp+52] neg ecx mov esi, [esp+56] cmp eax,edx jb L_invalid_distance_too_far add ecx,edx cmp dword ptr [esp+48],0 jne L_wrap_around_window sub eax,ecx add esi,eax ; 749 "inffast.S" mov eax, [esp+24] cmp eax,ecx jbe L_do_copy1 sub eax,ecx rep movsb mov esi,edi sub esi,edx jmp L_do_copy1 cmp eax,ecx jbe L_do_copy1 sub eax,ecx rep movsb mov esi,edi sub esi,edx jmp L_do_copy1 L_wrap_around_window: ; 793 "inffast.S" mov eax, [esp+48] cmp ecx,eax jbe L_contiguous_in_window add esi, [esp+52] add esi,eax sub esi,ecx sub ecx,eax mov eax, [esp+24] cmp eax,ecx jbe L_do_copy1 sub eax,ecx rep movsb mov esi, [esp+56] mov ecx, [esp+48] cmp eax,ecx jbe L_do_copy1 sub eax,ecx rep movsb mov esi,edi sub esi,edx jmp L_do_copy1 L_contiguous_in_window: ; 836 "inffast.S" add esi,eax sub esi,ecx mov eax, [esp+24] cmp eax,ecx jbe L_do_copy1 sub eax,ecx rep movsb mov esi,edi sub esi,edx L_do_copy1: ; 862 "inffast.S" mov ecx,eax rep movsb mov esi, [esp+44] jmp L_while_test ; 878 "inffast.S" ALIGN 4 L_init_mmx: emms movd mm0,ebp mov ebp,ebx ; 896 "inffast.S" movd mm4,dword ptr [esp+0] movq mm3,mm4 movd mm5,dword ptr [esp+4] movq mm2,mm5 pxor mm1,mm1 mov ebx, [esp+8] jmp L_do_loop_mmx ALIGN 4 L_do_loop_mmx: psrlq mm0,mm1 cmp ebp,32 ja L_get_length_code_mmx movd mm6,ebp movd mm7,dword ptr [esi] add esi,4 psllq mm7,mm6 add ebp,32 por mm0,mm7 L_get_length_code_mmx: pand mm4,mm0 movd eax,mm4 movq mm4,mm3 mov eax, [ebx+eax*4] L_dolen_mmx: movzx ecx,ah movd mm1,ecx sub ebp,ecx test al,al jnz L_test_for_length_base_mmx shr eax,16 stosb L_while_test_mmx: cmp [esp+16],edi jbe L_break_loop cmp [esp+20],esi ja L_do_loop_mmx jmp L_break_loop L_test_for_length_base_mmx: mov edx,eax shr edx,16 test al,16 jz L_test_for_second_level_length_mmx and eax,15 jz L_decode_distance_mmx psrlq mm0,mm1 movd mm1,eax movd ecx,mm0 sub ebp,eax and ecx, [inflate_fast_mask+eax*4] add edx,ecx L_decode_distance_mmx: psrlq mm0,mm1 cmp ebp,32 ja L_get_dist_code_mmx movd mm6,ebp movd mm7,dword ptr [esi] add esi,4 psllq mm7,mm6 add ebp,32 por mm0,mm7 L_get_dist_code_mmx: mov ebx, [esp+12] pand mm5,mm0 movd eax,mm5 movq mm5,mm2 mov eax, [ebx+eax*4] L_dodist_mmx: movzx ecx,ah mov ebx,eax shr ebx,16 sub ebp,ecx movd mm1,ecx test al,16 jz L_test_for_second_level_dist_mmx and eax,15 jz L_check_dist_one_mmx L_add_bits_to_dist_mmx: psrlq mm0,mm1 movd mm1,eax movd ecx,mm0 sub ebp,eax and ecx, [inflate_fast_mask+eax*4] add ebx,ecx L_check_window_mmx: mov [esp+44],esi mov eax,edi sub eax, [esp+40] cmp eax,ebx jb L_clip_window_mmx mov ecx,edx mov esi,edi sub esi,ebx sub ecx,3 mov al, [esi] mov [edi],al mov al, [esi+1] mov dl, [esi+2] add esi,3 mov [edi+1],al mov [edi+2],dl add edi,3 rep movsb mov esi, [esp+44] mov ebx, [esp+8] jmp L_while_test_mmx ALIGN 4 L_check_dist_one_mmx: cmp ebx,1 jne L_check_window_mmx cmp [esp+40],edi je L_check_window_mmx dec edi mov ecx,edx mov al, [edi] sub ecx,3 mov [edi+1],al mov [edi+2],al mov [edi+3],al add edi,4 rep stosb mov ebx, [esp+8] jmp L_while_test_mmx ALIGN 4 L_test_for_second_level_length_mmx: test al,64 jnz L_test_for_end_of_block and eax,15 psrlq mm0,mm1 movd ecx,mm0 and ecx, [inflate_fast_mask+eax*4] add ecx,edx mov eax, [ebx+ecx*4] jmp L_dolen_mmx ALIGN 4 L_test_for_second_level_dist_mmx: test al,64 jnz L_invalid_distance_code and eax,15 psrlq mm0,mm1 movd ecx,mm0 and ecx, [inflate_fast_mask+eax*4] mov eax, [esp+12] add ecx,ebx mov eax, [eax+ecx*4] jmp L_dodist_mmx ALIGN 4 L_clip_window_mmx: mov ecx,eax mov eax, [esp+52] neg ecx mov esi, [esp+56] cmp eax,ebx jb L_invalid_distance_too_far add ecx,ebx cmp dword ptr [esp+48],0 jne L_wrap_around_window_mmx sub eax,ecx add esi,eax cmp edx,ecx jbe L_do_copy1_mmx sub edx,ecx rep movsb mov esi,edi sub esi,ebx jmp L_do_copy1_mmx cmp edx,ecx jbe L_do_copy1_mmx sub edx,ecx rep movsb mov esi,edi sub esi,ebx jmp L_do_copy1_mmx L_wrap_around_window_mmx: mov eax, [esp+48] cmp ecx,eax jbe L_contiguous_in_window_mmx add esi, [esp+52] add esi,eax sub esi,ecx sub ecx,eax cmp edx,ecx jbe L_do_copy1_mmx sub edx,ecx rep movsb mov esi, [esp+56] mov ecx, [esp+48] cmp edx,ecx jbe L_do_copy1_mmx sub edx,ecx rep movsb mov esi,edi sub esi,ebx jmp L_do_copy1_mmx L_contiguous_in_window_mmx: add esi,eax sub esi,ecx cmp edx,ecx jbe L_do_copy1_mmx sub edx,ecx rep movsb mov esi,edi sub esi,ebx L_do_copy1_mmx: mov ecx,edx rep movsb mov esi, [esp+44] mov ebx, [esp+8] jmp L_while_test_mmx ; 1174 "inffast.S" L_invalid_distance_code: mov ecx, invalid_distance_code_msg mov edx,INFLATE_MODE_BAD jmp L_update_stream_state L_test_for_end_of_block: test al,32 jz L_invalid_literal_length_code mov ecx,0 mov edx,INFLATE_MODE_TYPE jmp L_update_stream_state L_invalid_literal_length_code: mov ecx, invalid_literal_length_code_msg mov edx,INFLATE_MODE_BAD jmp L_update_stream_state L_invalid_distance_too_far: mov esi, [esp+44] mov ecx, invalid_distance_too_far_msg mov edx,INFLATE_MODE_BAD jmp L_update_stream_state L_update_stream_state: mov eax, [esp+88] test ecx,ecx jz L_skip_msg mov [eax+24],ecx L_skip_msg: mov eax, [eax+28] mov [eax+mode_state],edx jmp L_break_loop ALIGN 4 L_break_loop: ; 1243 "inffast.S" cmp dword ptr [inflate_fast_use_mmx],2 jne L_update_next_in mov ebx,ebp L_update_next_in: ; 1266 "inffast.S" mov eax, [esp+88] mov ecx,ebx mov edx, [eax+28] shr ecx,3 sub esi,ecx shl ecx,3 sub ebx,ecx mov [eax+12],edi mov [edx+bits_state],ebx mov ecx,ebx lea ebx, [esp+28] cmp [esp+20],ebx jne L_buf_not_used sub esi,ebx mov ebx, [eax+0] mov [esp+20],ebx add esi,ebx mov ebx, [eax+4] sub ebx,11 add [esp+20],ebx L_buf_not_used: mov [eax+0],esi mov ebx,1 shl ebx,cl dec ebx cmp dword ptr [inflate_fast_use_mmx],2 jne L_update_hold psrlq mm0,mm1 movd ebp,mm0 emms L_update_hold: and ebp,ebx mov [edx+hold_state],ebp mov ebx, [esp+20] cmp ebx,esi jbe L_last_is_smaller sub ebx,esi add ebx,11 mov [eax+4],ebx jmp L_fixup_out L_last_is_smaller: sub esi,ebx neg esi add esi,11 mov [eax+4],esi L_fixup_out: mov ebx, [esp+16] cmp ebx,edi jbe L_end_is_smaller sub ebx,edi add ebx,257 mov [eax+16],ebx jmp L_done L_end_is_smaller: sub edi,ebx neg edi add edi,257 mov [eax+16],edi L_done: add esp,64 popfd pop ebx pop ebp pop esi pop edi ret _TEXT ends end bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx86/match686.asm000066400000000000000000000357321462133141200256750ustar00rootroot00000000000000; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86 ; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant. ; File written by Gilles Vollant, by converting match686.S from Brian Raiter ; for MASM. This is as assembly version of longest_match ; from Jean-loup Gailly in deflate.c ; ; http://www.zlib.net ; http://www.winimage.com/zLibDll ; http://www.muppetlabs.com/~breadbox/software/assembly.html ; ; For Visual C++ 4.x and higher and ML 6.x and higher ; ml.exe is distributed in ; http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 ; ; this file contain two implementation of longest_match ; ; this longest_match was written by Brian raiter (1998), optimized for Pentium Pro ; (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom) ; ; for using an assembly version of longest_match, you need define ASMV in project ; ; compile the asm file running ; ml /coff /Zi /c /Flmatch686.lst match686.asm ; and do not include match686.obj in your project ; ; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for ; Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor ; with autoselect (with cpu detection code) ; if you want support the old pentium optimization, you can still use these version ; ; this file is not optimized for old pentium, but it compatible with all x86 32 bits ; processor (starting 80386) ; ; ; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2 ;uInt longest_match(s, cur_match) ; deflate_state *s; ; IPos cur_match; /* current match */ NbStack equ 76 cur_match equ dword ptr[esp+NbStack-0] str_s equ dword ptr[esp+NbStack-4] ; 5 dword on top (ret,ebp,esi,edi,ebx) adrret equ dword ptr[esp+NbStack-8] pushebp equ dword ptr[esp+NbStack-12] pushedi equ dword ptr[esp+NbStack-16] pushesi equ dword ptr[esp+NbStack-20] pushebx equ dword ptr[esp+NbStack-24] chain_length equ dword ptr [esp+NbStack-28] limit equ dword ptr [esp+NbStack-32] best_len equ dword ptr [esp+NbStack-36] window equ dword ptr [esp+NbStack-40] prev equ dword ptr [esp+NbStack-44] scan_start equ word ptr [esp+NbStack-48] wmask equ dword ptr [esp+NbStack-52] match_start_ptr equ dword ptr [esp+NbStack-56] nice_match equ dword ptr [esp+NbStack-60] scan equ dword ptr [esp+NbStack-64] windowlen equ dword ptr [esp+NbStack-68] match_start equ dword ptr [esp+NbStack-72] strend equ dword ptr [esp+NbStack-76] NbStackAdd equ (NbStack-24) .386p name gvmatch .MODEL FLAT ; all the +zlib1222add offsets are due to the addition of fields ; in zlib in the deflate_state structure since the asm code was first written ; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). ; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). ; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). zlib1222add equ 8 ; Note : these value are good with a 8 bytes boundary pack structure dep_chain_length equ 74h+zlib1222add dep_window equ 30h+zlib1222add dep_strstart equ 64h+zlib1222add dep_prev_length equ 70h+zlib1222add dep_nice_match equ 88h+zlib1222add dep_w_size equ 24h+zlib1222add dep_prev equ 38h+zlib1222add dep_w_mask equ 2ch+zlib1222add dep_good_match equ 84h+zlib1222add dep_match_start equ 68h+zlib1222add dep_lookahead equ 6ch+zlib1222add _TEXT segment IFDEF NOUNDERLINE public longest_match public match_init ELSE public _longest_match public _match_init ENDIF MAX_MATCH equ 258 MIN_MATCH equ 3 MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) MAX_MATCH equ 258 MIN_MATCH equ 3 MIN_LOOKAHEAD equ (MAX_MATCH + MIN_MATCH + 1) MAX_MATCH_8_ equ ((MAX_MATCH + 7) AND 0FFF0h) ;;; stack frame offsets chainlenwmask equ esp + 0 ; high word: current chain len ; low word: s->wmask window equ esp + 4 ; local copy of s->window windowbestlen equ esp + 8 ; s->window + bestlen scanstart equ esp + 16 ; first two bytes of string scanend equ esp + 12 ; last two bytes of string scanalign equ esp + 20 ; dword-misalignment of string nicematch equ esp + 24 ; a good enough match size bestlen equ esp + 28 ; size of best match so far scan equ esp + 32 ; ptr to string wanting match LocalVarsSize equ 36 ; saved ebx byte esp + 36 ; saved edi byte esp + 40 ; saved esi byte esp + 44 ; saved ebp byte esp + 48 ; return address byte esp + 52 deflatestate equ esp + 56 ; the function arguments curmatch equ esp + 60 ;;; Offsets for fields in the deflate_state structure. These numbers ;;; are calculated from the definition of deflate_state, with the ;;; assumption that the compiler will dword-align the fields. (Thus, ;;; changing the definition of deflate_state could easily cause this ;;; program to crash horribly, without so much as a warning at ;;; compile time. Sigh.) dsWSize equ 36+zlib1222add dsWMask equ 44+zlib1222add dsWindow equ 48+zlib1222add dsPrev equ 56+zlib1222add dsMatchLen equ 88+zlib1222add dsPrevMatch equ 92+zlib1222add dsStrStart equ 100+zlib1222add dsMatchStart equ 104+zlib1222add dsLookahead equ 108+zlib1222add dsPrevLen equ 112+zlib1222add dsMaxChainLen equ 116+zlib1222add dsGoodMatch equ 132+zlib1222add dsNiceMatch equ 136+zlib1222add ;;; match686.asm -- Pentium-Pro-optimized version of longest_match() ;;; Written for zlib 1.1.2 ;;; Copyright (C) 1998 Brian Raiter ;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html ;;; ;; ;; This software is provided 'as-is', without any express or implied ;; warranty. In no event will the authors be held liable for any damages ;; arising from the use of this software. ;; ;; Permission is granted to anyone to use this software for any purpose, ;; including commercial applications, and to alter it and redistribute it ;; freely, subject to the following restrictions: ;; ;; 1. The origin of this software must not be misrepresented; you must not ;; claim that you wrote the original software. If you use this software ;; in a product, an acknowledgment in the product documentation would be ;; appreciated but is not required. ;; 2. Altered source versions must be plainly marked as such, and must not be ;; misrepresented as being the original software ;; 3. This notice may not be removed or altered from any source distribution. ;; ;GLOBAL _longest_match, _match_init ;SECTION .text ;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch) ;_longest_match: IFDEF NOUNDERLINE longest_match proc near ELSE _longest_match proc near ENDIF ;;; Save registers that the compiler may be using, and adjust esp to ;;; make room for our stack frame. push ebp push edi push esi push ebx sub esp, LocalVarsSize ;;; Retrieve the function arguments. ecx will hold cur_match ;;; throughout the entire function. edx will hold the pointer to the ;;; deflate_state structure during the function's setup (before ;;; entering the main loop. mov edx, [deflatestate] mov ecx, [curmatch] ;;; uInt wmask = s->w_mask; ;;; unsigned chain_length = s->max_chain_length; ;;; if (s->prev_length >= s->good_match) { ;;; chain_length >>= 2; ;;; } mov eax, [edx + dsPrevLen] mov ebx, [edx + dsGoodMatch] cmp eax, ebx mov eax, [edx + dsWMask] mov ebx, [edx + dsMaxChainLen] jl LastMatchGood shr ebx, 2 LastMatchGood: ;;; chainlen is decremented once beforehand so that the function can ;;; use the sign flag instead of the zero flag for the exit test. ;;; It is then shifted into the high word, to make room for the wmask ;;; value, which it will always accompany. dec ebx shl ebx, 16 or ebx, eax mov [chainlenwmask], ebx ;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; mov eax, [edx + dsNiceMatch] mov ebx, [edx + dsLookahead] cmp ebx, eax jl LookaheadLess mov ebx, eax LookaheadLess: mov [nicematch], ebx ;;; register Bytef *scan = s->window + s->strstart; mov esi, [edx + dsWindow] mov [window], esi mov ebp, [edx + dsStrStart] lea edi, [esi + ebp] mov [scan], edi ;;; Determine how many bytes the scan ptr is off from being ;;; dword-aligned. mov eax, edi neg eax and eax, 3 mov [scanalign], eax ;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? ;;; s->strstart - (IPos)MAX_DIST(s) : NIL; mov eax, [edx + dsWSize] sub eax, MIN_LOOKAHEAD sub ebp, eax jg LimitPositive xor ebp, ebp LimitPositive: ;;; int best_len = s->prev_length; mov eax, [edx + dsPrevLen] mov [bestlen], eax ;;; Store the sum of s->window + best_len in esi locally, and in esi. add esi, eax mov [windowbestlen], esi ;;; register ush scan_start = *(ushf*)scan; ;;; register ush scan_end = *(ushf*)(scan+best_len-1); ;;; Posf *prev = s->prev; movzx ebx, word ptr [edi] mov [scanstart], ebx movzx ebx, word ptr [edi + eax - 1] mov [scanend], ebx mov edi, [edx + dsPrev] ;;; Jump into the main loop. mov edx, [chainlenwmask] jmp short LoopEntry align 4 ;;; do { ;;; match = s->window + cur_match; ;;; if (*(ushf*)(match+best_len-1) != scan_end || ;;; *(ushf*)match != scan_start) continue; ;;; [...] ;;; } while ((cur_match = prev[cur_match & wmask]) > limit ;;; && --chain_length != 0); ;;; ;;; Here is the inner loop of the function. The function will spend the ;;; majority of its time in this loop, and majority of that time will ;;; be spent in the first ten instructions. ;;; ;;; Within this loop: ;;; ebx = scanend ;;; ecx = curmatch ;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) ;;; esi = windowbestlen - i.e., (window + bestlen) ;;; edi = prev ;;; ebp = limit LookupLoop: and ecx, edx movzx ecx, word ptr [edi + ecx*2] cmp ecx, ebp jbe LeaveNow sub edx, 00010000h js LeaveNow LoopEntry: movzx eax, word ptr [esi + ecx - 1] cmp eax, ebx jnz LookupLoop mov eax, [window] movzx eax, word ptr [eax + ecx] cmp eax, [scanstart] jnz LookupLoop ;;; Store the current value of chainlen. mov [chainlenwmask], edx ;;; Point edi to the string under scrutiny, and esi to the string we ;;; are hoping to match it up with. In actuality, esi and edi are ;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is ;;; initialized to -(MAX_MATCH_8 - scanalign). mov esi, [window] mov edi, [scan] add esi, ecx mov eax, [scanalign] mov edx, 0fffffef8h; -(MAX_MATCH_8) lea edi, [edi + eax + 0108h] ;MAX_MATCH_8] lea esi, [esi + eax + 0108h] ;MAX_MATCH_8] ;;; Test the strings for equality, 8 bytes at a time. At the end, ;;; adjust edx so that it is offset to the exact byte that mismatched. ;;; ;;; We already know at this point that the first three bytes of the ;;; strings match each other, and they can be safely passed over before ;;; starting the compare loop. So what this code does is skip over 0-3 ;;; bytes, as much as necessary in order to dword-align the edi ;;; pointer. (esi will still be misaligned three times out of four.) ;;; ;;; It should be confessed that this loop usually does not represent ;;; much of the total running time. Replacing it with a more ;;; straightforward "rep cmpsb" would not drastically degrade ;;; performance. LoopCmps: mov eax, [esi + edx] xor eax, [edi + edx] jnz LeaveLoopCmps mov eax, [esi + edx + 4] xor eax, [edi + edx + 4] jnz LeaveLoopCmps4 add edx, 8 jnz LoopCmps jmp short LenMaximum LeaveLoopCmps4: add edx, 4 LeaveLoopCmps: test eax, 0000FFFFh jnz LenLower add edx, 2 shr eax, 16 LenLower: sub al, 1 adc edx, 0 ;;; Calculate the length of the match. If it is longer than MAX_MATCH, ;;; then automatically accept it as the best possible match and leave. lea eax, [edi + edx] mov edi, [scan] sub eax, edi cmp eax, MAX_MATCH jge LenMaximum ;;; If the length of the match is not longer than the best match we ;;; have so far, then forget it and return to the lookup loop. mov edx, [deflatestate] mov ebx, [bestlen] cmp eax, ebx jg LongerMatch mov esi, [windowbestlen] mov edi, [edx + dsPrev] mov ebx, [scanend] mov edx, [chainlenwmask] jmp LookupLoop ;;; s->match_start = cur_match; ;;; best_len = len; ;;; if (len >= nice_match) break; ;;; scan_end = *(ushf*)(scan+best_len-1); LongerMatch: mov ebx, [nicematch] mov [bestlen], eax mov [edx + dsMatchStart], ecx cmp eax, ebx jge LeaveNow mov esi, [window] add esi, eax mov [windowbestlen], esi movzx ebx, word ptr [edi + eax - 1] mov edi, [edx + dsPrev] mov [scanend], ebx mov edx, [chainlenwmask] jmp LookupLoop ;;; Accept the current string, with the maximum possible length. LenMaximum: mov edx, [deflatestate] mov dword ptr [bestlen], MAX_MATCH mov [edx + dsMatchStart], ecx ;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; ;;; return s->lookahead; LeaveNow: mov edx, [deflatestate] mov ebx, [bestlen] mov eax, [edx + dsLookahead] cmp ebx, eax jg LookaheadRet mov eax, ebx LookaheadRet: ;;; Restore the stack and return from whence we came. add esp, LocalVarsSize pop ebx pop esi pop edi pop ebp ret ; please don't remove this string ! ; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary! db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah IFDEF NOUNDERLINE longest_match endp ELSE _longest_match endp ENDIF IFDEF NOUNDERLINE match_init proc near ret match_init endp ELSE _match_init proc near ret _match_init endp ENDIF _TEXT ends end bcmatroska2-5.3.101/corec/corec/helpers/zlib/contrib/masmx86/readme.txt000066400000000000000000000015161462133141200256220ustar00rootroot00000000000000 Summary ------- This directory contains ASM implementations of the functions longest_match() and inflate_fast(). Use instructions ---------------- Assemble using MASM, and copy the object files into the zlib source directory, then run the appropriate makefile, as suggested below. You can donwload MASM from here: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 You can also get objects files here: http://www.winimage.com/zLibDll/zlib124_masm_obj.zip Build instructions ------------------ * With Microsoft C and MASM: nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" * With Borland C and TASM: make -f win32/Makefile.bor LOCAL_ZLIB="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" OBJPA="+match686c.obj+match686.obj+inffas32.obj" bcmatroska2-5.3.101/corec/corec/helpers/zlib/crc32.c000066400000000000000000000325611462133141200217450ustar00rootroot00000000000000/* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2006, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Thanks to Rodney Brown for his contribution of faster * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing * tables for updating the shift register in one step with three exclusive-ors * instead of four steps with four exclusive-ors. This results in about a * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. */ /* @(#) $Id$ */ /* Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore protection on the static variables used to control the first-use generation of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should first call get_crc_table() to initialize the tables before allowing more than one thread to use crc32(). */ #ifdef MAKECRCH # include # ifndef DYNAMIC_CRC_TABLE # define DYNAMIC_CRC_TABLE # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ #include "zutil.h" /* for STDC and FAR definitions */ #define local static /* Find a four-byte integer type for crc32_little() and crc32_big(). */ #ifndef NOBYFOUR # ifdef STDC /* need ANSI C limits.h to determine sizes */ # include # define BYFOUR # if (UINT_MAX == 0xffffffffUL) typedef unsigned int u4; # else # if (ULONG_MAX == 0xffffffffUL) typedef unsigned long u4; # else # if (USHRT_MAX == 0xffffffffUL) typedef unsigned short u4; # else # undef BYFOUR /* can't find a four-byte integer type! */ # endif # endif # endif # endif /* STDC */ #endif /* !NOBYFOUR */ /* Definitions for doing the crc four data bytes at a time. */ #ifdef BYFOUR # define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ (((w)&0xff00)<<8)+(((w)&0xff)<<24)) local unsigned long crc32_little OF((unsigned long, const unsigned char FAR *, unsigned)); local unsigned long crc32_big OF((unsigned long, const unsigned char FAR *, unsigned)); # define TBLS 8 #else # define TBLS 1 #endif /* BYFOUR */ /* Local functions for crc concatenation */ local unsigned long gf2_matrix_times OF((unsigned long *mat, unsigned long vec)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); #ifdef DYNAMIC_CRC_TABLE local volatile int crc_table_empty = 1; local unsigned long FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH local void write_table OF((FILE *, const unsigned long FAR *)); #endif /* MAKECRCH */ /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The first table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRCs on data a byte at a time for all combinations of CRC register values and incoming bytes. The remaining tables allow for word-at-a-time CRC calculation for both big-endian and little- endian machines, where a word is four bytes. */ local void make_crc_table() { unsigned long c; int n, k; unsigned long poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static volatile int first = 1; /* flag to limit concurrent making */ static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; /* See if another task is already doing this (not thread-safe, but better than nothing -- significantly reduces duration of vulnerability in case the advice about DYNAMIC_CRC_TABLE is ignored) */ if (first) { first = 0; /* make exclusive-or pattern from polynomial (0xedb88320UL) */ poly = 0UL; for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) poly |= 1UL << (31 - p[n]); /* generate a crc for every 8-bit value */ for (n = 0; n < 256; n++) { c = (unsigned long)n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[0][n] = c; } #ifdef BYFOUR /* generate crc for each value followed by one, two, and three zeros, and then the byte reversal of those as well as the first table */ for (n = 0; n < 256; n++) { c = crc_table[0][n]; crc_table[4][n] = REV(c); for (k = 1; k < 4; k++) { c = crc_table[0][c & 0xff] ^ (c >> 8); crc_table[k][n] = c; crc_table[k + 4][n] = REV(c); } } #endif /* BYFOUR */ crc_table_empty = 0; } else { /* not first */ /* wait for the other guy to finish (not efficient, but rare) */ while (crc_table_empty) ; } #ifdef MAKECRCH /* write out CRC tables to crc32.h */ { FILE *out; out = fopen("crc32.h", "w"); if (out == NULL) return; fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); fprintf(out, "local const unsigned long FAR "); fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); write_table(out, crc_table[0]); # ifdef BYFOUR fprintf(out, "#ifdef BYFOUR\n"); for (k = 1; k < 8; k++) { fprintf(out, " },\n {\n"); write_table(out, crc_table[k]); } fprintf(out, "#endif\n"); # endif /* BYFOUR */ fprintf(out, " }\n};\n"); fclose(out); } #endif /* MAKECRCH */ } #ifdef MAKECRCH local void write_table(out, table) FILE *out; const unsigned long FAR *table; { int n; for (n = 0; n < 256; n++) fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ #else /* !DYNAMIC_CRC_TABLE */ /* ======================================================================== * Tables of CRC-32s of all single-byte values, made by make_crc_table(). */ #include "crc32.h" #endif /* DYNAMIC_CRC_TABLE */ /* ========================================================================= * This function can be used by asm versions of crc32() */ const unsigned long FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ return (const unsigned long FAR *)crc_table; } /* ========================================================================= */ #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 /* ========================================================================= */ unsigned long ZEXPORT crc32(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; uInt len; { if (buf == Z_NULL) return 0UL; #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ #ifdef BYFOUR if (sizeof(void *) == sizeof(ptrdiff_t)) { u4 endian; endian = 1; if (*((unsigned char *)(&endian))) return crc32_little(crc, buf, len); else return crc32_big(crc, buf, len); } #endif /* BYFOUR */ crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return crc ^ 0xffffffffUL; } #ifdef BYFOUR /* ========================================================================= */ #define DOLIT4 c ^= *buf4++; \ c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 /* ========================================================================= */ local unsigned long crc32_little(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = (u4)crc; c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); len--; } buf4 = (const u4 FAR *)(const void FAR *)buf; while (len >= 32) { DOLIT32; len -= 32; } while (len >= 4) { DOLIT4; len -= 4; } buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); } while (--len); c = ~c; return (unsigned long)c; } /* ========================================================================= */ #define DOBIG4 c ^= *++buf4; \ c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 /* ========================================================================= */ local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = REV((u4)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const u4 FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(REV(c)); } #endif /* BYFOUR */ #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ /* ========================================================================= */ local unsigned long gf2_matrix_times(mat, vec) unsigned long *mat; unsigned long vec; { unsigned long sum; sum = 0; while (vec) { if (vec & 1) sum ^= *mat; vec >>= 1; mat++; } return sum; } /* ========================================================================= */ local void gf2_matrix_square(square, mat) unsigned long *square; unsigned long *mat; { int n; for (n = 0; n < GF2_DIM; n++) square[n] = gf2_matrix_times(mat, mat[n]); } /* ========================================================================= */ local uLong crc32_combine_(crc1, crc2, len2) uLong crc1; uLong crc2; z_off64_t len2; { int n; unsigned long row; unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ /* degenerate case (also disallow negative lengths) */ if (len2 <= 0) return crc1; /* put operator for one zero bit in odd */ odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ row = 1; for (n = 1; n < GF2_DIM; n++) { odd[n] = row; row <<= 1; } /* put operator for two zero bits in even */ gf2_matrix_square(even, odd); /* put operator for four zero bits in odd */ gf2_matrix_square(odd, even); /* apply len2 zeros to crc1 (first square will put the operator for one zero byte, eight zero bits, in even) */ do { /* apply zeros operator for this bit of len2 */ gf2_matrix_square(even, odd); if (len2 & 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; /* if no more bits set, then done */ if (len2 == 0) break; /* another iteration of the loop with odd and even swapped */ gf2_matrix_square(odd, even); if (len2 & 1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; /* if no more bits set, then done */ } while (len2 != 0); /* return combined crc */ crc1 ^= crc2; return crc1; } /* ========================================================================= */ uLong ZEXPORT crc32_combine(crc1, crc2, len2) uLong crc1; uLong crc2; z_off_t len2; { return crc32_combine_(crc1, crc2, len2); } uLong ZEXPORT crc32_combine64(crc1, crc2, len2) uLong crc1; uLong crc2; z_off64_t len2; { return crc32_combine_(crc1, crc2, len2); } bcmatroska2-5.3.101/corec/corec/helpers/zlib/crc32.h000066400000000000000000000744411462133141200217550ustar00rootroot00000000000000/* crc32.h -- tables for rapid CRC calculation * Generated automatically by crc32.c */ local const unsigned long FAR crc_table[TBLS][256] = { { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 0x2d02ef8dUL #ifdef BYFOUR }, { 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, 0x9324fd72UL }, { 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, 0xbe9834edUL }, { 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, 0xde0506f1UL }, { 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, 0x8def022dUL }, { 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, 0x72fd2493UL }, { 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, 0xed3498beUL }, { 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, 0xf10605deUL #endif } }; bcmatroska2-5.3.101/corec/corec/helpers/zlib/deflate.c000066400000000000000000002046541462133141200224410ustar00rootroot00000000000000/* deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process depends on being able to identify portions * of the input text which are identical to earlier input (within a * sliding window trailing behind the input currently being processed). * * The most straightforward technique turns out to be the fastest for * most input files: try all possible matches and select the longest. * The key feature of this algorithm is that insertions into the string * dictionary are very simple and thus fast, and deletions are avoided * completely. Insertions are performed at each input character, whereas * string matches are performed only when the previous match ends. So it * is preferable to spend more time in matches to allow very fast string * insertions and avoid deletions. The matching algorithm for small * strings is inspired from that of Rabin & Karp. A brute force approach * is used to find longer strings when a small match has been found. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze * (by Leonid Broukhis). * A previous version of this file used a more sophisticated algorithm * (by Fiala and Greene) which is guaranteed to run in linear amortized * time, but has a larger average cost, uses more memory and is patented. * However the F&G algorithm may be faster for some highly redundant * files if the parameter max_chain_length (described below) is too large. * * ACKNOWLEDGEMENTS * * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and * I found it in 'freeze' written by Leonid Broukhis. * Thanks to many people for bug reports and testing. * * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". * Available in http://www.ietf.org/rfc/rfc1951.txt * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. * * Fiala,E.R., and Greene,D.H. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 * */ /* @(#) $Id$ */ #include "deflate.h" const char deflate_copyright[] = " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); /* Compression function. Returns the block state after the call. */ local void fill_window OF((deflate_state *s)); local block_state deflate_stored OF((deflate_state *s, int flush)); local block_state deflate_fast OF((deflate_state *s, int flush)); #ifndef FASTEST local block_state deflate_slow OF((deflate_state *s, int flush)); #endif local block_state deflate_rle OF((deflate_state *s, int flush)); local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV void match_init OF((void)); /* asm code initialization */ uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif #ifdef DEBUG local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { ush good_length; /* reduce lazy search above this match length */ ush max_lazy; /* do not perform lazy search above this match length */ ush nice_length; /* quit search above this match length */ ush max_chain; compress_func func; } config; #ifdef FASTEST local const config configuration_table[2] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ #else local const config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ #endif /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ #define EQUAL 0 /* result of memcmp for equal strings */ #ifndef NO_DUMMY_DECL struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * If this file is compiled with -DFASTEST, the compression level is forced * to 1, and no hash chains are maintained. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of str are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ #ifdef FASTEST #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #else #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #endif /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* ========================================================================= */ int ZEXPORT deflateInit_(strm, level, version, stream_size) z_streamp strm; int level; const char *version; int stream_size; { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, version, stream_size) z_streamp strm; int level; int method; int windowBits; int memLevel; int strategy; const char *version; int stream_size; { deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; ushf *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average * output size for (length,distance) codes is <= 24 bits. */ if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } #ifdef GZIP else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } #endif if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); if (s == Z_NULL) return Z_MEM_ERROR; strm->state = (struct internal_state FAR *)s; s->strm = strm; s->wrap = wrap; s->gzhead = Z_NULL; s->w_bits = windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->high_water = 0; /* nothing written to s->window yet */ s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); s->pending_buf = (uchf *) overlay; s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { s->status = FINISH_STATE; strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); deflateEnd (strm); return Z_MEM_ERROR; } s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s->level = level; s->strategy = strategy; s->method = (Byte)method; return deflateReset(strm); } /* ========================================================================= */ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { deflate_state *s; uInt length = dictLength; uInt n; IPos hash_head = 0; if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || strm->state->wrap == 2 || (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) return Z_STREAM_ERROR; s = strm->state; if (s->wrap) strm->adler = adler32(strm->adler, dictionary, dictLength); if (length < MIN_MATCH) return Z_OK; if (length > s->w_size) { length = s->w_size; dictionary += dictLength - length; /* use the tail of the dictionary */ } zmemcpy(s->window, dictionary, length); s->strstart = length; s->block_start = (long)length; /* Insert all strings in the hash table (except for the last two bytes). * s->lookahead stays null, so s->ins_h will be recomputed at the next * call of fill_window. */ s->ins_h = s->window[0]; UPDATE_HASH(s, s->ins_h, s->window[1]); for (n = 0; n <= length - MIN_MATCH; n++) { INSERT_STRING(s, n, hash_head); } if (hash_head) hash_head = 0; /* to make compiler happy */ return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateReset (strm) z_streamp strm; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { return Z_STREAM_ERROR; } strm->total_in = strm->total_out = 0; strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->wrap < 0) { s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ } s->status = s->wrap ? INIT_STATE : BUSY_STATE; strm->adler = #ifdef GZIP s->wrap == 2 ? crc32(0L, Z_NULL, 0) : #endif adler32(0L, Z_NULL, 0); s->last_flush = Z_NO_FLUSH; _tr_init(s); lm_init(s); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; gz_headerp head; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm->state->wrap != 2) return Z_STREAM_ERROR; strm->state->gzhead = head; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; strm->state->bi_valid = bits; strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateParams(strm, level, strategy) z_streamp strm; int level; int strategy; { deflate_state *s; compress_func func; int err = Z_OK; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } func = configuration_table[s->level].func; if ((strategy != s->strategy || func != configuration_table[level].func) && strm->total_in != 0) { /* Flush the last buffer: */ err = deflate(strm, Z_BLOCK); } if (s->level != level) { s->level = level; s->max_lazy_match = configuration_table[level].max_lazy; s->good_match = configuration_table[level].good_length; s->nice_match = configuration_table[level].nice_length; s->max_chain_length = configuration_table[level].max_chain; } s->strategy = strategy; return err; } /* ========================================================================= */ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) z_streamp strm; int good_length; int max_lazy; int nice_length; int max_chain; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; s->good_match = good_length; s->max_lazy_match = max_lazy; s->nice_match = nice_length; s->max_chain_length = max_chain; return Z_OK; } /* ========================================================================= * For the default windowBits of 15 and memLevel of 8, this function returns * a close to exact, as well as small, upper bound on the compressed size. * They are coded as constants here for a reason--if the #define's are * changed, then this function needs to be changed as well. The return * value for 15 and 8 only works for those exact settings. * * For any setting other than those defaults for windowBits and memLevel, * the value returned is a conservative worst case for the maximum expansion * resulting from using fixed blocks instead of stored blocks, which deflate * can emit on compressed data for some combinations of the parameters. * * This function could be more sophisticated to provide closer upper bounds for * every combination of windowBits and memLevel. But even the conservative * upper bound of about 14% expansion does not seem onerous for output buffer * allocation. */ uLong ZEXPORT deflateBound(strm, sourceLen) z_streamp strm; uLong sourceLen; { deflate_state *s; uLong complen, wraplen; Bytef *str; /* conservative upper bound for compressed data */ complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; /* if can't get parameters, return conservative bound plus zlib wrapper */ if (strm == Z_NULL || strm->state == Z_NULL) return complen + 6; /* compute wrapper length */ s = strm->state; switch (s->wrap) { case 0: /* raw deflate */ wraplen = 0; break; case 1: /* zlib wrapper */ wraplen = 6 + (s->strstart ? 4 : 0); break; case 2: /* gzip wrapper */ wraplen = 18; if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ if (s->gzhead->extra != Z_NULL) wraplen += 2 + s->gzhead->extra_len; str = s->gzhead->name; if (str != Z_NULL) do { wraplen++; } while (*str++); str = s->gzhead->comment; if (str != Z_NULL) do { wraplen++; } while (*str++); if (s->gzhead->hcrc) wraplen += 2; } break; default: /* for compiler happiness */ wraplen = 6; } /* if not default parameters, return conservative bound */ if (s->w_bits != 15 || s->hash_bits != 8 + 7) return complen + wraplen; /* default settings: return tight bound for that case */ return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13 - 6 + wraplen; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ local void putShortMSB (s, b) deflate_state *s; uInt b; { put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ local void flush_pending(strm) z_streamp strm; { unsigned len = strm->state->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; zmemcpy(strm->next_out, strm->state->pending_out, len); strm->next_out += len; strm->state->pending_out += len; strm->total_out += len; strm->avail_out -= len; strm->state->pending -= len; if (strm->state->pending == 0) { strm->state->pending_out = strm->state->pending_buf; } } /* ========================================================================= */ int ZEXPORT deflate (strm, flush) z_streamp strm; int flush; { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || flush > Z_BLOCK || flush < 0) { return Z_STREAM_ERROR; } s = strm->state; if (strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0) || (s->status == FINISH_STATE && flush != Z_FINISH)) { ERR_RETURN(strm, Z_STREAM_ERROR); } if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); s->strm = strm; /* just in case */ old_flush = s->last_flush; s->last_flush = flush; /* Write the header */ if (s->status == INIT_STATE) { #ifdef GZIP if (s->wrap == 2) { strm->adler = crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (s->gzhead == Z_NULL) { put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s->status = BUSY_STATE; } else { put_byte(s, (s->gzhead->text ? 1 : 0) + (s->gzhead->hcrc ? 2 : 0) + (s->gzhead->extra == Z_NULL ? 0 : 4) + (s->gzhead->name == Z_NULL ? 0 : 8) + (s->gzhead->comment == Z_NULL ? 0 : 16) ); put_byte(s, (Byte)(s->gzhead->time & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, s->gzhead->os & 0xff); if (s->gzhead->extra != Z_NULL) { put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); } if (s->gzhead->hcrc) strm->adler = crc32(strm->adler, s->pending_buf, s->pending); s->gzindex = 0; s->status = EXTRA_STATE; } } else #endif { uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags; if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) level_flags = 0; else if (s->level < 6) level_flags = 1; else if (s->level == 6) level_flags = 2; else level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); s->status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = adler32(0L, Z_NULL, 0); } } #ifdef GZIP if (s->status == EXTRA_STATE) { if (s->gzhead->extra != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) break; } put_byte(s, s->gzhead->extra[s->gzindex]); s->gzindex++; } if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (s->gzindex == s->gzhead->extra_len) { s->gzindex = 0; s->status = NAME_STATE; } } else s->status = NAME_STATE; } if (s->status == NAME_STATE) { if (s->gzhead->name != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->name[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) { s->gzindex = 0; s->status = COMMENT_STATE; } } else s->status = COMMENT_STATE; } if (s->status == COMMENT_STATE) { if (s->gzhead->comment != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->comment[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) s->status = HCRC_STATE; } else s->status = HCRC_STATE; } if (s->status == HCRC_STATE) { if (s->gzhead->hcrc) { if (s->pending + 2 > s->pending_buf_size) flush_pending(strm); if (s->pending + 2 <= s->pending_buf_size) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); strm->adler = crc32(0L, Z_NULL, 0); s->status = BUSY_STATE; } } else s->status = BUSY_STATE; } #endif /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm->avail_in == 0 && flush <= old_flush && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { ERR_RETURN(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : (s->strategy == Z_RLE ? deflate_rle(s, flush) : (*(configuration_table[s->level].func))(s, flush)); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, (char*)0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; } } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } Assert(strm->avail_out > 0, "bug2"); if (flush != Z_FINISH) return Z_OK; if (s->wrap <= 0) return Z_STREAM_END; /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); put_byte(s, (Byte)(strm->total_in & 0xff)); put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); } else #endif { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int ZEXPORT deflateEnd (strm) z_streamp strm; { int status; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; status = strm->state->status; if (status != INIT_STATE && status != EXTRA_STATE && status != NAME_STATE && status != COMMENT_STATE && status != HCRC_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } /* Deallocate in reverse order of allocations: */ TRY_FREE(strm, strm->state->pending_buf); TRY_FREE(strm, strm->state->head); TRY_FREE(strm, strm->state->prev); TRY_FREE(strm, strm->state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* ========================================================================= * Copy the source state to the destination state. * To simplify the source, this is not supported for 16-bit MSDOS (which * doesn't have enough memory anyway to duplicate compression states). */ int ZEXPORT deflateCopy (dest, source) z_streamp dest; z_streamp source; { #ifdef MAXSEG_64K return Z_STREAM_ERROR; #else deflate_state *ds; deflate_state *ss; ushf *overlay; if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { return Z_STREAM_ERROR; } ss = source->state; zmemcpy(dest, source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; zmemcpy(ds, ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); ds->pending_buf = (uchf *) overlay; if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { deflateEnd (dest); return Z_MEM_ERROR; } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; ds->bl_desc.dyn_tree = ds->bl_tree; return Z_OK; #endif /* MAXSEG_64K */ } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ local int read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; { unsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; if (strm->state->wrap == 1) { strm->adler = adler32(strm->adler, strm->next_in, len); } #ifdef GZIP else if (strm->state->wrap == 2) { strm->adler = crc32(strm->adler, strm->next_in, len); } #endif zmemcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; return (int)len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ local void lm_init (s) deflate_state *s; { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; #ifndef FASTEST #ifdef ASMV match_init(); /* initialize the asm code */ #endif #endif } #ifndef FASTEST /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV /* For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Posf *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register Bytef *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(ushf*)(match+best_len-1) != scan_end || *(ushf*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ Assert(scan[2] == match[2], "scan[2]?"); scan++, match++; do { } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match++; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(ushf*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return (uInt)best_len; return s->lookahead; } #endif /* ASMV */ #else /* FASTEST */ /* --------------------------------------------------------------------------- * Optimized version for FASTEST only */ #ifndef ASMV local #endif uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ register Bytef *strend = s->window + s->strstart + MAX_MATCH; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Return failure if the match length is less than 2: */ if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match += 2; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); if (len < MIN_MATCH) return MIN_MATCH - 1; s->match_start = cur_match; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; } #endif /* FASTEST */ #ifdef DEBUG /* =========================================================================== * Check that the match at match_start is indeed a match. */ local void check_match(s, start, match, length) deflate_state *s; IPos start, match; int length; { /* check that the match is indeed a match */ if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) { fprintf(stderr, " start %u, match %u, length %d\n", start, match, length); do { fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); } while (--length != 0); z_error("invalid match"); } if (z_verbose > 1) { fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0); } } #else # define check_match(s, start, match, length) #endif /* DEBUG */ /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ local void fill_window(s) deflate_state *s; { register unsigned n, m; register Posf *p; unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); /* Deal with !@#$% 64K limit: */ if (sizeof(int) <= 2) { if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if * strstart == 0 && lookahead == 1 (input done a byte at time) */ more--; } } /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s->strstart >= wsize+MAX_DIST(s)) { zmemcpy(s->window, s->window+wsize, (unsigned)wsize); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (long) wsize; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); } while (--n); n = wsize; #ifndef FASTEST p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); #endif more += wsize; } if (s->strm->avail_in == 0) return; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ Assert(more >= 2, "more < 2"); n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead >= MIN_MATCH) { s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ if (s->high_water < s->window_size) { ulg curr = s->strstart + (ulg)(s->lookahead); ulg init; if (s->high_water < curr) { /* Previous high water mark below current data -- zero WIN_INIT * bytes or up to end of window, whichever is less. */ init = s->window_size - curr; if (init > WIN_INIT) init = WIN_INIT; zmemzero(s->window + curr, (unsigned)init); s->high_water = curr + init; } else if (s->high_water < (ulg)curr + WIN_INIT) { /* High water mark at or above current data, but below current data * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up * to end of window, whichever is less. */ init = (ulg)curr + WIN_INIT - s->high_water; if (init > s->window_size - s->high_water) init = s->window_size - s->high_water; zmemzero(s->window + s->high_water, (unsigned)init); s->high_water += init; } } } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, last) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (charf *)&s->window[(unsigned)s->block_start] : \ (charf *)Z_NULL), \ (ulg)((long)s->strstart - s->block_start), \ (last)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ Tracev((stderr,"[FLUSH]")); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, last) { \ FLUSH_BLOCK_ONLY(s, last); \ if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ local block_state deflate_stored(s, flush) deflate_state *s; int flush; { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ ulg max_block_size = 0xffff; ulg max_start; if (max_block_size > s->pending_buf_size - 5) { max_block_size = s->pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s->lookahead <= 1) { Assert(s->strstart < s->w_size+MAX_DIST(s) || s->block_start >= (long)s->w_size, "slide too late"); fill_window(s); if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0) break; /* flush the current block */ } Assert(s->block_start >= 0L, "block gone"); s->strstart += s->lookahead; s->lookahead = 0; /* Emit a stored block if pending_buf will be full: */ max_start = s->block_start + max_block_size; if (s->strstart == 0 || (ulg)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s->lookahead = (uInt)(s->strstart - max_start); s->strstart = (uInt)max_start; FLUSH_BLOCK(s, 0); } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { FLUSH_BLOCK(s, 0); } } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ local block_state deflate_fast(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ } if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->match_start, s->match_length); _tr_tally_dist(s, s->strstart - s->match_start, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ #ifndef FASTEST if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else #endif { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } #ifndef FASTEST /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } #endif /* FASTEST */ /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ local block_state deflate_rle(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ uInt prev; /* byte at distance one to match */ Bytef *scan, *strend; /* scan goes up to strend for length of run */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest encodable run. */ if (s->lookahead < MAX_MATCH) { fill_window(s); if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* See how many times the previous byte repeats */ s->match_length = 0; if (s->lookahead >= MIN_MATCH && s->strstart > 0) { scan = s->window + s->strstart - 1; prev = *scan; if (prev == *++scan && prev == *++scan && prev == *++scan) { strend = s->window + s->strstart + MAX_MATCH; do { } while (prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && scan < strend); s->match_length = MAX_MATCH - (int)(strend - scan); if (s->match_length > s->lookahead) s->match_length = s->lookahead; } } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->strstart - 1, s->match_length); _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; s->strstart += s->match_length; s->match_length = 0; } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ local block_state deflate_huff(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s->lookahead == 0) { fill_window(s); if (s->lookahead == 0) { if (flush == Z_NO_FLUSH) return need_more; break; /* flush the current block */ } } /* Output a literal byte */ s->match_length = 0; Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/deflate.h000066400000000000000000000306001462133141200224320ustar00rootroot00000000000000/* deflate.h -- internal compression state * Copyright (C) 1995-2010 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef DEFLATE_H #define DEFLATE_H #include "zutil.h" /* define NO_GZIP when compiling if you want to disable gzip header and trailer creation by deflate(). NO_GZIP would be used to avoid linking in the crc code when it is not needed. For shared libraries, gzip encoding should be left enabled. */ #ifndef NO_GZIP # define GZIP #endif /* =========================================================================== * Internal compression state. */ #define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ #define LITERALS 256 /* number of literal bytes 0..255 */ #define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ #define D_CODES 30 /* number of distance codes */ #define BL_CODES 19 /* number of codes used to transfer the bit lengths */ #define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ #define INIT_STATE 42 #define EXTRA_STATE 69 #define NAME_STATE 73 #define COMMENT_STATE 91 #define HCRC_STATE 103 #define BUSY_STATE 113 #define FINISH_STATE 666 /* Stream status */ /* Data structure describing a single value and its code string. */ typedef struct ct_data_s { union { ush freq; /* frequency count */ ush code; /* bit string */ } fc; union { ush dad; /* father node in Huffman tree */ ush len; /* length of bit string */ } dl; } FAR ct_data; #define Freq fc.freq #define Code fc.code #define Dad dl.dad #define Len dl.len typedef struct static_tree_desc_s static_tree_desc; typedef struct tree_desc_s { ct_data *dyn_tree; /* the dynamic tree */ int max_code; /* largest code with non zero frequency */ static_tree_desc *stat_desc; /* the corresponding static tree */ } FAR tree_desc; typedef ush Pos; typedef Pos FAR Posf; typedef unsigned IPos; /* A Pos is an index in the character window. We use short instead of int to * save space in the various tables. IPos is used only for parameter passing. */ typedef struct internal_state { z_streamp strm; /* pointer back to this zlib stream */ int status; /* as the name implies */ Bytef *pending_buf; /* output still pending */ ulg pending_buf_size; /* size of pending_buf */ Bytef *pending_out; /* next pending byte to output to the stream */ uInt pending; /* nb of bytes in the pending buffer */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ gz_headerp gzhead; /* gzip header information to write */ uInt gzindex; /* where in extra, name, or comment */ Byte method; /* STORED (for zip only) or DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ uInt w_mask; /* w_size - 1 */ Bytef *window; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. Also, it limits * the window size to 64K, which is quite useful on MSDOS. * To do: use the user input buffer as sliding window. */ ulg window_size; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ Posf *prev; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ Posf *head; /* Heads of the hash chains or NIL. */ uInt ins_h; /* hash index of string to be inserted */ uInt hash_size; /* number of elements in hash table */ uInt hash_bits; /* log2(hash_size) */ uInt hash_mask; /* hash_size-1 */ uInt hash_shift; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ long block_start; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ uInt match_length; /* length of best match */ IPos prev_match; /* previous match */ int match_available; /* set if previous match exists */ uInt strstart; /* start of string to insert */ uInt match_start; /* start of matching string */ uInt lookahead; /* number of valid bytes ahead in window */ uInt prev_length; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ uInt max_chain_length; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ uInt max_lazy_match; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ # define max_insert_length max_lazy_match /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ int level; /* compression level (1..9) */ int strategy; /* favor or force Huffman coding*/ uInt good_match; /* Use a faster search when the previous match is longer than this */ int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to supress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ struct tree_desc_s l_desc; /* desc. for literal tree */ struct tree_desc_s d_desc; /* desc. for distance tree */ struct tree_desc_s bl_desc; /* desc. for bit length tree */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ int heap_len; /* number of elements in the heap */ int heap_max; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ uch depth[2*L_CODES+1]; /* Depth of each subtree used as tie breaker for trees of equal frequency */ uchf *l_buf; /* buffer for literals or lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ uInt last_lit; /* running index in l_buf */ ushf *d_buf; /* Buffer for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ uInt matches; /* number of string matches in current block */ int last_eob_len; /* bit length of EOB code for last block */ #ifdef DEBUG ulg compressed_len; /* total bit length of compressed file mod 2^32 */ ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ #endif ush bi_buf; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ int bi_valid; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ ulg high_water; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } FAR deflate_state; /* Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */ #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) /* In order to simplify the code, particularly on 16 bit machines, match * distances are limited to MAX_DIST instead of WSIZE. */ #define WIN_INIT MAX_MATCH /* Number of bytes after end of data in window to initialize in order to avoid memory checker errors from longest match routines */ /* in trees.c */ void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); #define d_code(dist) \ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. _dist_code[256] and _dist_code[257] are never * used. */ #ifndef DEBUG /* Inline versions of _tr_tally for speed: */ #if defined(GEN_TREES_H) || !defined(STDC) extern uch ZLIB_INTERNAL _length_code[]; extern uch ZLIB_INTERNAL _dist_code[]; #else extern const uch ZLIB_INTERNAL _length_code[]; extern const uch ZLIB_INTERNAL _dist_code[]; #endif # define _tr_tally_lit(s, c, flush) \ { uch cc = (c); \ s->d_buf[s->last_lit] = 0; \ s->l_buf[s->last_lit++] = cc; \ s->dyn_ltree[cc].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } # define _tr_tally_dist(s, distance, length, flush) \ { uch len = (length); \ ush dist = (distance); \ s->d_buf[s->last_lit] = dist; \ s->l_buf[s->last_lit++] = len; \ dist--; \ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ s->dyn_dtree[d_code(dist)].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } #else # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) # define _tr_tally_dist(s, distance, length, flush) \ flush = _tr_tally(s, distance, length) #endif #endif /* DEFLATE_H */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/example.c000066400000000000000000000400161462133141200224560ustar00rootroot00000000000000/* example.c -- usage example of the zlib compression library * Copyright (C) 1995-2006 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zlib.h" #include #ifdef STDC # include # include #endif #if defined(VMS) || defined(RISCOS) # define TESTFILE "foo-gz" #else # define TESTFILE "foo.gz" #endif #define CHECK_ERR(err, msg) { \ if (err != Z_OK) { \ fprintf(stderr, "%s error: %d\n", msg, err); \ exit(1); \ } \ } const char hello[] = "hello, hello!"; /* "hello world" would be more standard, but the repeated "hello" * stresses the compression code better, sorry... */ const char dictionary[] = "hello"; uLong dictId; /* Adler32 value of the dictionary */ void test_compress OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_gzio OF((const char *fname, Byte *uncompr, uLong uncomprLen)); void test_deflate OF((Byte *compr, uLong comprLen)); void test_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_deflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_flush OF((Byte *compr, uLong *comprLen)); void test_sync OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_dict_deflate OF((Byte *compr, uLong comprLen)); void test_dict_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); int main OF((int argc, char *argv[])); /* =========================================================================== * Test compress() and uncompress() */ void test_compress(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; uLong len = (uLong)strlen(hello)+1; err = compress(compr, &comprLen, (const Bytef*)hello, len); CHECK_ERR(err, "compress"); strcpy((char*)uncompr, "garbage"); err = uncompress(uncompr, &uncomprLen, compr, comprLen); CHECK_ERR(err, "uncompress"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad uncompress\n"); exit(1); } else { printf("uncompress(): %s\n", (char *)uncompr); } } /* =========================================================================== * Test read/write of .gz files */ void test_gzio(fname, uncompr, uncomprLen) const char *fname; /* compressed file name */ Byte *uncompr; uLong uncomprLen; { #ifdef NO_GZCOMPRESS fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); #else int err; int len = (int)strlen(hello)+1; gzFile file; z_off_t pos; file = gzopen(fname, "wb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } gzputc(file, 'h'); if (gzputs(file, "ello") != 4) { fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); exit(1); } if (gzprintf(file, ", %s!", "hello") != 8) { fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); exit(1); } gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ gzclose(file); file = gzopen(fname, "rb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } strcpy((char*)uncompr, "garbage"); if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); exit(1); } else { printf("gzread(): %s\n", (char*)uncompr); } pos = gzseek(file, -8L, SEEK_CUR); if (pos != 6 || gztell(file) != pos) { fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", (long)pos, (long)gztell(file)); exit(1); } if (gzgetc(file) != ' ') { fprintf(stderr, "gzgetc error\n"); exit(1); } if (gzungetc(' ', file) != ' ') { fprintf(stderr, "gzungetc error\n"); exit(1); } gzgets(file, (char*)uncompr, (int)uncomprLen); if (strlen((char*)uncompr) != 7) { /* " hello!" */ fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello + 6)) { fprintf(stderr, "bad gzgets after gzseek\n"); exit(1); } else { printf("gzgets() after gzseek: %s\n", (char*)uncompr); } gzclose(file); #endif } /* =========================================================================== * Test deflate() with small buffers */ void test_deflate(compr, comprLen) Byte *compr; uLong comprLen; { z_stream c_stream; /* compression stream */ int err; uLong len = (uLong)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; while (c_stream.total_in != len && c_stream.total_out < comprLen) { c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); } /* Finish the stream, still forcing small buffers: */ for (;;) { c_stream.avail_out = 1; err = deflate(&c_stream, Z_FINISH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with small buffers */ void test_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 0; d_stream.next_out = uncompr; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate\n"); exit(1); } else { printf("inflate(): %s\n", (char *)uncompr); } } /* =========================================================================== * Test deflate() with large buffers and dynamic change of compression level */ void test_large_deflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_SPEED); CHECK_ERR(err, "deflateInit"); c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; /* At this point, uncompr is still mostly zeroes, so it should compress * very well: */ c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); if (c_stream.avail_in != 0) { fprintf(stderr, "deflate not greedy\n"); exit(1); } /* Feed in already compressed data and switch to no compression: */ deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); c_stream.next_in = compr; c_stream.avail_in = (uInt)comprLen/2; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); /* Switch back to compressing mode: */ deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with large buffers */ void test_large_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); for (;;) { d_stream.next_out = uncompr; /* discard the output */ d_stream.avail_out = (uInt)uncomprLen; err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "large inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (d_stream.total_out != 2*uncomprLen + comprLen/2) { fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); exit(1); } else { printf("large_inflate(): OK\n"); } } /* =========================================================================== * Test deflate() with full flush */ void test_flush(compr, comprLen) Byte *compr; uLong *comprLen; { z_stream c_stream; /* compression stream */ int err; uInt len = (uInt)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; c_stream.avail_in = 3; c_stream.avail_out = (uInt)*comprLen; err = deflate(&c_stream, Z_FULL_FLUSH); CHECK_ERR(err, "deflate"); compr[3]++; /* force an error in first compressed block */ c_stream.avail_in = len - 3; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); *comprLen = c_stream.total_out; } /* =========================================================================== * Test inflateSync() */ void test_sync(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 2; /* just read the zlib header */ err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; inflate(&d_stream, Z_NO_FLUSH); CHECK_ERR(err, "inflate"); d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ err = inflateSync(&d_stream); /* but skip the damaged part */ CHECK_ERR(err, "inflateSync"); err = inflate(&d_stream, Z_FINISH); if (err != Z_DATA_ERROR) { fprintf(stderr, "inflate should report DATA_ERROR\n"); /* Because of incorrect adler32 */ exit(1); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); printf("after inflateSync(): hel%s\n", (char *)uncompr); } /* =========================================================================== * Test deflate() with preset dictionary */ void test_dict_deflate(compr, comprLen) Byte *compr; uLong comprLen; { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_COMPRESSION); CHECK_ERR(err, "deflateInit"); err = deflateSetDictionary(&c_stream, (const Bytef*)dictionary, sizeof(dictionary)); CHECK_ERR(err, "deflateSetDictionary"); dictId = c_stream.adler; c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; c_stream.next_in = (Bytef*)hello; c_stream.avail_in = (uInt)strlen(hello)+1; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with a preset dictionary */ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; if (err == Z_NEED_DICT) { if (d_stream.adler != dictId) { fprintf(stderr, "unexpected dictionary"); exit(1); } err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, sizeof(dictionary)); } CHECK_ERR(err, "inflate with dict"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate with dict\n"); exit(1); } else { printf("inflate with dictionary: %s\n", (char *)uncompr); } } /* =========================================================================== * Usage: example [output.gz [input.gz]] */ int main(argc, argv) int argc; char *argv[]; { Byte *compr, *uncompr; uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ uLong uncomprLen = comprLen; static const char* myVersion = ZLIB_VERSION; if (zlibVersion()[0] != myVersion[0]) { fprintf(stderr, "incompatible zlib version\n"); exit(1); } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { fprintf(stderr, "warning: different zlib version\n"); } printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); compr = (Byte*)calloc((uInt)comprLen, 1); uncompr = (Byte*)calloc((uInt)uncomprLen, 1); /* compr and uncompr are cleared to avoid reading uninitialized * data and to ensure that uncompr compresses well. */ if (compr == Z_NULL || uncompr == Z_NULL) { printf("out of memory\n"); exit(1); } test_compress(compr, comprLen, uncompr, uncomprLen); test_gzio((argc > 1 ? argv[1] : TESTFILE), uncompr, uncomprLen); test_deflate(compr, comprLen); test_inflate(compr, comprLen, uncompr, uncomprLen); test_large_deflate(compr, comprLen, uncompr, uncomprLen); test_large_inflate(compr, comprLen, uncompr, uncomprLen); test_flush(compr, &comprLen); test_sync(compr, comprLen, uncompr, uncomprLen); comprLen = uncomprLen; test_dict_deflate(compr, comprLen); test_dict_inflate(compr, comprLen, uncompr, uncomprLen); free(compr); free(uncompr); return 0; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/gzclose.c000066400000000000000000000012461462133141200224730ustar00rootroot00000000000000/* gzclose.c -- zlib gzclose() function * Copyright (C) 2004, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* gzclose() is in a separate file so that it is linked in only if it is used. That way the other gzclose functions can be used instead to avoid linking in unneeded compression or decompression routines. */ int ZEXPORT gzclose(file) gzFile file; { #ifndef NO_GZCOMPRESS gz_statep state; if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); #else return gzclose_r(file); #endif } bcmatroska2-5.3.101/corec/corec/helpers/zlib/gzguts.h000066400000000000000000000111051462133141200223500ustar00rootroot00000000000000/* gzguts.h -- zlib internal header definitions for gz* operations * Copyright (C) 2004, 2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #ifdef _LARGEFILE64_SOURCE # ifndef _LARGEFILE_SOURCE # define _LARGEFILE_SOURCE 1 # endif # ifdef _FILE_OFFSET_BITS # undef _FILE_OFFSET_BITS # endif #endif #if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) # define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) #else # define ZLIB_INTERNAL #endif #include #include "zlib.h" #ifdef STDC # include # include # include #endif #include #ifdef NO_DEFLATE /* for compatibility with old definition */ # define NO_GZCOMPRESS #endif #ifdef _MSC_VER # include # define vsnprintf _vsnprintf #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ /* gz* functions always use library allocation functions */ #ifndef STDC extern voidp malloc OF((uInt size)); extern void free OF((voidpf ptr)); #endif /* get errno and strerror definition */ #if defined UNDER_CE # include # define zstrerror() gz_strwinerror((DWORD)GetLastError()) #else # ifdef STDC # include # define zstrerror() strerror(errno) # else # define zstrerror() "stdio error (consult errno)" # endif #endif /* provide prototypes for these when building zlib without LFS */ #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); #endif /* default i/o buffer size -- double this for output when reading */ #define GZBUFSIZE 8192 /* gzip modes, also provide a little integrity check on the passed structure */ #define GZ_NONE 0 #define GZ_READ 7247 #define GZ_WRITE 31153 #define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ /* values for gz_state how */ #define LOOK 0 /* look for a gzip header */ #define COPY 1 /* copy input directly */ #define GZIP 2 /* decompress a gzip stream */ /* internal gzip file state data structure */ typedef struct { /* used for both reading and writing */ int mode; /* see gzip modes above */ int fd; /* file descriptor */ char *path; /* path or fd for error messages */ z_off64_t pos; /* current position in uncompressed data */ unsigned size; /* buffer size, zero if not allocated yet */ unsigned want; /* requested buffer size, default is GZBUFSIZE */ unsigned char *in; /* input buffer */ unsigned char *out; /* output buffer (double-sized when reading) */ unsigned char *next; /* next output data to deliver or write */ /* just for reading */ unsigned have; /* amount of output data unused at next */ int eof; /* true if end of input file reached */ z_off64_t start; /* where the gzip data started, for rewinding */ z_off64_t raw; /* where the raw data started, for seeking */ int how; /* 0: get header, 1: copy, 2: decompress */ int direct; /* true if last read direct, false if gzip */ /* just for writing */ int level; /* compression level */ int strategy; /* compression strategy */ /* seek request */ z_off64_t skip; /* amount to skip (already rewound if backwards) */ int seek; /* true if seek request pending */ /* error information */ int err; /* error code */ char *msg; /* error message */ /* zlib inflate or deflate stream */ z_stream strm; /* stream structure in-place (not a pointer) */ } gz_state; typedef gz_state FAR *gz_statep; /* shared functions */ void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); #if defined UNDER_CE char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); #endif /* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t value -- needed when comparing unsigned to z_off64_t, which is signed (possible z_off64_t types off_t, off64_t, and long are all signed) */ #ifdef INT_MAX # define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) #else unsigned ZLIB_INTERNAL gz_intmax OF((void)); # define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) #endif bcmatroska2-5.3.101/corec/corec/helpers/zlib/gzlib.c000066400000000000000000000333671462133141200221450ustar00rootroot00000000000000/* gzlib.c -- zlib functions common to reading and writing gzip files * Copyright (C) 2004, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif /* Local functions */ local void gz_reset OF((gz_statep)); local gzFile gz_open OF((const char *, int, const char *)); #if defined UNDER_CE /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come from GetLastError. The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to gz_strwinerror The gz_strwinerror function does not change the current setting of GetLastError. */ char ZLIB_INTERNAL *gz_strwinerror (error) DWORD error; { static char buf[1024]; wchar_t *msgbuf; DWORD lasterr = GetLastError(); DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, /* Default language */ (LPVOID)&msgbuf, 0, NULL); if (chars != 0) { /* If there is an \r\n appended, zap it. */ if (chars >= 2 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { chars -= 2; msgbuf[chars] = 0; } if (chars > sizeof (buf) - 1) { chars = sizeof (buf) - 1; msgbuf[chars] = 0; } wcstombs(buf, msgbuf, chars + 1); LocalFree(msgbuf); } else { sprintf(buf, "unknown win32 error (%ld)", error); } SetLastError(lasterr); return buf; } #endif /* UNDER_CE */ /* Reset gzip file state */ local void gz_reset(state) gz_statep state; { if (state->mode == GZ_READ) { /* for reading ... */ state->have = 0; /* no output data available */ state->eof = 0; /* not at end of file */ state->how = LOOK; /* look for gzip header */ state->direct = 1; /* default for empty file */ } state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ state->pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) const char *path; int fd; const char *mode; { gz_statep state; /* allocate gzFile structure to return */ state = malloc(sizeof(gz_state)); if (state == NULL) return NULL; state->size = 0; /* no buffers allocated yet */ state->want = GZBUFSIZE; /* requested buffer size */ state->msg = NULL; /* no error message yet */ /* interpret mode */ state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; else switch (*mode) { case 'r': state->mode = GZ_READ; break; #ifndef NO_GZCOMPRESS case 'w': state->mode = GZ_WRITE; break; case 'a': state->mode = GZ_APPEND; break; #endif case '+': /* can't read and write at the same time */ free(state); return NULL; case 'b': /* ignore -- will request binary anyway */ break; case 'f': state->strategy = Z_FILTERED; break; case 'h': state->strategy = Z_HUFFMAN_ONLY; break; case 'R': state->strategy = Z_RLE; break; case 'F': state->strategy = Z_FIXED; default: /* could consider as an error, but just ignore */ ; } mode++; } /* must provide an "r", "w", or "a" */ if (state->mode == GZ_NONE) { free(state); return NULL; } /* save the path name for error messages */ state->path = malloc(strlen(path) + 1); if (state->path == NULL) { free(state); return NULL; } strcpy(state->path, path); /* open the file with the appropriate mode (or just use fd) */ state->fd = fd != -1 ? fd : open(path, #ifdef O_LARGEFILE O_LARGEFILE | #endif #ifdef O_BINARY O_BINARY | #endif (state->mode == GZ_READ ? O_RDONLY : (O_WRONLY | O_CREAT | ( state->mode == GZ_WRITE ? O_TRUNC : O_APPEND))), 0666); if (state->fd == -1) { free(state->path); free(state); return NULL; } if (state->mode == GZ_APPEND) state->mode = GZ_WRITE; /* simplify later checks */ /* save the current position for rewinding (only if reading) */ if (state->mode == GZ_READ) { state->start = LSEEK(state->fd, 0, SEEK_CUR); if (state->start == -1) state->start = 0; } /* initialize stream */ gz_reset(state); /* return stream */ return (gzFile)state; } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen64(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzdopen(fd, mode) int fd; const char *mode; { char *path; /* identifier for error messages */ gzFile gz; if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL) return NULL; sprintf(path, "", fd); /* for debugging */ gz = gz_open(path, fd, mode); free(path); return gz; } /* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; unsigned size; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* make sure we haven't already allocated memory */ if (state->size != 0) return -1; /* check and set requested size */ if (size == 0) return -1; state->want = size; return 0; } /* -- see zlib.h -- */ int ZEXPORT gzrewind(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || state->err != Z_OK) return -1; /* back up and start over */ if (LSEEK(state->fd, state->start, SEEK_SET) == -1) return -1; gz_reset(state); return 0; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzseek64(file, offset, whence) gzFile file; z_off64_t offset; int whence; { unsigned n; z_off64_t ret; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* check that there's no error */ if (state->err != Z_OK) return -1; /* can only seek from start or relative to current position */ if (whence != SEEK_SET && whence != SEEK_CUR) return -1; /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) offset -= state->pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && state->pos + offset >= state->raw) { ret = LSEEK(state->fd, offset - state->have, SEEK_CUR); if (ret == -1) return -1; state->have = 0; state->eof = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; state->pos += offset; return state->pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; offset += state->pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ return -1; } /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { n = GT_OFF(state->have) || (z_off64_t)state->have > offset ? (unsigned)offset : state->have; state->have -= n; state->next += n; state->pos += n; offset -= n; } /* request skip (if not zero) */ if (offset) { state->seek = 1; state->skip = offset; } return state->pos + offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzseek(file, offset, whence) gzFile file; z_off_t offset; int whence; { z_off64_t ret; ret = gzseek64(file, (z_off64_t)offset, whence); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gztell64(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* return position */ return state->pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ z_off_t ZEXPORT gztell(file) gzFile file; { z_off64_t ret; ret = gztell64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzoffset64(file) gzFile file; { z_off64_t offset; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* compute and return effective offset in file */ offset = LSEEK(state->fd, 0, SEEK_CUR); if (offset == -1) return -1; if (state->mode == GZ_READ) /* reading */ offset -= state->strm.avail_in; /* don't count buffered input */ return offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzoffset(file) gzFile file; { z_off64_t ret; ret = gzoffset64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ int ZEXPORT gzeof(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return 0; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return 0; /* return end-of-file state */ return state->mode == GZ_READ ? (state->eof && state->strm.avail_in == 0 && state->have == 0) : 0; } /* -- see zlib.h -- */ const char * ZEXPORT gzerror(file, errnum) gzFile file; int *errnum; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return NULL; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return NULL; /* return error information */ if (errnum != NULL) *errnum = state->err; return state->msg == NULL ? "" : state->msg; } /* -- see zlib.h -- */ void ZEXPORT gzclearerr(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return; /* clear error and end-of-file */ if (state->mode == GZ_READ) state->eof = 0; gz_error(state, Z_OK, NULL); } /* Create an error message in allocated memory and set state->err and state->msg accordingly. Free any previous error message already there. Do not try to free or allocate space if the error is Z_MEM_ERROR (out of memory). Simply save the error message as a static string. If there is an allocation failure constructing the error message, then convert the error to out of memory. */ void ZLIB_INTERNAL gz_error(state, err, msg) gz_statep state; int err; const char *msg; { /* free previously allocated message and clear */ if (state->msg != NULL) { if (state->err != Z_MEM_ERROR) free(state->msg); state->msg = NULL; } /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) return; /* for an out of memory error, save as static string */ if (err == Z_MEM_ERROR) { state->msg = (char *)msg; return; } /* construct error message with path */ if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { state->err = Z_MEM_ERROR; state->msg = (char *)"out of memory"; return; } strcpy(state->msg, state->path); strcat(state->msg, ": "); strcat(state->msg, msg); return; } #ifndef INT_MAX /* portably return maximum value for an int (when limits.h presumed not available) -- we need to do this to cover cases where 2's complement not used, since C standard permits 1's complement and sign-bit representations, otherwise we could just use ((unsigned)-1) >> 1 */ unsigned ZLIB_INTERNAL gz_intmax() { unsigned p, q; p = 1; do { q = p; p <<= 1; p++; } while (p > q); return q >> 1; } #endif bcmatroska2-5.3.101/corec/corec/helpers/zlib/gzread.c000066400000000000000000000501361462133141200223030ustar00rootroot00000000000000/* gzread.c -- zlib functions for reading gzip files * Copyright (C) 2004, 2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* Local functions */ local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); local int gz_avail OF((gz_statep)); local int gz_next4 OF((gz_statep, unsigned long *)); local int gz_head OF((gz_statep)); local int gz_decomp OF((gz_statep)); local int gz_make OF((gz_statep)); local int gz_skip OF((gz_statep, z_off64_t)); /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from state->fd, and update state->eof, state->err, and state->msg as appropriate. This function needs to loop on read(), since read() is not guaranteed to read the number of bytes requested, depending on the type of descriptor. */ local int gz_load(state, buf, len, have) gz_statep state; unsigned char *buf; unsigned len; unsigned *have; { int ret; *have = 0; do { ret = read(state->fd, buf + *have, len - *have); if (ret <= 0) break; *have += ret; } while (*have < len); if (ret < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } if (ret == 0) state->eof = 1; return 0; } /* Load up input buffer and set eof flag if last data loaded -- return -1 on error, 0 otherwise. Note that the eof flag is set when the end of the input file is reached, even though there may be unused data in the buffer. Once that data has been used, no more attempts will be made to read the file. gz_avail() assumes that strm->avail_in == 0. */ local int gz_avail(state) gz_statep state; { z_streamp strm = &(state->strm); if (state->err != Z_OK) return -1; if (state->eof == 0) { if (gz_load(state, state->in, state->size, (unsigned *)&(strm->avail_in)) == -1) return -1; strm->next_in = state->in; } return 0; } /* Get next byte from input, or -1 if end or error. */ #define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \ (strm->avail_in == 0 ? -1 : \ (strm->avail_in--, *(strm->next_in)++))) /* Get a four-byte little-endian integer and return 0 on success and the value in *ret. Otherwise -1 is returned and *ret is not modified. */ local int gz_next4(state, ret) gz_statep state; unsigned long *ret; { int ch; unsigned long val; z_streamp strm = &(state->strm); val = NEXT(); val += (unsigned)NEXT() << 8; val += (unsigned long)NEXT() << 16; ch = NEXT(); if (ch == -1) return -1; val += (unsigned long)ch << 24; *ret = val; return 0; } /* Look for gzip header, set up for inflate or copy. state->have must be zero. If this is the first time in, allocate required memory. state->how will be left unchanged if there is no more input data available, will be set to COPY if there is no gzip header and direct copying will be performed, or it will be set to GZIP for decompression, and the gzip header will be skipped so that the next available input data is the raw deflate stream. If direct copying, then leftover input data from the input buffer will be copied to the output buffer. In that case, all further file reads will be directly to either the output buffer or a user buffer. If decompressing, the inflate state and the check value will be initialized. gz_head() will return 0 on success or -1 on failure. Failures may include read errors or gzip header errors. */ local int gz_head(state) gz_statep state; { z_streamp strm = &(state->strm); int flags; unsigned len; /* allocate read buffers and inflate memory */ if (state->size == 0) { /* allocate buffers */ state->in = malloc(state->want); state->out = malloc(state->want << 1); if (state->in == NULL || state->out == NULL) { if (state->out != NULL) free(state->out); if (state->in != NULL) free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } state->size = state->want; /* allocate inflate memory */ state->strm.zalloc = Z_NULL; state->strm.zfree = Z_NULL; state->strm.opaque = Z_NULL; state->strm.avail_in = 0; state->strm.next_in = Z_NULL; if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */ free(state->out); free(state->in); state->size = 0; gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } } /* get some data in the input buffer */ if (strm->avail_in == 0) { if (gz_avail(state) == -1) return -1; if (strm->avail_in == 0) return 0; } /* look for the gzip magic header bytes 31 and 139 */ if (strm->next_in[0] == 31) { strm->avail_in--; strm->next_in++; if (strm->avail_in == 0 && gz_avail(state) == -1) return -1; if (strm->avail_in && strm->next_in[0] == 139) { /* we have a gzip header, woo hoo! */ strm->avail_in--; strm->next_in++; /* skip rest of header */ if (NEXT() != 8) { /* compression method */ gz_error(state, Z_DATA_ERROR, "unknown compression method"); return -1; } flags = NEXT(); if (flags & 0xe0) { /* reserved flag bits */ gz_error(state, Z_DATA_ERROR, "unknown header flags set"); return -1; } NEXT(); /* modification time */ NEXT(); NEXT(); NEXT(); NEXT(); /* extra flags */ NEXT(); /* operating system */ if (flags & 4) { /* extra field */ len = (unsigned)NEXT(); len += (unsigned)NEXT() << 8; while (len--) if (NEXT() < 0) break; } if (flags & 8) /* file name */ while (NEXT() > 0) ; if (flags & 16) /* comment */ while (NEXT() > 0) ; if (flags & 2) { /* header crc */ NEXT(); NEXT(); } /* an unexpected end of file is not checked for here -- it will be noticed on the first request for uncompressed data */ /* set up for decompression */ inflateReset(strm); strm->adler = crc32(0L, Z_NULL, 0); state->how = GZIP; state->direct = 0; return 0; } else { /* not a gzip file -- save first byte (31) and fall to raw i/o */ state->out[0] = 31; state->have = 1; } } /* doing raw i/o, save start of raw data for seeking, copy any leftover input to output -- this assumes that the output buffer is larger than the input buffer, which also assures space for gzungetc() */ state->raw = state->pos; state->next = state->out; if (strm->avail_in) { memcpy(state->next + state->have, strm->next_in, strm->avail_in); state->have += strm->avail_in; strm->avail_in = 0; } state->how = COPY; state->direct = 1; return 0; } /* Decompress from input to the provided next_out and avail_out in the state. If the end of the compressed data is reached, then verify the gzip trailer check value and length (modulo 2^32). state->have and state->next are set to point to the just decompressed data, and the crc is updated. If the trailer is verified, state->how is reset to LOOK to look for the next gzip stream or raw data, once state->have is depleted. Returns 0 on success, -1 on failure. Failures may include invalid compressed data or a failed gzip trailer verification. */ local int gz_decomp(state) gz_statep state; { int ret; unsigned had; unsigned long crc, len; z_streamp strm = &(state->strm); /* fill output buffer up to end of deflate stream */ had = strm->avail_out; do { /* get more input for inflate() */ if (strm->avail_in == 0 && gz_avail(state) == -1) return -1; if (strm->avail_in == 0) { gz_error(state, Z_DATA_ERROR, "unexpected end of file"); return -1; } /* decompress and handle errors */ ret = inflate(strm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { gz_error(state, Z_STREAM_ERROR, "internal error: inflate stream corrupt"); return -1; } if (ret == Z_MEM_ERROR) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ gz_error(state, Z_DATA_ERROR, strm->msg == NULL ? "compressed data error" : strm->msg); return -1; } } while (strm->avail_out && ret != Z_STREAM_END); /* update available output and crc check value */ state->have = had - strm->avail_out; state->next = strm->next_out - state->have; strm->adler = crc32(strm->adler, state->next, state->have); /* check gzip trailer if at end of deflate stream */ if (ret == Z_STREAM_END) { if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { gz_error(state, Z_DATA_ERROR, "unexpected end of file"); return -1; } if (crc != strm->adler) { gz_error(state, Z_DATA_ERROR, "incorrect data check"); return -1; } if (len != (strm->total_out & 0xffffffffL)) { gz_error(state, Z_DATA_ERROR, "incorrect length check"); return -1; } state->how = LOOK; /* ready for next stream, once have is 0 (leave state->direct unchanged to remember how) */ } /* good decompression */ return 0; } /* Make data and put in the output buffer. Assumes that state->have == 0. Data is either copied from the input file or decompressed from the input file depending on state->how. If state->how is LOOK, then a gzip header is looked for (and skipped if found) to determine wither to copy or decompress. Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY or GZIP unless the end of the input file has been reached and all data has been processed. */ local int gz_make(state) gz_statep state; { z_streamp strm = &(state->strm); if (state->how == LOOK) { /* look for gzip header */ if (gz_head(state) == -1) return -1; if (state->have) /* got some data from gz_head() */ return 0; } if (state->how == COPY) { /* straight copy */ if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1) return -1; state->next = state->out; } else if (state->how == GZIP) { /* decompress */ strm->avail_out = state->size << 1; strm->next_out = state->out; if (gz_decomp(state) == -1) return -1; } return 0; } /* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ local int gz_skip(state, len) gz_statep state; z_off64_t len; { unsigned n; /* skip over len bytes or reach end-of-file, whichever comes first */ while (len) /* skip over whatever is in output buffer */ if (state->have) { n = GT_OFF(state->have) || (z_off64_t)state->have > len ? (unsigned)len : state->have; state->have -= n; state->next += n; state->pos += n; len -= n; } /* output buffer empty -- return if we're at the end of the input */ else if (state->eof && state->strm.avail_in == 0) break; /* need more data to skip -- load up output buffer */ else { /* get more output, looking for header if required */ if (gz_make(state) == -1) return -1; } return 0; } /* -- see zlib.h -- */ int ZEXPORT gzread(file, buf, len) gzFile file; voidp buf; unsigned len; { unsigned got, n; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || state->err != Z_OK) return -1; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); return -1; } /* if len is zero, avoid unnecessary operations */ if (len == 0) return 0; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return -1; } /* get len bytes to buf, or less than len if at the end */ got = 0; do { /* first just try copying data from the output buffer */ if (state->have) { n = state->have > len ? len : state->have; memcpy(buf, state->next, n); state->next += n; state->have -= n; } /* output buffer empty -- return if we're at the end of the input */ else if (state->eof && strm->avail_in == 0) break; /* need output data -- for small len or new stream load up our output buffer */ else if (state->how == LOOK || len < (state->size << 1)) { /* get more output, looking for header if required */ if (gz_make(state) == -1) return -1; continue; /* no progress yet -- go back to memcpy() above */ /* the copy above assures that we will leave with space in the output buffer, allowing at least one gzungetc() to succeed */ } /* large len -- read directly into user buffer */ else if (state->how == COPY) { /* read directly */ if (gz_load(state, buf, len, &n) == -1) return -1; } /* large len -- decompress directly into user buffer */ else { /* state->how == GZIP */ strm->avail_out = len; strm->next_out = buf; if (gz_decomp(state) == -1) return -1; n = state->have; state->have = 0; } /* update progress */ len -= n; buf = (char *)buf + n; got += n; state->pos += n; } while (len); /* return number of bytes read into user buffer (will fit in int) */ return (int)got; } /* -- see zlib.h -- */ int ZEXPORT gzgetc(file) gzFile file; { int ret; unsigned char buf[1]; gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || state->err != Z_OK) return -1; /* try output buffer (no need to check for skip request) */ if (state->have) { state->have--; state->pos++; return *(state->next)++; } /* nothing there -- try gzread() */ ret = gzread(file, buf, 1); return ret < 1 ? -1 : buf[0]; } /* -- see zlib.h -- */ int ZEXPORT gzungetc(c, file) int c; gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || state->err != Z_OK) return -1; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return -1; } /* can't push EOF */ if (c < 0) return -1; /* if output buffer empty, put byte at end (allows more pushing) */ if (state->have == 0) { state->have = 1; state->next = state->out + (state->size << 1) - 1; state->next[0] = c; state->pos--; return c; } /* if no room, give up (must have already done a gzungetc()) */ if (state->have == (state->size << 1)) { gz_error(state, Z_BUF_ERROR, "out of room to push characters"); return -1; } /* slide output data if needed and insert byte before existing data */ if (state->next == state->out) { unsigned char *src = state->out + state->have; unsigned char *dest = state->out + (state->size << 1); while (src > state->out) *--dest = *--src; state->next = dest; } state->have++; state->next--; state->next[0] = c; state->pos--; return c; } /* -- see zlib.h -- */ char * ZEXPORT gzgets(file, buf, len) gzFile file; char *buf; int len; { unsigned left, n; char *str; unsigned char *eol; gz_statep state; /* check parameters and get internal structure */ if (file == NULL || buf == NULL || len < 1) return NULL; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || state->err != Z_OK) return NULL; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return NULL; } /* copy output bytes up to new line or len - 1, whichever comes first -- append a terminating zero to the string (we don't check for a zero in the contents, let the user worry about that) */ str = buf; left = (unsigned)len - 1; if (left) do { /* assure that something is in the output buffer */ if (state->have == 0) { if (gz_make(state) == -1) return NULL; /* error */ if (state->have == 0) { /* end of file */ if (buf == str) /* got bupkus */ return NULL; break; /* got something -- return it */ } } /* look for end-of-line in current output buffer */ n = state->have > left ? left : state->have; eol = memchr(state->next, '\n', n); if (eol != NULL) n = (unsigned)(eol - state->next) + 1; /* copy through end-of-line, or remainder if not found */ memcpy(buf, state->next, n); state->have -= n; state->next += n; state->pos += n; left -= n; buf += n; } while (left && eol == NULL); /* found end-of-line or out of space -- terminate string and return it */ buf[0] = 0; return str; } /* -- see zlib.h -- */ int ZEXPORT gzdirect(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're reading */ if (state->mode != GZ_READ) return 0; /* if the state is not known, but we can find out, then do so (this is mainly for right after a gzopen() or gzdopen()) */ if (state->how == LOOK && state->have == 0) (void)gz_head(state); /* return 1 if reading direct, 0 if decompressing a gzip stream */ return state->direct; } /* -- see zlib.h -- */ int ZEXPORT gzclose_r(file) gzFile file; { int ret; gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're reading */ if (state->mode != GZ_READ) return Z_STREAM_ERROR; /* free memory and close file */ if (state->size) { inflateEnd(&(state->strm)); free(state->out); free(state->in); } gz_error(state, Z_OK, NULL); free(state->path); ret = close(state->fd); free(state); return ret ? Z_ERRNO : Z_OK; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/gzwrite.c000066400000000000000000000344121462133141200225210ustar00rootroot00000000000000/* gzwrite.c -- zlib functions for writing gzip files * Copyright (C) 2004, 2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* Local functions */ local int gz_init OF((gz_statep)); local int gz_comp OF((gz_statep, int)); local int gz_zero OF((gz_statep, z_off64_t)); /* Initialize state for writing a gzip file. Mark initialization by setting state->size to non-zero. Return -1 on failure or 0 on success. */ local int gz_init(state) gz_statep state; { int ret; z_streamp strm = &(state->strm); /* allocate input and output buffers */ state->in = malloc(state->want); state->out = malloc(state->want); if (state->in == NULL || state->out == NULL) { if (state->out != NULL) free(state->out); if (state->in != NULL) free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* allocate deflate memory, set up for gzip compression */ strm->zalloc = Z_NULL; strm->zfree = Z_NULL; strm->opaque = Z_NULL; ret = deflateInit2(strm, state->level, Z_DEFLATED, 15 + 16, 8, state->strategy); if (ret != Z_OK) { free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* mark state as initialized */ state->size = state->want; /* initialize write buffer */ strm->avail_out = state->size; strm->next_out = state->out; state->next = strm->next_out; return 0; } /* Compress whatever is at avail_in and next_in and write to the output file. Return -1 if there is an error writing to the output file, otherwise 0. flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, then the deflate() state is reset to start a new gzip stream. */ local int gz_comp(state, flush) gz_statep state; int flush; { int ret, got; unsigned have; z_streamp strm = &(state->strm); /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return -1; /* run deflate() on provided input until it produces no more output */ ret = Z_OK; do { /* write out current buffer contents if full, or if flushing, but if doing Z_FINISH then don't write until we get to Z_STREAM_END */ if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && (flush != Z_FINISH || ret == Z_STREAM_END))) { have = (unsigned)(strm->next_out - state->next); if (have && ((got = write(state->fd, state->next, have)) < 0 || (unsigned)got != have)) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } if (strm->avail_out == 0) { strm->avail_out = state->size; strm->next_out = state->out; } state->next = strm->next_out; } /* compress */ have = strm->avail_out; ret = deflate(strm, flush); if (ret == Z_STREAM_ERROR) { gz_error(state, Z_STREAM_ERROR, "internal error: deflate stream corrupt"); return -1; } have -= strm->avail_out; } while (have); /* if that completed a deflate stream, allow another to start */ if (flush == Z_FINISH) deflateReset(strm); /* all done, no errors */ return 0; } /* Compress len zeros to output. Return -1 on error, 0 on success. */ local int gz_zero(state, len) gz_statep state; z_off64_t len; { int first; unsigned n; z_streamp strm = &(state->strm); /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return -1; /* compress len zeros (len guaranteed > 0) */ first = 1; while (len) { n = GT_OFF(state->size) || (z_off64_t)state->size > len ? (unsigned)len : state->size; if (first) { memset(state->in, 0, n); first = 0; } strm->avail_in = n; strm->next_in = state->in; state->pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return -1; len -= n; } return 0; } /* -- see zlib.h -- */ int ZEXPORT gzwrite(file, buf, len) gzFile file; voidpc buf; unsigned len; { unsigned put = len; unsigned n; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); return 0; } /* if len is zero, avoid unnecessary operations */ if (len == 0) return 0; /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return 0; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return 0; } /* for small len, copy to input buffer, otherwise compress directly */ if (len < state->size) { /* copy to input buffer, compress when full */ do { if (strm->avail_in == 0) strm->next_in = state->in; n = state->size - strm->avail_in; if (n > len) n = len; memcpy(strm->next_in + strm->avail_in, buf, n); strm->avail_in += n; state->pos += n; buf = (char *)buf + n; len -= n; if (len && gz_comp(state, Z_NO_FLUSH) == -1) return 0; } while (len); } else { /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return 0; /* directly compress user buffer to file */ strm->avail_in = len; strm->next_in = (voidp)buf; state->pos += len; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; } /* input was all buffered or compressed (put will fit in int) */ return (int)put; } /* -- see zlib.h -- */ int ZEXPORT gzputc(file, c) gzFile file; int c; { unsigned char buf[1]; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return -1; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return -1; } /* try writing to input buffer for speed (state->size == 0 if buffer not initialized) */ if (strm->avail_in < state->size) { if (strm->avail_in == 0) strm->next_in = state->in; strm->next_in[strm->avail_in++] = c; state->pos++; return c; } /* no room in buffer or not initialized, use gz_write() */ buf[0] = c; if (gzwrite(file, buf, 1) != 1) return -1; return c; } /* -- see zlib.h -- */ int ZEXPORT gzputs(file, str) gzFile file; const char *str; { int ret; unsigned len; /* write string */ len = (unsigned)strlen(str); ret = gzwrite(file, str, len); return ret == 0 && len != 0 ? -1 : ret; } #ifdef STDC #include /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) { int size, len; gz_statep state; z_streamp strm; va_list va; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return 0; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return 0; } /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return 0; /* do the printf() into the input buffer, put length in len */ size = (int)(state->size); state->in[size - 1] = 0; va_start(va, format); #ifdef NO_vsnprintf # ifdef HAS_vsprintf_void (void)vsprintf(state->in, format, va); va_end(va); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else len = vsprintf(state->in, format, va); va_end(va); # endif #else # ifdef HAS_vsnprintf_void (void)vsnprintf(state->in, size, format, va); va_end(va); len = strlen(state->in); # else len = vsnprintf((char *)(state->in), size, format, va); va_end(va); # endif #endif /* check that printf() results fit in buffer */ if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) return 0; /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; state->pos += len; return len; } #else /* !STDC */ /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) gzFile file; const char *format; int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; { int size, len; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return 0; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return 0; } /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return 0; /* do the printf() into the input buffer, put length in len */ size = (int)(state->size); state->in[size - 1] = 0; #ifdef NO_snprintf # ifdef HAS_sprintf_void sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #else # ifdef HAS_snprintf_void snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); len = strlen(state->in); # else len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #endif /* check that printf() results fit in buffer */ if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) return 0; /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; state->pos += len; return len; } #endif /* -- see zlib.h -- */ int ZEXPORT gzflush(file, flush) gzFile file; int flush; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* check flush parameter */ if (flush < 0 || flush > Z_FINISH) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return -1; } /* compress remaining data with requested flush */ gz_comp(state, flush); return state->err; } /* -- see zlib.h -- */ int ZEXPORT gzsetparams(file, level, strategy) gzFile file; int level; int strategy; { gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* if no change is requested, then do nothing */ if (level == state->level && strategy == state->strategy) return Z_OK; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return -1; } /* change compression parameters for subsequent input */ if (state->size) { /* flush previous input with previous parameters before changing */ if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1) return state->err; deflateParams(strm, level, strategy); } state->level = level; state->strategy = strategy; return Z_OK; } /* -- see zlib.h -- */ int ZEXPORT gzclose_w(file) gzFile file; { int ret = 0; gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're writing */ if (state->mode != GZ_WRITE) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; ret += gz_zero(state, state->skip); } /* flush, free memory, and close file */ ret += gz_comp(state, Z_FINISH); (void)deflateEnd(&(state->strm)); free(state->out); free(state->in); gz_error(state, Z_OK, NULL); free(state->path); ret += close(state->fd); free(state); return ret ? Z_ERRNO : Z_OK; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/infback.c000066400000000000000000000541361462133141200224300ustar00rootroot00000000000000/* infback.c -- inflate using a call-back interface * Copyright (C) 1995-2009 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* This code is largely copied from inflate.c. Normally either infback.o or inflate.o would be linked into an application--not both. The interface with inffast.c is retained so that optimized assembler-coded versions of inflate_fast() can be used with either inflate.c or infback.c. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); /* strm provides memory allocation functions in zalloc and zfree, or Z_NULL to use the library memory allocation functions. windowBits is in the range 8..15, and window is a user-supplied window and output buffer that is 2**windowBits bytes. */ int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) z_streamp strm; int windowBits; unsigned char FAR *window; const char *version; int stream_size; { struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL || window == Z_NULL || windowBits < 8 || windowBits > 15) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->dmax = 32768U; state->wbits = windowBits; state->wsize = 1U << windowBits; state->window = window; state->wnext = 0; state->whave = 0; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } /* Macros for inflateBack(): */ /* Load returned state from inflate_fast() */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Set state from registers for inflate_fast() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Assure that some input is available. If input is requested, but denied, then return a Z_BUF_ERROR from inflateBack(). */ #define PULL() \ do { \ if (have == 0) { \ have = in(in_desc, &next); \ if (have == 0) { \ next = Z_NULL; \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflateBack() with an error if there is no input available. */ #define PULLBYTE() \ do { \ PULL(); \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflateBack() with an error. */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Assure that some output space is available, by writing out the window if it's full. If the write fails, return from inflateBack() with a Z_BUF_ERROR. */ #define ROOM() \ do { \ if (left == 0) { \ put = state->window; \ left = state->wsize; \ state->whave = left; \ if (out(out_desc, put, left)) { \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* strm provides the memory allocation functions and window buffer on input, and provides information on the unused input on return. For Z_DATA_ERROR returns, strm will also provide an error message. in() and out() are the call-back input and output functions. When inflateBack() needs more input, it calls in(). When inflateBack() has filled the window with output, or when it completes with data in the window, it calls out() to write out the data. The application must not change the provided input until in() is called again or inflateBack() returns. The application must not change the window/output buffer until inflateBack() returns. in() and out() are called with a descriptor parameter provided in the inflateBack() call. This parameter can be a structure that provides the information required to do the read or write, as well as accumulated information on the input and output such as totals and check values. in() should return zero on failure. out() should return non-zero on failure. If either in() or out() fails, than inflateBack() returns a Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it was in() or out() that caused in the error. Otherwise, inflateBack() returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format error, or Z_MEM_ERROR if it could not allocate memory for the state. inflateBack() can also return Z_STREAM_ERROR if the input parameters are not correct, i.e. strm is Z_NULL or the state was not initialized. */ int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) z_streamp strm; in_func in; void FAR *in_desc; out_func out; void FAR *out_desc; { struct inflate_state FAR *state; unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* Check that the strm exists and that the state was initialized */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* Reset the state */ strm->msg = Z_NULL; state->mode = TYPE; state->last = 0; state->whave = 0; next = strm->next_in; have = next != Z_NULL ? strm->avail_in : 0; hold = 0; bits = 0; put = state->window; left = state->wsize; /* Inflate until end of block marked as last */ for (;;) switch (state->mode) { case TYPE: /* determine and dispatch block type */ if (state->last) { BYTEBITS(); state->mode = DONE; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN; /* decode codes */ break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: /* get and verify stored block length */ BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); /* copy stored block from input to output */ while (state->length != 0) { copy = state->length; PULL(); ROOM(); if (copy > have) copy = have; if (copy > left) copy = left; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: /* get dynamic table entries descriptor */ NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); /* get code length code lengths (not a typo) */ state->have = 0; while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); /* get length and distance code code lengths */ state->have = 0; while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = (unsigned)(state->lens[state->have - 1]); copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN; case LEN: /* use inflate_fast() if we have enough input and output */ if (have >= 6 && left >= 258) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; inflate_fast(strm, state->wsize); LOAD(); break; } /* get a literal, length, or end-of-block code */ for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); state->length = (unsigned)here.val; /* process literal */ if (here.op == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); ROOM(); *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; } /* process end of block */ if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } /* invalid code */ if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } /* length code -- get extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); } Tracevv((stderr, "inflate: length %u\n", state->length)); /* get distance code */ for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; /* get distance extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); } if (state->offset > state->wsize - (state->whave < state->wsize ? left : 0)) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } Tracevv((stderr, "inflate: distance %u\n", state->offset)); /* copy match from window to output */ do { ROOM(); copy = state->wsize - state->offset; if (copy < left) { from = put + copy; copy = left - copy; } else { from = put - state->offset; copy = left; } if (copy > state->length) copy = state->length; state->length -= copy; left -= copy; do { *put++ = *from++; } while (--copy); } while (state->length != 0); break; case DONE: /* inflate stream terminated properly -- write leftover output */ ret = Z_STREAM_END; if (left < state->wsize) { if (out(out_desc, state->window, state->wsize - left)) ret = Z_BUF_ERROR; } goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; default: /* can't happen, but makes compilers happy */ ret = Z_STREAM_ERROR; goto inf_leave; } /* Return unused input */ inf_leave: strm->next_in = next; strm->avail_in = have; return ret; } int ZEXPORT inflateBackEnd(strm) z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/inffast.c000066400000000000000000000321771462133141200224660ustar00rootroot00000000000000/* inffast.c -- fast decoding * Copyright (C) 1995-2008, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifndef ASMINF /* Allow machine dependent optimization for post-increment or pre-increment. Based on testing to date, Pre-increment preferred for: - PowerPC G3 (Adler) - MIPS R5000 (Randers-Pehrson) Post-increment preferred for: - none No measurable difference: - Pentium III (Anderson) - M68060 (Nikl) */ #ifdef POSTINC # define OFF 0 # define PUP(a) *(a)++ #else # define OFF 1 # define PUP(a) *++(a) #endif /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state->mode == LEN strm->avail_in >= 6 strm->avail_out >= 258 start >= strm->avail_out state->bits < 8 On return, state->mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { struct inflate_state FAR *state; unsigned char FAR *in; /* local strm->next_in */ unsigned char FAR *last; /* while in < last, enough input available */ unsigned char FAR *out; /* local strm->next_out */ unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ unsigned char FAR *end; /* while out < end, enough space available */ #ifdef INFLATE_STRICT unsigned dmax; /* maximum distance from zlib header */ #endif unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ unsigned long hold; /* local strm->hold */ unsigned bits; /* local strm->bits */ code const FAR *lcode; /* local strm->lencode */ code const FAR *dcode; /* local strm->distcode */ unsigned lmask; /* mask for first level of length codes */ unsigned dmask; /* mask for first level of distance codes */ code here; /* retrieved table entry */ unsigned op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ unsigned len; /* match length, unused bytes */ unsigned dist; /* match distance */ unsigned char FAR *from; /* where to copy match from */ /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; in = strm->next_in - OFF; last = in + (strm->avail_in - 5); out = strm->next_out - OFF; beg = out - (start - strm->avail_out); end = out + (strm->avail_out - 257); #ifdef INFLATE_STRICT dmax = state->dmax; #endif wsize = state->wsize; whave = state->whave; wnext = state->wnext; window = state->window; hold = state->hold; bits = state->bits; lcode = state->lencode; dcode = state->distcode; lmask = (1U << state->lenbits) - 1; dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ do { if (bits < 15) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; hold += (unsigned long)(PUP(in)) << bits; bits += 8; } here = lcode[hold & lmask]; dolen: op = (unsigned)(here.bits); hold >>= op; bits -= op; op = (unsigned)(here.op); if (op == 0) { /* literal */ Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); PUP(out) = (unsigned char)(here.val); } else if (op & 16) { /* length base */ len = (unsigned)(here.val); op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; } len += (unsigned)hold & ((1U << op) - 1); hold >>= op; bits -= op; } Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; hold += (unsigned long)(PUP(in)) << bits; bits += 8; } here = dcode[hold & dmask]; dodist: op = (unsigned)(here.bits); hold >>= op; bits -= op; op = (unsigned)(here.op); if (op & 16) { /* distance base */ dist = (unsigned)(here.val); op &= 15; /* number of extra bits */ if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; } } dist += (unsigned)hold & ((1U << op) - 1); #ifdef INFLATE_STRICT if (dist > dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif hold >>= op; bits -= op; Tracevv((stderr, "inflate: distance %u\n", dist)); op = (unsigned)(out - beg); /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR if (len <= op - whave) { do { PUP(out) = 0; } while (--len); continue; } len -= op - whave; do { PUP(out) = 0; } while (--op > whave); if (op == 0) { from = out - dist; do { PUP(out) = PUP(from); } while (--len); continue; } #endif } from = window - OFF; if (wnext == 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = window - OFF; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } while (len > 2) { PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } else { from = out - dist; /* copy direct from output */ do { /* minimum length is three */ PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } while (len > 2); if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } } else if ((op & 64) == 0) { /* 2nd level distance code */ here = dcode[here.val + (hold & ((1U << op) - 1))]; goto dodist; } else { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } } else if ((op & 64) == 0) { /* 2nd level length code */ here = lcode[here.val + (hold & ((1U << op) - 1))]; goto dolen; } else if (op & 32) { /* end-of-block */ Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } else { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } } while (in < last && out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; in -= len; bits -= len << 3; hold &= (1U << bits) - 1; /* update state and return */ strm->next_in = in + OFF; strm->next_out = out + OFF; strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); strm->avail_out = (unsigned)(out < end ? 257 + (end - out) : 257 - (out - end)); state->hold = hold; state->bits = bits; return; } /* inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - Using bit fields for code structure - Different op definition to avoid & for extra bits (do & for table bits) - Three separate decoding do-loops for direct, window, and wnext == 0 - Special case for distance > 1 copies to do overlapped load and store copy - Explicit branch predictions (based on measured branch probabilities) - Deferring match copy and interspersed it with decoding subsequent codes - Swapping literal/length else - Swapping window/direct else - Larger unrolled copy loops (three is about right) - Moving len -= 3 statement into middle of loop */ #endif /* !ASMINF */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/inffast.h000066400000000000000000000006531462133141200224650ustar00rootroot00000000000000/* inffast.h -- header to use inffast.c * Copyright (C) 1995-2003, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); bcmatroska2-5.3.101/corec/corec/helpers/zlib/inffixed.h000066400000000000000000000144451462133141200226330ustar00rootroot00000000000000 /* inffixed.h -- table for decoding fixed codes * Generated automatically by makefixed(). */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ static const code lenfix[512] = { {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, {0,9,255} }; static const code distfix[32] = { {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, {22,5,193},{64,5,0} }; bcmatroska2-5.3.101/corec/corec/helpers/zlib/inflate.c000066400000000000000000001466171462133141200224630ustar00rootroot00000000000000/* inflate.c -- zlib decompression * Copyright (C) 1995-2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * Change history: * * 1.2.beta0 24 Nov 2002 * - First version -- complete rewrite of inflate to simplify code, avoid * creation of window when not needed, minimize use of window when it is * needed, make inffast.c even faster, implement gzip decoding, and to * improve code readability and style over the previous zlib inflate code * * 1.2.beta1 25 Nov 2002 * - Use pointers for available input and output checking in inffast.c * - Remove input and output counters in inffast.c * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 * - Remove unnecessary second byte pull from length extra in inffast.c * - Unroll direct copy to three copies per loop in inffast.c * * 1.2.beta2 4 Dec 2002 * - Change external routine names to reduce potential conflicts * - Correct filename to inffixed.h for fixed tables in inflate.c * - Make hbuf[] unsigned char to match parameter type in inflate.c * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) * to avoid negation problem on Alphas (64 bit) in inflate.c * * 1.2.beta3 22 Dec 2002 * - Add comments on state->bits assertion in inffast.c * - Add comments on op field in inftrees.h * - Fix bug in reuse of allocated window after inflateReset() * - Remove bit fields--back to byte structure for speed * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths * - Change post-increments to pre-increments in inflate_fast(), PPC biased? * - Add compile time option, POSTINC, to use post-increments instead (Intel?) * - Make MATCH copy in inflate() much faster for when inflate_fast() not used * - Use local copies of stream next and avail values, as well as local bit * buffer and bit count in inflate()--for speed when inflate_fast() not used * * 1.2.beta4 1 Jan 2003 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings * - Move a comment on output buffer sizes from inffast.c to inflate.c * - Add comments in inffast.c to introduce the inflate_fast() routine * - Rearrange window copies in inflate_fast() for speed and simplification * - Unroll last copy for window match in inflate_fast() * - Use local copies of window variables in inflate_fast() for speed * - Pull out common wnext == 0 case for speed in inflate_fast() * - Make op and len in inflate_fast() unsigned for consistency * - Add FAR to lcode and dcode declarations in inflate_fast() * - Simplified bad distance check in inflate_fast() * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new * source file infback.c to provide a call-back interface to inflate for * programs like gzip and unzip -- uses window as output buffer to avoid * window copying * * 1.2.beta5 1 Jan 2003 * - Improved inflateBack() interface to allow the caller to provide initial * input in strm. * - Fixed stored blocks bug in inflateBack() * * 1.2.beta6 4 Jan 2003 * - Added comments in inffast.c on effectiveness of POSTINC * - Typecasting all around to reduce compiler warnings * - Changed loops from while (1) or do {} while (1) to for (;;), again to * make compilers happy * - Changed type of window in inflateBackInit() to unsigned char * * * 1.2.beta7 27 Jan 2003 * - Changed many types to unsigned or unsigned short to avoid warnings * - Added inflateCopy() function * * 1.2.0 9 Mar 2003 * - Changed inflateBack() interface to provide separate opaque descriptors * for the in() and out() functions * - Changed inflateBack() argument and in_func typedef to swap the length * and buffer address return values for the input function * - Check next_in and next_out for Z_NULL on entry to inflate() * * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifdef MAKEFIXED # ifndef BUILDFIXED # define BUILDFIXED # endif #endif /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); local int updatewindow OF((z_streamp strm, unsigned out)); #ifdef BUILDFIXED void makefixed OF((void)); #endif local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, unsigned len)); int ZEXPORT inflateReset(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->msg = Z_NULL; strm->adler = 1; /* to support ill-conceived Java test suite */ state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = Z_NULL; state->wsize = 0; state->whave = 0; state->wnext = 0; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; state->sane = 1; state->back = -1; Tracev((stderr, "inflate: reset\n")); return Z_OK; } int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; { int wrap; struct inflate_state FAR *state; /* get the state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; #ifdef GUNZIP if (windowBits < 48) windowBits &= 15; #endif } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) return Z_STREAM_ERROR; if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { ZFREE(strm, state->window); state->window = Z_NULL; } /* update state and reset the rest of it */ state->wrap = wrap; state->wbits = (unsigned)windowBits; return inflateReset(strm); } int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) z_streamp strm; int windowBits; const char *version; int stream_size; { int ret; struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->window = Z_NULL; ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); strm->state = Z_NULL; } return ret; } int ZEXPORT inflateInit_(strm, version, stream_size) z_streamp strm; const char *version; int stream_size; { return inflateInit2_(strm, DEF_WBITS, version, stream_size); } int ZEXPORT inflatePrime(strm, bits, value) z_streamp strm; int bits; int value; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (bits < 0) { state->hold = 0; state->bits = 0; return Z_OK; } if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; value &= (1L << bits) - 1; state->hold += value << state->bits; state->bits += bits; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } #ifdef MAKEFIXED #include /* Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also defines BUILDFIXED, so the tables are built on the fly. makefixed() writes those tables to stdout, which would be piped to inffixed.h. A small program can simply call makefixed to do this: void makefixed(void); int main(void) { makefixed(); return 0; } Then that can be linked with zlib built with MAKEFIXED defined and run: a.out > inffixed.h */ void makefixed() { unsigned low, size; struct inflate_state state; fixedtables(&state); puts(" /* inffixed.h -- table for decoding fixed codes"); puts(" * Generated automatically by makefixed()."); puts(" */"); puts(""); puts(" /* WARNING: this file should *not* be used by applications."); puts(" It is part of the implementation of this library and is"); puts(" subject to change. Applications should only use zlib.h."); puts(" */"); puts(""); size = 1U << 9; printf(" static const code lenfix[%u] = {", size); low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); size = 1U << 5; printf("\n static const code distfix[%u] = {", size); low = 0; for (;;) { if ((low % 6) == 0) printf("\n "); printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, state.distcode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); } #endif /* MAKEFIXED */ /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ local int updatewindow(strm, out) z_streamp strm; unsigned out; { struct inflate_state FAR *state; unsigned copy, dist; state = (struct inflate_state FAR *)strm->state; /* if it hasn't been done already, allocate space for the window */ if (state->window == Z_NULL) { state->window = (unsigned char FAR *) ZALLOC(strm, 1U << state->wbits, sizeof(unsigned char)); if (state->window == Z_NULL) return 1; } /* if window not in use yet, initialize */ if (state->wsize == 0) { state->wsize = 1U << state->wbits; state->wnext = 0; state->whave = 0; } /* copy state->wsize or less output bytes into the circular window */ copy = out - strm->avail_out; if (copy >= state->wsize) { zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); state->wnext = 0; state->whave = state->wsize; } else { dist = state->wsize - state->wnext; if (dist > copy) dist = copy; zmemcpy(state->window + state->wnext, strm->next_out - copy, dist); copy -= dist; if (copy) { zmemcpy(state->window, strm->next_out - copy, copy); state->wnext = copy; state->whave = state->wsize; } else { state->wnext += dist; if (state->wnext == state->wsize) state->wnext = 0; if (state->whave < state->wsize) state->whave += dist; } } return 0; } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #ifdef GUNZIP # define UPDATE(check, buf, len) \ (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) #else # define UPDATE(check, buf, len) adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP # define CRC2(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ check = crc32(check, hbuf, 2); \ } while (0) # define CRC4(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ hbuf[2] = (unsigned char)((word) >> 16); \ hbuf[3] = (unsigned char)((word) >> 24); \ check = crc32(check, hbuf, 4); \ } while (0) #endif /* Load registers with state in inflate() for speed */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Restore state from registers in inflate() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflate() if there is no input available. */ #define PULLBYTE() \ do { \ if (have == 0) goto inf_leave; \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflate(). */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Reverse the bytes in a 32-bit value */ #define REVERSE(q) \ ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is structured roughly as follows: for (;;) switch (state) { ... case STATEn: if (not enough input data or output space to make progress) return; ... make progress ... state = STATEm; break; ... } so when inflate() is called again, the same case is attempted again, and if the appropriate resources are provided, the machine proceeds to the next state. The NEEDBITS() macro is usually the way the state evaluates whether it can proceed or should return. NEEDBITS() does the return if the requested bits are not available. The typical use of the BITS macros is: NEEDBITS(n); ... do something with BITS(n) ... DROPBITS(n); where NEEDBITS(n) either returns from inflate() if there isn't enough input left to load n bits into the accumulator, or it continues. BITS(n) gives the low n bits in the accumulator. When done, DROPBITS(n) drops the low n bits off the accumulator. INITBITS() clears the accumulator and sets the number of available bits to zero. BYTEBITS() discards just enough bits to put the accumulator on a byte boundary. After BYTEBITS() and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return if there is no input available. The decoding of variable length codes uses PULLBYTE() directly in order to pull just enough bytes to decode the next code, and no more. Some states loop until they get enough input, making sure that enough state information is maintained to continue the loop where it left off if NEEDBITS() returns in the loop. For example, want, need, and keep would all have to actually be part of the saved state in case NEEDBITS() returns: case STATEw: while (want < need) { NEEDBITS(n); keep[want++] = BITS(n); DROPBITS(n); } state = STATEx; case STATEx: As shown above, if the next state is also the next case, then the break is omitted. A state may also return if there is not enough output space available to complete that state. Those states are copying stored data, writing a literal byte, and copying a matching string. When returning, a "goto inf_leave" is used to update the total counters, update the check value, and determine whether any progress has been made during that inflate() call in order to return the proper return code. Progress is defined as a change in either strm->avail_in or strm->avail_out. When there is a window, goto inf_leave will update the window with the last output written. If a goto inf_leave occurs in the middle of decompression and there is no window currently, goto inf_leave will create one and copy output to the window for the next call of inflate(). In this implementation, the flush parameter of inflate() only affects the return code (per zlib.h). inflate() always writes as much as possible to strm->next_out, given the space available and the provided input--the effect documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers the allocation of and copying into a sliding window until necessary, which provides the effect documented in zlib.h for Z_FINISH when the entire input stream available. So the only thing the flush parameter actually does is: when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it will return Z_BUF_ERROR if it has not reached the end of the stream. */ int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ state->check = crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } state->flags = 0; /* expect zlib header */ if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; else if (len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = TIME; case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if (state->flags & 0x0200) CRC4(state->check, hold); INITBITS(); state->mode = OS; case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if (hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = REVERSE(hold); INITBITS(); state->mode = DICT; case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = TYPE; case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; case COPY_: state->mode = COPY; case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; case LEN_: state->mode = LEN; case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if (out) strm->adler = state->check = UPDATE(state->check, put - out, out); out = left; if (( #ifdef GUNZIP state->flags ? hold : #endif REVERSE(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if (hold != (state->total & 0xffffffffUL)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) if (updatewindow(strm, out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if (state->wrap && out) strm->adler = state->check = UPDATE(state->check, strm->next_out - out, out); strm->data_type = state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } int ZEXPORT inflateEnd(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->window != Z_NULL) ZFREE(strm, state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; unsigned long id; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; /* check for correct dictionary id */ if (state->mode == DICT) { id = adler32(0L, Z_NULL, 0); id = adler32(id, dictionary, dictLength); if (id != state->check) return Z_DATA_ERROR; } /* copy dictionary to window */ if (updatewindow(strm, strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } if (dictLength > state->wsize) { zmemcpy(state->window, dictionary + dictLength - state->wsize, state->wsize); state->whave = state->wsize; } else { zmemcpy(state->window + state->wsize - dictLength, dictionary, dictLength); state->whave = dictLength; } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } int ZEXPORT inflateGetHeader(strm, head) z_streamp strm; gz_headerp head; { struct inflate_state FAR *state; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; /* save header structure */ state->head = head; head->done = 0; return Z_OK; } /* Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found or when out of input. When called, *have is the number of pattern bytes found in order so far, in 0..3. On return *have is updated to the new state. If on return *have equals four, then the pattern was found and the return value is how many bytes were read including the last byte of the pattern. If *have is less than four, then the pattern has not been found yet and the return value is len. In the latter case, syncsearch() can be called again with more data and the *have state. *have is initialized to zero for the first call. */ local unsigned syncsearch(have, buf, len) unsigned FAR *have; unsigned char FAR *buf; unsigned len; { unsigned got; unsigned next; got = *have; next = 0; while (next < len && got < 4) { if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) got++; else if (buf[next]) got = 0; else got = 4 - got; next++; } *have = got; return next; } int ZEXPORT inflateSync(strm) z_streamp strm; { unsigned len; /* number of bytes to look at or looked at */ unsigned long in, out; /* temporary to save total_in and total_out */ unsigned char buf[4]; /* to restore bit buffer to byte string */ struct inflate_state FAR *state; /* check parameters */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; /* if first time, start search in bit buffer */ if (state->mode != SYNC) { state->mode = SYNC; state->hold <<= state->bits & 7; state->bits -= state->bits & 7; len = 0; while (state->bits >= 8) { buf[len++] = (unsigned char)(state->hold); state->hold >>= 8; state->bits -= 8; } state->have = 0; syncsearch(&(state->have), buf, len); } /* search available input */ len = syncsearch(&(state->have), strm->next_in, strm->avail_in); strm->avail_in -= len; strm->next_in += len; strm->total_in += len; /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->mode = TYPE; return Z_OK; } /* Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored block. When decompressing, PPP checks that at the end of input packet, inflate is waiting for these length bytes. */ int ZEXPORT inflateSyncPoint(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; return state->mode == STORED && state->bits == 0; } int ZEXPORT inflateCopy(dest, source) z_streamp dest; z_streamp source; { struct inflate_state FAR *state; struct inflate_state FAR *copy; unsigned char FAR *window; unsigned wsize; /* check input */ if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); if (copy == Z_NULL) return Z_MEM_ERROR; window = Z_NULL; if (state->window != Z_NULL) { window = (unsigned char FAR *) ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); return Z_MEM_ERROR; } } /* copy state */ zmemcpy(dest, source, sizeof(z_stream)); zmemcpy(copy, state, sizeof(struct inflate_state)); if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); copy->distcode = copy->codes + (state->distcode - state->codes); } copy->next = copy->codes + (state->next - state->codes); if (window != Z_NULL) { wsize = 1U << state->wbits; zmemcpy(window, state->window, wsize); } copy->window = window; dest->state = (struct internal_state FAR *)copy; return Z_OK; } int ZEXPORT inflateUndermine(strm, subvert) z_streamp strm; int subvert; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; state->sane = !subvert; #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR return Z_OK; #else state->sane = 1; return Z_DATA_ERROR; #endif } long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } bcmatroska2-5.3.101/corec/corec/helpers/zlib/inflate.h000066400000000000000000000143771462133141200224650ustar00rootroot00000000000000/* inflate.h -- internal inflate state definition * Copyright (C) 1995-2009 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* define NO_GZIP when compiling if you want to disable gzip header and trailer decoding by inflate(). NO_GZIP would be used to avoid linking in the crc code when it is not needed. For shared libraries, gzip decoding should be left enabled. */ #ifndef NO_GZIP # define GUNZIP #endif /* Possible inflate modes between inflate() calls */ typedef enum { HEAD, /* i: waiting for magic header */ FLAGS, /* i: waiting for method and flags (gzip) */ TIME, /* i: waiting for modification time (gzip) */ OS, /* i: waiting for extra flags and operating system (gzip) */ EXLEN, /* i: waiting for extra length (gzip) */ EXTRA, /* i: waiting for extra bytes (gzip) */ NAME, /* i: waiting for end of file name (gzip) */ COMMENT, /* i: waiting for end of comment (gzip) */ HCRC, /* i: waiting for header crc (gzip) */ DICTID, /* i: waiting for dictionary check value */ DICT, /* waiting for inflateSetDictionary() call */ TYPE, /* i: waiting for type bits, including last-flag bit */ TYPEDO, /* i: same, but skip check to exit inflate on new block */ STORED, /* i: waiting for stored size (length and complement) */ COPY_, /* i/o: same as COPY below, but only first time in */ COPY, /* i/o: waiting for input or output to copy stored block */ TABLE, /* i: waiting for dynamic block table lengths */ LENLENS, /* i: waiting for code length code lengths */ CODELENS, /* i: waiting for length/lit and distance code lengths */ LEN_, /* i: same as LEN below, but only first time in */ LEN, /* i: waiting for length/lit/eob code */ LENEXT, /* i: waiting for length extra bits */ DIST, /* i: waiting for distance code */ DISTEXT, /* i: waiting for distance extra bits */ MATCH, /* o: waiting for output space to copy string */ LIT, /* o: waiting for output space to write literal */ CHECK, /* i: waiting for 32-bit check value */ LENGTH, /* i: waiting for 32-bit length (gzip) */ DONE, /* finished check, done -- remain here until reset */ BAD, /* got a data error -- remain here until reset */ MEM, /* got an inflate() memory error -- remain here until reset */ SYNC /* looking for synchronization bytes to restart inflate() */ } inflate_mode; /* State transitions between above modes - (most modes can go to BAD or MEM on error -- not shown for clarity) Process header: HEAD -> (gzip) or (zlib) or (raw) (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> HCRC -> TYPE (zlib) -> DICTID or TYPE DICTID -> DICT -> TYPE (raw) -> TYPEDO Read deflate blocks: TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK STORED -> COPY_ -> COPY -> TYPE TABLE -> LENLENS -> CODELENS -> LEN_ LEN_ -> LEN Read deflate codes in fixed or dynamic block: LEN -> LENEXT or LIT or TYPE LENEXT -> DIST -> DISTEXT -> MATCH -> LEN LIT -> LEN Process trailer: CHECK -> LENGTH -> DONE */ /* state maintained between inflate() calls. Approximately 10K bytes. */ struct inflate_state { inflate_mode mode; /* current inflate mode */ int last; /* true if processing last block */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int havedict; /* true if dictionary provided */ int flags; /* gzip header method and flags (0 if zlib) */ unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ unsigned long check; /* protected copy of check value */ unsigned long total; /* protected copy of output count */ gz_headerp head; /* where to save gzip header information */ /* sliding window */ unsigned wbits; /* log base 2 of requested window size */ unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if needed */ /* bit accumulator */ unsigned long hold; /* input bit accumulator */ unsigned bits; /* number of bits in "in" */ /* for string and stored block copying */ unsigned length; /* literal or length of data to copy */ unsigned offset; /* distance back to copy string from */ /* for table and code decoding */ unsigned extra; /* extra bits needed */ /* fixed and dynamic code tables */ code const FAR *lencode; /* starting table for length/literal codes */ code const FAR *distcode; /* starting table for distance codes */ unsigned lenbits; /* index bits for lencode */ unsigned distbits; /* index bits for distcode */ /* dynamic table building */ unsigned ncode; /* number of code length code lengths */ unsigned nlen; /* number of length code lengths */ unsigned ndist; /* number of distance code lengths */ unsigned have; /* number of code lengths in lens[] */ code FAR *next; /* next available space in codes[] */ unsigned short lens[320]; /* temporary storage for code lengths */ unsigned short work[288]; /* work area for code table building */ code codes[ENOUGH]; /* space for code tables */ int sane; /* if false, allow invalid distance too far */ int back; /* bits back of last unprocessed length/lit */ unsigned was; /* initial length of match */ }; bcmatroska2-5.3.101/corec/corec/helpers/zlib/inftrees.c000066400000000000000000000327111462133141200226450ustar00rootroot00000000000000/* inftrees.c -- generate Huffman trees for efficient decoding * Copyright (C) 1995-2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #define MAXBITS 15 const char inflate_copyright[] = " inflate 1.2.5 Copyright 1995-2010 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* Build a set of tables to decode the provided canonical Huffman code. The code lengths are lens[0..codes-1]. The result starts at *table, whose indices are 0..2^bits-1. work is a writable array of at least lens shorts, which is used as a work area. type is the type of code to be generated, CODES, LENS, or DISTS. On return, zero is success, -1 is an invalid code, and +1 means that ENOUGH isn't enough. table on return points to the next available entry's address. bits is the requested root table index bits, and on return it is the actual root table index bits. It will differ if the request is greater than the longest code or if it is less than the shortest code. */ int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) codetype type; unsigned short FAR *lens; unsigned codes; code FAR * FAR *table; unsigned FAR *bits; unsigned short FAR *work; { unsigned len; /* a code's length in bits */ unsigned sym; /* index of code symbols */ unsigned min, max; /* minimum and maximum code lengths */ unsigned root; /* number of index bits for root table */ unsigned curr; /* number of index bits for current table */ unsigned drop; /* code bits to drop for sub-table */ int left; /* number of prefix codes available */ unsigned used; /* code entries in table used */ unsigned huff; /* Huffman code */ unsigned incr; /* for incrementing code, index */ unsigned fill; /* index for replicating entries */ unsigned low; /* low bits for current root entry */ unsigned mask; /* mask for low root bits */ code here; /* table entry for duplication */ code FAR *next; /* next available space in table */ const unsigned short FAR *base; /* base value table to use */ const unsigned short FAR *extra; /* extra bits table to use */ int end; /* use base and extra for symbol > end */ unsigned short count[MAXBITS+1]; /* number of codes of each length */ unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ static const unsigned short lbase[31] = { /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64}; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) count[len] = 0; for (sym = 0; sym < codes; sym++) count[lens[sym]]++; /* bound code lengths, force root to be within code lengths */ root = *bits; for (max = MAXBITS; max >= 1; max--) if (count[max] != 0) break; if (root > max) root = max; if (max == 0) { /* no symbols to code at all */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)1; here.val = (unsigned short)0; *(*table)++ = here; /* make a table to force an error */ *(*table)++ = here; *bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) if (count[min] != 0) break; if (root < min) root = min; /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) return -1; /* over-subscribed */ } if (left > 0 && (type == CODES || max != 1)) return -1; /* incomplete set */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + count[len]; /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ switch (type) { case CODES: base = extra = work; /* dummy value--not used */ end = 19; break; case LENS: base = lbase; base -= 257; extra = lext; extra -= 257; end = 256; break; default: /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize state for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = *table; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = (unsigned)(-1); /* trigger new sub-table when len > root */ used = 1U << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type == LENS && used >= ENOUGH_LENS) || (type == DISTS && used >= ENOUGH_DISTS)) return 1; /* process all codes and make table entries */ for (;;) { /* create table entry */ here.bits = (unsigned char)(len - drop); if ((int)(work[sym]) < end) { here.op = (unsigned char)0; here.val = work[sym]; } else if ((int)(work[sym]) > end) { here.op = (unsigned char)(extra[work[sym]]); here.val = base[work[sym]]; } else { here.op = (unsigned char)(32 + 64); /* end of block */ here.val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1U << (len - drop); fill = 1U << curr; min = fill; /* save offset to next table */ do { fill -= incr; next[(huff >> drop) + fill] = here; } while (fill != 0); /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; /* go to next symbol, update count, len */ sym++; if (--(count[len]) == 0) { if (len == max) break; len = lens[work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) != low) { /* if first time, transition to sub-tables */ if (drop == 0) drop = root; /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = (int)(1 << curr); while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) break; curr++; left <<= 1; } /* check for enough space */ used += 1U << curr; if ((type == LENS && used >= ENOUGH_LENS) || (type == DISTS && used >= ENOUGH_DISTS)) return 1; /* point entry in root table to sub-table */ low = huff & mask; (*table)[low].op = (unsigned char)curr; (*table)[low].bits = (unsigned char)root; (*table)[low].val = (unsigned short)(next - *table); } } /* Fill in rest of table for incomplete codes. This loop is similar to the loop above in incrementing huff for table indices. It is assumed that len is equal to curr + drop, so there is no loop needed to increment through high index bits. When the current sub-table is filled, the loop drops back to the root table to fill in any remaining entries there. */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)(len - drop); here.val = (unsigned short)0; while (huff != 0) { /* when done with sub-table, drop back to root table */ if (drop != 0 && (huff & mask) != low) { drop = 0; len = root; next = *table; here.bits = (unsigned char)len; } /* put invalid code marker in table */ next[huff >> drop] = here; /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; } /* set return parameters */ *table += used; *bits = root; return 0; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/inftrees.h000066400000000000000000000055601462133141200226540ustar00rootroot00000000000000/* inftrees.h -- header to use inftrees.c * Copyright (C) 1995-2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* Structure for decoding tables. Each entry provides either the information needed to do the operation requested by the code that indexed that table entry, or it provides a pointer to another table that indexes more bits of the code. op indicates whether the entry is a pointer to another table, a literal, a length or distance, an end-of-block, or an invalid code. For a table pointer, the low four bits of op is the number of index bits of that table. For a length or distance, the low four bits of op is the number of extra bits to get after the code. bits is the number of bits in this code or part of the code to drop off of the bit buffer. val is the actual byte to output in the case of a literal, the base length or distance, or the offset from the current table to the next table. Each entry is four bytes. */ typedef struct { unsigned char op; /* operation, extra bits, table bits */ unsigned char bits; /* bits in this part of the code */ unsigned short val; /* offset in table or code value */ } code; /* op values as set by inflate_table(): 00000000 - literal 0000tttt - table link, tttt != 0 is the number of table index bits 0001eeee - length or distance, eeee is the number of extra bits 01100000 - end of block 01000000 - invalid code */ /* Maximum size of the dynamic table. The maximum number of code structures is 1444, which is the sum of 852 for literal/length codes and 592 for distance codes. These values were found by exhaustive searches using the program examples/enough.c found in the zlib distribtution. The arguments to that program are the number of symbols, the initial root table size, and the maximum bit length of a code. "enough 286 9 15" for literal/length codes returns returns 852, and "enough 30 6 15" for distance codes returns 592. The initial root table size (9 or 6) is found in the fifth argument of the inflate_table() calls in inflate.c and infback.c. If the root table size is changed, then these maximum sizes would be need to be recalculated and updated. */ #define ENOUGH_LENS 852 #define ENOUGH_DISTS 592 #define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) /* Type of code to build for inflate_table() */ typedef enum { CODES, LENS, DISTS } codetype; int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, unsigned codes, code FAR * FAR *table, unsigned FAR *bits, unsigned short FAR *work)); bcmatroska2-5.3.101/corec/corec/helpers/zlib/minigzip.c000066400000000000000000000257201462133141200226560ustar00rootroot00000000000000/* minigzip.c -- simulate gzip using the zlib compression library * Copyright (C) 1995-2006, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* * minigzip is a minimal implementation of the gzip utility. This is * only an example of using zlib and isn't meant to replace the * full-featured gzip. No attempt is made to deal with file systems * limiting names to 14 or 8+3 characters, etc... Error checking is * very limited. So use minigzip only for testing; use gzip for the * real thing. On MSDOS, use only on file names without extension * or in pipe mode. */ /* @(#) $Id$ */ #include "zlib.h" #include #ifdef STDC # include # include #endif #ifdef USE_MMAP # include # include # include #endif #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) # include # include # ifdef UNDER_CE # include # endif # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else # define SET_BINARY_MODE(file) #endif #ifdef VMS # define unlink delete # define GZ_SUFFIX "-gz" #endif #ifdef RISCOS # define unlink remove # define GZ_SUFFIX "-gz" # define fileno(file) file->__file #endif #if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os # include /* for fileno */ #endif #if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) #ifndef WIN32 /* unlink already in stdio.h for WIN32 */ extern int unlink OF((const char *)); #endif #endif #if defined(UNDER_CE) # include # define perror(s) pwinerror(s) /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come from GetLastError. The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to strwinerror The strwinerror function does not change the current setting of GetLastError. */ static char *strwinerror (error) DWORD error; { static char buf[1024]; wchar_t *msgbuf; DWORD lasterr = GetLastError(); DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, /* Default language */ (LPVOID)&msgbuf, 0, NULL); if (chars != 0) { /* If there is an \r\n appended, zap it. */ if (chars >= 2 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { chars -= 2; msgbuf[chars] = 0; } if (chars > sizeof (buf) - 1) { chars = sizeof (buf) - 1; msgbuf[chars] = 0; } wcstombs(buf, msgbuf, chars + 1); LocalFree(msgbuf); } else { sprintf(buf, "unknown win32 error (%ld)", error); } SetLastError(lasterr); return buf; } static void pwinerror (s) const char *s; { if (s && *s) fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); else fprintf(stderr, "%s\n", strwinerror(GetLastError ())); } #endif /* UNDER_CE */ #ifndef GZ_SUFFIX # define GZ_SUFFIX ".gz" #endif #define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) #define BUFLEN 16384 #define MAX_NAME_LEN 1024 #ifdef MAXSEG_64K # define local static /* Needed for systems with limitation on stack size. */ #else # define local #endif char *prog; void error OF((const char *msg)); void gz_compress OF((FILE *in, gzFile out)); #ifdef USE_MMAP int gz_compress_mmap OF((FILE *in, gzFile out)); #endif void gz_uncompress OF((gzFile in, FILE *out)); void file_compress OF((char *file, char *mode)); void file_uncompress OF((char *file)); int main OF((int argc, char *argv[])); /* =========================================================================== * Display error message and exit */ void error(msg) const char *msg; { fprintf(stderr, "%s: %s\n", prog, msg); exit(1); } /* =========================================================================== * Compress input to output then close both files. */ void gz_compress(in, out) FILE *in; gzFile out; { local char buf[BUFLEN]; int len; int err; #ifdef USE_MMAP /* Try first compressing with mmap. If mmap fails (minigzip used in a * pipe), use the normal fread loop. */ if (gz_compress_mmap(in, out) == Z_OK) return; #endif for (;;) { len = (int)fread(buf, 1, sizeof(buf), in); if (ferror(in)) { perror("fread"); exit(1); } if (len == 0) break; if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); } fclose(in); if (gzclose(out) != Z_OK) error("failed gzclose"); } #ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ /* Try compressing the input file at once using mmap. Return Z_OK if * if success, Z_ERRNO otherwise. */ int gz_compress_mmap(in, out) FILE *in; gzFile out; { int len; int err; int ifd = fileno(in); caddr_t buf; /* mmap'ed buffer for the entire input file */ off_t buf_len; /* length of the input file */ struct stat sb; /* Determine the size of the file, needed for mmap: */ if (fstat(ifd, &sb) < 0) return Z_ERRNO; buf_len = sb.st_size; if (buf_len <= 0) return Z_ERRNO; /* Now do the actual mmap: */ buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); if (buf == (caddr_t)(-1)) return Z_ERRNO; /* Compress the whole file at once: */ len = gzwrite(out, (char *)buf, (unsigned)buf_len); if (len != (int)buf_len) error(gzerror(out, &err)); munmap(buf, buf_len); fclose(in); if (gzclose(out) != Z_OK) error("failed gzclose"); return Z_OK; } #endif /* USE_MMAP */ /* =========================================================================== * Uncompress input to output then close both files. */ void gz_uncompress(in, out) gzFile in; FILE *out; { local char buf[BUFLEN]; int len; int err; for (;;) { len = gzread(in, buf, sizeof(buf)); if (len < 0) error (gzerror(in, &err)); if (len == 0) break; if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { error("failed fwrite"); } } if (fclose(out)) error("failed fclose"); if (gzclose(in) != Z_OK) error("failed gzclose"); } /* =========================================================================== * Compress the given file: create a corresponding .gz file and remove the * original. */ void file_compress(file, mode) char *file; char *mode; { local char outfile[MAX_NAME_LEN]; FILE *in; gzFile out; if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { fprintf(stderr, "%s: filename too long\n", prog); exit(1); } strcpy(outfile, file); strcat(outfile, GZ_SUFFIX); in = fopen(file, "rb"); if (in == NULL) { perror(file); exit(1); } out = gzopen(outfile, mode); if (out == NULL) { fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); exit(1); } gz_compress(in, out); unlink(file); } /* =========================================================================== * Uncompress the given file and remove the original. */ void file_uncompress(file) char *file; { local char buf[MAX_NAME_LEN]; char *infile, *outfile; FILE *out; gzFile in; size_t len = strlen(file); if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { fprintf(stderr, "%s: filename too long\n", prog); exit(1); } strcpy(buf, file); if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { infile = file; outfile = buf; outfile[len-3] = '\0'; } else { outfile = file; infile = buf; strcat(infile, GZ_SUFFIX); } in = gzopen(infile, "rb"); if (in == NULL) { fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); exit(1); } out = fopen(outfile, "wb"); if (out == NULL) { perror(file); exit(1); } gz_uncompress(in, out); unlink(infile); } /* =========================================================================== * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] * -c : write to standard output * -d : decompress * -f : compress with Z_FILTERED * -h : compress with Z_HUFFMAN_ONLY * -r : compress with Z_RLE * -1 to -9 : compression level */ int main(argc, argv) int argc; char *argv[]; { int copyout = 0; int uncompr = 0; gzFile file; char *bname, outmode[20]; strcpy(outmode, "wb6 "); prog = argv[0]; bname = strrchr(argv[0], '/'); if (bname) bname++; else bname = argv[0]; argc--, argv++; if (!strcmp(bname, "gunzip")) uncompr = 1; else if (!strcmp(bname, "zcat")) copyout = uncompr = 1; while (argc > 0) { if (strcmp(*argv, "-c") == 0) copyout = 1; else if (strcmp(*argv, "-d") == 0) uncompr = 1; else if (strcmp(*argv, "-f") == 0) outmode[3] = 'f'; else if (strcmp(*argv, "-h") == 0) outmode[3] = 'h'; else if (strcmp(*argv, "-r") == 0) outmode[3] = 'R'; else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && (*argv)[2] == 0) outmode[2] = (*argv)[1]; else break; argc--, argv++; } if (outmode[3] == ' ') outmode[3] = 0; if (argc == 0) { SET_BINARY_MODE(stdin); SET_BINARY_MODE(stdout); if (uncompr) { file = gzdopen(fileno(stdin), "rb"); if (file == NULL) error("can't gzdopen stdin"); gz_uncompress(file, stdout); } else { file = gzdopen(fileno(stdout), outmode); if (file == NULL) error("can't gzdopen stdout"); gz_compress(stdin, file); } } else { if (copyout) { SET_BINARY_MODE(stdout); } do { if (uncompr) { if (copyout) { file = gzopen(*argv, "rb"); if (file == NULL) fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); else gz_uncompress(file, stdout); } else { file_uncompress(*argv); } } else { if (copyout) { FILE * in = fopen(*argv, "rb"); if (in == NULL) { perror(*argv); } else { file = gzdopen(fileno(stdout), outmode); if (file == NULL) error("can't gzdopen stdout"); gz_compress(in, file); } } else { file_compress(*argv, outmode); } } } while (argv++, --argc); } return 0; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/trees.c000066400000000000000000001302721462133141200221510ustar00rootroot00000000000000/* trees.c -- output deflated data using Huffman coding * Copyright (C) 1995-2010 Jean-loup Gailly * detect_data_type() function provided freely by Cosmin Truta, 2006 * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process uses several Huffman trees. The more * common source values are represented by shorter bit sequences. * * Each code tree is stored in a compressed form which is itself * a Huffman encoding of the lengths of all the code strings (in * ascending order by source values). The actual code strings are * reconstructed from the lengths in the inflate process, as described * in the deflate specification. * * REFERENCES * * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc * * Storer, James A. * Data Compression: Methods and Theory, pp. 49-50. * Computer Science Press, 1988. ISBN 0-7167-8156-5. * * Sedgewick, R. * Algorithms, p290. * Addison-Wesley, 1983. ISBN 0-201-06672-6. */ /* @(#) $Id$ */ /* #define GEN_TREES_H */ #include "deflate.h" #ifdef DEBUG # include #endif /* =========================================================================== * Constants */ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define END_BLOCK 256 /* end of block literal code */ #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; local const int extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; local const uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ #define Buf_size (8 * 2*sizeof(char)) /* Number of bits used within bi_buf. (bi_buf might be implemented on * more than 16 bits on some systems.) */ /* =========================================================================== * Local data. These are initialized only once. */ #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ #if defined(GEN_TREES_H) || !defined(STDC) /* non ANSI compilers may not accept trees.h */ local ct_data static_ltree[L_CODES+2]; /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ local ct_data static_dtree[D_CODES]; /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ uch _dist_code[DIST_CODE_LEN]; /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ uch _length_code[MAX_MATCH-MIN_MATCH+1]; /* length code for each normalized match length (0 == MIN_MATCH) */ local int base_length[LENGTH_CODES]; /* First normalized length for each code (0 = MIN_MATCH) */ local int base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ #else # include "trees.h" #endif /* GEN_TREES_H */ struct static_tree_desc_s { const ct_data *static_tree; /* static tree or NULL */ const intf *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ }; local static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; local static_tree_desc static_d_desc = {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; local static_tree_desc static_bl_desc = {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; /* =========================================================================== * Local (static) routines in this file. */ local void tr_static_init OF((void)); local void init_block OF((deflate_state *s)); local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); local void build_tree OF((deflate_state *s, tree_desc *desc)); local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); local int build_bl_tree OF((deflate_state *s)); local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, int blcodes)); local void compress_block OF((deflate_state *s, ct_data *ltree, ct_data *dtree)); local int detect_data_type OF((deflate_state *s)); local unsigned bi_reverse OF((unsigned value, int length)); local void bi_windup OF((deflate_state *s)); local void bi_flush OF((deflate_state *s)); local void copy_block OF((deflate_state *s, charf *buf, unsigned len, int header)); #ifdef GEN_TREES_H local void gen_trees_header OF((void)); #endif #ifndef DEBUG # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) /* Send a code of the given tree. c and tree must not have side effects */ #else /* DEBUG */ # define send_code(s, c, tree) \ { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(s, tree[c].Code, tree[c].Len); } #endif /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ #define put_short(s, w) { \ put_byte(s, (uch)((w) & 0xff)); \ put_byte(s, (uch)((ush)(w) >> 8)); \ } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ #ifdef DEBUG local void send_bits OF((deflate_state *s, int value, int length)); local void send_bits(s, value, length) deflate_state *s; int value; /* value to send */ int length; /* number of bits */ { Tracevv((stderr," l %2d v %4x ", length, value)); Assert(length > 0 && length <= 15, "invalid length"); s->bits_sent += (ulg)length; /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) * unused bits in value. */ if (s->bi_valid > (int)Buf_size - length) { s->bi_buf |= (ush)value << s->bi_valid; put_short(s, s->bi_buf); s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); s->bi_valid += length - Buf_size; } else { s->bi_buf |= (ush)value << s->bi_valid; s->bi_valid += length; } } #else /* !DEBUG */ #define send_bits(s, value, length) \ { int len = length;\ if (s->bi_valid > (int)Buf_size - len) {\ int val = value;\ s->bi_buf |= (ush)val << s->bi_valid;\ put_short(s, s->bi_buf);\ s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ s->bi_valid += len - Buf_size;\ } else {\ s->bi_buf |= (ush)(value) << s->bi_valid;\ s->bi_valid += len;\ }\ } #endif /* DEBUG */ /* the arguments must not have side effects */ /* =========================================================================== * Initialize the various 'constant' tables. */ local void tr_static_init() { #if defined(GEN_TREES_H) || !defined(STDC) static int static_init_done = 0; int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ #ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1< dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = bi_reverse((unsigned)n, 5); } static_init_done = 1; # ifdef GEN_TREES_H gen_trees_header(); # endif #endif /* defined(GEN_TREES_H) || !defined(STDC) */ } /* =========================================================================== * Genererate the file trees.h describing the static trees. */ #ifdef GEN_TREES_H # ifndef DEBUG # include # endif # define SEPARATOR(i, last, width) \ ((i) == (last)? "\n};\n\n" : \ ((i) % (width) == (width)-1 ? ",\n" : ", ")) void gen_trees_header() { FILE *header = fopen("trees.h", "w"); int i; Assert (header != NULL, "Can't open trees.h"); fprintf(header, "/* header created automatically with -DGEN_TREES_H */\n\n"); fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); for (i = 0; i < L_CODES+2; i++) { fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); } fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); } fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); for (i = 0; i < DIST_CODE_LEN; i++) { fprintf(header, "%2u%s", _dist_code[i], SEPARATOR(i, DIST_CODE_LEN-1, 20)); } fprintf(header, "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { fprintf(header, "%2u%s", _length_code[i], SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); } fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); for (i = 0; i < LENGTH_CODES; i++) { fprintf(header, "%1u%s", base_length[i], SEPARATOR(i, LENGTH_CODES-1, 20)); } fprintf(header, "local const int base_dist[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "%5u%s", base_dist[i], SEPARATOR(i, D_CODES-1, 10)); } fclose(header); } #endif /* GEN_TREES_H */ /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ void ZLIB_INTERNAL _tr_init(s) deflate_state *s; { tr_static_init(); s->l_desc.dyn_tree = s->dyn_ltree; s->l_desc.stat_desc = &static_l_desc; s->d_desc.dyn_tree = s->dyn_dtree; s->d_desc.stat_desc = &static_d_desc; s->bl_desc.dyn_tree = s->bl_tree; s->bl_desc.stat_desc = &static_bl_desc; s->bi_buf = 0; s->bi_valid = 0; s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG s->compressed_len = 0L; s->bits_sent = 0L; #endif /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Initialize a new block. */ local void init_block(s) deflate_state *s; { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->last_lit = s->matches = 0; } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(s, tree, top) \ {\ top = s->heap[SMALLEST]; \ s->heap[SMALLEST] = s->heap[s->heap_len--]; \ pqdownheap(s, tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m, depth) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ local void pqdownheap(s, tree, k) deflate_state *s; ct_data *tree; /* the tree to restore */ int k; /* node to move down */ { int v = s->heap[k]; int j = k << 1; /* left son of k */ while (j <= s->heap_len) { /* Set j to the smallest of the two sons: */ if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s->heap[j], s->depth)) break; /* Exchange v with the smallest son */ s->heap[k] = s->heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s->heap[k] = v; } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ local void gen_bitlen(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; int max_code = desc->max_code; const ct_data *stree = desc->stat_desc->static_tree; const intf *extra = desc->stat_desc->extra_bits; int base = desc->stat_desc->extra_base; int max_length = desc->stat_desc->max_length; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ for (h = s->heap_max+1; h < HEAP_SIZE; h++) { n = s->heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s->bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; s->opt_len += (ulg)f * (bits + xbits); if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); } if (overflow == 0) return; Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s->bl_count[bits] == 0) bits--; s->bl_count[bits]--; /* move one leaf down the tree */ s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ s->bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = s->bl_count[bits]; while (n != 0) { m = s->heap[--h]; if (m > max_code) continue; if ((unsigned) tree[m].Len != (unsigned) bits) { Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s->opt_len += ((long)bits - (long)tree[m].Len) *(long)tree[m].Freq; tree[m].Len = (ush)bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ local void gen_codes (tree, max_code, bl_count) ct_data *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */ ushf *bl_count; /* number of codes at each bit length */ { ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ush code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; const ct_data *stree = desc->stat_desc->static_tree; int elems = desc->stat_desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s->heap_len = 0, s->heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { s->heap[++(s->heap_len)] = max_code = n; s->depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s->heap_len < 2) { node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); tree[node].Freq = 1; s->depth[node] = 0; s->opt_len--; if (stree) s->static_len -= stree[node].Len; /* node is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { pqremove(s, tree, n); /* n = node of least frequency */ m = s->heap[SMALLEST]; /* m = node of next least frequency */ s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ s->heap[--(s->heap_max)] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? s->depth[n] : s->depth[m]) + 1); tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE if (tree == s->bl_tree) { fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); } #endif /* and insert the new node in the heap */ s->heap[SMALLEST] = node++; pqdownheap(s, tree, SMALLEST); } while (s->heap_len >= 2); s->heap[--(s->heap_max)] = s->heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, (tree_desc *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data *)tree, max_code, s->bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ local void scan_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (ush)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { s->bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) s->bl_tree[curlen].Freq++; s->bl_tree[REP_3_6].Freq++; } else if (count <= 10) { s->bl_tree[REPZ_3_10].Freq++; } else { s->bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ local void send_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s->bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(s, curlen, s->bl_tree); count--; } Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ local int build_bl_tree(s) deflate_state *s; { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); /* Build the bit length tree: */ build_tree(s, (tree_desc *)(&(s->bl_desc))); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ s->opt_len += 3*(max_blindex+1) + 5+5+4; Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ local void send_all_trees(s, lcodes, dcodes, blcodes) deflate_state *s; int lcodes, dcodes, blcodes; /* number of codes for each tree */ { int rank; /* index in bl_order */ Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); } Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Send a stored block */ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ #ifdef DEBUG s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; s->compressed_len += (stored_len + 4) << 3; #endif copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. * The current inflate code requires 9 bits of lookahead. If the * last two codes for the previous block (real code plus EOB) were coded * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode * the last real code. In this case we send two empty static blocks instead * of one. (There are no problems if the previous block is stored or fixed.) * To simplify the code, we assume the worst case of last real code encoded * on one bit only. */ void ZLIB_INTERNAL _tr_align(s) deflate_state *s; { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif bi_flush(s); /* Of the 10 bits for the empty block, we have already sent * (10 - bi_valid) bits. The lookahead for the last real code (before * the EOB of the previous block) was thus at least one plus the length * of the EOB plus what we have just sent of the empty static block. */ if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG s->compressed_len += 10L; #endif bi_flush(s); } s->last_eob_len = 7; } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { /* Check if the file is binary or text */ if (s->strm->data_type == Z_UNKNOWN) s->strm->data_type = detect_data_type(s); /* Construct the literal and distance trees */ build_tree(s, (tree_desc *)(&(s->l_desc))); Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, s->static_len)); build_tree(s, (tree_desc *)(&(s->d_desc))); Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->last_lit)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } #ifdef FORCE_STORED if (buf != (char*)0) { /* force stored block */ #else if (stored_len+4 <= opt_lenb && buf != (char*)0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); #ifdef FORCE_STATIC } else if (static_lenb >= 0) { /* force static trees */ #else } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { #endif send_bits(s, (STATIC_TREES<<1)+last, 3); compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); #ifdef DEBUG s->compressed_len += 3 + s->static_len; #endif } else { send_bits(s, (DYN_TREES<<1)+last, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); #ifdef DEBUG s->compressed_len += 3 + s->opt_len; #endif } Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); #ifdef DEBUG s->compressed_len += 7; /* align on byte boundary */ #endif } Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ int ZLIB_INTERNAL _tr_tally (s, dist, lc) deflate_state *s; unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { s->d_buf[s->last_lit] = (ush)dist; s->l_buf[s->last_lit++] = (uch)lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; } else { s->matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ Assert((ush)dist < (ush)MAX_DIST(s) && (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } #ifdef TRUNCATE_BLOCK /* Try to guess if it is profitable to stop the current block here */ if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { /* Compute an upper bound for the compressed length */ ulg out_length = (ulg)s->last_lit*8L; ulg in_length = (ulg)((long)s->strstart - s->block_start); int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += (ulg)s->dyn_dtree[dcode].Freq * (5L+extra_dbits[dcode]); } out_length >>= 3; Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", s->last_lit, in_length, out_length, 100L - out_length*100L/in_length)); if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; } #endif return (s->last_lit == s->lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ local void compress_block(s, ltree, dtree) deflate_state *s; ct_data *ltree; /* literal tree */ ct_data *dtree; /* distance tree */ { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ unsigned lx = 0; /* running index in l_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (s->last_lit != 0) do { dist = s->d_buf[lx]; lc = s->l_buf[lx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, "pendingBuf overflow"); } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ local int detect_data_type(s) deflate_state *s; { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ unsigned long black_mask = 0xf3ffc07fUL; int n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>= 1) if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) return Z_BINARY; /* Check for textual ("white-listed") bytes. */ if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0) return Z_TEXT; for (n = 32; n < LITERALS; n++) if (s->dyn_ltree[n].Freq != 0) return Z_TEXT; /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ local unsigned bi_reverse(code, len) unsigned code; /* the value to invert */ int len; /* its bit length */ { register unsigned res = 0; do { res |= code & 1; code >>= 1, res <<= 1; } while (--len > 0); return res >> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ local void bi_flush(s) deflate_state *s; { if (s->bi_valid == 16) { put_short(s, s->bi_buf); s->bi_buf = 0; s->bi_valid = 0; } else if (s->bi_valid >= 8) { put_byte(s, (Byte)s->bi_buf); s->bi_buf >>= 8; s->bi_valid -= 8; } } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ local void bi_windup(s) deflate_state *s; { if (s->bi_valid > 8) { put_short(s, s->bi_buf); } else if (s->bi_valid > 0) { put_byte(s, (Byte)s->bi_buf); } s->bi_buf = 0; s->bi_valid = 0; #ifdef DEBUG s->bits_sent = (s->bits_sent+7) & ~7; #endif } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ local void copy_block(s, buf, len, header) deflate_state *s; charf *buf; /* the input data */ unsigned len; /* its length */ int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (ush)len); put_short(s, (ush)~len); #ifdef DEBUG s->bits_sent += 2*16; #endif } #ifdef DEBUG s->bits_sent += (ulg)len<<3; #endif while (len--) { put_byte(s, *buf++); } } bcmatroska2-5.3.101/corec/corec/helpers/zlib/trees.h000066400000000000000000000204301462133141200221500ustar00rootroot00000000000000/* header created automatically with -DGEN_TREES_H */ local const ct_data static_ltree[L_CODES+2] = { {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} }; local const ct_data static_dtree[D_CODES] = { {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} }; const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; local const int base_length[LENGTH_CODES] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; local const int base_dist[D_CODES] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; bcmatroska2-5.3.101/corec/corec/helpers/zlib/uncompr.c000066400000000000000000000037121462133141200225100ustar00rootroot00000000000000/* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int ZEXPORT uncompress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } bcmatroska2-5.3.101/corec/corec/helpers/zlib/zconf.h000066400000000000000000000320771462133141200221570ustar00rootroot00000000000000/* zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #ifndef ZCONF_H #define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * Even better than compiling with -DZ_PREFIX would be to use configure to set * this permanently in zconf.h using "./configure --zprefix". */ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ /* all linked symbols */ # define _dist_code z__dist_code # define _length_code z__length_code # define _tr_align z__tr_align # define _tr_flush_block z__tr_flush_block # define _tr_init z__tr_init # define _tr_stored_block z__tr_stored_block # define _tr_tally z__tr_tally # define adler32 z_adler32 # define adler32_combine z_adler32_combine # define adler32_combine64 z_adler32_combine64 # define compress z_compress # define compress2 z_compress2 # define compressBound z_compressBound # define crc32 z_crc32 # define crc32_combine z_crc32_combine # define crc32_combine64 z_crc32_combine64 # define deflate z_deflate # define deflateBound z_deflateBound # define deflateCopy z_deflateCopy # define deflateEnd z_deflateEnd # define deflateInit2_ z_deflateInit2_ # define deflateInit_ z_deflateInit_ # define deflateParams z_deflateParams # define deflatePrime z_deflatePrime # define deflateReset z_deflateReset # define deflateSetDictionary z_deflateSetDictionary # define deflateSetHeader z_deflateSetHeader # define deflateTune z_deflateTune # define deflate_copyright z_deflate_copyright # define get_crc_table z_get_crc_table # define gz_error z_gz_error # define gz_intmax z_gz_intmax # define gz_strwinerror z_gz_strwinerror # define gzbuffer z_gzbuffer # define gzclearerr z_gzclearerr # define gzclose z_gzclose # define gzclose_r z_gzclose_r # define gzclose_w z_gzclose_w # define gzdirect z_gzdirect # define gzdopen z_gzdopen # define gzeof z_gzeof # define gzerror z_gzerror # define gzflush z_gzflush # define gzgetc z_gzgetc # define gzgets z_gzgets # define gzoffset z_gzoffset # define gzoffset64 z_gzoffset64 # define gzopen z_gzopen # define gzopen64 z_gzopen64 # define gzprintf z_gzprintf # define gzputc z_gzputc # define gzputs z_gzputs # define gzread z_gzread # define gzrewind z_gzrewind # define gzseek z_gzseek # define gzseek64 z_gzseek64 # define gzsetparams z_gzsetparams # define gztell z_gztell # define gztell64 z_gztell64 # define gzungetc z_gzungetc # define gzwrite z_gzwrite # define inflate z_inflate # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd # define inflateBackInit_ z_inflateBackInit_ # define inflateCopy z_inflateCopy # define inflateEnd z_inflateEnd # define inflateGetHeader z_inflateGetHeader # define inflateInit2_ z_inflateInit2_ # define inflateInit_ z_inflateInit_ # define inflateMark z_inflateMark # define inflatePrime z_inflatePrime # define inflateReset z_inflateReset # define inflateReset2 z_inflateReset2 # define inflateSetDictionary z_inflateSetDictionary # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateUndermine z_inflateUndermine # define inflate_copyright z_inflate_copyright # define inflate_fast z_inflate_fast # define inflate_table z_inflate_table # define uncompress z_uncompress # define zError z_zError # define zcalloc z_zcalloc # define zcfree z_zcfree # define zlibCompileFlags z_zlibCompileFlags # define zlibVersion z_zlibVersion /* all zlib typedefs in zlib.h and zconf.h */ # define Byte z_Byte # define Bytef z_Bytef # define alloc_func z_alloc_func # define charf z_charf # define free_func z_free_func # define gzFile z_gzFile # define gz_header z_gz_header # define gz_headerp z_gz_headerp # define in_func z_in_func # define intf z_intf # define out_func z_out_func # define uInt z_uInt # define uIntf z_uIntf # define uLong z_uLong # define uLongf z_uLongf # define voidp z_voidp # define voidpc z_voidpc # define voidpf z_voidpf /* all zlib structs in zlib.h and zconf.h */ # define gz_header_s z_gz_header_s # define internal_state z_internal_state #endif #if defined(__MSDOS__) && !defined(MSDOS) # define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) # define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) # define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) # ifndef WIN32 # define WIN32 # endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # ifndef SYS16BIT # define SYS16BIT # endif # endif #endif /* * Compile with -DMAXSEG_64K if the alloc function cannot allocate more * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT # define MAXSEG_64K #endif #ifdef MSDOS # define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ # ifndef STDC # define STDC # endif # if __STDC_VERSION__ >= 199901L # ifndef STDC99 # define STDC99 # endif # endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) # define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) # define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) # define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) # define STDC #endif #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ # define STDC #endif #ifndef STDC # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ # define const /* note: need a more gentle solution here */ # endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL # ifdef MAXSEG_64K # define MAX_MEM_LEVEL 8 # else # define MAX_MEM_LEVEL 9 # endif #endif /* Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif /* The memory requirements for deflate are (in bytes): (1 << (windowBits+2)) + (1 << (memLevel+9)) that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, compile with make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes) 1 << windowBits that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. */ /* Type declarations */ #ifndef OF /* function prototypes */ # ifdef STDC # define OF(args) args # else # define OF(args) () # endif #endif /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT # if defined(M_I86SM) || defined(M_I86MM) /* MSC small or medium model */ # define SMALL_MEDIUM # ifdef _MSC_VER # define FAR _far # else # define FAR far # endif # endif # if (defined(__SMALL__) || defined(__MEDIUM__)) /* Turbo C small or medium model */ # define SMALL_MEDIUM # ifdef __BORLANDC__ # define FAR _far # else # define FAR far # endif # endif #endif #if defined(WINDOWS) || defined(WIN32) /* If building or using zlib as a DLL, define ZLIB_DLL. * This is not mandatory, but it offers a little performance increase. */ # ifdef ZLIB_DLL # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) # ifdef ZLIB_INTERNAL # define ZEXTERN extern __declspec(dllexport) # else # define ZEXTERN extern __declspec(dllimport) # endif # endif # endif /* ZLIB_DLL */ /* If building or using zlib with the WINAPI/WINAPIV calling convention, * define ZLIB_WINAPI. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. */ # ifdef ZLIB_WINAPI # ifdef FAR # undef FAR # endif # include /* No need for _export, use ZLIB.DEF instead. */ /* For complete Windows compatibility, use WINAPI, not __stdcall. */ # define ZEXPORT WINAPI # ifdef WIN32 # define ZEXPORTVA WINAPIV # else # define ZEXPORTVA FAR CDECL # endif # endif #endif #if defined (__BEOS__) # ifdef ZLIB_DLL # ifdef ZLIB_INTERNAL # define ZEXPORT __declspec(dllexport) # define ZEXPORTVA __declspec(dllexport) # else # define ZEXPORT __declspec(dllimport) # define ZEXPORTVA __declspec(dllimport) # endif # endif #endif #ifndef ZEXTERN # define ZEXTERN extern #endif #ifndef ZEXPORT # define ZEXPORT #endif #ifndef ZEXPORTVA # define ZEXPORTVA #endif #ifndef FAR # define FAR #endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ #endif typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ # define Bytef Byte FAR #else typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC typedef void const *voidpc; typedef void FAR *voidpf; typedef void *voidp; #else typedef Byte const *voidpc; typedef Byte FAR *voidpf; typedef Byte *voidp; #endif #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ # define Z_HAVE_UNISTD_H #endif #ifdef STDC # include /* for off_t */ #endif /* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even * though the former does not conform to the LFS document), but considering * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as * equivalently requesting no 64-bit operations */ #if -_LARGEFILE64_SOURCE - -1 == 1 # undef _LARGEFILE64_SOURCE #endif #if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) # include /* for SEEK_* and off_t */ # ifdef VMS # include /* for off_t */ # endif # ifndef z_off_t # define z_off_t off_t # endif #endif #ifndef SEEK_SET # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t # define z_off_t long #endif #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define z_off64_t off64_t #else # define z_off64_t z_off_t #endif #if defined(__OS400__) # define NO_vsnprintf #endif #if defined(__MVS__) # define NO_vsnprintf #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") #pragma map(deflateInit2_,"DEIN2") #pragma map(deflateEnd,"DEEND") #pragma map(deflateBound,"DEBND") #pragma map(inflateInit_,"ININ") #pragma map(inflateInit2_,"ININ2") #pragma map(inflateEnd,"INEND") #pragma map(inflateSync,"INSY") #pragma map(inflateSetDictionary,"INSEDI") #pragma map(compressBound,"CMBND") #pragma map(inflate_table,"INTABL") #pragma map(inflate_fast,"INFA") #pragma map(inflate_copyright,"INCOPY") #endif #endif /* ZCONF_H */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/zconf.h.in000066400000000000000000000320771462133141200225640ustar00rootroot00000000000000/* zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #ifndef ZCONF_H #define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * Even better than compiling with -DZ_PREFIX would be to use configure to set * this permanently in zconf.h using "./configure --zprefix". */ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ /* all linked symbols */ # define _dist_code z__dist_code # define _length_code z__length_code # define _tr_align z__tr_align # define _tr_flush_block z__tr_flush_block # define _tr_init z__tr_init # define _tr_stored_block z__tr_stored_block # define _tr_tally z__tr_tally # define adler32 z_adler32 # define adler32_combine z_adler32_combine # define adler32_combine64 z_adler32_combine64 # define compress z_compress # define compress2 z_compress2 # define compressBound z_compressBound # define crc32 z_crc32 # define crc32_combine z_crc32_combine # define crc32_combine64 z_crc32_combine64 # define deflate z_deflate # define deflateBound z_deflateBound # define deflateCopy z_deflateCopy # define deflateEnd z_deflateEnd # define deflateInit2_ z_deflateInit2_ # define deflateInit_ z_deflateInit_ # define deflateParams z_deflateParams # define deflatePrime z_deflatePrime # define deflateReset z_deflateReset # define deflateSetDictionary z_deflateSetDictionary # define deflateSetHeader z_deflateSetHeader # define deflateTune z_deflateTune # define deflate_copyright z_deflate_copyright # define get_crc_table z_get_crc_table # define gz_error z_gz_error # define gz_intmax z_gz_intmax # define gz_strwinerror z_gz_strwinerror # define gzbuffer z_gzbuffer # define gzclearerr z_gzclearerr # define gzclose z_gzclose # define gzclose_r z_gzclose_r # define gzclose_w z_gzclose_w # define gzdirect z_gzdirect # define gzdopen z_gzdopen # define gzeof z_gzeof # define gzerror z_gzerror # define gzflush z_gzflush # define gzgetc z_gzgetc # define gzgets z_gzgets # define gzoffset z_gzoffset # define gzoffset64 z_gzoffset64 # define gzopen z_gzopen # define gzopen64 z_gzopen64 # define gzprintf z_gzprintf # define gzputc z_gzputc # define gzputs z_gzputs # define gzread z_gzread # define gzrewind z_gzrewind # define gzseek z_gzseek # define gzseek64 z_gzseek64 # define gzsetparams z_gzsetparams # define gztell z_gztell # define gztell64 z_gztell64 # define gzungetc z_gzungetc # define gzwrite z_gzwrite # define inflate z_inflate # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd # define inflateBackInit_ z_inflateBackInit_ # define inflateCopy z_inflateCopy # define inflateEnd z_inflateEnd # define inflateGetHeader z_inflateGetHeader # define inflateInit2_ z_inflateInit2_ # define inflateInit_ z_inflateInit_ # define inflateMark z_inflateMark # define inflatePrime z_inflatePrime # define inflateReset z_inflateReset # define inflateReset2 z_inflateReset2 # define inflateSetDictionary z_inflateSetDictionary # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateUndermine z_inflateUndermine # define inflate_copyright z_inflate_copyright # define inflate_fast z_inflate_fast # define inflate_table z_inflate_table # define uncompress z_uncompress # define zError z_zError # define zcalloc z_zcalloc # define zcfree z_zcfree # define zlibCompileFlags z_zlibCompileFlags # define zlibVersion z_zlibVersion /* all zlib typedefs in zlib.h and zconf.h */ # define Byte z_Byte # define Bytef z_Bytef # define alloc_func z_alloc_func # define charf z_charf # define free_func z_free_func # define gzFile z_gzFile # define gz_header z_gz_header # define gz_headerp z_gz_headerp # define in_func z_in_func # define intf z_intf # define out_func z_out_func # define uInt z_uInt # define uIntf z_uIntf # define uLong z_uLong # define uLongf z_uLongf # define voidp z_voidp # define voidpc z_voidpc # define voidpf z_voidpf /* all zlib structs in zlib.h and zconf.h */ # define gz_header_s z_gz_header_s # define internal_state z_internal_state #endif #if defined(__MSDOS__) && !defined(MSDOS) # define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) # define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) # define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) # ifndef WIN32 # define WIN32 # endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # ifndef SYS16BIT # define SYS16BIT # endif # endif #endif /* * Compile with -DMAXSEG_64K if the alloc function cannot allocate more * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT # define MAXSEG_64K #endif #ifdef MSDOS # define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ # ifndef STDC # define STDC # endif # if __STDC_VERSION__ >= 199901L # ifndef STDC99 # define STDC99 # endif # endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) # define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) # define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) # define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) # define STDC #endif #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ # define STDC #endif #ifndef STDC # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ # define const /* note: need a more gentle solution here */ # endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL # ifdef MAXSEG_64K # define MAX_MEM_LEVEL 8 # else # define MAX_MEM_LEVEL 9 # endif #endif /* Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif /* The memory requirements for deflate are (in bytes): (1 << (windowBits+2)) + (1 << (memLevel+9)) that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, compile with make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes) 1 << windowBits that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. */ /* Type declarations */ #ifndef OF /* function prototypes */ # ifdef STDC # define OF(args) args # else # define OF(args) () # endif #endif /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT # if defined(M_I86SM) || defined(M_I86MM) /* MSC small or medium model */ # define SMALL_MEDIUM # ifdef _MSC_VER # define FAR _far # else # define FAR far # endif # endif # if (defined(__SMALL__) || defined(__MEDIUM__)) /* Turbo C small or medium model */ # define SMALL_MEDIUM # ifdef __BORLANDC__ # define FAR _far # else # define FAR far # endif # endif #endif #if defined(WINDOWS) || defined(WIN32) /* If building or using zlib as a DLL, define ZLIB_DLL. * This is not mandatory, but it offers a little performance increase. */ # ifdef ZLIB_DLL # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) # ifdef ZLIB_INTERNAL # define ZEXTERN extern __declspec(dllexport) # else # define ZEXTERN extern __declspec(dllimport) # endif # endif # endif /* ZLIB_DLL */ /* If building or using zlib with the WINAPI/WINAPIV calling convention, * define ZLIB_WINAPI. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. */ # ifdef ZLIB_WINAPI # ifdef FAR # undef FAR # endif # include /* No need for _export, use ZLIB.DEF instead. */ /* For complete Windows compatibility, use WINAPI, not __stdcall. */ # define ZEXPORT WINAPI # ifdef WIN32 # define ZEXPORTVA WINAPIV # else # define ZEXPORTVA FAR CDECL # endif # endif #endif #if defined (__BEOS__) # ifdef ZLIB_DLL # ifdef ZLIB_INTERNAL # define ZEXPORT __declspec(dllexport) # define ZEXPORTVA __declspec(dllexport) # else # define ZEXPORT __declspec(dllimport) # define ZEXPORTVA __declspec(dllimport) # endif # endif #endif #ifndef ZEXTERN # define ZEXTERN extern #endif #ifndef ZEXPORT # define ZEXPORT #endif #ifndef ZEXPORTVA # define ZEXPORTVA #endif #ifndef FAR # define FAR #endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ #endif typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ # define Bytef Byte FAR #else typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC typedef void const *voidpc; typedef void FAR *voidpf; typedef void *voidp; #else typedef Byte const *voidpc; typedef Byte FAR *voidpf; typedef Byte *voidp; #endif #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ # define Z_HAVE_UNISTD_H #endif #ifdef STDC # include /* for off_t */ #endif /* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even * though the former does not conform to the LFS document), but considering * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as * equivalently requesting no 64-bit operations */ #if -_LARGEFILE64_SOURCE - -1 == 1 # undef _LARGEFILE64_SOURCE #endif #if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) # include /* for SEEK_* and off_t */ # ifdef VMS # include /* for off_t */ # endif # ifndef z_off_t # define z_off_t off_t # endif #endif #ifndef SEEK_SET # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t # define z_off_t long #endif #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define z_off64_t off64_t #else # define z_off64_t z_off_t #endif #if defined(__OS400__) # define NO_vsnprintf #endif #if defined(__MVS__) # define NO_vsnprintf #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") #pragma map(deflateInit2_,"DEIN2") #pragma map(deflateEnd,"DEEND") #pragma map(deflateBound,"DEBND") #pragma map(inflateInit_,"ININ") #pragma map(inflateInit2_,"ININ2") #pragma map(inflateEnd,"INEND") #pragma map(inflateSync,"INSY") #pragma map(inflateSetDictionary,"INSEDI") #pragma map(compressBound,"CMBND") #pragma map(inflate_table,"INTABL") #pragma map(inflate_fast,"INFA") #pragma map(inflate_copyright,"INCOPY") #endif #endif /* ZCONF_H */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/zlib.3000066400000000000000000000102131462133141200216770ustar00rootroot00000000000000.TH ZLIB 3 "19 Apr 2010" .SH NAME zlib \- compression/decompression library .SH SYNOPSIS [see .I zlib.h for full description] .SH DESCRIPTION The .I zlib library is a general purpose data compression library. The code is thread safe, assuming that the standard library functions used are thread safe, such as memory allocation routines. It provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms may be added later with the same stream interface. .LP Compression can be done in a single step if the buffers are large enough or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. .LP The library also supports reading and writing files in .IR gzip (1) (.gz) format with an interface similar to that of stdio. .LP The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in the case of corrupted input. .LP All functions of the compression library are documented in the file .IR zlib.h . The distribution source includes examples of use of the library in the files .I example.c and .IR minigzip.c, as well as other examples in the .IR examples/ directory. .LP Changes to this version are documented in the file .I ChangeLog that accompanies the source. .LP .I zlib is available in Java using the java.util.zip package: .IP http://java.sun.com/developer/technicalArticles/Programming/compression/ .LP A Perl interface to .IR zlib , written by Paul Marquess (pmqs@cpan.org), is available at CPAN (Comprehensive Perl Archive Network) sites, including: .IP http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .LP A Python interface to .IR zlib , written by A.M. Kuchling (amk@magnet.com), is available in Python 1.5 and later versions: .IP http://www.python.org/doc/lib/module-zlib.html .LP .I zlib is built into .IR tcl: .IP http://wiki.tcl.tk/4610 .LP An experimental package to read and write files in .zip format, written on top of .I zlib by Gilles Vollant (info@winimage.com), is available at: .IP http://www.winimage.com/zLibDll/minizip.html and also in the .I contrib/minizip directory of the main .I zlib source distribution. .SH "SEE ALSO" The .I zlib web site can be found at: .IP http://zlib.net/ .LP The data format used by the zlib library is described by RFC (Request for Comments) 1950 to 1952 in the files: .IP http://www.ietf.org/rfc/rfc1950.txt (for the zlib header and trailer format) .br http://www.ietf.org/rfc/rfc1951.txt (for the deflate compressed data format) .br http://www.ietf.org/rfc/rfc1952.txt (for the gzip header and trailer format) .LP Mark Nelson wrote an article about .I zlib for the Jan. 1997 issue of Dr. Dobb's Journal; a copy of the article is available at: .IP http://marknelson.us/1997/01/01/zlib-engine/ .SH "REPORTING PROBLEMS" Before reporting a problem, please check the .I zlib web site to verify that you have the latest version of .IR zlib ; otherwise, obtain the latest version and see if the problem still exists. Please read the .I zlib FAQ at: .IP http://zlib.net/zlib_faq.html .LP before asking for help. Send questions and/or comments to zlib@gzip.org, or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). .SH AUTHORS Version 1.2.5 Copyright (C) 1995-2010 Jean-loup Gailly (jloup@gzip.org) and Mark Adler (madler@alumni.caltech.edu). .LP This software is provided "as-is," without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. See the distribution directory with respect to requirements governing redistribution. The deflate format used by .I zlib was defined by Phil Katz. The deflate and .I zlib specifications were written by L. Peter Deutsch. Thanks to all the people who reported problems and suggested various improvements in .IR zlib ; who are too numerous to cite here. .LP UNIX manual page by R. P. C. Rodgers, U.S. National Library of Medicine (rodgers@nlm.nih.gov). .\" end of man page bcmatroska2-5.3.101/corec/corec/helpers/zlib/zlib.3.pdf000066400000000000000000000207561462133141200224640ustar00rootroot00000000000000%PDF-1.4 %Çì¢ 5 0 obj <> stream xœ¥Zےܶ}߯À›9U ¼(/^KŠKŠ,)ÒTªâ]?p9ÜZrÄ‹V«‡|Aò)ùÇtãFp.’])—JòlݧOŸnî'RFBüÏü]ì¯Vï²í¯Bò3üÙ^}ºbj1{òÓ¥øƒõý•~‘„“$4ÍÈz%²”ʈ¬®‚__¿üé6· âþµXÿ20@3‰6DLÖ¯¯‚7׿¼XüàÙ†Ÿ/'ë œm}­«;ò_R´ûCWö}Õ6«MéýçZgqFãί.9RõzÞ‘Ç“½—<”¸vÉbšâúàÃ?ß¼}÷áå½ôô,ÁM_–ú! ÍSÎhg™ÞñFt…Ý-~[¿ºZ†TuáYã1i–êõÁ}‹æ8MR\•Òü™gÝ=> õƒ4u”Gn‚±®É¦ì‹n±d’†a"‚ê0€/~S;ϯÊBFDhºëóž½ùnýò훋×]ïNnR.ÜéÕeg/³”Ææ¡‹ˆ€WBv)$,¡! ¹¹ #}»ª'9Ù–MÙ-à!‹â ¯Éa„ÛŠ08´}I6ù“ àÝYšÒD^Ú‚Ž>…s±)tíœÍ"xÃ>°' v%ìµ) lØue¾!}®!fßË8½÷„~¯|BòÉtL¥KÐ÷ã¾j¶ÊˆÈ"š$ô4‹3õú°Ëذ$ý7›¼Û8¤CÊeq¿á×LdÌžÆÚ»›AÒ“±/7$ïÊK×a‚S)L4åÆÜ§÷ïsn“±Ø‘¼'ûrߪ£ Œ,%•ib¯ÿ˜û.²D™©ë¶Èñ°¤kÇ¡jJµ1¸P¥T"i*mô^N¦8 §°êJÏ(g™Ãõ¡Si‡»Ú-)ÕžŸ+È)R5KïðRèÓg¢äN_L[ª%æôHˆ™Ó”sÿÌ2Kc {™'•—÷°‚ÙŒjŠzÜ`àxC©`ccs*¤d–8&’&–™†GRìÊbÁ2š¥2 >ö¤½Ghi¢qH#p‚ñ\ã lÎpÁ”£ |`Ì×2¶ëäÇç`že§n­÷ñò3hY:;Ý”rÉ&d ý¸‡¶#ƒò]ÄiÊÂãmS?’¶)g¼°/‡]»!·Á¦üO¾Tˆàè±x^dÀE°ÊÕÝ‚#åÈ,ÒÂÉ;’×Û‰î•ñ$¨†Ýð«ÛXöf@í·î~+IŠf‚R¯Sá‰G 7Áf^­ó¶x£:Óó=¦;$å^EꀰX” EöYP7&#Êâ‰Ø•\§Ï3ÏEÞ; LtMÀ$=à¨ÆmÊ©tx•sÑÐ`&ï%§^°%5t½â:ï¶%)›vÜîÈßëNÇ“SÚ”|4) Î?8“Ì0WJpÈìÔµÅ(9—Dt±ŒÃ’2 ^6aù€®,ò^£JOi·Ãµ¤M¤'ƒ_Y¥Ç`’I} 0–uehïªÐØù¡€i„„A€*Lq¸+˜›ãªj€$`ƒº²Ü—ê¼@køä6°\`“mÚý"È,ïÀej>.s`Zô“ƒÆÀk¼G¬élmÓî‡+-”ߪÉ97Puû–èÔ[,£P ¡'X3ð˜Èq³ÔÀŸþ»V,j”ˆ“,•”9¢Û~­Gò!£Ì!-¸ Üù6 Û¯ð·‚bÄ<õ´äª`ÚwŒ*¨à®aP¥² €é%Te˜P û 0lhpÉDvL -Q…ÀØ›ª]XGh¿‡4ÓsþŽÒo¹;Iîìû›üÖ´œ >(¼¼Ñ•B ¼¸rÊáR©÷k,ñìéJ\mM;R]vºz²XY’8ÒzÚW?@/ÒÉY¸° &•-™dX!öçÙwÙò,þMy§¼êôOøQEu«zÜ5ÙLÍuMî5¹û¡¼± xxxXHÓvÓƒŽ˜ÌtJ –¯ûv3ÖåÒè\Ó"î†}}RoA_¥x¯?\pÕH|*œcUc“x ˜(£)-“ Eýtnt‰cÝ$§Ð¨>V^ ÃÇU*\»2öÛ 5MÁö¢Ñ-Wö ÕZD*7¹b (fˆ±ªêfN¶8Ó7ªÐ¢rRCiº€=$¿-U¢ïµ—Ø×N,5 À9ûj üÔõÖÓ]!S‡öºÿ¨ƒ$ ;ÎL+bfQL½‰DœéïÉÏåPü8¨Šik½¦ªñªÿPžV´»µõÒLÑBü2tô:op¦T5÷ªí ì! „}#Tð?¡ã .ªYyÄpŽö½4šÎcB«TÐ××ÕÝóº^a‚mˆ n’‚4°tfZ¨´RøPª©1ðB”AõqÃŒ)èEÛ ÷;·Ë,AbPBþKg{,n.¯¡±)42Ï;P‡îóª9_fÇ๘úZ¾›žwúܧýîõ<ô̇?~šúß8_¼ ׯ?¼=j€¾÷Ñïæìæ^A˜ÏA¸7áîæS+oŽÙm¦ÇfD·lGŒ±Ou™;Eלt¡Ú¬ì‡ 8΢iP§> ê±b­ì%þ0cÅDL5ÏZQßÐŒ@̸º«ÀÏ`®jNƒfÆV®œÂîê“¶ÃÀøÐySÆÒi÷Ä}$µ_€1‰’ ¡¤gßWÓ•þ%¬°|ïëtæF*7Á_Ÿg¼/Q²Êýx}P=Hãýí‚°L†V ,¹šzÈ9Öa÷zÙ^UžïÔª¦h«rÚÝøw¤Ãä2ì­ì+ïí DàÇä…¢"!ƒ¼ªá‡º0@#I“è|\µ¶\š%s ý³çd—ΉŸœ†iôf&ŸöttyÙ·O§—ü§ã—N‡£ž#/²ðÈ Ì.ÌÛÍ6ÅLD ù¨Ò”&gÓW–ÄŒÛÞ”ÀÝ Tø|”ã\d±ÇPª%ù];'ŸÚ“§œtô»ø9AØá›ù] `ÉÎü²Å”©6!YäÍc_iž y]$B–@ÕìGšï™ô¦=Ïón¶NÂÜwêç3ês9o‚öNÌP9ßý`ò×Hýn·uÞ„œ±#M^ÿÅžBé0rs¾ Ÿ}¼Î·ÚÃì­Ù—¿à±½ðÖ½#ø•ýøË ~H3QEà騞jŽ˜©_qùÓÓ#[2S~–@‘²Ys}èµ’åÛcŸáO^¬¯þÿýá+[ endstream endobj 6 0 obj 3478 endobj 14 0 obj <> stream xœ}WÛrÛF}çWLå ÜGsÅÞ_âõÚ‘o2MEJmAäˆD Š¡¿!ûÏÛ=€¤¥’ˆ™ééËéÓ„QN~ÂßÅfrymȪ›0ò ~W“‡ wHø³ØçsØ”áƒùýÄŸãÄbrI³œÌ7™gT+2ßO’_¯^?¿Mäí” ÿMç¿O`ûL¦d¾œÌM¥Ûºîûí“ËËMÑ’/µ­º¦¦»î’ç¹¹d¾VåÝÌÖ«²¶—häò:/h®Ñ‘šä)ÍÐ(Cƒ7ÉõËﯧ‚QÆt2ýîù0|}ÿüêåÛOÓßæoŽ¢—f\ …ä¹½Ç;¸¢†31¢Yšf™óµi-ií¶iqâ4Õ&÷}_Ö+RmÛܹ[¹áIe7d[Ù¢³d±¶ 瀤*…3‹ Ц"XJ¾ôh¹N…Jó°°¶>|ÎbÀKcÂ*¦ ×gXU8{T¬üØÊÞY9º7™!UÑÛ®÷ª” g3—y0&¥æ”IïzW65iîÏ’+•LçgÙ¬sy–^M͘Á6£¯‚r-ãB¿¶í¾ìì‰i(Ï^üÅÙ›ä®/ÊšôÇqfòL+Ïù_ÔKÒY EpÛú à9ÒT¤2²Ñüßï¯?}4@/F%EøýlÉTÉØk@nÌãÉ·-ÕäE³ucJS-RqNq ¸ÕÚq‘äTf&?³u“Ü&/ K0¼ôL0ðè-êYÕì¶äUy;@–~ǯ¡nØÂ0”°np [ømÑԘ̅& ´Á8žádÀ–qü$Ëʶ¡ššÊ1þÛdSàÚÓ¢Úmê’.Šª·‹5µËÖQíÒ}5ÁˆRŒbþ›d¾.;Ò5÷ý~ sÀ‘H@‡‡@,®¢LåÉc¹´KòCÑÍÊÎíËDž\ü@öe¿nv=äbQ”§©‹…ÃËÐCÉÁÏ5$<ùcÛÚ®C—›mUÂ{Ü™åâ(±hÛ)G´åYø;„´åÊ]å:q úÚ…èÇ ©ý&©ë©‚,¤ מŽ$0# f> /Contents 5 0 R >> endobj 13 0 obj <> /Contents 14 0 R >> endobj 3 0 obj << /Type /Pages /Kids [ 4 0 R 13 0 R ] /Count 2 /Rotate 0>> endobj 1 0 obj <> endobj 7 0 obj <>endobj 11 0 obj <> endobj 12 0 obj <> endobj 16 0 obj <> endobj 17 0 obj <> endobj 8 0 obj <> endobj 18 0 obj <> endobj 10 0 obj <> endobj 9 0 obj <> endobj 19 0 obj <>stream groff version 1.19.2 Untitled endstream endobj 2 0 obj <>endobj xref 0 20 0000000000 65535 f 0000006046 00000 n 0000007979 00000 n 0000005971 00000 n 0000005649 00000 n 0000000015 00000 n 0000003563 00000 n 0000006111 00000 n 0000006312 00000 n 0000006544 00000 n 0000006471 00000 n 0000006152 00000 n 0000006182 00000 n 0000005809 00000 n 0000003583 00000 n 0000005628 00000 n 0000006232 00000 n 0000006262 00000 n 0000006392 00000 n 0000006613 00000 n trailer << /Size 20 /Root 1 0 R /Info 2 0 R /ID [<2B179FE3FD26D7E9DB44003C3A06AD01><2B179FE3FD26D7E9DB44003C3A06AD01>] >> startxref 8133 %%EOF bcmatroska2-5.3.101/corec/corec/helpers/zlib/zlib.h000066400000000000000000002333141462133141200217750ustar00rootroot00000000000000/* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.5, April 19th, 2010 Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.5" #define ZLIB_VERNUM 0x1250 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 5 #define ZLIB_VER_SUBREVISION 0 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total nb of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total nb of bytes output so far */ char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text */ uLong adler; /* adler32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use in the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff). If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed code block. If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space; if deflate returns with Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least the value returned by deflateBound (see below). If deflate does not return Z_STREAM_END, then it must be called again as described above. deflate() sets strm->adler to the adler32 checksum of all input read so far (that is, total_in bytes). deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. If next_in is not Z_NULL and avail_in is large enough (the exact value depends on the compression method), inflateInit determines the compression method from the zlib header and allocates all data structures accordingly; otherwise the allocation will be deferred to the first call of inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call of inflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. Also to assist in this, on return inflate() will set strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster approach may be used for the single inflate() call. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the only effect of the flush parameter in this implementation is on the return value of inflate(), as noted below, or when it returns early because Z_BLOCK or Z_TREES is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the adler32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained, so applications that need that information should instead use raw inflate, see inflateInit2() below, or inflateBack() and perform their own processing of the gzip header and trailer. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is desired. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute an adler32 check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to 255 (unknown). If a gzip stream is being written, strm->adler is a crc32 instead of an adler32. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. This function must be called immediately after deflateInit, deflateInit2 or deflateReset, before any call of deflate. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the adler32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The adler32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the adler32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if the compression method is bsort). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate all the internal compression state. The stream will keep the same compression level and any other attributes that may have been set by deflateInit2. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2. This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression level is changed, the input available so far is compressed with the old level (and may be flushed); the new level will take effect only at the next call of deflate(). Before the call of deflateParams, the stream state must be set as for a call of deflate(), since the currently available input may have to be compressed and flushed. In particular, strm->avail_out must be non-zero. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if strm->avail_out was zero. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an adler32 or a crc32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a crc32 instead of an adler32. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the adler32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called immediately after inflateInit2() or inflateReset() and before any call of inflate() to set the dictionary. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a full flush point (see above the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate all the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, int windowBits)); /* This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid. */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); /* This function returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code. A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data. inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate. inflateMark returns the value noted above or -1 << 16 if the provided source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the paramaters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is more efficient than inflate() for file i/o applications in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. This function trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the normal behavior of inflate(), which expects either a zlib or gzip header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero--buf is ignored in that case--and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. */ /* gzip file access functions */ /* This library supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio, using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. */ typedef voidp gzFile; /* opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) Also "a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened. */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1). */ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); /* Set the internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Two buffers are allocated, either both of the specified size when writing, or one of the specified size and the other twice that size when reading. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading). The new buffer size also affects the maximum length for gzprintf(). gzbuffer() returns 0 on success, or -1 on failure, such as being called too late. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not opened for writing. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file was not in gzip format, gzread copies the given number of bytes into the buffer. After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream, or failing that, reading the rest of the input file directly without decompression. The entire input file will be read if gzread is called until it returns less than the requested len. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error. */ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or 0 in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags(). */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. gzgets returns buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing. If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatented gzip streams. gzflush should be called only when strictly necessary because it will degrade compression if called too often. */ /* ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ /* ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen(). gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ /* ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); Returns the current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1. */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size. If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed. This state can change from false to true while reading the input file if the end of a gzip stream is reached, but is followed by data that is not another gzip stream. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); /* Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library. */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available. gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ /* ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ /* ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) #define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, sizeof(z_stream)) /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # ifdef _LARGEFILE64_SOURCE ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif /* hack for buggy compilers */ #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) struct internal_state {int dummy;}; #endif /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); #ifdef __cplusplus } #endif #endif /* ZLIB_H */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/zlib.proj000066400000000000000000000040071462133141200225130ustar00rootroot00000000000000IF CONFIG_ZLIB GROUP(!HAVE_ZLIB) zlib { INCLUDE . EXPINCLUDE . SUBINCLUDE . DEFINE FASTEST DEFINE NO_ERRNO_H DEFINE(CONFIG_BUILDFIXED) BUILDFIXED DEFINE(CONFIG_BUILDFIXED) DYNAMIC_CRC_TABLE DEFINE(TARGET_WIN && !COREMAKE_STATIC) ZLIB_DLL SOURCE adler32.c SOURCE crc32.c SOURCE inffast.c SOURCE inflate.c SOURCE inftrees.c SOURCE uncompr.c SOURCE zutil.c //uses masm and not yasm SOURCE(COMPILER_MSVC && IX86) contrib/masmx86/inffas32.asm //uses masm and not yasm SOURCE(COMPILER_MSVC && IX86) contrib/masmx86/match686.asm //uses masm and not yasm SOURCE(COMPILER_MSVC && IX86_64) contrib/masmx64/gvmat64.asm //uses masm and not yasm SOURCE(COMPILER_MSVC && IX86_64) contrib/masmx64/inffas8664.c //uses masm and not yasm SOURCE(COMPILER_MSVC && IX86_64) contrib/masmx64/inffasx64.asm DEFINE(COMPILER_GCC && IX86 && !TARGET_OSX) ASMINF SOURCE(COMPILER_GCC && IX86 && !TARGET_OSX) contrib/inflate86/inffas86.c //SOURCE(COMPILER_GCC && IX86 && !TARGET_OSX) contrib/inflate86/inffast.S DEFINE(COMPILER_GCC && (IX86 || IX86_64) && !TARGET_OSX) ASMV SOURCE(COMPILER_GCC && IX86 && !TARGET_OSX) contrib/asm686/match.S SOURCE(COMPILER_GCC && IX86_64 && !TARGET_OSX) contrib/gcc_gvmat64/gvmat64.S SOURCE(COMPILER_GCC && IX86_64 && !TARGET_OSX) contrib/amd64/amd64-match.S HEADER crc32.h HEADER inffast.h HEADER inffixed.h HEADER inflate.h HEADER inftrees.h HEADER zconf.h HEADER zlib.h HEADER zutil.h } GROUP(!HAVE_ZLIB) zlib_adler32 { SUBINCLUDE . SOURCE adler32.c HEADER zconf.h HEADER zlib.h HEADER zutil.h } GROUP(!HAVE_ZLIB) zlib_deflate { USE zlib SOURCE compress.c SOURCE deflate.c SOURCE trees.c HEADER deflate.h HEADER trees.h } DLL zlib1 { USE zlib SOURCE compress.c SOURCE deflate.c SOURCE gzclose.c SOURCE gzlib.c SOURCE gzread.c SOURCE gzwrite.c SOURCE infback.c SOURCE trees.c HEADER deflate.h HEADER gzguts.h HEADER trees.h } ENDIF bcmatroska2-5.3.101/corec/corec/helpers/zlib/zutil.c000066400000000000000000000162211462133141200221730ustar00rootroot00000000000000/* zutil.c -- target dependent utility functions for the compression library * Copyright (C) 1995-2005, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ #endif const char * const z_errmsg[10] = { "need dictionary", /* Z_NEED_DICT 2 */ "stream end", /* Z_STREAM_END 1 */ "", /* Z_OK 0 */ "file error", /* Z_ERRNO (-1) */ "stream error", /* Z_STREAM_ERROR (-2) */ "data error", /* Z_DATA_ERROR (-3) */ "insufficient memory", /* Z_MEM_ERROR (-4) */ "buffer error", /* Z_BUF_ERROR (-5) */ "incompatible version",/* Z_VERSION_ERROR (-6) */ ""}; const char * ZEXPORT zlibVersion() { return ZLIB_VERSION; } uLong ZEXPORT zlibCompileFlags() { uLong flags; flags = 0; switch ((int)(sizeof(uInt))) { case 2: break; case 4: flags += 1; break; case 8: flags += 2; break; default: flags += 3; } switch ((int)(sizeof(uLong))) { case 2: break; case 4: flags += 1 << 2; break; case 8: flags += 2 << 2; break; default: flags += 3 << 2; } switch ((int)(sizeof(voidpf))) { case 2: break; case 4: flags += 1 << 4; break; case 8: flags += 2 << 4; break; default: flags += 3 << 4; } switch ((int)(sizeof(z_off_t))) { case 2: break; case 4: flags += 1 << 6; break; case 8: flags += 2 << 6; break; default: flags += 3 << 6; } #ifdef DEBUG flags += 1 << 8; #endif #if defined(ASMV) || defined(ASMINF) flags += 1 << 9; #endif #ifdef ZLIB_WINAPI flags += 1 << 10; #endif #ifdef BUILDFIXED flags += 1 << 12; #endif #ifdef DYNAMIC_CRC_TABLE flags += 1 << 13; #endif #ifdef NO_GZCOMPRESS flags += 1L << 16; #endif #ifdef NO_GZIP flags += 1L << 17; #endif #ifdef PKZIP_BUG_WORKAROUND flags += 1L << 20; #endif #ifdef FASTEST flags += 1L << 21; #endif #ifdef STDC # ifdef NO_vsnprintf flags += 1L << 25; # ifdef HAS_vsprintf_void flags += 1L << 26; # endif # else # ifdef HAS_vsnprintf_void flags += 1L << 26; # endif # endif #else flags += 1L << 24; # ifdef NO_snprintf flags += 1L << 25; # ifdef HAS_sprintf_void flags += 1L << 26; # endif # else # ifdef HAS_snprintf_void flags += 1L << 26; # endif # endif #endif return flags; } #ifdef DEBUG # ifndef verbose # define verbose 0 # endif int ZLIB_INTERNAL z_verbose = verbose; void ZLIB_INTERNAL z_error (m) char *m; { fprintf(stderr, "%s\n", m); exit(1); } #endif /* exported to allow conversion of error code to string for compress() and * uncompress() */ const char * ZEXPORT zError(err) int err; { return ERR_MSG(err); } #if defined(_WIN32_WCE) /* The Microsoft C Run-Time Library for Windows CE doesn't have * errno. We define it as a global variable to simplify porting. * Its value is always 0 and should not be used. */ int errno = 0; #endif #ifndef HAVE_MEMCPY void ZLIB_INTERNAL zmemcpy(dest, source, len) Bytef* dest; const Bytef* source; uInt len; { if (len == 0) return; do { *dest++ = *source++; /* ??? to be unrolled */ } while (--len != 0); } int ZLIB_INTERNAL zmemcmp(s1, s2, len) const Bytef* s1; const Bytef* s2; uInt len; { uInt j; for (j = 0; j < len; j++) { if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; } return 0; } void ZLIB_INTERNAL zmemzero(dest, len) Bytef* dest; uInt len; { if (len == 0) return; do { *dest++ = 0; /* ??? to be unrolled */ } while (--len != 0); } #endif #ifdef SYS16BIT #ifdef __TURBOC__ /* Turbo C in 16-bit mode */ # define MY_ZCALLOC /* Turbo C malloc() does not allow dynamic allocation of 64K bytes * and farmalloc(64K) returns a pointer with an offset of 8, so we * must fix the pointer. Warning: the pointer must be put back to its * original form in order to free it, use zcfree(). */ #define MAX_PTR 10 /* 10*64K = 640K */ local int next_ptr = 0; typedef struct ptr_table_s { voidpf org_ptr; voidpf new_ptr; } ptr_table; local ptr_table table[MAX_PTR]; /* This table is used to remember the original form of pointers * to large buffers (64K). Such pointers are normalized with a zero offset. * Since MSDOS is not a preemptive multitasking OS, this table is not * protected from concurrent access. This hack doesn't work anyway on * a protected system like OS/2. Use Microsoft C instead. */ voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) { voidpf buf = opaque; /* just to make some compilers happy */ ulg bsize = (ulg)items*size; /* If we allocate less than 65520 bytes, we assume that farmalloc * will return a usable pointer which doesn't have to be normalized. */ if (bsize < 65520L) { buf = farmalloc(bsize); if (*(ush*)&buf != 0) return buf; } else { buf = farmalloc(bsize + 16L); } if (buf == NULL || next_ptr >= MAX_PTR) return NULL; table[next_ptr].org_ptr = buf; /* Normalize the pointer to seg:0 */ *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; *(ush*)&buf = 0; table[next_ptr++].new_ptr = buf; return buf; } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { int n; if (*(ush*)&ptr != 0) { /* object < 64K */ farfree(ptr); return; } /* Find the original pointer */ for (n = 0; n < next_ptr; n++) { if (ptr != table[n].new_ptr) continue; farfree(table[n].org_ptr); while (++n < next_ptr) { table[n-1] = table[n]; } next_ptr--; return; } ptr = opaque; /* just to make some compilers happy */ Assert(0, "zcfree: ptr not found"); } #endif /* __TURBOC__ */ #ifdef M_I86 /* Microsoft C in 16-bit mode */ # define MY_ZCALLOC #if (!defined(_MSC_VER) || (_MSC_VER <= 600)) # define _halloc halloc # define _hfree hfree #endif voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) { if (opaque) opaque = 0; /* to make compiler happy */ return _halloc((long)items, size); } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { if (opaque) opaque = 0; /* to make compiler happy */ _hfree(ptr); } #endif /* M_I86 */ #endif /* SYS16BIT */ #ifndef MY_ZCALLOC /* Any system without a special alloc function */ #ifndef STDC extern voidp malloc OF((uInt size)); extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) voidpf opaque; unsigned items; unsigned size; { if (opaque) items += size - size; /* make compiler happy */ return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : (voidpf)calloc(items, size); } void ZLIB_INTERNAL zcfree (opaque, ptr) voidpf opaque; voidpf ptr; { free(ptr); if (opaque) return; /* make compiler happy */ } #endif /* MY_ZCALLOC */ bcmatroska2-5.3.101/corec/corec/helpers/zlib/zutil.h000066400000000000000000000157611462133141200222100ustar00rootroot00000000000000/* zutil.h -- internal interface and configuration of the compression library * Copyright (C) 1995-2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef ZUTIL_H #define ZUTIL_H #if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) # define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) #else # define ZLIB_INTERNAL #endif #include "zlib.h" #ifdef STDC # if !(defined(_WIN32_WCE) && defined(_MSC_VER)) # include # endif # include # include #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ typedef unsigned char uch; typedef uch FAR uchf; typedef unsigned short ush; typedef ush FAR ushf; typedef unsigned long ulg; extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ /* (size given to avoid silly warnings with Visual C++) */ #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] #define ERR_RETURN(strm,err) \ return (strm->msg = (char*)ERR_MSG(err), (err)) /* To be used only when the state is known to be valid */ /* common constants */ #ifndef DEF_WBITS # define DEF_WBITS MAX_WBITS #endif /* default windowBits for decompression. MAX_WBITS is for compression only */ #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 /* The three kinds of block type */ #define MIN_MATCH 3 #define MAX_MATCH 258 /* The minimum and maximum match lengths */ #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ /* target dependencies */ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) # define OS_CODE 0x00 # if defined(__TURBOC__) || defined(__BORLANDC__) # if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) /* Allow compilation with ANSI keywords only enabled */ void _Cdecl farfree( void *block ); void *_Cdecl farmalloc( unsigned long nbytes ); # else # include # endif # else /* MSC or DJGPP */ # include # endif #endif #ifdef AMIGA # define OS_CODE 0x01 #endif #if defined(VAXC) || defined(VMS) # define OS_CODE 0x02 # define F_OPEN(name, mode) \ fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") #endif #if defined(ATARI) || defined(atarist) # define OS_CODE 0x05 #endif #ifdef OS2 # define OS_CODE 0x06 # ifdef M_I86 # include # endif #endif #if defined(MACOS) || defined(TARGET_OS_MAC) # define OS_CODE 0x07 # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os # include /* for fdopen */ # else # ifndef fdopen # define fdopen(fd,mode) NULL /* No fdopen() */ # endif # endif #endif #ifdef TOPS20 # define OS_CODE 0x0a #endif #ifdef WIN32 # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ # define OS_CODE 0x0b # endif #endif #ifdef __50SERIES /* Prime/PRIMOS */ # define OS_CODE 0x0f #endif #if defined(_BEOS_) || defined(RISCOS) # define fdopen(fd,mode) NULL /* No fdopen() */ #endif #if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX # if defined(_WIN32_WCE) # define fdopen(fd,mode) NULL /* No fdopen() */ # ifndef _PTRDIFF_T_DEFINED typedef int ptrdiff_t; # define _PTRDIFF_T_DEFINED # endif # else # define fdopen(fd,type) _fdopen(fd,type) # endif #endif #if defined(__BORLANDC__) #pragma warn -8004 #pragma warn -8008 #pragma warn -8066 #endif /* provide prototypes for these when building zlib without LFS */ #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); #endif /* common defaults */ #ifndef OS_CODE # define OS_CODE 0x03 /* assume Unix */ #endif #ifndef F_OPEN # define F_OPEN(name, mode) fopen((name), (mode)) #endif /* functions */ #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) # ifndef HAVE_VSNPRINTF # define HAVE_VSNPRINTF # endif #endif #if defined(__CYGWIN__) # ifndef HAVE_VSNPRINTF # define HAVE_VSNPRINTF # endif #endif #ifndef HAVE_VSNPRINTF # ifdef MSDOS /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), but for now we just assume it doesn't. */ # define NO_vsnprintf # endif # ifdef __TURBOC__ # define NO_vsnprintf # endif # ifdef WIN32 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ # if !defined(vsnprintf) && !defined(NO_vsnprintf) # if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) # define vsnprintf _vsnprintf # endif # endif # endif # ifdef __SASC # define NO_vsnprintf # endif #endif #ifdef VMS # define NO_vsnprintf #endif #if defined(pyr) # define NO_MEMCPY #endif #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) /* Use our own functions for small and medium model with MSC <= 5.0. * You may have to use the same strategy for Borland C (untested). * The __SC__ check is for Symantec. */ # define NO_MEMCPY #endif #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) # define HAVE_MEMCPY #endif #ifdef HAVE_MEMCPY # ifdef SMALL_MEDIUM /* MSDOS small or medium model */ # define zmemcpy _fmemcpy # define zmemcmp _fmemcmp # define zmemzero(dest, len) _fmemset(dest, 0, len) # else # define zmemcpy memcpy # define zmemcmp memcmp # define zmemzero(dest, len) memset(dest, 0, len) # endif #else void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); #endif /* Diagnostic functions */ #ifdef DEBUG # include extern int ZLIB_INTERNAL z_verbose; extern void ZLIB_INTERNAL z_error OF((char *m)); # define Assert(cond,msg) {if(!(cond)) z_error(msg);} # define Trace(x) {if (z_verbose>=0) fprintf x ;} # define Tracev(x) {if (z_verbose>0) fprintf x ;} # define Tracevv(x) {if (z_verbose>1) fprintf x ;} # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} #else # define Assert(cond,msg) # define Trace(x) # define Tracev(x) # define Tracevv(x) # define Tracec(c,x) # define Tracecv(c,x) #endif voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, unsigned size)); void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} #endif /* ZUTIL_H */ bcmatroska2-5.3.101/corec/corec/libc/000077500000000000000000000000001462133141200171655ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/libc/iphone/000077500000000000000000000000001462133141200204475ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/libc/iphone/memory.h000066400000000000000000000000501462133141200221230ustar00rootroot00000000000000#include #include bcmatroska2-5.3.101/corec/corec/libc/libc.proj000066400000000000000000000017431462133141200207770ustar00rootroot00000000000000GROUP libc { IF TARGET_PALMOS USE palmone_sdk USE sony_sdk USEINCLUDE corec USEINCLUDE peal SYSINCLUDE palmos SOURCE palmos/assert.c SOURCE(ARM) palmos/math.c SOURCE(ARM) palmos/qsort.c SOURCE(ARM) palmos/rand.c SOURCE(ARM) palmos/sincos.c SOURCE(ARM) palmos/vsprintf.c SOURCE(ARM) palmos/setjmp.S SOURCE palmos/pace.c SOURCE palmos/pace2.c SOURCE palmos/strings.c SOURCE(IX86) palmos/native_x86.c SOURCE(ARM) palmos/native_arm.S ENDIF IF TARGET_SYMBIAN SYSINCLUDE symbian ENDIF IF TARGET_WINCE USEINCLUDE corec SOURCE wince/assert.c SYSINCLUDE wince ENDIF IF TARGET_PS2SDK USE ps2event SYSINCLUDE ps2sdk ENDIF IF TARGET_IPHONE_SDK SYSINCLUDE iphone ENDIF } GROUP con_to_exe { SOURCE(TARGET_WINCE) wince/console_wince.c IF TARGET_PALMOS USEINCLUDE peal USE peal USE libc SOURCE palmos/console_palmos.c SOURCE_M68K palmos/console_palmos_m68k.c ENDIF } bcmatroska2-5.3.101/corec/corec/libc/palmos/000077500000000000000000000000001462133141200204605ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/libc/palmos/assert.c000066400000000000000000000045611462133141200221330ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #ifndef NDEBUG #ifdef LIBC_EXPORTS #define ASSERT_DLL DLLEXPORT #else #define ASSERT_DLL #endif #define WarningOKAlert 10031 extern uint16_t FrmCustomAlert(uint16_t alertId, const char *s1, const char *s2, const char *s3); ASSERT_DLL void _Assert(const char* Exp, const char* File, int Line) { char Msg[MAXPATH]; size_t i; int n=1000000; Msg[0] = '\n'; for (i=1;i1 && Line #include #include "m68k/peal.h" #include #include #define PALMOS_IX86_DLL(name) #name #define PALMOS_IX86_FUNC(name,func) (NativeFuncType*)(PALMOS_IX86_DLL(name) ".dll\0" #func) #define SWAP16(a) ((((UInt16)(a) >> 8) & 0x00FF) | (((UInt16)(a) << 8) & 0xFF00)) #define SWAP32(a) ((((UInt32)(a) >> 24) & 0x000000FF) | (((UInt32)(a) >> 8) & 0x0000FF00) |\ (((UInt32)(a) << 8) & 0x00FF0000) | (((UInt32)(a) << 24) & 0xFF000000)) typedef struct vfspath { UInt16 volRefNum; Char path[256]; } vfspath; typedef struct launch { MemPtr PealCall; PealModule* Module; void* LoadModule; void* FreeModule; void* GetSymbol; MemPtr launchParameters; UInt16 launchCode; UInt16 launchFlags; } launch; static Err RomVersionCheck(UInt16 launchFlags) { UInt32 Version; FtrGet(sysFtrCreator, sysFtrNumROMVersion, &Version); if (Version < sysMakeROMVersion(5,0,0,sysROMStageDevelopment,0)) { if ((launchFlags & sysAppLaunchFlagNewGlobals) != 0 && (launchFlags & sysAppLaunchFlagUIApp) != 0) { FrmCustomAlert(WarningOKAlert, "System version 5.0 or greater is required to run this application!", " ", " "); // Palm OS 1.0 requires you to explicitly launch another app if (Version < sysMakeROMVersion(1,0,0,sysROMStageRelease,0)) { AppLaunchWithCommand(sysFileCDefaultApp, sysAppLaunchCmdNormalLaunch, NULL); } } return sysErrRomIncompatible; } return errNone; } static PealModule* Module = NULL; static void* PaceMain = NULL; static void* LookupSymbol86(void* Module,const char* Name) { return NULL; } static void* LoadModule(UInt16 ftrId,Boolean mem,Boolean onlyftr,Boolean memsema) { return PealLoadFromResources('armc',1000,Module,PROJECT_FOURCC,ftrId,mem,onlyftr,memsema); } static UInt32 PealCall86(void* Module,void* Func,void* Param) { return PceNativeCall((NativeFuncType*)Func,Param); } static UInt16 GetHeapId() { MemPtr p=MemPtrNew(8); UInt16 Id=MemPtrHeapID(p); MemPtrFree(p); return Id; } UInt32 PilotMain(UInt16 launchCode, MemPtr launchParameters, UInt16 launchFlags) { UInt32 Value; UInt32 Result = errNone; UInt32 CPU; launch Launch; Launch.launchParameters = launchParameters; Launch.launchCode = launchCode; Launch.launchFlags = launchFlags; if ((launchCode == sysAppLaunchCmdNormalLaunch || launchCode == sysAppLaunchCmdOpenDB || launchCode == sysAppLaunchCmdCustomBase) && !RomVersionCheck(launchFlags)) { FtrGet(sysFileCSystem, sysFtrNumProcessorID, &CPU); if (CPU == sysFtrNumProcessorx86) { Module = PealLoadFromResources('armc', 1000, NULL, PROJECT_FOURCC,32,0,0,0); // just for testing Launch.FreeModule = PealUnload; Launch.LoadModule = LoadModule; Launch.GetSymbol = LookupSymbol86; Launch.PealCall = PealCall86; Launch.Module = Module; PceNativeCall(PALMOS_IX86_FUNC(PROJECT_OUTPUT,PaceMain86),&Launch); if (Module) PealUnload(Module); } else if (sysFtrNumProcessorIsARM(CPU)) { UInt32 Version; Boolean MemSema; FtrGet(sysFtrCreator, sysFtrNumROMVersion, &Version); MemSema = Version < sysMakeROMVersion(6,0,0,sysROMStageDevelopment,0); Module = PealLoadFromResources('armc', 1000, NULL, PROJECT_FOURCC,32,0,0,MemSema); if (Module) { PaceMain = PealLookupSymbol(Module, "PaceMain"); if (PaceMain) { Launch.FreeModule = PealUnload; Launch.LoadModule = LoadModule; Launch.GetSymbol = PealLookupSymbol; Launch.PealCall = PealCall; Launch.Module = Module; Result = PealCall(Module,PaceMain,&Launch); } PealUnload(Module); MemHeapCompact(GetHeapId()); } } else FrmCustomAlert(WarningOKAlert, "ARM processor is required to run this application!", " ", " "); if (FtrGet(PROJECT_FOURCC,20,&Value)==errNone) FtrPtrFree(PROJECT_FOURCC,20); } else if (launchCode == sysAppLaunchCmdNotify && (launchFlags & sysAppLaunchFlagSubCall)!=0) { FtrGet(sysFileCSystem, sysFtrNumProcessorID, &CPU); if (CPU == sysFtrNumProcessorx86) Result = PceNativeCall(PALMOS_IX86_FUNC(PROJECT_OUTPUT,PaceMain86),&Launch); else if (sysFtrNumProcessorIsARM(CPU) && Module && PaceMain) Result = PealCall(Module,PaceMain,&Launch); } return Result; } bcmatroska2-5.3.101/corec/corec/libc/palmos/math.c000066400000000000000000000035731462133141200215650ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" double log(double a) { return 0; } double pow(double a,double b) { return 0; } double sqrt(double a) { return 0; } double exp(double a) { return 1.0+a+a*a/2.0+a*a*a/6.0; } bcmatroska2-5.3.101/corec/corec/libc/palmos/math.h000066400000000000000000000004461462133141200215660ustar00rootroot00000000000000#ifndef __MATH_H_ #define __MATH_H_ extern double fabs(double); extern double pow(double,double); extern double floor(double); extern double log(double); extern double sin(double); extern double cos(double); extern double exp(double); extern double sqrt(double); extern long labs(long); #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/memory.h000066400000000000000000000000241462133141200221350ustar00rootroot00000000000000#include bcmatroska2-5.3.101/corec/corec/libc/palmos/native_arm.S000066400000000000000000000077301462133141200227400ustar00rootroot00000000000000@***************************************************************************** @* @* Copyright (c) 2008-2010, CoreCodec, Inc. @* All rights reserved. @* @* Redistribution and use in source and binary forms, with or without @* modification, are permitted provided that the following conditions are met: @* * Redistributions of source code must retain the above copyright @* notice, this list of conditions and the following disclaimer. @* * Redistributions in binary form must reproduce the above copyright @* notice, this list of conditions and the following disclaimer in the @* documentation and/or other materials provided with the distribution. @* * Neither the name of CoreCodec, Inc. nor the @* names of its contributors may be used to endorse or promote products @* derived from this software without specific prior written permission. @* @* THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY @* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED @* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE @* DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY @* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES @* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; @* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND @* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT @* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS @* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @* @***************************************************************************** .globl SonyInvalidateDCache .globl SonyCleanDCache .globl SysGetEntryAddresses .globl SysFindModule .globl HALDelay .globl HALDisplayWake .globl HALDisplayOff_TREO650 .globl SysLoadModule .globl SysUnloadModule .globl PceCall .globl PalmCall .globl PalmCall2 AddrPceCall: .DC.L PceCall @r0,r1 SonyCleanDCache: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] swi 0xb5 ldmia sp!, {r9, pc} @r0,r1 SonyInvalidateDCache: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] swi 0xb4 ldmia sp!, {r9, pc} @r0,r1,r2,r3 SysGetEntryAddresses: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-8] mov lr, pc ldr pc, [ip, #2104] ldmia sp!, {r9, pc} @r0,r1,r2,r3,[sp] SysFindModule: ldr ip, [sp, #0] stmdb sp!, {r9, lr} stmdb sp!, {ip} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-8] mov lr, pc ldr pc, [ip, #2092] add sp, sp, #4 ldmia sp!, {r9, pc} @r0,r1,r2,r3,[sp] SysLoadModule: ldr ip, [sp, #0] stmdb sp!, {r9, lr} stmdb sp!, {ip} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-8] mov lr, pc ldr pc, [ip, #2176] add sp, sp, #4 ldmia sp!, {r9, pc} @r0 SysUnloadModule: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-8] mov lr, pc ldr pc, [ip, #2312] ldmia sp!, {r9, pc} @r0 HALDelay: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-4] mov lr, pc ldr pc, [ip, #0x28] ldmia sp!, {r9, pc} HALDisplayWake: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-4] mov lr, pc ldr pc, [ip, #0x40] ldmia sp!, {r9, pc} HALDisplayOff_TREO650: stmdb sp!, {r9, lr} ldr r9, AddrPceCall ldr r9, [r9, #0] ldr ip, [r9, #-4] mov lr, pc ldr pc, [ip, #0x358] ldmia sp!, {r9, pc} PalmCall: stmdb sp!, {r9, lr} mov ip, r0 mov r0, r1 mov r1, r2 mov r2, r3 ldr r3, [sp, #8] ldr r9, AddrPceCall ldr r9, [r9, #0] mov lr, pc mov pc, ip ldmia sp!, {r9, pc} PalmCall2: stmdb sp!, {r9, lr} sub sp, sp, #16 ldr ip, [sp, #8+16+4] ldr r9, [sp, #8+16+8] str ip, [sp, #0] str r9, [sp, #4] ldr ip, [sp, #8+16+12] ldr r9, [sp, #8+16+16] str ip, [sp, #8] str r9, [sp, #12] mov ip, r0 mov r0, r1 mov r1, r2 mov r2, r3 ldr r3, [sp, #8+16] ldr r9, AddrPceCall ldr r9, [r9, #0] mov lr, pc mov pc, ip add sp, sp, #16 ldmia sp!, {r9, pc} bcmatroska2-5.3.101/corec/corec/libc/palmos/native_x86.c000066400000000000000000000054471462133141200226310ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #if defined(TARGET_PALMOS) && defined(IX86) #include "pace.h" Err SysGetEntryAddresses(UInt32 refNum, UInt32 entryNumStart, UInt32 entryNumEnd, void **addressP) { return 1; //fail } Err SysFindModule(UInt32 dbType, UInt32 dbCreator, UInt16 rsrcID, UInt32 flags, UInt32 *refNumP) { return 1; } Err SysLoadModule(UInt32 dbType, UInt32 dbCreator, UInt16 rsrcID, UInt32 flags, UInt32 *refNumP) { return 1; } Err SysUnloadModule(UInt32 refNum) { return 1; } #include void** HALDispatch() { static void** Table = NULL; if (!Table) { HMODULE Module = LoadLibrary(T("dal.dll")); void (__cdecl *GetDispath)(void***) = (void (__cdecl*)(void***)) GetProcAddress(Module,"__ExportDispatchTable"); GetDispath(&Table); //FreeLibrary(Module); } return Table; } void SonyCleanDCache(void* p, UInt32 n) {} void SonyInvalidateDCache(void* p, UInt32 n) {} void HALDelay(UInt32 n) { ((void (__cdecl*)(UInt32))HALDispatch()[0x0A])(n); } void HALDisplayWake() { ((void (__cdecl*)())HALDispatch()[0x10])(); } void HALDisplayOff_TREO650() { ((void (__cdecl*)())HALDispatch()[0xD6])(); } #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/pace.c000066400000000000000000000665441462133141200215530ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #if defined(TARGET_PALMOS) #include "pace.h" #include "arm/pealstub.h" #define memNewChunkFlagAllowLarge 0x1000 //tremor uses lot of alloca() #define STACKSIZE 0x8000 //#define STACKCHECK #ifdef HAVE_PALMONE_SDK #define NO_HSEXT_TRAPS #include <68K/System/HardwareUtils68K.h> #include #include <68K/System/HsExt.h> #endif typedef struct launch { UInt32 PealCall; //BE UInt32 Module; //BE UInt32 LoadModule; //BE UInt32 FreeModule; //BE UInt32 GetSymbol; //BE UInt16 launchParameters[2]; UInt16 launchCode; UInt16 launchFlags; } launch; typedef struct gadgethandler { uint8_t Code[68]; struct gadgethandler* Next; FormGadgetTypeInCallback* Gadget; //BE uint16_t* Event; //BE UInt16 Cmd; //BE UInt32 Module; //BE UInt32 PealCall; //BE UInt32 Wrapper; //BE FormType* Form; int Index; FormGadgetHandlerType* Handler; } gadgethandler; typedef struct eventhandler { uint8_t Code[48]; struct eventhandler* Next; uint16_t* Event; //BE UInt32 Module; //BE UInt32 PealCall; //BE UInt32 Wrapper; //BE FormType* Form; FormEventHandlerExType *Handler; void* This; } eventhandler; static gadgethandler* GadgetHandler = NULL; static eventhandler* EventHandler = NULL; static launch Peal = {0}; static NOINLINE void FreeHandlers() { gadgethandler* j; eventhandler* i; while ((i=EventHandler)!=NULL) { EventHandler = i->Next; MemPtrFree(i); } while ((j=GadgetHandler)!=NULL) { GadgetHandler = j->Next; MemPtrFree(j); } } static NOINLINE void SwapLaunchParameters(int launchCode,void* launchParameters,bool_t From) { if (launchCode == sysAppLaunchCmdCustomBase) { vfspath* p = (vfspath*)launchParameters; p->volRefNum = SWAP16(p->volRefNum); } if (launchCode == sysAppLaunchCmdOpenDB) { UInt16 tmp; SysAppLaunchCmdOpenDBType2* p = (SysAppLaunchCmdOpenDBType2*)launchParameters; p->cardNo = SWAP16(p->cardNo); tmp = p->dbID[0]; p->dbID[0] = SWAP16(p->dbID[1]); p->dbID[1] = SWAP16(tmp); } if (launchCode == sysAppLaunchCmdNotify) { SysNotifyParamType* p = (SysNotifyParamType*)launchParameters; UInt32 Type = p->notifyType; void* Details = p->notifyDetailsP; p->notifyType = SWAP32(p->notifyType); p->broadcaster = SWAP32(p->broadcaster); p->notifyDetailsP = (void*)SWAP32(p->notifyDetailsP); p->userDataP = (void*)SWAP32(p->userDataP); if (From) { Type = p->notifyType; Details = p->notifyDetailsP; } if (Type == sysNotifySleepRequestEvent) { SleepEventParamType* i = (SleepEventParamType*)Details; i->reason = SWAP16(i->reason); i->deferSleep = SWAP16(i->deferSleep); } } } static INLINE uint32_t ReadSwap32(const void* p) { return (((const uint8_t*)p)[0] << 24)| (((const uint8_t*)p)[1] << 16)| (((const uint8_t*)p)[2] << 8)| (((const uint8_t*)p)[3] << 0); } static INLINE void WriteSwap32(void* p,uint32_t i) { ((uint8_t*)p)[0] = ((uint8_t*)&i)[3]; ((uint8_t*)p)[1] = ((uint8_t*)&i)[2]; ((uint8_t*)p)[2] = ((uint8_t*)&i)[1]; ((uint8_t*)p)[3] = ((uint8_t*)&i)[0]; } void Event_M68K_To_ARM(const uint16_t* In,EventType* Out) { Out->eType = SWAP16(In[0]); Out->penDown = ((uint8_t*)In)[2]; Out->tapCount = ((uint8_t*)In)[3]; Out->screenX = SWAP16(In[2]); Out->screenY = SWAP16(In[3]); switch (Out->eType) { // 1*16bit case frmLoadEvent: case menuEvent: Out->data.menu.itemID = SWAP16(In[4]); break; // 3*16bit case frmUpdateEvent: case keyUpEvent: case keyDownEvent: case keyHoldEvent: Out->data.keyDown.chr = SWAP16(In[4]); Out->data.keyDown.keyCode = SWAP16(In[5]); Out->data.keyDown.modifiers = SWAP16(In[6]); break; // 16bit,32bit case fldChangedEvent: case fldEnterEvent: case ctlEnterEvent: case ctlExitEvent: Out->data.fldChanged.fieldID = SWAP16(In[4]); Out->data.fldChanged.pField = (FieldType*)ReadSwap32(In+5); break; // 16bit,32bit,16bit,32bit,16bit,16bit case popSelectEvent: Out->data.popSelect.controlID = SWAP16(In[4]); Out->data.popSelect.controlP = (ControlType*)ReadSwap32(In+5); Out->data.popSelect.listID = SWAP16(In[7]); Out->data.popSelect.listP = (ListType*)SWAP32(*(uint32_t*)(In+8)); Out->data.popSelect.selection = SWAP16(In[10]); Out->data.popSelect.priorSelection = SWAP16(In[11]); break; // 16bit,32bit,16bit case lstSelectEvent: Out->data.lstSelect.listID = SWAP16(In[4]); Out->data.lstSelect.pList = (ListType*)ReadSwap32(In+5); Out->data.lstSelect.selection = SWAP16(In[7]); break; // 16bit,16bit,32bit case frmObjectFocusLostEvent: Out->data.frmObjectFocusLost.formID = SWAP16(In[4]); Out->data.frmObjectFocusLost.objectID = SWAP16(In[5]); Out->data.frmObjectFocusLost.dispatchHint = ReadSwap32(In+6); break; //custom case sclRepeatEvent: Out->data.sclRepeat.scrollBarID = SWAP16(In[4]); Out->data.sclRepeat.pScrollBar = (ScrollBarType*)ReadSwap32(In+5); Out->data.sclRepeat.value = SWAP16(In[7]); Out->data.sclRepeat.newValue = SWAP16(In[8]); Out->data.sclRepeat.time = ReadSwap32(In+9); break; //custom case ctlRepeatEvent: Out->data.ctlRepeat.controlID = SWAP16(In[4]); Out->data.ctlRepeat.pControl = (ControlType*)ReadSwap32(In+5); Out->data.ctlRepeat.time = ReadSwap32(In+7); Out->data.ctlRepeat.value = SWAP16(In[9]); break; //custom case ctlSelectEvent: Out->data.ctlSelect.controlID = SWAP16(In[4]); Out->data.ctlSelect.pControl = (ControlType*)ReadSwap32(In+5); Out->data.ctlSelect.on = ((uint8_t*)In)[14]; Out->data.ctlSelect.reserved1 = ((uint8_t*)In)[15]; Out->data.ctlSelect.value = SWAP16(In[8]); break; // 2*32bit case winEnterEvent: case winExitEvent: Out->data.winExit.enterWindow = (WinHandle)SWAP32(((uint32_t*)In)[2]); Out->data.winExit.exitWindow = (WinHandle)SWAP32(((uint32_t*)In)[3]); break; default: memcpy(Out->data.generic.datum,In+4,sizeof(uint16_t)*8); break; } } void Event_ARM_To_M68K(const EventType* In,uint16_t* Out) { Out[0] = SWAP16(In->eType); ((uint8_t*)Out)[2] = In->penDown; ((uint8_t*)Out)[3] = In->tapCount; Out[2] = SWAP16(In->screenX); Out[3] = SWAP16(In->screenY); switch (In->eType) { // 1*16bit case frmLoadEvent: case menuEvent: Out[4] = SWAP16(In->data.menu.itemID); break; // 3*16bit case frmUpdateEvent: case keyUpEvent: case keyDownEvent: case keyHoldEvent: Out[4] = SWAP16(In->data.keyDown.chr); Out[5] = SWAP16(In->data.keyDown.keyCode); Out[6] = SWAP16(In->data.keyDown.modifiers); break; // 16bit,32bit,16bit case lstSelectEvent: Out[4] = SWAP16(In->data.lstSelect.listID); WriteSwap32(Out+5,(uint32_t)In->data.lstSelect.pList); Out[7] = SWAP16(In->data.lstSelect.selection); break; // 16bit,16bit,32bit case frmObjectFocusLostEvent: Out[4] = SWAP16(In->data.frmObjectFocusLost.formID); Out[5] = SWAP16(In->data.frmObjectFocusLost.objectID); WriteSwap32(Out+6,(uint32_t)In->data.frmObjectFocusLost.dispatchHint); break; // 16bit,32bit case fldChangedEvent: case fldEnterEvent: case ctlEnterEvent: case ctlExitEvent: Out[4] = SWAP16(In->data.fldChanged.fieldID); WriteSwap32(Out+5,(uint32_t)In->data.fldChanged.pField); break; // 16bit,32bit,16bit,32bit,16bit,16bit case popSelectEvent: Out[4] = SWAP16(In->data.popSelect.controlID); WriteSwap32(Out+5,(uint32_t)In->data.popSelect.controlP); Out[7] = SWAP16(In->data.popSelect.listID); WriteSwap32(Out+8,(uint32_t)In->data.popSelect.listP); Out[10] = SWAP16(In->data.popSelect.selection); Out[11] = SWAP16(In->data.popSelect.priorSelection); break; //custom case sclRepeatEvent: Out[4] = SWAP16(In->data.sclRepeat.scrollBarID); WriteSwap32(Out+5,(uint32_t)In->data.sclRepeat.pScrollBar); Out[7] = SWAP16(In->data.sclRepeat.value); Out[8] = SWAP16(In->data.sclRepeat.newValue); WriteSwap32(Out+9,In->data.sclRepeat.time); break; //custom case ctlRepeatEvent: Out[4] = SWAP16(In->data.ctlRepeat.controlID); WriteSwap32(Out+5,(uint32_t)In->data.ctlRepeat.pControl); WriteSwap32(Out+7,In->data.ctlRepeat.time); Out[9] = SWAP16(In->data.ctlRepeat.value); break; //custom case ctlSelectEvent: Out[4] = SWAP16(In->data.ctlSelect.controlID); WriteSwap32(Out+5,(uint32_t)In->data.ctlSelect.pControl); ((uint8_t*)Out)[14] = In->data.ctlSelect.on; ((uint8_t*)Out)[15] = In->data.ctlSelect.reserved1; Out[8] = SWAP16(In->data.ctlSelect.value); break; // 2*32bit case winEnterEvent: case winExitEvent: ((uint32_t*)Out)[2] = SWAP32(In->data.winExit.enterWindow); ((uint32_t*)Out)[3] = SWAP32(In->data.winExit.exitWindow); break; default: memcpy(Out+4,In->data.generic.datum,sizeof(uint16_t)*8); break; } } static void GadgetTypeInCallback_M68K_To_ARM(const uint16_t* In,FormGadgetTypeInCallback* Out) { Out->id = SWAP16(In[0]); *(UInt16*)&Out->attr = SWAP16(In[1]); Out->rect.topLeft.x = SWAP16(In[2]); Out->rect.topLeft.y = SWAP16(In[3]); Out->rect.extent.x = SWAP16(In[4]); Out->rect.extent.y = SWAP16(In[5]); Out->data = (const void*)SWAP32(*(const uint32_t*)(In+6)); Out->handler = (FormGadgetHandlerType*)SWAP32(*(const uint32_t*)(In+8)); } static void GadgetTypeInCallback_ARM_To_M68K(const FormGadgetTypeInCallback* In,uint16_t* Out) { Out[0] = SWAP16(In->id); Out[1] = SWAP16(*(UInt16*)&In->attr); Out[2] = SWAP16(In->rect.topLeft.x); Out[3] = SWAP16(In->rect.topLeft.y); Out[4] = SWAP16(In->rect.extent.x); Out[5] = SWAP16(In->rect.extent.y); *(uint32_t*)(Out+6) = SWAP32(In->data); *(uint32_t*)(Out+8) = SWAP32(In->handler); } static NOINLINE bool_t CmdLaunch(int Code) { return Code == sysAppLaunchCmdNormalLaunch || Code == sysAppLaunchCmdOpenDB || Code == sysAppLaunchCmdCustomBase; } #if defined(IX86) #define NONE 0 pcecall PceCall = {NULL}; char DLLName[MAXPATH]; #include NativeFuncType* IX86CallBack(const char* Func,char* Buffer) { size_t n = strlen(DLLName)+1; memcpy(Buffer,DLLName,n); strcpy(Buffer+n,Func); return (NativeFuncType*)Buffer; } BOOL WINAPI DllMain(HINSTANCE hDLL,DWORD fdwReason,LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) GetModuleFileNameA(hDLL,DLLName,sizeof(DLLName)); return TRUE; } DLLEXPORT uint32_t PaceMain86(const void *emulStateP, launch* Launch, Call68KFuncType *call68KFuncP) { MemPtr Parameters = (MemPtr)((SWAP16(Launch->launchParameters[0])<<16)|(SWAP16(Launch->launchParameters[1]))); int Code = SWAP16(Launch->launchCode); uint32_t Result; pcecall Old = PceCall; if (CmdLaunch(Code)) memcpy(&Peal,Launch,sizeof(launch)); PceCall.Func = call68KFuncP; PceCall.State = emulStateP; SwapLaunchParameters(Code,Parameters,1); Result = PilotMain((UInt16)Code,Parameters,SWAP16(Launch->launchFlags)); SwapLaunchParameters(Code,Parameters,0); if (CmdLaunch(Code)) FreeHandlers(); PceCall = Old; return Result; } void SaveSysRegs(sysregs* p) { } void LoadSysRegs(sysregs* p) { } NOINLINE uint32_t Call68K(uint32_t trapOrFunction, const void *argsOnStackP, uint32_t argsSizeAndwantA0) { pcecall* Call = &PceCall; return Call->Func(Call->State,trapOrFunction,argsOnStackP,argsSizeAndwantA0); } DLLEXPORT Boolean WrapperEventHandler86(const void *emulStateP, eventhandler* i, Call68KFuncType *call68KFuncP) { Boolean Result; EventType EventARM; uint16_t* EventM68K = (uint16_t*) SWAP32(i->Event); pcecall Old = PceCall; PceCall.Func = call68KFuncP; PceCall.State = emulStateP; Event_M68K_To_ARM(EventM68K,&EventARM); Result = i->Handler(&EventARM,i->This); if (!Result && EventARM.eType == frmCloseEvent) i->Form = NULL; PceCall = Old; return Result; } DLLEXPORT Boolean WrapperGadgetHandler86(const void *emulStateP, gadgethandler* i, Call68KFuncType *call68KFuncP) { EventType EventARM; Boolean Result; FormGadgetTypeInCallback GadgetARM; uint16_t* Gadget = (uint16_t*) SWAP32(i->Gadget); UInt16 Cmd = SWAP16(i->Cmd); uint16_t* EventM68K = (uint16_t*) SWAP32(i->Event); pcecall Old = PceCall; PceCall.Func = call68KFuncP; PceCall.State = emulStateP; GadgetTypeInCallback_M68K_To_ARM(Gadget,&GadgetARM); if (Cmd == formGadgetHandleEventCmd) Event_M68K_To_ARM(EventM68K,&EventARM); Result = i->Handler(&GadgetARM,Cmd,&EventARM); GadgetTypeInCallback_ARM_To_M68K(&GadgetARM,Gadget); if (Cmd == formGadgetDeleteCmd) i->Form = NULL; PceCall = Old; return Result; } #elif defined(ARM) #define NONE void SaveSysRegs(sysregs* p) { p->SysReg = PceCall.SysReg; asm volatile( "mov %0, r10\n\t" : "=&r"(p->GOT) : : "cc"); } void LoadSysRegs(sysregs* p) { asm volatile( "mov r9,%0\n\t" "mov r10,%1\n\t" : : "r"(p->SysReg),"r"(p->GOT): "cc"); } NOINLINE uint32_t Call68K(uint32_t trapOrFunction, const void *argsOnStackP, uint32_t argsSizeAndwantA0) { pcecall* Call = &PceCall; unsigned long Result; register void *SysReg asm("r9") = Call->SysReg; Result = Call->Func(Call->State,trapOrFunction,argsOnStackP,argsSizeAndwantA0); Call->SysReg = SysReg; return Result; } static NOINLINE void SafeMemCpy(void* d,const void* s,int n) { uint8_t* d8 = (uint8_t*)d; const uint8_t* s8= (const uint8_t*)s; for (;n>0;--n,++d8,++s8) *d8 = *s8; } #ifdef STACKCHECK static void NOINLINE StackCheck(char* p) { int i; for (i=0;ilaunchParameters[0])<<16)|(SWAP16(Launch->launchParameters[1]))); int Code = SWAP16(Launch->launchCode); void* Old = NULL; char* Stack = NULL; uint32_t Result; if (CmdLaunch(Code)) { SafeMemCpy(&Peal,Launch,sizeof(launch)); Stack = MemGluePtrNew(STACKSIZE); if (!Stack) return errNone; memset(Stack,0x55,STACKSIZE); Old = SwapSP(Stack+STACKSIZE); } SwapLaunchParameters(Code,Parameters,1); Result = PilotMain(Code,Parameters,SWAP16(Launch->launchFlags)); SwapLaunchParameters(Code,Parameters,0); if (Stack) { SwapSP(Old); #ifdef STACKCHECK StackCheck(Stack); #endif MemPtrFree(Stack); FreeHandlers(); } return Result; } static Boolean WrapperEventHandler(eventhandler* i) { Boolean Result; EventType EventARM; const uint16_t* EventM68K = (const uint16_t*) SWAP32(i->Event); Event_M68K_To_ARM(EventM68K,&EventARM); Result = i->Handler(&EventARM,i->This); if (!Result && EventARM.eType == frmCloseEvent) i->Form = NULL; return Result; } static Boolean WrapperGadgetHandler(gadgethandler* i) { EventType EventARM; Boolean Result; FormGadgetTypeInCallback GadgetARM; uint16_t* Gadget = (uint16_t*) SWAP32(i->Gadget); UInt16 Cmd = SWAP16(i->Cmd); const uint16_t* EventM68K = (const uint16_t*) SWAP32(i->Event); GadgetTypeInCallback_M68K_To_ARM(Gadget,&GadgetARM); if (Cmd == formGadgetHandleEventCmd) Event_M68K_To_ARM(EventM68K,&EventARM); Result = i->Handler(&GadgetARM,Cmd,&EventARM); GadgetTypeInCallback_ARM_To_M68K(&GadgetARM,Gadget); if (Cmd == formGadgetDeleteCmd) i->Form = NULL; return Result; } #else #error Not supported platform #endif //--------------------------------------------------------------------- static NOINLINE eventhandler* FindEventHandler(FormType *Form) { eventhandler *i,*j; for (i=EventHandler,j=NULL;i;j=i,i=i->Next) if (i->Form == Form) { if (j) { // move ahead for faster search next time j->Next = i->Next; i->Next = EventHandler; EventHandler = i; } return i; } return NULL; } Boolean FrmCallEventHandlerEx(FormType *Form, EventType* eventP) { eventhandler* p = FindEventHandler(Form); if (p) return p->Handler(eventP,p->This); return 0; } Boolean _FrmDispatchEvent(EventType *eventP); Boolean FrmDispatchEvent(EventType *eventP) { // avoid using m68k wrapper for some common events (which are sent to the active form) if (eventP->eType == keyHoldEvent || eventP->eType == keyDownEvent || eventP->eType == keyUpEvent || eventP->eType == nilEvent || eventP->eType == penDownEvent || eventP->eType == penMoveEvent || eventP->eType == penUpEvent) { FormType *Form = FrmGetActiveForm(); eventhandler* p= FindEventHandler(Form); if (p) { // call ARM event handler if (p->Handler(eventP,p->This)) return 1; // call system event handler return FrmHandleEvent(Form,eventP); } } return _FrmDispatchEvent(eventP); } static void SetCodePtr(uint8_t* p,void* Ptr) { p[0] = (uint8_t)(((uint32_t)Ptr) >> 24); p[1] = (uint8_t)(((uint32_t)Ptr) >> 16); p[2] = (uint8_t)(((uint32_t)Ptr) >> 8); p[3] = (uint8_t)(((uint32_t)Ptr) >> 0); } static void RemoveHandler(FormType *Form) { eventhandler* i; for (i=EventHandler;i;i=i->Next) if (i->Form == Form) i->Form = NULL; } void _FrmDeleteForm(FormType *formP); void FrmDeleteForm( FormType *formP ) { _FrmDeleteForm(formP); RemoveHandler(formP); } void _FrmReturnToForm(UInt16 formId); void FrmReturnToForm( UInt16 formId ) { FormType* Form = FrmGetActiveForm(); _FrmReturnToForm(formId); RemoveHandler(Form); } void* m68kCallBack(m68kcallback p,NativeFuncType* Func) { static const uint8_t Code[24] = { 0x4E,0x56,0x00,0x00, // link a6,#0 0x48,0x6E,0x00,0x08, // pea 8(a6) 0x2F,0x3C,0x00,0x00,0x00,0x00, // move.l #$ARM,-(sp) 0x4E,0x4F, // trap #$F 0xA4,0x5A, // dc.w $A45A 0x70,0x00, // moveq #0,d0 0x4E,0x5E, // unlk a6 0x4E,0x75 }; // rts memcpy(p,Code,sizeof(m68kcallback)); SetCodePtr((uint8_t*)p+10,(void*)(uint32_t)Func); return p; } void _FrmSetGadgetHandler(FormType *formP, UInt16 objIndex,FormGadgetHandlerType *attrP); void FrmSetGadgetHandler(FormType *formP, UInt16 objIndex,FormGadgetHandlerType *attrP) { gadgethandler* i; gadgethandler* Free = NULL; for (i=GadgetHandler;i;i=i->Next) { if (i->Form == formP && i->Index == objIndex) break; if (!i->Form) Free = i; } if (!i) { if (Free) i = Free; else { i = MemGluePtrNew(sizeof(gadgethandler)); i->Next = GadgetHandler; GadgetHandler = i; } } if (i) { static const uint8_t Code[68] = { 0x4E,0x56,0x00,0x00, // link a6,#0 0x30,0x2E,0x00,0x0C, // move.w $C(a6),d0 0x22,0x2E,0x00,0x0E, // move.l $E(a6),d1 0x23,0xEE,0x00,0x08,0x00,0x00,0x00,0x00, // move.l 8(a6),($Gadget).l 0x33,0xC0,0x00,0x00,0x00,0x00, // move.w d0,($Cmd).l 0x23,0xC1,0x00,0x00,0x00,0x00, // move.l d1,($Event).l 0x2F,0x3C,0x00,0x00,0x00,0x00, // move.l #This,-(sp) 0x2F,0x39,0x00,0x00,0x00,0x00, // move.l (Wrapper).l,-(sp) 0x2F,0x39,0x00,0x00,0x00,0x00, // move.l (Module).l,-(sp) 0x20,0x79,0x00,0x00,0x00,0x00, // movea.l (PealCall).l,a0 0x4E,0x90, // jsr (a0) 0x02,0x80,0x00,0x00,0x00,0xFF, // andi.l #$FF,d0 0x4E,0x5E, // unlk a6 0x4E,0x75 }; // rts #if defined(IX86) static char Callback[MAXPATH]; i->Wrapper = SWAP32(IX86CallBack("WrapperGadgetHandler86",Callback)); #else i->Wrapper = SWAP32(WrapperGadgetHandler); #endif i->Form = formP; i->Index = objIndex; i->Handler = attrP; i->Module = Peal.Module; i->PealCall = Peal.PealCall; memcpy(i->Code,Code,sizeof(Code)); SetCodePtr(i->Code+16,&i->Gadget); SetCodePtr(i->Code+22,&i->Cmd); SetCodePtr(i->Code+28,&i->Event); SetCodePtr(i->Code+34,i); SetCodePtr(i->Code+40,&i->Wrapper); SetCodePtr(i->Code+46,&i->Module); SetCodePtr(i->Code+52,&i->PealCall); _FrmSetGadgetHandler(formP,objIndex,(FormGadgetHandlerType*)i->Code); } } void _FrmSetEventHandler(FormType *formP,FormEventHandlerType *handler); void FrmSetEventHandlerEx(FormType *formP,FormEventHandlerExType *handler,void* This) { eventhandler* i; eventhandler* Free = NULL; for (i=EventHandler;i;i=i->Next) { if (i->Form == formP) break; if (!i->Form) Free = i; } if (!i) { if (Free) i = Free; else { i = MemGluePtrNew(sizeof(eventhandler)); i->Next = EventHandler; EventHandler = i; } } if (i) { static const uint8_t Code[48] = { 0x4E,0x56,0x00,0x00, // link a6,#0 0x23,0xEE,0x00,0x08,0x00,0x00,0x00,0x00, // move.l arg_0(a6),(Event).l 0x2F,0x3C,0x00,0x00,0x00,0x00, // move.l #This,-(sp) 0x2F,0x39,0x00,0x00,0x00,0x00, // move.l (Wrapper).l,-(sp) 0x2F,0x39,0x00,0x00,0x00,0x00, // move.l (Module).l,-(sp) 0x20,0x79,0x00,0x00,0x00,0x00, // movea.l (PealCall).l,a0 0x4E,0x90, // jsr (a0) 0x4E,0x5E, // unlk a6 0x02,0x80,0x00,0x00,0x00,0xFF, // andi.l #$FF,d0 0x4E,0x75 }; // rts #if defined(IX86) static char Callback[MAXPATH]; i->Wrapper = SWAP32(IX86CallBack("WrapperEventHandler86",Callback)); #else i->Wrapper = SWAP32(WrapperEventHandler); #endif i->This = This; i->Form = formP; i->Handler = handler; i->Module = Peal.Module; i->PealCall = Peal.PealCall; i->Event = NULL; memcpy(i->Code,Code,sizeof(Code)); SetCodePtr(i->Code+8,&i->Event); SetCodePtr(i->Code+14,i); SetCodePtr(i->Code+20,&i->Wrapper); SetCodePtr(i->Code+26,&i->Module); SetCodePtr(i->Code+32,&i->PealCall); _FrmSetEventHandler(formP,(FormEventHandlerType*)i->Code); } } static NOINLINE void ReplaceForm(FormType* Old, FormType* New) { if (New && Old && New != Old) { eventhandler* i; for (i=EventHandler;i;i=i->Next) if (i->Form == Old) i->Form = New; } } Err _LstNewList(void **formPP, UInt16 id, Coord x, Coord y, Coord width, Coord height, FontID font, Int16 visibleItems, Int16 triggerId); Err LstNewList (void **formPP, UInt16 id, Coord x, Coord y, Coord width, Coord height, FontID font, Int16 visibleItems, Int16 triggerId) { Err err; FormType* Old = (FormType*)*formPP; err = _LstNewList(formPP,id,x,y,width,height,font,visibleItems,triggerId); ReplaceForm(Old,*formPP); return err; } FieldType* _FldNewField(void **formPP, UInt16 id, Coord x, Coord y, Coord width, Coord height, FontID font, UInt32 maxChars, Boolean editable, Boolean underlined, Boolean singleLine, Boolean dynamicSize, JustificationType justification, Boolean autoShift, Boolean hasScrollBar, Boolean numeric); FieldType* FldNewField(void **formPP, UInt16 id, Coord x, Coord y, Coord width, Coord height, FontID font, UInt32 maxChars, Boolean editable, Boolean underlined, Boolean singleLine, Boolean dynamicSize, JustificationType justification, Boolean autoShift, Boolean hasScrollBar, Boolean numeric) { FieldType* Field; FormType* Old = (FormType*)*formPP; Field = _FldNewField(formPP,id,x,y,width,height,font,maxChars,editable,underlined,singleLine,dynamicSize, justification,autoShift,hasScrollBar,numeric); ReplaceForm(Old,(FormType*)*formPP); return Field; } Err _FrmRemoveObject(FormType **formPP, UInt16 objIndex); Err FrmRemoveObject(FormType **formPP, UInt16 objIndex) { Err err; FormType* Old = *formPP; err = _FrmRemoveObject(formPP,objIndex); ReplaceForm(Old,*formPP); return err; } Err FrmGlueNavGetFocusRingInfo(const FormType* formP, UInt16* objectIDP, Int16* extraInfoP, RectangleType* boundsInsideRingP, FrmNavFocusRingStyleEnum* ringStyleP) { UInt32 ver; if (FtrGet(sysFileCSystem, sysFtrNumFiveWayNavVersion, &ver)==errNone) return FrmNavGetFocusRingInfo(formP,objectIDP,extraInfoP,boundsInsideRingP,ringStyleP); #ifdef HAVE_PALMONE_SDK else if (FtrGet(hsFtrCreator,hsFtrIDNavigationSupported,&ver)==errNone) return HsNavGetFocusRingInfo(formP,objectIDP,extraInfoP,boundsInsideRingP,ringStyleP); #endif return uilibErrObjectFocusModeOff; } Err FrmGlueNavDrawFocusRing(FormType* formP, UInt16 objectID, Int16 extraInfo, RectangleType* boundsInsideRingP, FrmNavFocusRingStyleEnum ringStyle, Boolean forceRestore) { UInt32 ver; if (FtrGet(sysFileCSystem, sysFtrNumFiveWayNavVersion, &ver)==errNone) return FrmNavDrawFocusRing(formP,objectID,extraInfo,boundsInsideRingP,ringStyle,forceRestore); #ifdef HAVE_PALMONE_SDK else if (FtrGet(hsFtrCreator,hsFtrIDNavigationSupported,&ver)==errNone) return HsNavDrawFocusRing(formP,objectID,extraInfo,boundsInsideRingP,ringStyle,forceRestore); #endif return uilibErrObjectFocusModeOff; } Err FrmGlueNavRemoveFocusRing (FormType* formP) { UInt32 ver; if (FtrGet(sysFileCSystem, sysFtrNumFiveWayNavVersion, &ver)==errNone) return FrmNavRemoveFocusRing(formP); #ifdef HAVE_PALMONE_SDK else if (FtrGet(hsFtrCreator,hsFtrIDNavigationSupported,&ver)==errNone) return HsNavRemoveFocusRing(formP); #endif return uilibErrObjectFocusModeOff; } void FrmGlueNavObjectTakeFocus(FormType* formP, UInt16 objID) { UInt32 ver; if (FtrGet(sysFileCSystem, sysFtrNumFiveWayNavVersion, &ver)==errNone) FrmNavObjectTakeFocus(formP,objID); #ifdef HAVE_PALMONE_SDK else if (FtrGet(hsFtrCreator,hsFtrIDNavigationSupported,&ver)==errNone) HsNavObjectTakeFocus(formP,objID); #endif } Boolean FrmGlueNavIsSupported(void) { UInt32 ver; if (FtrGet(sysFileCSystem, sysFtrNumFiveWayNavVersion, &ver)==errNone) return 1; #ifdef HAVE_PALMONE_SDK if (FtrGet(hsFtrCreator,hsFtrIDNavigationSupported,&ver)==errNone) return 1; #endif return 0; } SysAppInfoPtr SysGetAppInfo(SysAppInfoPtr *uiAppPP, SysAppInfoPtr* actionCodeAppPP); NOINLINE MemPtr MemGluePtrNew(UInt32 Size) { MemPtr p = MemPtrNew(Size); if (!p) { SysAppInfoPtr appInfoP; UInt16 OwnerID = SysGetAppInfo(&appInfoP,&appInfoP)->memOwnerID; p = MemChunkNew(0, Size,(UInt16)(OwnerID | memNewChunkFlagNonMovable | memNewChunkFlagAllowLarge)); } return p; } void* PealLoadModule(uint16_t FtrId,Boolean Mem,Boolean OnlyFtr,Boolean MemSema) { uint16_t Param[4]; Param[0] = SWAP16(FtrId); Param[1] = (uint8_t)Mem; Param[2] = (uint8_t)OnlyFtr; Param[3] = (uint8_t)MemSema; return (void*)Call68K(SWAP32(Peal.LoadModule),Param,sizeof(Param)|kPceNativeWantA0); } void* PealGetSymbol(void* Module,const tchar_t* Name) { uint32_t Param[2]; Param[0] = SWAP32(Module); Param[1] = SWAP32(Name); return (void*)Call68K(SWAP32(Peal.GetSymbol),Param,sizeof(Param)|kPceNativeWantA0); } void PealFreeModule(void* Module) { uint32_t Param[1]; Param[0] = SWAP32(Module); Call68K(SWAP32(Peal.FreeModule),Param,sizeof(Param)); } #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/pace.h000066400000000000000000000113661462133141200215500ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __PACE_H #define __PACE_H #if defined(TARGET_PALMOS) #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if PALMOS_SDK_VERSION < 0x0541 #error Please update to Palm OS 5 SDK R4 #endif typedef struct sysregs { void* GOT; void* SysReg; } sysregs; void SaveSysRegs(sysregs* p); void LoadSysRegs(sysregs* p); extern Int32 GetOEMSleepMode(); extern Err SetOEMSleepMode(Int32 Mode); extern void* PealLoadModule(uint16_t FtrId,Boolean Mem,Boolean OnlyFtr,Boolean MemSema); extern void PealFreeModule(void*); extern void* PealGetSymbol(void*,const tchar_t* Name); extern Err SysGetEntryAddresses(UInt32 refNum, UInt32 entryNumStart, UInt32 entryNumEnd, void **addressP); extern Err SysFindModule(UInt32 dbType, UInt32 dbCreator, UInt16 rsrcID, UInt32 flags, UInt32 *refNumP); extern Err SysLoadModule(UInt32 dbType, UInt32 dbCreator, UInt16 rsrcID, UInt32 flags, UInt32 *refNumP); extern Err SysUnloadModule(UInt32 refNum); extern void HALDelay(UInt32 microSec); extern void HALDisplayWake(); extern void HALDisplayOff_TREO650(); extern void SonyCleanDCache(void*, UInt32); extern void SonyInvalidateDCache(void*, UInt32); extern int PalmCall(void* Func,...); //0..4 extern int PalmCall2(void* Func,...); //5..8 #if defined(_MSC_VER) #define PALMCALL0(Func) Func() #define PALMCALL1(Func,a) Func(a) #define PALMCALL2(Func,a,b) Func(a,b) #define PALMCALL3(Func,a,b,c) Func(a,b,c) #define PALMCALL4(Func,a,b,c,d) Func(a,b,c,d) #define PALMCALL5(Func,a,b,c,d,e) Func(a,b,c,d,e) #define PALMCALL6(Func,a,b,c,d,e,f) Func(a,b,c,d,e,f) #define PALMCALL7(Func,a,b,c,d,e,f,g) Func(a,b,c,d,e,f,g) #define PALMCALL8(Func,a,b,c,d,e,f,g,h) Func(a,b,c,d,e,f,g,h) #else #define PALMCALL0(Func) PalmCall(Func) #define PALMCALL1(Func,a) PalmCall(Func,a) #define PALMCALL2(Func,a,b) PalmCall(Func,a,b) #define PALMCALL3(Func,a,b,c) PalmCall(Func,a,b,c) #define PALMCALL4(Func,a,b,c,d) PalmCall(Func,a,b,c,d) #define PALMCALL5(Func,a,b,c,d,e) PalmCall2(Func,a,b,c,d,e) #define PALMCALL6(Func,a,b,c,d,e,f) PalmCall2(Func,a,b,c,d,e,f) #define PALMCALL7(Func,a,b,c,d,e,f,g) PalmCall2(Func,a,b,c,d,e,f,g) #define PALMCALL8(Func,a,b,c,d,e,f,g,h) PalmCall2(Func,a,b,c,d,e,f,g,h) #endif typedef uint16_t m68kcallback[12]; extern void* m68kCallBack(m68kcallback,NativeFuncType*); typedef Boolean FormEventHandlerExType(EventType *eventP, void* This); extern void FrmSetEventHandlerEx(FormType *formP,FormEventHandlerExType *handler,void* This); extern Boolean FrmCallEventHandlerEx(FormType *Form, EventType* eventP); typedef struct SysAppLaunchCmdOpenDBType2 { UInt16 cardNo; UInt16 dbID[2]; } SysAppLaunchCmdOpenDBType2; typedef struct vfspath { UInt16 volRefNum; Char path[256]; } vfspath; #if defined(IX86) NativeFuncType* IX86CallBack(const char* Func,char* Buffer); #endif #endif #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/pace2.c000066400000000000000000001647451462133141200216370ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #if defined(TARGET_PALMOS) #include #include #include #define NavSelectorFrmNavDrawFocusRing 7 #define NavSelectorFrmNavRemoveFocusRing 8 #define NavSelectorFrmNavGetFocusRingInfo 9 #define NavSelectorFrmNavObjectTakeFocus 10 #define sysTrapVFSMgr sysTrapFileSystemDispatch #define vfsTrapFileCreate 2 #define vfsTrapFileOpen 3 #define vfsTrapFileClose 4 #define vfsTrapFileReadData 5 #define vfsTrapFileRead 6 #define vfsTrapFileWrite 7 #define vfsTrapFileDelete 8 #define vfsTrapFileRename 9 #define vfsTrapFileSeek 10 #define vfsTrapFileEOF 11 #define vfsTrapFileTell 12 #define vfsTrapFileResize 13 #define vfsTrapFileGetAttributes 14 #define vfsTrapFileSetAttributes 15 #define vfsTrapFileGetDate 16 #define vfsTrapFileSetDate 17 #define vfsTrapFileSize 18 #define vfsTrapDirCreate 19 #define vfsTrapDirEntryEnumerate 20 #define vfsTrapGetDefaultDirectory 21 #define vfsTrapRegisterDefaultDirectory 22 #define vfsTrapUnregisterDefaultDirectory 23 #define vfsTrapVolumeFormat 24 #define vfsTrapVolumeMount 25 #define vfsTrapVolumeUnmount 26 #define vfsTrapVolumeEnumerate 27 #define vfsTrapVolumeInfo 28 #define vfsTrapVolumeGetLabel 29 #define vfsTrapVolumeSetLabel 30 #define vfsTrapVolumeSize 31 #define vfsTrapInstallFSLib 32 #define vfsTrapRemoveFSLib 33 #define vfsTrapImportDatabaseFromFile 34 #define vfsTrapExportDatabaseToFile 35 #define vfsTrapFileDBGetResource 36 #define vfsTrapFileDBInfo 37 #define vfsTrapFileDBGetRecord 38 #define vfsTrapImportDatabaseFromFileCustom 39 #define vfsTrapExportDatabaseToFileCustom 40 #define HDSelectorWinSetCoordinateSystem 8 #define HDSelectorWinGetCoordinateSystem 9 #define HDSelectorWinScalePoint 10 #define HDSelectorWinUnscalePoint 11 #define HDSelectorWinScaleRectangle 12 #define HDSelectorWinUnscaleRectangle 13 #define HDSelectorWinScreenGetAttribute 14 #define HDSelectorWinScaleCoord 18 #define HDSelectorWinUnscaleCoord 19 #define pinPINSetInputAreaState 0 #define pinPINGetInputAreaState 1 #define pinPINSetInputTriggerState 2 #define pinPINGetInputTriggerState 3 #define pinWinSetConstraintsSize 13 #define pinFrmSetDIAPolicyAttr 14 #define pinFrmGetDIAPolicyAttr 15 #define pinStatHide 16 #define pinStatShow 17 #define pinStatGetAttribute 18 #define pinSysGetOrientation 19 #define pinSysSetOrientation 20 #define pinSysGetOrientationTriggerState 21 #define pinSysSetOrientationTriggerState 22 #define netLibTrapAddrINToA (sysLibTrapCustom+0) #define netLibTrapAddrAToIN (sysLibTrapCustom+1) #define netLibTrapSocketOpen (sysLibTrapCustom+2) #define netLibTrapSocketClose (sysLibTrapCustom+3) #define netLibTrapSocketOptionSet (sysLibTrapCustom+4) #define netLibTrapSocketOptionGet (sysLibTrapCustom+5) #define netLibTrapSocketBind (sysLibTrapCustom+6) #define netLibTrapSocketConnect (sysLibTrapCustom+7) #define netLibTrapSocketListen (sysLibTrapCustom+8) #define netLibTrapSocketAccept (sysLibTrapCustom+9) #define netLibTrapSocketShutdown (sysLibTrapCustom+10) #define netLibTrapSendPB (sysLibTrapCustom+11) #define netLibTrapSend (sysLibTrapCustom+12) #define netLibTrapReceivePB (sysLibTrapCustom+13) #define netLibTrapReceive (sysLibTrapCustom+14) #define netLibTrapDmReceive (sysLibTrapCustom+15) #define netLibTrapSelect (sysLibTrapCustom+16) #define netLibTrapPrefsGet (sysLibTrapCustom+17) #define netLibTrapPrefsSet (sysLibTrapCustom+18) #define netLibTrapGetHostByName (sysLibTrapCustom+22) #define netLibTrapGetHostByAddr (sysLibTrapCustom+34) #define netLibTrapGetServByName (sysLibTrapCustom+35) #define netLibTrapSocketAddr (sysLibTrapCustom+36) #include "arm/pealstub.h" typedef struct emustate { uint32_t instr; uint32_t regD[8]; uint32_t regA[8]; uint32_t regPC; } emustate; #define PACE_ADD16 1, #define PACE_ADD32 2, #define PACE_TRAP(Trap) 3,PceNativeTrapNo(Trap) & 255,PceNativeTrapNo(Trap)>>8, #define PACE_TRAP32(Trap) 3,PceNativeTrapNo(Trap) & 255,PceNativeTrapNo(Trap)>>8, #define PACE_TRAPPTR(Trap) 4,PceNativeTrapNo(Trap) & 255,PceNativeTrapNo(Trap)>>8, #define PACE_TRAP16(Trap) 5,PceNativeTrapNo(Trap) & 255,PceNativeTrapNo(Trap)>>8, #define PACE_DATA16(n) 6,n, #define PACE_DATA32(n) 7,n, #define PACE_ADD8 8, #define PACE_SWAP_BEGIN(n) 9,n, #define PACE_SWAP16 2, #define PACE_SWAP32 4, #define PACE_SWAP_SKIP(n) (n)^1, #define PACE_SWAP_END 0, #define PACE_COPY(n,size) 10,n,size, #define PACE_SEL(sel) 11,(sel)&255,(sel)>>8, #define PACE_TRAP8(Trap) 12,PceNativeTrapNo(Trap) & 255,PceNativeTrapNo(Trap)>>8, #define PACE_EVENT_ARM_TO_M68K(n) 13,n, #define PACE_ADDCOPY 14, #define PACE_EVENT_M68K_TO_ARM(n) 15,n, #define PACE_UNPOPPED(c) 16,(c)&255,(c)>>8, #define PACE_SWAP32LIST16(n,m) 17,n,m, #define PACE_SWAP16DATA(n,m) 18,n,m, #define PACE_SWAP32LISTPTR32(n,m) 19,n,m, #define PACE_BEGIN @@error@@ #define PACE_BEGIN0(Name) uint32_t Name() { static const uint8_t cmd[] = { #define PACE_END0 0}; return PaceParse(NULL,cmd); } #define PACE_BEGIN1(Name) uint32_t Name(uint32_t a) { static const uint8_t cmd[] = { #define PACE_END1 0}; return PaceParse_1(a,cmd); } #define PACE_BEGIN2(Name) uint32_t Name(uint32_t a,uint32_t b) { static const uint8_t cmd[] = { #define PACE_END2 0}; return PaceParse_2(a,b,cmd); } #define PACE_BEGIN3(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c) { static const uint8_t cmd[] = { #define PACE_END3 0}; return PaceParse_3(a,b,c,cmd); } #define PACE_BEGIN4(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d) { static const uint8_t cmd[] = { #define PACE_END4 0}; return PaceParse_4(a,b,c,d,cmd); } #define PACE_BEGIN5(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e) { static const uint8_t cmd[] = { #define PACE_END5 0}; return PaceParse_5(a,b,c,d,e,cmd); } #define PACE_BEGIN6(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f) { static const uint8_t cmd[] = { #define PACE_END6 0}; return PaceParse_6(a,b,c,d,e,f,cmd); } #define PACE_BEGIN7(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g) { static const uint8_t cmd[] = { #define PACE_END7 0}; return PaceParse_7(a,b,c,d,e,f,g,cmd); } #define PACE_BEGIN8(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g,uint32_t h) { static const uint8_t cmd[] = { #define PACE_END8 0}; return PaceParse_8(a,b,c,d,e,f,g,h,cmd); } #define PACE_BEGIN9(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g,uint32_t h,uint32_t i) { static const uint8_t cmd[] = { #define PACE_END9 0}; return PaceParse_9(a,b,c,d,e,f,g,h,i,cmd); } #define PACE_BEGIN10(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g,uint32_t h,uint32_t i,uint32_t j) { static const uint8_t cmd[] = { #define PACE_END10 0}; return PaceParse_10(a,b,c,d,e,f,g,h,i,j,cmd); } #define PACE_BEGIN13(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g,uint32_t h,uint32_t i,uint32_t j,uint32_t k,uint32_t l,uint32_t m) { static const uint8_t cmd[] = { #define PACE_END13 0}; return PaceParse_13(a,b,c,d,e,f,g,h,i,j,k,l,m,cmd); } #define PACE_BEGIN16(Name) uint32_t Name(uint32_t a,uint32_t b,uint32_t c,uint32_t d,uint32_t e,uint32_t f,uint32_t g,uint32_t h,uint32_t i,uint32_t j,uint32_t k,uint32_t l,uint32_t m,uint32_t n,uint32_t p,uint32_t q) { static const uint8_t cmd[] = { #define PACE_END16 0}; return PaceParse_16(a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,cmd); } #define MAX_COPY 32 #define MAX_ARGS 32 void Event_M68K_To_ARM(const uint16_t* In,void* Out); void Event_ARM_To_M68K(const void* In,uint16_t* Out); uint32_t Call68K(uint32_t trapOrFunction, const void *argsOnStackP, uint32_t argsSizeAndwantA0); static NOINLINE uint32_t PaceParse(uint32_t* param, const uint8_t* cmd) { uint16_t args[MAX_ARGS]; uint16_t* pos = args; uint32_t* i = param; uint32_t result = 0; uint8_t* ptr8; uint16_t* ptr16; uint32_t* ptr32; uint32_t* cnt32; uint8_t copy[MAX_COPY]; uint8_t* copypos = copy; size_t num; for (;*cmd;++cmd) { switch (*cmd) { case 1: *(pos++) = SWAP16(*i); ++i; assert(pos<=args+MAX_ARGS); break; case 2: *(pos++) = SWAP16(*i >> 16); *(pos++) = SWAP16(*i); ++i; assert(pos<=args+MAX_ARGS); break; case 3: result = Call68K(cmd[1]|(cmd[2]<<8),args,((uint8_t*)pos - (uint8_t*)args)); cmd += 2; break; case 4: result = Call68K(cmd[1]|(cmd[2]<<8),args,((uint8_t*)pos - (uint8_t*)args) | kPceNativeWantA0); cmd += 2; break; case 5: result = (uint16_t)Call68K(cmd[1]|(cmd[2]<<8),args,((uint8_t*)pos - (uint8_t*)args)); cmd += 2; break; case 12: result = (uint8_t)Call68K(cmd[1]|(cmd[2]<<8),args,((uint8_t*)pos - (uint8_t*)args)); cmd += 2; break; case 6: ptr16 = (uint16_t*)param[*(++cmd)]; if (ptr16) *ptr16 = SWAP16(*ptr16); break; case 7: ptr32 = (uint32_t*)param[*(++cmd)]; if (ptr32) *ptr32 = SWAP32(*ptr32); break; case 8: //PACE_ADD8 *(pos++) = (uint8_t)(*i); ++i; break; case 9: //PACE_SWAP_BEGIN ptr8 = (uint8_t*)param[*(++cmd)]; while (*(++cmd)) if (ptr8) { if (*cmd & 1) { // skip if (*cmd == 1) ++ptr8; else ptr8 += *cmd ^ 1; } else { // swap switch (*cmd) { case 4: *((uint32_t*)ptr8) = SWAP32(*((uint32_t*)ptr8)); break; case 2: *((uint16_t*)ptr8) = SWAP16(*((uint16_t*)ptr8)); break; } ptr8 += *cmd; } } break; case 10: ptr8 = (uint8_t*)param[cmd[1]]; if (ptr8) { memcpy(copypos,ptr8,cmd[2]); param[cmd[1]] = (uint32_t)copypos; copypos += cmd[2]; assert(copyposregD[2] = cmd[1]|(cmd[2]<<8); cmd += 2; break; case 13: Event_ARM_To_M68K((void*)param[*(++cmd)],(uint16_t*)copypos); param[*cmd] = (uint32_t)copypos; copypos += 12*2; assert(copypos> 16); *(pos++) = SWAP16((uint32_t)copy); ++i; assert(pos<=args+MAX_ARGS); break; case 15: Event_M68K_To_ARM((uint16_t*)copy,(void*)param[*(++cmd)]); break; case 16: ((emustate*)PceCall.State)->regA[7] -= 2; *(pos++) = (uint16_t)(cmd[2]|(cmd[1]<<8)); cmd += 2; assert(pos<=args+MAX_ARGS); break; case 17: ptr32 = (uint32_t*)param[*(++cmd)]; num = (uint16_t)param[*(++cmd)]; if (ptr32) { size_t i; for (i=0;i PACE_BEGIN5(HsNavGetFocusRingInfo) PACE_UNPOPPED(hsSelNavGetFocusRingInfo) PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_TRAP16(sysTrapOEMDispatch) PACE_DATA16(1) PACE_DATA16(2) PACE_SWAP_BEGIN(3) PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP_END PACE_DATA16(4) PACE_END5 PACE_BEGIN6(HsNavDrawFocusRing) PACE_COPY(3,2*4) PACE_SWAP_BEGIN(3) PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP_END PACE_UNPOPPED(hsSelNavDrawFocusRing) PACE_ADD32 PACE_ADD16 PACE_ADD16 PACE_ADD32 PACE_ADD16 PACE_ADD8 PACE_TRAP16(sysTrapOEMDispatch) PACE_END6 PACE_BEGIN1(HsNavRemoveFocusRing) PACE_UNPOPPED(hsSelNavRemoveFocusRing) PACE_ADD32 PACE_TRAP16(sysTrapOEMDispatch) PACE_END1 PACE_BEGIN2(HsNavObjectTakeFocus) PACE_UNPOPPED(hsSelNavObjectTakeFocus) PACE_ADD32 PACE_ADD16 PACE_TRAP(sysTrapOEMDispatch) PACE_END2 PACE_BEGIN2(HsLightCircumstance) PACE_UNPOPPED(hsSelLightCircumstance) PACE_ADD8 PACE_ADD16 PACE_TRAP16(sysTrapOEMDispatch) PACE_END2 PACE_BEGIN0(HsCurrentLightCircumstance) PACE_UNPOPPED(hsGetCurrentLightCircumstance) PACE_TRAP16(sysTrapOEMDispatch) PACE_END0 PACE_BEGIN3(HsAttrGet) PACE_UNPOPPED(hsSelAttrGet) PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_TRAP16(sysTrapOEMDispatch) PACE_DATA32(2) PACE_END3 PACE_BEGIN3(HsAttrSet) PACE_UNPOPPED(hsSelAttrSet) PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_DATA32(2) PACE_TRAP16(sysTrapOEMDispatch) PACE_DATA32(2) PACE_END3 PACE_BEGIN2(HWUBlinkLED) PACE_ADD16 PACE_ADD8 PACE_TRAP16((sysLibTrapCustom+0)) PACE_END2 PACE_BEGIN2(HWUSetBlinkRate) PACE_ADD16 PACE_ADD16 PACE_TRAP16((sysLibTrapCustom+1)) PACE_END2 PACE_BEGIN2(HWUEnableDisplay) PACE_ADD16 PACE_ADD8 PACE_TRAP16((sysLibTrapCustom+2)) PACE_END2 PACE_BEGIN1(HWUGetDisplayState) PACE_ADD16 PACE_TRAP8((sysLibTrapCustom+3)) PACE_END1 PACE_BEGIN1(DexGetDisplayAddress) PACE_ADD16 PACE_TRAPPTR((sysLibTrapCustom+4)) PACE_END1 PACE_BEGIN4(DexGetDisplayDimensions) PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_TRAP((sysLibTrapCustom+5)) PACE_DATA16(1) PACE_DATA16(2) PACE_DATA16(3) PACE_END4 #endif #ifdef HAVE_SONY_SDK PACE_BEGIN1(VskGetAPIVersion) PACE_ADD16 PACE_TRAP32((sysLibTrapCustom+3)) PACE_END1 PACE_BEGIN3(VskSetState) PACE_ADD16 PACE_ADD16 PACE_ADD16 PACE_TRAP16((sysLibTrapCustom+6)) PACE_END3 PACE_BEGIN3(VskGetState) PACE_ADD16 PACE_ADD16 PACE_ADD32 PACE_TRAP16((sysLibTrapCustom+7)) PACE_DATA16(2) PACE_END3 #endif PACE_BEGIN3(SysLibLoad) PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_TRAP16(sysTrapSysLibLoad) PACE_DATA16(2) PACE_END3 PACE_BEGIN2(SysLibFind) PACE_ADD32 PACE_ADD32 PACE_TRAP16(sysTrapSysLibFind) PACE_DATA16(1) PACE_END2 PACE_BEGIN5(FrmNavGetFocusRingInfo) PACE_UNPOPPED(NavSelectorFrmNavGetFocusRingInfo) PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_TRAP16(sysTrapNavSelector) PACE_DATA16(1) PACE_DATA16(2) PACE_SWAP_BEGIN(3) PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP_END PACE_DATA16(4) PACE_END5 PACE_BEGIN6(FrmNavDrawFocusRing) PACE_COPY(3,2*4) PACE_SWAP_BEGIN(3) PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP16 PACE_SWAP_END PACE_UNPOPPED(NavSelectorFrmNavDrawFocusRing) PACE_ADD32 PACE_ADD16 PACE_ADD16 PACE_ADD32 PACE_ADD16 PACE_ADD8 PACE_TRAP16(sysTrapNavSelector) PACE_END6 PACE_BEGIN1(FrmNavRemoveFocusRing) PACE_UNPOPPED(NavSelectorFrmNavRemoveFocusRing) PACE_ADD32 PACE_TRAP16(sysTrapNavSelector) PACE_END1 PACE_BEGIN2(FrmNavObjectTakeFocus) PACE_UNPOPPED(NavSelectorFrmNavObjectTakeFocus) PACE_ADD32 PACE_ADD16 PACE_TRAP(sysTrapNavSelector) PACE_END2 PACE_BEGIN2(NetLibOpen) PACE_ADD16 PACE_ADD32 PACE_TRAP16(sysLibTrapOpen) PACE_DATA16(1) PACE_END2 PACE_BEGIN2(NetLibClose) PACE_ADD16 PACE_ADD16 PACE_TRAP16(sysLibTrapClose) PACE_END2 PACE_BEGIN6(NetLibSocketOpen) PACE_ADD16 //libRefnum PACE_ADD8 //domain PACE_ADD8 //type PACE_ADD16 //protocol PACE_ADD32 //timeout PACE_ADD32 //errP PACE_TRAP16(netLibTrapSocketOpen) PACE_DATA16(5) PACE_END6 PACE_BEGIN5(NetLibSocketShutdown) PACE_ADD16 //libRefnum PACE_ADD16 //socket PACE_ADD16 //direction PACE_ADD32 //timeout PACE_ADD32 //errP PACE_TRAP16(netLibTrapSocketShutdown) PACE_DATA16(4) PACE_END5 PACE_BEGIN4(NetLibSocketClose) PACE_ADD16 //libRefnum PACE_ADD16 //socket PACE_ADD32 //timeout PACE_ADD32 //errP PACE_TRAP16(netLibTrapSocketClose) PACE_DATA16(3) PACE_END4 PACE_BEGIN3(NetLibAddrINToA) PACE_ADD16 //libRefnum PACE_ADD32 //inet PACE_ADD32 //spaceP PACE_TRAPPTR(netLibTrapAddrINToA) PACE_END3 PACE_BEGIN2(NetLibAddrAToIN) PACE_ADD16 //libRefnum PACE_ADD32 //addr PACE_TRAP32(netLibTrapAddrAToIN) PACE_END2 PACE_BEGIN6(NetLibSocketBind) PACE_ADD16 //libRefnum PACE_ADD16 //socket PACE_ADD32 //sockAddrP PACE_ADD16 //addrLen PACE_ADD32 //timeout PACE_ADD32 //errP PACE_SWAP_BEGIN(2) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_TRAP16(netLibTrapSocketBind) PACE_DATA16(5) PACE_SWAP_BEGIN(2) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_END6 PACE_BEGIN6(NetLibSocketConnect) PACE_ADD16 //libRefnum PACE_ADD16 //socket PACE_ADD32 //sockAddrP PACE_ADD16 //addrLen PACE_ADD32 //timeout PACE_ADD32 //errP PACE_SWAP_BEGIN(2) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_TRAP16(netLibTrapSocketConnect) PACE_DATA16(5) PACE_SWAP_BEGIN(2) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_END6 PACE_BEGIN9(NetLibReceive) PACE_ADD16 //libRefNum PACE_ADD16 //socket PACE_ADD32 //bufP PACE_ADD16 //bufLen PACE_ADD16 //flags PACE_ADD32 //fromAddrP PACE_ADD32 //fromLenP PACE_ADD32 //timeout PACE_ADD32 //errP PACE_DATA16(6) PACE_SWAP_BEGIN(5) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_TRAP16(netLibTrapReceive) PACE_DATA16(6) PACE_SWAP_BEGIN(5) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_DATA16(8) PACE_END9 PACE_BEGIN9(NetLibSend) PACE_ADD16 //libRefNum PACE_ADD16 //socket PACE_ADD32 //bufP PACE_ADD16 //bufLen PACE_ADD16 //flags PACE_ADD32 //toAddrP PACE_ADD16 //toLen PACE_ADD32 //timeout PACE_ADD32 //errP PACE_SWAP_BEGIN(5) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_TRAP16(netLibTrapSend) PACE_SWAP_BEGIN(5) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_DATA16(8) PACE_END9 PACE_BEGIN8(NetLibSocketAddr) PACE_ADD16 //libRefnum PACE_ADD16 //socketRef PACE_ADD32 //locAddrP PACE_ADD32 //locAddrLenP PACE_ADD32 //remAddrP PACE_ADD32 //remAddrLenP PACE_ADD32 //timeout PACE_ADD32 //errP PACE_DATA16(5) PACE_DATA16(3) PACE_TRAP16(netLibTrapSocketAddr) PACE_DATA16(5) PACE_SWAP_BEGIN(4) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_DATA16(3) PACE_SWAP_BEGIN(2) PACE_SWAP16 PACE_SWAP16 PACE_SWAP32 PACE_SWAP_END PACE_DATA16(7) PACE_END8 PACE_BEGIN5(NetLibGetHostByName) PACE_ADD16 //libRefNum PACE_ADD32 //nameP PACE_ADD32 //bufP PACE_ADD32 //timeout PACE_ADD32 //errP PACE_TRAPPTR(netLibTrapGetHostByName) PACE_DATA16(4) PACE_SWAP_BEGIN(2) PACE_SWAP32 // nameP PACE_SWAP32 // nameAliasesP PACE_SWAP16 // addrType PACE_SWAP16 // addrLen PACE_SWAP32 // addrListP PACE_SWAP_SKIP(128) // name[netDNSMaxDomainName+1] PACE_SWAP_SKIP(128) // name[netDNSMaxDomainName+1] PACE_SWAP32 // aliasList[0] PACE_SWAP32 // aliasList[1] PACE_SWAP_SKIP(128) // aliases[0][netDNSMaxDomainName+1] PACE_SWAP_SKIP(128) // aliases[0][anetDNSMaxDomainName+1] PACE_SWAP32 // addressList[0] PACE_SWAP32 // addressList[1] PACE_SWAP32 // addressList[2] PACE_SWAP32 // addressList[3] PACE_SWAP32 // address[0] PACE_SWAP32 // address[1] PACE_SWAP32 // address[2] PACE_SWAP32 // address[3] PACE_SWAP_END PACE_END5 PACE_BEGIN7(NetLibSelect) PACE_ADD16 //libRefNum PACE_ADD16 //width PACE_ADD32 //readFDs PACE_ADD32 //writeFDs PACE_ADD32 //exceptFDs PACE_ADD32 //timeout PACE_ADD32 //errP PACE_DATA32(2) PACE_DATA32(3) PACE_DATA32(4) PACE_TRAP16(netLibTrapSelect) PACE_DATA32(2) PACE_DATA32(3) PACE_DATA32(4) PACE_DATA16(6) PACE_END7 PACE_BEGIN8(NetLibSocketOptionSet) PACE_ADD16 //libRefnum PACE_ADD16 //socket, PACE_ADD16 //level PACE_ADD16 //option PACE_ADD32 //optValueP PACE_ADD16 //optValueLen PACE_ADD32 //timeout PACE_ADD32 //errP PACE_SWAP16DATA(4,5) PACE_TRAP16(netLibTrapSocketOptionSet) PACE_SWAP16DATA(4,5) PACE_DATA16(7) PACE_END8 PACE_BEGIN6(TxtCompare) PACE_ADD32 PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_ADD16 PACE_ADD32 PACE_SEL(intlTxtCompare) PACE_TRAP16(sysTrapIntlDispatch) PACE_DATA16(2) PACE_DATA16(5) PACE_END6 PACE_BEGIN6(TxtCaselessCompare) PACE_ADD32 PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_ADD16 PACE_ADD32 PACE_SEL(intlTxtCaselessCompare) PACE_TRAP16(sysTrapIntlDispatch) PACE_DATA16(2) PACE_DATA16(5) PACE_END6 PACE_BEGIN5(TxtTransliterate) PACE_ADD32 PACE_ADD16 PACE_ADD32 PACE_ADD32 PACE_ADD16 PACE_DATA16(3) PACE_SEL(intlTxtTransliterate) PACE_TRAP16(sysTrapIntlDispatch) PACE_DATA16(3) PACE_END5 PACE_BEGIN1(TxtNameToEncoding) PACE_ADD32 PACE_SEL(intlTxtNameToEncoding) PACE_TRAP8(sysTrapIntlDispatch) PACE_END1 PACE_BEGIN10(TxtConvertEncoding) PACE_ADD8 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD8 PACE_ADD32 PACE_ADD32 PACE_ADD8 PACE_ADD32 PACE_ADD16 PACE_DATA16(3) PACE_DATA16(6) PACE_SEL(intlTxtConvertEncoding) PACE_TRAP16(sysTrapIntlDispatch) PACE_DATA16(3) PACE_DATA16(6) PACE_END10 PACE_BEGIN1(TxtEncodingName) PACE_ADD8 PACE_SEL(intlTxtEncodingName) PACE_TRAPPTR(sysTrapIntlDispatch) PACE_END1 PACE_BEGIN6(DlkGetSyncInfo) PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_ADD32 PACE_DATA32(5) PACE_TRAP16(sysTrapDlkGetSyncInfo) PACE_DATA32(0) PACE_DATA32(1) PACE_DATA32(5) PACE_END6 PACE_BEGIN3(ExgGetDefaultApplication) PACE_ADD32 //creatorID PACE_ADD16 //typeId PACE_ADD32 //dataTypesP PACE_TRAP16(sysTrapExgGetDefaultApplication) PACE_DATA32(0) PACE_END3 PACE_BEGIN3(ExgSetDefaultApplication) PACE_ADD32 //creatorID PACE_ADD16 //typeId PACE_ADD32 //dataTypesP PACE_TRAP16(sysTrapExgSetDefaultApplication) PACE_END3 PACE_BEGIN5(ExgRegisterDatatype) PACE_ADD32 //creatorID PACE_ADD16 //typeId PACE_ADD32 //dataTypesP PACE_ADD32 //descriptionsP PACE_ADD16 //flags PACE_TRAP16(sysTrapExgRegisterDatatype) PACE_END5 PACE_BEGIN6(ExgGetRegisteredApplications) PACE_ADD32 //creatorIDsP PACE_ADD32 //numAppsP PACE_ADD32 //namesP PACE_ADD32 //descriptionsP PACE_ADD16 //typeId PACE_ADD32 //dataTypesP PACE_TRAP16(sysTrapExgGetRegisteredApplications) PACE_DATA32(0) PACE_DATA32(1) PACE_DATA32(2) PACE_DATA32(3) PACE_SWAP32LISTPTR32(0,1) PACE_END6 PACE_BEGIN3(TimTimeZoneToUTC) PACE_ADD32 // seconds PACE_ADD16 // timeZone PACE_ADD16 // daylightSavingAdjustment PACE_TRAP32(sysTrapTimTimeZoneToUTC) PACE_END3 PACE_BEGIN3(TimUTCToTimeZone) PACE_ADD32 // seconds PACE_ADD16 // timeZone PACE_ADD16 // daylightSavingAdjustment PACE_TRAP32(sysTrapTimUTCToTimeZone) PACE_END3 #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/qsort.c000066400000000000000000000042331462133141200217760ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" // cheap fake bubble sort :))) void qsort(void *const base, size_t num, size_t size,int (*cmp)(const void*, const void*)) { if (num>1) { void* tmp = alloca(size); int changed; do { char* p = (char*)base; char* pe = p + num*size; changed = 0; for (p+=size;p!=pe;p+=size) if (cmp(p-size,p)>0) { memcpy(tmp,p,size); memcpy(p,p-size,size); memcpy(p-size,tmp,size); changed = 1; } } while (changed); } } bcmatroska2-5.3.101/corec/corec/libc/palmos/rand.c000066400000000000000000000035501462133141200215530ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" static unsigned int rndseed = 1; int rand() { rndseed = rndseed*0x8088405+1; return rndseed & 0x7FFF; } void srand(unsigned int i) { rndseed = i; } bcmatroska2-5.3.101/corec/corec/libc/palmos/setjmp.S000066400000000000000000000035401462133141200221100ustar00rootroot00000000000000@***************************************************************************** @* @* Copyright (c) 2008-2010, CoreCodec, Inc. @* All rights reserved. @* @* Redistribution and use in source and binary forms, with or without @* modification, are permitted provided that the following conditions are met: @* * Redistributions of source code must retain the above copyright @* notice, this list of conditions and the following disclaimer. @* * Redistributions in binary form must reproduce the above copyright @* notice, this list of conditions and the following disclaimer in the @* documentation and/or other materials provided with the distribution. @* * Neither the name of CoreCodec, Inc. nor the @* names of its contributors may be used to endorse or promote products @* derived from this software without specific prior written permission. @* @* THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY @* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED @* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE @* DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY @* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES @* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; @* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND @* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT @* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS @* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @* @***************************************************************************** .global setjmp .global longjmp setjmp: mov r12,#0 stmia r0,{r4-r12,sp,lr} mov r0,#0 mov pc,lr longjmp: ldmia r0!,{r4-r12,sp,lr} movs r0,r1 moveq r0,#1 mov pc,lr bcmatroska2-5.3.101/corec/corec/libc/palmos/setjmp.h000066400000000000000000000037141462133141200221400ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __SETJMP_H_ #define __SETJMP_H_ // for MatroskaParser.c #ifndef EOF #define EOF -1 #endif // for lua #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 void exit( int status ); typedef int jmp_buf[16]; int setjmp(jmp_buf jp); int longjmp(jmp_buf jp, int ret); #endif bcmatroska2-5.3.101/corec/corec/libc/palmos/sincos.c000066400000000000000000000046311462133141200221260ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #define PI 3.14159265358979324 NOINLINE double floor(double i); NOINLINE double ceil(double i) { if (i<0) return -floor(-i); else { double d = floor(i); if (d!=i) d+=1.0; return d; } } NOINLINE double floor(double i) { if (i<0) return -ceil(-i); else return (double)(int)i; } NOINLINE double sin(double i) { int n,k; double j,sum; int sign = 0; if (i<0) { sign = 1; i = -i; } i *= 1.0/(2*PI); i -= floor(i); if (i>=0.5) { i -= 0.5; sign ^= 1; } i *= 2*PI; k = 1; j = sum = i; for (n=3;n<14;n+=2) { k *= (n-1)*n; j *= i*i; if (n & 2) sum -= j/k; else sum += j/k; } return sign ? -sum:sum; } NOINLINE double cos(double i) { return sin(i+PI/2); } bcmatroska2-5.3.101/corec/corec/libc/palmos/strings.c000066400000000000000000000035611462133141200223220ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" char *strdup(const char *s) { size_t slen = strlen(s); char *out = malloc(slen+1); if (!out) return NULL; strcpy(out,s); return out; } bcmatroska2-5.3.101/corec/corec/libc/palmos/vsprintf.c000066400000000000000000000106461462133141200225060ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" int vsprintf(tchar_t *s0, const tchar_t *fmt, va_list args) { tchar_t Num[80]; tchar_t *s; for (s=s0;*fmt;++fmt) { if (fmt[0]=='%' && fmt[1]) { const tchar_t *str; bool_t Left = 0; bool_t Sign = 0; bool_t Large = 0; bool_t ZeroPad = 0; int Width = -1; int Type = -1; int Base = 10; tchar_t ch,cs; int Len; long n; for (;;) { switch (*(++fmt)) { case '-': Left = 1; continue; case '0': ZeroPad = 1; continue; default: break; } break; } if (*fmt>='0' && *fmt<='9') { Width = 0; for (;*fmt>='0' && *fmt<='9';++fmt) Width = Width*10 + (*fmt-'0'); } else if (*fmt == '*') { ++fmt; Width = va_arg(args, int); if (Width < 0) { Left = 1; Width = -Width; } } if (*fmt == 'h' || *fmt == 'L' || *fmt == 'l') Type = *(fmt++); switch (*fmt) { case 'c': for (;!Left && Width>1;--Width) *(s++) = ' '; *(s++) = (char)va_arg(args,int); for (;Width>1;--Width) *(s++) = ' '; continue; case 's': str = va_arg(args,const tchar_t*); if (!s) str = T(""); Len = tcslen(str); for (;!Left && Width>Len;--Width) *(s++) = ' '; for (;Len>0;--Len,--Width) *(s++) = *(str++); for (;Width>0;--Width) *(s++) = ' '; continue; case 'o': Base = 8; break; case 'X': Large = 1; case 'x': Base = 16; break; case 'i': case 'd': Sign = 1; case 'u': break; default: if (*fmt != '%') *(s++) = '%'; *(s++) = *fmt; continue; } if (Type == 'l') n = va_arg(args,unsigned long); else if (Type == 'h') if (Sign) n = (short)va_arg(args,int); else n = (unsigned short)va_arg(args,unsigned int); else if (Sign) n = va_arg(args,int); else n= va_arg(args,unsigned int); if (Left) ZeroPad = 0; if (Large) str = T("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); else str = T("0123456789abcdefghijklmnopqrstuvwxyz"); ch = ' '; if (ZeroPad) ch = '0'; cs = 0; if (n<0 && Sign) { cs = '-'; n=-n; } Len = 0; if (n==0) Num[Len++] = '0'; else { unsigned long un = n; while (un != 0) { Num[Len++] = str[un%Base]; un /= Base; } } if (cs) ++Len; for (;!Left && Width>Len;--Width) *(s++) = ch; if (cs) { *(s++) = cs; --Len; --Width; } for (;Len;--Width) *(s++) = Num[--Len]; for (;Width>0;--Width) *(s++) = ' '; } else *(s++) = *fmt; } *(s++) = 0; return s-s0; } int sprintf(tchar_t *s, const tchar_t *fmt, ...) { int i; va_list Args; va_start(Args,fmt); i=vsprintf(s,fmt,Args); va_end(Args); return i; } bcmatroska2-5.3.101/corec/corec/libc/symbian/000077500000000000000000000000001462133141200206275ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/libc/symbian/malloc.h000066400000000000000000000000241462133141200222430ustar00rootroot00000000000000#include bcmatroska2-5.3.101/corec/corec/libc/symbian/memory.h000066400000000000000000000000501462133141200223030ustar00rootroot00000000000000#include #include bcmatroska2-5.3.101/corec/corec/libc/wince/000077500000000000000000000000001462133141200202725ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/libc/wince/assert.c000066400000000000000000000045501462133141200217430ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "corec/corec.h" #ifndef NDEBUG #ifndef STRICT #define STRICT #endif #include ASSERT_DLL void _Assert(const char* Exp,const char* File,int Line) { WCHAR WExp[MAXPATH]; WCHAR WFile[MAXPATH]; size_t i; int n=1000000; for (i=0;i1 && Line extern int main(int argc,char** argv); int __cdecl wprintf(const WCHAR* fmt,...) { WCHAR sw[1024]; int i; va_list Args; va_start(Args,fmt); i=vswprintf(sw,fmt,Args); va_end(Args); OutputDebugString(sw); return i; } int __cdecl printf(const char* fmt,...) { WCHAR sw[1024]; char s[1024]; int i; va_list Args; va_start(Args,fmt); i=vsprintf(s,fmt,Args); va_end(Args); MultiByteToWideChar(CP_ACP,0,s,-1,sw,1024); OutputDebugString(sw); return i; } int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hParent,WCHAR* Cmd,int CmdShow) { char *i,*j; char Cmd8[1024]; int n=1; char* argv[64]; argv[0] = ""; WideCharToMultiByte(CP_ACP,0,Cmd,-1,Cmd8,sizeof(Cmd8),0,0); for (i=Cmd8;*i;) { while (isspace(*i)) ++i; if (*i) { int quote = 0; argv[n++] = i; j = i; for (;*i && (quote || !isspace(*i));++i) { if (*i=='"') quote = !quote; else *(j++) = *i; } if (*i) ++i; *j = 0; } } argv[n] = NULL; //_wfreopen(L"\\stdin",L"rb",stdin); //_wfreopen(L"\\stdout",L"w+b",stdout); return main(n,argv); } bcmatroska2-5.3.101/corec/corec/libc/wince/math.h000066400000000000000000000044611462133141200214010ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __MATH_H #define __MATH_H #include "stdlib.h" #define sinf(x) ((float)sin(x)) #define sinhf(x) ((float)sinh(x)) #define cosf(x) ((float)cos(x)) #define coshf(x) ((float)cosh(x)) #define tanf(x) ((float)tan(x)) #define tanhf(x) ((float)tanh(x)) #define asinf(x) ((float)asin(x)) #define acosf(x) ((float)acos(x)) #define atanf(x) ((float)atan(x)) #define atan2f(x,y) ((float)atan2(x,y)) #define powf(x,y) ((float)pow(x,y)) #define logf(x) ((float)log(x)) #define log10f(x) ((float)log10(x)) #define expf(x) ((float)exp(x)) #define frexpf(x,y) ((float)frexp(x,y)) #define ldexpf(x,y) ((float)ldexp(x,y)) #endif /* __MATH_H*/ bcmatroska2-5.3.101/corec/corec/memalloc.h000066400000000000000000000047411462133141200202240ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __MEMALLOC_H #define __MEMALLOC_H typedef struct cc_memalloc { void* (*Alloc)(const void* This,size_t); void (*Free)(const void* This,void*); void* (*ReAlloc)(const void* This,void*,size_t); } cc_memalloc; #define MemAlloc_Alloc(p,a) ((cc_memalloc*)(p))->Alloc(p,a) #define MemAlloc_Free(p,a) ((cc_memalloc*)(p))->Free(p,a) #define MemAlloc_ReAlloc(p,a,b) ((cc_memalloc*)(p))->ReAlloc(p,a,b) #define MEMALLOC_DEFAULT \ static void* __Alloc(const void* UNUSED_PARAM(p),size_t Size) { return malloc(Size); }\ static void __Free(const void* UNUSED_PARAM(p),void* Ptr) { free(Ptr); }\ static void* __ReAlloc(const void* UNUSED_PARAM(p),void* Ptr,size_t Size) { return realloc(Ptr,Size); }\ static const cc_memalloc MemAlloc_Default = { __Alloc,__Free,__ReAlloc }; #endif bcmatroska2-5.3.101/corec/corec/memheap.h000066400000000000000000000067121462133141200200470ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __MEMHEAP_H #define __MEMHEAP_H #define MEMHEAP_OPTIONAL 0x0001 typedef struct cc_memheap cc_memheap; typedef void* (*memheap_alloc)(const void* This,size_t,int Flags); typedef void (*memheap_free)(const void* This,void*,size_t); typedef void* (*memheap_realloc)(const void* This,void*,size_t Old,size_t New); typedef void (*memheap_write)(const void* This,void*,const void* Src,size_t Pos,size_t Size); #define DATA_FLAG_HEAP (((size_t)1)<<(sizeof(size_t)*8-1)) #define DATA_FLAG_MEMHEAP (((size_t)1)<<(sizeof(size_t)*8-2)) typedef struct dataheaphead { const cc_memheap* Heap; size_t Size; } dataheaphead; struct cc_memheap { memheap_alloc Alloc; memheap_free Free; memheap_realloc ReAlloc; memheap_write Write; dataheaphead Null; }; #define MemHeap_Alloc(p,a,b) ((cc_memheap*)(p))->Alloc(p,a,b) #define MemHeap_Free(p,a,b) ((cc_memheap*)(p))->Free(p,a,b) #define MemHeap_ReAlloc(p,a,b,c) ((cc_memheap*)(p))->ReAlloc(p,a,b,c) #define MemHeap_Write(p,a,b,c,d) ((cc_memheap*)(p))->Write(p,a,b,c,d) #define MemHeap_Null(p) ((uint8_t*)(&((cc_memheap*)(p))->Null+1)) #define MEMHEAP_DEFAULT \ static void* __HAlloc(const void* UNUSED_PARAM(p),size_t Size,int UNUSED_PARAM(Flags)) { return malloc(Size); }\ static void __HFree(const void* UNUSED_PARAM(p),void* Ptr,size_t UNUSED_PARAM(Size)) { free(Ptr); }\ static void* __HReAlloc(const void* UNUSED_PARAM(p),void* Ptr,size_t UNUSED_PARAM(OldSize),size_t Size) { return realloc(Ptr,Size); }\ static void __HWrite(const void* UNUSED_PARAM(p),void* Ptr,const void* Src,size_t Pos,size_t Size) { memcpy((uint8_t*)Ptr+Pos,Src,Size); }\ static const cc_memheap MemHeap_Default = { __HAlloc,__HFree,__HReAlloc,__HWrite,{ &MemHeap_Default, DATA_FLAG_MEMHEAP } }; #endif bcmatroska2-5.3.101/corec/corec/multithread/000077500000000000000000000000001462133141200205765ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/multithread/multithread.h000066400000000000000000000103111462133141200232650ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __MULTITHREAD_H #define __MULTITHREAD_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #if defined(MULTITHREAD_EXPORTS) #define MULTITHREAD_DLL DLLEXPORT #elif defined(MULTITHREAD_IMPORTS) #define MULTITHREAD_DLL DLLIMPORT #else #define MULTITHREAD_DLL #endif #define MULTITHREAD_PRIORITY_HIGH 100 #define MULTITHREAD_PRIORITY_USERINPUT 50 #define MULTITHREAD_PRIORITY_IO 25 #define MULTITHREAD_PRIORITY_NORMAL 0 #define MULTITHREAD_PRIORITY_LOW -50 #define MULTITHREAD_PRIORITY_IDLE -100 #ifdef CONFIG_MULTITHREAD MULTITHREAD_DLL void* LockCreate(); MULTITHREAD_DLL void LockDelete(void*); MULTITHREAD_DLL void LockEnter(void*); MULTITHREAD_DLL void LockLeave(void*); #else #define LockCreate() ((void*)1) #define LockDelete(p) #define LockEnter(p) #define LockLeave(p) #endif MULTITHREAD_DLL void ThreadSleepMs(int msTime); MULTITHREAD_DLL void ThreadSleepTicks(systick_t Ticks); #ifdef TARGET_WIN #define THREADCALL STDCALL #else #define THREADCALL #endif #ifdef CONFIG_MULTITHREAD typedef int (THREADCALL *threadfunc)(void*); MULTITHREAD_DLL void* ThreadCreate(threadfunc Start,void* Parameter); MULTITHREAD_DLL void ThreadCPU(void*,int CPU); MULTITHREAD_DLL uint32_t ThreadCPUMask(); MULTITHREAD_DLL int ThreadGetPriority(void*); MULTITHREAD_DLL void ThreadSetPriority(void*, int); MULTITHREAD_DLL uintptr_t ThreadId(); MULTITHREAD_DLL void* ThreadSelf(); MULTITHREAD_DLL void ThreadExit(uintptr_t ExitCode); MULTITHREAD_DLL bool_t ThreadDetach(void* Handle); MULTITHREAD_DLL bool_t ThreadJoin(void* Handle,uintptr_t* ExitCode); MULTITHREAD_DLL void* SemaphoreCreate(int Init); MULTITHREAD_DLL void SemaphoreClose(void* Handle); MULTITHREAD_DLL bool_t SemaphoreWait(void* Handle,int Tick); // Tick=-1 : INFINITE MULTITHREAD_DLL void SemaphoreRelease(void* Handle,int n); MULTITHREAD_DLL void* ConditionCreate(); MULTITHREAD_DLL void ConditionClose(void* Handle); MULTITHREAD_DLL bool_t ConditionWait(void* Handle,int Tick,void* Lock); MULTITHREAD_DLL void ConditionBroadcast(void* Handle); MULTITHREAD_DLL void ConditionSignal(void* Handle); MULTITHREAD_DLL void *ThreadStorageCreate(); MULTITHREAD_DLL void ThreadStorageSet(void *Storage, const void *Value); MULTITHREAD_DLL void *ThreadStorageGet(void *Storage); MULTITHREAD_DLL void ThreadStorageDelete(void *Storage); #else static INLINE int ThreadGetPriority(void* UNUSED_PARAM(p)) { return MULTITHREAD_PRIORITY_NORMAL; } static INLINE void ThreadSetPriority(void* UNUSED_PARAM(p), int UNUSED_PARAM(n)) {} #endif #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/multithread/multithread.proj000066400000000000000000000006131462133141200240140ustar00rootroot00000000000000GROUP(CONFIG_MULTITHREAD) multithread { USE corec HEADER multithread.h SOURCE(TARGET_WIN) multithread_win32.c SOURCE(TARGET_LINUX || TARGET_OSX || TARGET_ANDROID) multithread_pthread.c SOURCE(TARGET_SYMBIAN) multithread_symbian.cpp SOURCE(TARGET_PALMOS) multithread_palmos.c SOURCE(TARGET_PS2SDK) multithread_ps2sdk.c USE(TARGET_PS2SDK) ps2timer LIBS(TARGET_LINUX) pthread } bcmatroska2-5.3.101/corec/corec/multithread/multithread_palmos.c000066400000000000000000000035741462133141200246500ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "multithread.h" #include "pace.h" void ThreadSleepTicks(systick_t Ticks) { SysTaskDelay(Ticks); } void ThreadSleepMs(int msTime) { SysTaskDelay(msTime*1000/SysTicksPerSecond()); } bcmatroska2-5.3.101/corec/corec/multithread/multithread_ps2sdk.c000066400000000000000000000200461462133141200245540ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "multithread.h" #if defined(TARGET_PS2SDK) #include #include #if defined(CONFIG_MULTITHREAD) extern void *_gp; typedef struct lock_t { s32 SemaId; s32 ThreadId; s32 Counter; } lock_t; void* LockCreate() { lock_t* p = NULL; s32 SemaId; ee_sema_t Sema; Sema.init_count = 1; Sema.max_count = 1; Sema.option = 0; Sema.attr = 0; SemaId = CreateSema(&Sema); if (SemaId>=0) { p = malloc(sizeof(lock_t)); if (p) { p->SemaId = SemaId; p->ThreadId = -1; p->Counter = 0; } } return p; } void LockDelete(void* Handle) { if (Handle) { lock_t* p = Handle; DeleteSema(p->SemaId); free(p); } } void LockEnter(void* Handle) { if (Handle) { lock_t* p = Handle; s32 ThreadId = GetThreadId(); if (p->ThreadId == ThreadId) ++p->Counter; else { WaitSema(p->SemaId); p->ThreadId =ThreadId; p->Counter = 1; } } } void LockLeave(void* Handle) { if (Handle) { lock_t* p = Handle; assert(p->ThreadId == GetThreadId() && p->Counter>=0); if (--p->Counter==0) { p->ThreadId = -1; SignalSema(p->SemaId); } } } uintptr_t ThreadId() { return GetThreadId(); } typedef struct thread_t thread_t; static thread_t* Threads = NULL; struct thread_t { thread_t *Next; s32 ThreadId; int (*Func)(void*); void* Cookie; uintptr_t ExitCode; uint8_t Stack[32768]; }; int ThreadGetPriority(void* Handle) { return MULTITHREAD_PRIORITY_NORMAL; } void ThreadSetPriority(void* Handle,int Priority) { if (Handle) { thread_t* p = Handle; ChangeThreadPriority(p->ThreadId,64 + (MULTITHREAD_PRIORITY_USERINPUT - Priority)/5); // ULTITHREAD_PRIORITY_USERINPUT=64 is the reference } } static void ThreadFunc(void* Handle) { thread_t* p = Handle; p->ExitCode = p->Func(p->Cookie); p->Func = NULL; ExitThread(); } void* ThreadCreate(int(*Func)(void*),void* Cookie) { ee_thread_t Thread; thread_t* p = NULL; thread_t** i; DI(); for (i=&Threads;*i;i=&(*i)->Next) if ((*i)->ThreadId==-1) { p=*i; *i=p->Next; break; } EI(); if (!p) { p = malloc(sizeof(thread_t)); if (!p) return NULL; } memset(&Thread,0,sizeof(Thread)); Thread.func = ThreadFunc; Thread.stack = (void*)ALIGN16((uintptr_t)p->Stack); Thread.stack_size = sizeof(p->Stack)-16; Thread.gp_reg = (void *)&_gp; Thread.initial_priority = 64 + (MULTITHREAD_PRIORITY_USERINPUT - MULTITHREAD_PRIORITY_NORMAL)/5; p->ThreadId = CreateThread(&Thread); if (p->ThreadId < 0) { free(p); return NULL; } p->Cookie = Cookie; p->Func = Func; DI(); p->Next = Threads; Threads = p; EI(); StartThread(p->ThreadId,p); return p; } bool_t ThreadJoin(void* Handle,uintptr_t *ExitCode) { bool_t Result=0; if (Handle) { thread_t* p = Handle; size_t n; for (n=0;n<5000;++n) { if (!p->Func) { if (ExitCode) *ExitCode = p->ExitCode; Result=1; break; } ThreadSleepTicks(1); } TerminateThread(p->ThreadId); DeleteThread(p->ThreadId); p->ThreadId=-1; } return 0; } void* ThreadSelf() { s32 ThreadId = GetThreadId(); thread_t* p; for (p=Threads;p;p=p->Next) if (p->ThreadId==ThreadId) return p; return NULL; } bool_t ThreadDetach(void* Handle) { return 0; } void ThreadExit(uintptr_t ExitCode) { thread_t* p = ThreadSelf(); if (p) { p->ExitCode = ExitCode; p->Func = NULL; ExitThread(); } ExitDeleteThread(); } void* SemaphoreCreate(int Init) { s32 SemaId; ee_sema_t Sema; Sema.init_count = Init; Sema.max_count = INT_MAX; Sema.option = 0; Sema.attr = 0; SemaId = CreateSema(&Sema); if (SemaId<0) return NULL; return (void*)SemaId; } void SemaphoreClose(void* Handle) { if (Handle) DeleteSema((s32)Handle); } bool_t SemaphoreWait(void* Handle,int Tick) { //TODO: support timeout WaitSema((s32)Handle); return 1; } void SemaphoreRelease(void* Handle,int n) { for (;n>0;--n) SignalSema((s32)Handle); } int LockedInc(int* v) { int i; DI(); i = ++(*v); EI(); return i; } int LockedDec(int* v) { int i; DI(); i = --(*v); EI(); return i; } typedef struct condition_t { int waiters; void *semaphore; } condition_t; void* ConditionCreate() { condition_t *cond = (condition_t *)malloc(sizeof(condition_t)); cond->waiters = 0; cond->semaphore = SemaphoreCreate(0); return (void *)cond; } void ConditionClose(void* Handle) { condition_t *cond = (condition_t *)Handle; SemaphoreClose(cond->semaphore); free(cond); } bool_t ConditionWait(void* Handle, int Tick, void *Lock) { condition_t *cond = (condition_t *)Handle; bool_t ret; LockedInc(&cond->waiters); LockLeave(Lock); ret = SemaphoreWait(cond->semaphore, Tick); if (!ret) LockedDec(&cond->waiters); LockEnter(Lock); return ret; } void ConditionBroadcast(void* Handle) { condition_t *cond = (condition_t *)Handle; while (LockedDec(&cond->waiters)>=0) SemaphoreRelease(cond->semaphore, 1); LockedInc(&cond->waiters); } void ConditionSignal(void* Handle) { condition_t *cond = (condition_t *)Handle; if (LockedDec(&cond->waiters)>=0) SemaphoreRelease(cond->semaphore, 1); else LockedInc(&cond->waiters); } #endif void ThreadSleepTicks(systick_t Ticks) { if (Ticks) { s32 ThreadId = GetThreadId(); CancelWakeupThread(ThreadId); if (WakeupThreadLater(ThreadId,Ticks)) { SleepThread(); return; } } RotateThreadReadyQueue(64); } // same as ThreadSleepTicks() as 1 systick_t = 1 ms void ThreadSleepMs(int msTime) { if (msTime) { s32 ThreadId = GetThreadId(); CancelWakeupThread(ThreadId); if (WakeupThreadLater(ThreadId,msTime)) { SleepThread(); return; } } RotateThreadReadyQueue(64); } #endif bcmatroska2-5.3.101/corec/corec/multithread/multithread_pthread.c000066400000000000000000000223071462133141200247770ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "multithread.h" #if defined(TARGET_LINUX) || defined(TARGET_OSX) || defined(TARGET_ANDROID) #include #if defined(TARGET_OSX) #include #include #if defined(TARGET_IPHONE) #include #endif #define POLL_NO_WARN #include #endif #if defined(CONFIG_MULTITHREAD) #ifdef __GLIBC__ #define __USE_GNU #endif #include #include #include #include #include void* LockCreate() { pthread_mutex_t *pmt = malloc(sizeof(pthread_mutex_t)); if (pmt) { #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) pthread_mutex_t lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; *pmt = lock; return pmt; #else #ifndef PTHREAD_MUTEX_RECURSIVE_NP #define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE #endif pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); if (pthread_mutex_init(pmt, &attr) == 0) return pmt; free(pmt); #endif } return NULL; } void LockDelete(void* p) { if (p) { pthread_mutex_destroy(p); free(p); } } void LockEnter(void* p) { if (p) pthread_mutex_lock(p); } void LockLeave(void* p) { if (p) pthread_mutex_unlock(p); } uintptr_t ThreadId() { return (uintptr_t)pthread_self(); } void* ThreadSelf() { return (void*)pthread_self(); } bool_t ThreadDetach(void* p) { bool_t Result=0; if (p) Result = pthread_detach(*(pthread_t*)p)==0; //TODO: memory leak. pthread_t is never freed return Result; } void ThreadExit(uintptr_t ExitCode) { pthread_exit((void*)ExitCode); } bool_t ThreadJoin(void* p,uintptr_t* ExitCode) { bool_t Result=0; if (p) { Result = pthread_join(*(pthread_t*)p,(void**)ExitCode)==0; free(p); } return Result; } void* ThreadCreate(threadfunc Start,void* Parameter) { pthread_t *p = malloc(sizeof(pthread_t)); if (pthread_create(p, NULL, (void*(*)(void*)) Start, Parameter) != 0) { free(p); return NULL; } return p; } void *ThreadStorageCreate() { pthread_key_t Key; int Res = pthread_key_create(&Key,NULL); if (Res) return NULL; return (void*)Key; } void ThreadStorageSet(void *Storage, const void *Value) { pthread_setspecific((pthread_key_t)Storage,Value); } void *ThreadStorageGet(void *Storage) { return pthread_getspecific((pthread_key_t)Storage); } void ThreadStorageDelete(void *Storage) { pthread_key_delete((pthread_key_t)Storage); } int ThreadGetPriority(void* Thread) { return MULTITHREAD_PRIORITY_NORMAL; } void ThreadSetPriority(void* Thread,int Priority) { } void ThreadCPU(void* Handle,int CPU) { } uint32_t ThreadCPUMask() { int n; #ifdef TARGET_OSX size_t Size = sizeof(n); int hw_ncpu[2] = { CTL_HW, HW_NCPU }; if (sysctl(hw_ncpu, 2, &n, &Size, NULL, 0)<0) n=0; #else n=sysconf(_SC_NPROCESSORS_CONF); if (n<0) n=0; #endif return (1<0;--n) if (sem_post((sem_t*)Handle) != 0) break; } #else typedef struct iphone_semaphore_hack_t { pthread_cond_t Condition; pthread_mutex_t ConditionMutex; int SemaphoreCount; } iphone_semaphore_hack_t; void* SemaphoreCreate(int Init) { iphone_semaphore_hack_t* p = malloc(sizeof(iphone_semaphore_hack_t)); if (p) { memset(p,0,sizeof(iphone_semaphore_hack_t)); p->SemaphoreCount = Init; if (pthread_cond_init(&p->Condition, NULL) == 0) { if (pthread_mutex_init(&p->ConditionMutex, NULL) == 0) { return p; } pthread_cond_destroy(&p->Condition); } free(p); } return NULL; } void SemaphoreClose(void* Handle) { iphone_semaphore_hack_t* p = (iphone_semaphore_hack_t*)Handle; if (p) { pthread_mutex_destroy(&p->ConditionMutex); pthread_cond_destroy(&p->Condition); free(p); } } bool_t SemaphoreWait(void* Handle,int Time) // -1 = INFINITE { iphone_semaphore_hack_t* p = (iphone_semaphore_hack_t*)Handle; int success; pthread_mutex_lock(&p->ConditionMutex); if (Time != 0) { while (p->SemaphoreCount <= 0) if (pthread_cond_wait(&p->Condition,&p->ConditionMutex) != 0) break; } success = (p->SemaphoreCount > 0); if (success) p->SemaphoreCount--; pthread_mutex_unlock(&p->ConditionMutex); return success; } void SemaphoreRelease(void* Handle,int n) { iphone_semaphore_hack_t* p = (iphone_semaphore_hack_t*)Handle; for (;n>0;--n) { pthread_mutex_lock(&p->ConditionMutex); p->SemaphoreCount++; pthread_mutex_unlock(&p->ConditionMutex); pthread_cond_signal(&p->Condition); } } #endif void* ConditionCreate() { pthread_cond_t *cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); if (pthread_cond_init(cond, NULL) != 0) { free(cond); cond = NULL; } return (void *)cond; } void ConditionClose(void* Handle) { pthread_cond_t *cond = (pthread_cond_t *)Handle; pthread_cond_destroy(cond); free(cond); } bool_t ConditionWait(void* Handle, int Tick, void *Lock) { pthread_cond_t *cond = (pthread_cond_t *)Handle; pthread_mutex_t *mutex = (pthread_mutex_t *)Lock; struct timespec t = {0}; struct timeval tp = {0}; int seconds; if (Tick == -1) // INFINTE return pthread_cond_wait(cond, mutex) == 0; gettimeofday(&tp, NULL); t.tv_sec = tp.tv_sec; t.tv_nsec = tp.tv_usec * 1000; seconds = Tick / 1000; t.tv_sec += seconds; t.tv_nsec += (Tick - (seconds * 1000)) * 1000; return pthread_cond_timedwait(cond, mutex, &t); } void ConditionBroadcast(void* Handle) { pthread_cond_t *cond = (pthread_cond_t *)Handle; pthread_cond_broadcast(cond); } void ConditionSignal(void* Handle) { pthread_cond_t *cond = (pthread_cond_t *)Handle; pthread_cond_signal(cond); } #endif //CONFIG_MULTITHREAD void ThreadSleepTicks(systick_t Ticks) { #if defined(TARGET_OSX) && !defined(TARGET_IPHONE) // for some reason usleep and nanosleep sometimes blocks forever under OSX struct pollfd foo; poll(&foo,0,Ticks); #else usleep(Ticks*1000); //struct timespec tv; //int msec = Time % 1000; //tv.tv_sec = Time-msec; //tv.tv_nsec = msec*1000000; //nanosleep(&tv, NULL); #endif } // same as ThreadSleepTicks() as 1 systick_t = 1 ms void ThreadSleepMs(int msTime) { #if defined(TARGET_OSX) && !defined(TARGET_IPHONE) // for some reason usleep and nanosleep sometimes blocks forever under OSX struct pollfd foo; poll(&foo,0,msTime); #else usleep(msTime*1000); //struct timespec tv; //int msec = Time % 1000; //tv.tv_sec = Time-msec; //tv.tv_nsec = msec*1000000; //nanosleep(&tv, NULL); #endif } #endif bcmatroska2-5.3.101/corec/corec/multithread/multithread_symbian.cpp000066400000000000000000000215731462133141200253560ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "multithread.h" #if defined(TARGET_SYMBIAN) //#error todo: remove RThread::Rendezvous usage //#error todo: SemaphoreWait with timeout for pre Symbian9 #undef T #undef NULL #include #include #include #ifdef CONFIG_MULTITHREAD #define STACKSIZE 25000 #if defined(SYMBIAN90) void* LockCreate() { RMutex p; p.CreateLocal(); return (void*)p.Handle(); } void LockDelete(void* Handle) { RMutex p; p.SetHandle((int)Handle); p.Close(); } void LockEnter(void* Handle) { RMutex p; p.SetHandle((int)Handle); p.Wait(); } void LockLeave(void* Handle) { RMutex p; p.SetHandle((int)Handle); p.Signal(); } #else typedef struct lock_t { int Handle; volatile TUint Thread; volatile size_t Counter; } lock_t; void* LockCreate() { lock_t *lock = (lock_t *)malloc(sizeof(lock_t)); if (lock) { RMutex p; p.CreateLocal(); lock->Handle = p.Handle(); lock->Counter = 0; lock->Thread = 0; } return lock; } void LockDelete(void* Handle) { lock_t *lock = (lock_t *)Handle; if (lock) { RMutex p; p.SetHandle(lock->Handle); p.Close(); free(lock); } } void LockEnter(void* Handle) { lock_t *lock = (lock_t *)Handle; if (lock) { RThread current; TUint currentId = current.Id(); if (lock->Thread == currentId) ++lock->Counter; else { RMutex p; p.SetHandle(lock->Handle); p.Wait(); assert(lock->Counter==0); lock->Counter = 1; lock->Thread = currentId; } } } void LockLeave(void* Handle) { lock_t *lock = (lock_t *)Handle; if (lock && --lock->Counter == 0) { lock->Thread = 0; RMutex p; p.SetHandle(lock->Handle); p.Signal(); } } #endif uintptr_t ThreadId() { RThread current; return current.Id(); } class thread { public: RThread Thread; RSemaphore Semaphore; void* Tls; int(*Start)(void*); void* Parameter; }; int ThreadGetPriority(void* Handle) { RThread Thread; Thread.SetHandle((TInt)Handle); TThreadPriority v = Thread.Priority(); if (v<=EPriorityMuchLess) return MULTITHREAD_PRIORITY_IDLE; if (v<=EPriorityLess) return MULTITHREAD_PRIORITY_LOW; if (v<=EPriorityNormal) return MULTITHREAD_PRIORITY_NORMAL; if (v<=EPriorityMore) return MULTITHREAD_PRIORITY_IO; if (v<=EPriorityMuchMore) return MULTITHREAD_PRIORITY_USERINPUT; return MULTITHREAD_PRIORITY_HIGH; } void ThreadSetPriority(void* Handle,int Priority) { RThread Thread; Thread.SetHandle((TInt)Handle); TThreadPriority v; if (Priority<=MULTITHREAD_PRIORITY_IDLE) v = EPriorityMuchLess; else if (Priority<=MULTITHREAD_PRIORITY_LOW) v = EPriorityLess; else if (Priority<=MULTITHREAD_PRIORITY_NORMAL) v = EPriorityNormal; else if (Priority<=MULTITHREAD_PRIORITY_IO) v = EPriorityMore; else if (Priority<=MULTITHREAD_PRIORITY_USERINPUT) v = EPriorityMuchMore; else v = EPriorityRealTime; Thread.SetPriority(v); } static int ThreadFunc(TAny* data) { thread* Param = (thread*)data; #if !defined(SYMBIAN90) Dll::SetTls(Param->Tls); #endif // Run actual thread function Param->Start(Param->Parameter); // Signal that we've stopped Param->Semaphore.Signal(); Param->Semaphore.Close(); delete Param; return 0; } void* ThreadCreate(int(*Start)(void*),void* Parameter) { thread* Thread = new thread; Thread->Semaphore.CreateLocal(0); #if !defined(SYMBIAN90) Thread->Tls = Dll::Tls(); #endif Thread->Start = Start; Thread->Parameter = Parameter; TInt Err; TBuf<32> Name; do { Name.Format(_L("__%08x_%08x"),(uintptr_t)Start,Math::Random()); Err = Thread->Thread.Create(Name,ThreadFunc,STACKSIZE,NULL,Thread); } while (Err == KErrAlreadyExists); if (Err != KErrNone) { Thread->Semaphore.Close(); delete Thread; return NULL; } Thread->Thread.Resume(); return (void *)Thread->Thread.Handle(); } bool_t ThreadJoin(void* Handle,uintptr_t *ExitCode) { RThread Thread; Thread.SetHandle((TInt)Handle); //!!! todo // This is only supported in Symbian 9.2, but it's the only clean way // Thread.Rendezvous(0); if (ExitCode) *ExitCode = Thread.ExitReason(); Thread.Close(); return 1; } void* ThreadSelf() { RThread Thread; return (void *)Thread.Handle(); } bool_t ThreadDetach(void* Handle) { RThread Thread; Thread.SetHandle((TInt)Handle); Thread.Close(); return 1; } void ThreadExit(uintptr_t ExitCode) { User::Exit((TInt)ExitCode); } void* SemaphoreCreate(int Init) { RSemaphore p; p.CreateLocal(Init); return (void *)p.Handle(); } void SemaphoreClose(void* Handle) { RSemaphore p; p.SetHandle((int)Handle); p.Close(); } bool_t SemaphoreWait(void* Handle,int Tick) { RSemaphore p; p.SetHandle((int)Handle); if (Tick>=0) { #if defined(SYMBIAN90) return p.Wait(Tick*1000) == KErrNone; #else //!!! todo #endif } p.Wait(); return 1; } void SemaphoreRelease(void* Handle,int n) { RSemaphore p; p.SetHandle((int)Handle); p.Signal(n); } #if defined(SYMBIAN90) void* ConditionCreate() { RCondVar p; p.CreateLocal(); return (void *)p.Handle(); } void ConditionClose(void* Handle) { RCondVar p; p.SetHandle((int)Handle); p.Close(); } bool_t ConditionWait(void* Handle,int Tick,void* Lock) { RCondVar p; RMutex m; p.SetHandle((int)Handle); m.SetHandle((int)Lock); // Increase the tick by one to mimic other platforms // which is -1 = Wait forever, 0 = Return // For Symbian, 0 = Wait forever Tick++; return p.TimedWait(m, Tick*1000) == KErrNone; } void ConditionBroadcast(void* Handle) { RCondVar p; p.SetHandle((int)Handle); p.Broadcast(); } void ConditionSignal(void* Handle) { RCondVar p; p.SetHandle((int)Handle); p.Signal(); } #else typedef struct condition_t { TInt waiters; void *semaphore; } condition_t; void* ConditionCreate() { condition_t *cond = (condition_t *)malloc(sizeof(condition_t)); if (cond) { cond->waiters = 0; cond->semaphore = SemaphoreCreate(0); } return cond; } void ConditionClose(void* Handle) { condition_t *cond = (condition_t *)Handle; SemaphoreClose(cond->semaphore); free(cond); } bool_t ConditionWait(void* Handle, int Tick, void *Lock) { condition_t *cond = (condition_t *)Handle; bool_t ret; User::LockedInc(cond->waiters); LockLeave(Lock); ret = SemaphoreWait(cond->semaphore, Tick); if (!ret) User::LockedDec(cond->waiters); LockEnter(Lock); return ret; } void ConditionBroadcast(void* Handle) { condition_t *cond = (condition_t *)Handle; while (User::LockedDec(cond->waiters)>0) SemaphoreRelease(cond->semaphore, 1); User::LockedInc(cond->waiters); } void ConditionSignal(void* Handle) { condition_t *cond = (condition_t *)Handle; if (User::LockedDec(cond->waiters)>0) SemaphoreRelease(cond->semaphore, 1); else User::LockedInc(cond->waiters); } #endif #endif void ThreadSleepTicks(systick_t Ticks) { if (Ticks) { TTimeIntervalMicroSeconds32 n; UserHal::TickPeriod(n); Ticks *= n.Int(); } User::After(Ticks); } void ThreadSleepMs(int msTime) { User::After(msTime*1000); } #endif bcmatroska2-5.3.101/corec/corec/multithread/multithread_win32.c000066400000000000000000000200471462133141200243110ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "multithread.h" #if defined(TARGET_WIN) //#define LOCK_TIMEOUT #ifndef STRICT #define STRICT #endif #include #if defined(CONFIG_MULTITHREAD) #if defined(TARGET_WINCE) static BOOL (WINAPI* FuncCeSetThreadQuantum)(HANDLE, DWORD) = NULL; static NOINLINE bool_t FindCeSetThreadQuantum() { // slow, but multithread safe HMODULE CoreDLL = GetModuleHandleW(L"coredll.dll"); if (CoreDLL) *(FARPROC*)(void*)&FuncCeSetThreadQuantum = GetProcAddressW(CoreDLL,L"CeSetThreadQuantum"); return FuncCeSetThreadQuantum != NULL; } #undef CreateEvent #define CreateEvent CreateEventW #endif void* LockCreate() { #ifndef LOCK_TIMEOUT void* p = malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection((LPCRITICAL_SECTION)p); return p; #else return CreateMutex(NULL,FALSE,NULL); #endif } void LockDelete(void* p) { if (p) { #ifndef LOCK_TIMEOUT DeleteCriticalSection((LPCRITICAL_SECTION)p); free(p); #else CloseHandle(p); #endif } } void LockEnter(void* p) { if (p) #ifndef LOCK_TIMEOUT EnterCriticalSection((LPCRITICAL_SECTION)p); #else while (WaitForSingleObject(p,3000)==WAIT_TIMEOUT) DebugBreak(); #endif } void LockLeave(void* p) { if (p) #ifndef LOCK_TIMEOUT LeaveCriticalSection((LPCRITICAL_SECTION)p); #else ReleaseMutex(p); #endif } int ThreadGetPriority(void* Thread) { int v = GetThreadPriority(Thread); #if defined(TARGET_WINCE) v = v - THREAD_PRIORITY_NORMAL; #else v = THREAD_PRIORITY_NORMAL - v; #endif if (v>1) return MULTITHREAD_PRIORITY_IDLE; if (v==1) return MULTITHREAD_PRIORITY_LOW; if (v==0) return MULTITHREAD_PRIORITY_NORMAL; if (v==-1) return MULTITHREAD_PRIORITY_USERINPUT; return MULTITHREAD_PRIORITY_HIGH; } void ThreadSetPriority(void* Thread,int Priority) { int v; if (Priority<=MULTITHREAD_PRIORITY_IDLE) v=2; else if (Priority<=MULTITHREAD_PRIORITY_LOW) v=1; else if (Priority<=MULTITHREAD_PRIORITY_IO) // normal and I/O are same under windows to keep old behaviour v=0; else if (Priority<=MULTITHREAD_PRIORITY_USERINPUT) v=-1; else v=-2; #if defined(TARGET_WINCE) v = THREAD_PRIORITY_NORMAL + v; if (v > THREAD_PRIORITY_IDLE) v = THREAD_PRIORITY_IDLE; if (v < THREAD_PRIORITY_TIME_CRITICAL) v = THREAD_PRIORITY_TIME_CRITICAL; SetThreadPriority(Thread,v); #else v = THREAD_PRIORITY_NORMAL - v; if (v < THREAD_PRIORITY_IDLE) v = THREAD_PRIORITY_IDLE; if (v > THREAD_PRIORITY_TIME_CRITICAL) v = THREAD_PRIORITY_TIME_CRITICAL; SetThreadPriority(Thread,v); #endif } uintptr_t ThreadId() { return GetCurrentThreadId(); } void* ThreadSelf() { return GetCurrentThread(); }; void ThreadExit(uintptr_t ExitCode) { ExitThread((DWORD)ExitCode); } bool_t ThreadDetach(void* Handle) { return Handle && CloseHandle(Handle) != 0; } bool_t ThreadJoin(void* Handle,uintptr_t* ExitCode) { bool_t Result = 0; if (Handle) { DWORD v = WaitForSingleObject(Handle,5000); if (v == WAIT_OBJECT_0) Result = 1; else if (v == WAIT_TIMEOUT) TerminateThread(Handle,0); if (ExitCode) { DWORD dwExitCode = 0; GetExitCodeThread(Handle, &dwExitCode); *ExitCode = dwExitCode; } CloseHandle(Handle); } return Result; } void* ThreadCreate(int(THREADCALL *Start)(void*),void* Parameter) { DWORD Id; HANDLE Handle = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Start,Parameter,0,&Id); #if defined(TARGET_WINCE) if (Handle && (FuncCeSetThreadQuantum || FindCeSetThreadQuantum())) FuncCeSetThreadQuantum(Handle,25); #endif return Handle; } #if !defined(TARGET_WINCE) static DWORD (WINAPI* FuncSetThreadIdealProcessor)(HANDLE, DWORD) = NULL; static BOOL (WINAPI* FuncGetProcessAffinityMask)(HANDLE, uintptr_t*, uintptr_t*) = NULL; static bool_t FindSetThreadIdealProcessor() { // slow, but multithread safe HMODULE DLL = GetModuleHandle(T("kernel32.dll")); if (DLL) *(FARPROC*)(void*)&FuncSetThreadIdealProcessor = GetProcAddress(DLL,"SetThreadIdealProcessor"); return FuncSetThreadIdealProcessor != NULL; } static bool_t FindGetProcessAffinityMask() { // slow, but multithread safe HMODULE DLL = GetModuleHandle(T("kernel32.dll")); if (DLL) *(FARPROC*)(void*)&FuncGetProcessAffinityMask = GetProcAddress(DLL,"GetProcessAffinityMask"); return FuncGetProcessAffinityMask != NULL; } #endif void ThreadCPU(void* Handle,int CPU) { #if !defined(TARGET_WINCE) if (CPU<0) CPU = MAXIMUM_PROCESSORS; if (FuncSetThreadIdealProcessor || FindSetThreadIdealProcessor()) FuncSetThreadIdealProcessor(Handle,CPU); #endif } uint32_t ThreadCPUMask() { uintptr_t a=0; #if !defined(TARGET_WINCE) uintptr_t b; if ((!FuncGetProcessAffinityMask && !FindGetProcessAffinityMask()) || !FuncGetProcessAffinityMask(GetCurrentProcess(),&a,&b)) a = 0; #endif return (uint32_t)a; } void* SemaphoreCreate(int Init) { return CreateSemaphore(NULL,Init,32000,NULL); } void SemaphoreClose(void* Handle) { CloseHandle(Handle); } bool_t SemaphoreWait(void* Handle,int Time) { return WaitForSingleObject(Handle,Time) == WAIT_OBJECT_0; } void SemaphoreRelease(void* Handle,int n) { ReleaseSemaphore(Handle,n,NULL); } typedef struct condition_t { LONG waiters; void *semaphore; } condition_t; void* ConditionCreate() { condition_t *cond = (condition_t *)malloc(sizeof(condition_t)); cond->waiters = 0; cond->semaphore = SemaphoreCreate(0); return (void *)cond; } void ConditionClose(void* Handle) { condition_t *cond = (condition_t *)Handle; SemaphoreClose(cond->semaphore); free(cond); } bool_t ConditionWait(void* Handle, int Tick, void *Lock) { condition_t *cond = (condition_t *)Handle; bool_t ret; InterlockedIncrement(&cond->waiters); LockLeave(Lock); ret = SemaphoreWait(cond->semaphore, Tick); if (!ret) InterlockedDecrement(&cond->waiters); LockEnter(Lock); return ret; } void ConditionBroadcast(void* Handle) { condition_t *cond = (condition_t *)Handle; while (InterlockedDecrement(&cond->waiters)>=0) SemaphoreRelease(cond->semaphore, 1); InterlockedIncrement(&cond->waiters); } void ConditionSignal(void* Handle) { condition_t *cond = (condition_t *)Handle; if (InterlockedDecrement(&cond->waiters)>=0) SemaphoreRelease(cond->semaphore, 1); else InterlockedIncrement(&cond->waiters); } #endif //CONFIG_MULTITHREAD void ThreadSleepTicks(systick_t Ticks) { Sleep(Ticks); } // same as ThreadSleepTicks() as 1 systick_t = 1 ms void ThreadSleepMs(int msTime) { Sleep(msTime); } #endif bcmatroska2-5.3.101/corec/corec/node/000077500000000000000000000000001462133141200172015ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/node/corec.html000066400000000000000000000356351462133141200211760ustar00rootroot00000000000000 Core-C FAQ

Core-C Frequently Asked Questions

Introduction

Core-C is a set of C structures that adds a whole Object Oriented layer to the C language. It is fully and only based on the C language.
As any Object Oriented language it uses the concept of classes and of class instances, called node in Core-C. Each class can have properties, instance variables, actions and methods. And each class is identified in the code by its FourCC value.
Each class can only inherit from one other class (no multiple inheritences). The base class for all classes is the node class. It inherits its variables, actions and methods and can override them if needed.

Class Properties

Each class has its own properties used by the Core-C engine to enable some special treatments depending on the flags. The properties are not inherited by child classes.
Local - CFLAG_LOCAL
A local class is not saved during a NodeDump().
Appears in Settings - CFLAG_SETTINGS
This class is available in the user settings for configuration.
Saved Settings - CFLAG_CONFIG
This class saves and restores its settings in the config.xml file.
Abstract - CFLAG_ABSTRACT
This class defines an API via the variables, actions and methods. But only children of that class can be instanciated. It's equivalent to a virtual class in C++.
Singleton - CFLAG_SINGLETON

Instance Variables

Most of a class is defined by its instance variables. It defines all that can be read/written on each class instance. The most basic features of a variable are the Set (Node_Set) and Get (Node_Get) calls.
Each variable has a type and flags to define particular use of the variable. It can also have an internal name (use by CoreUI).

The possible types include:

TYPE_BOOLEAN
a boolean value, with the type bool_t.
TYPE_INT
a signed integer, with the type int.
TYPE_FRACTION
a fraction, with the type fraction_t.
TYPE_STRING
a NULL terminated string, with the type tchar_t.
TYPE_RECT
a rectangle, with the type cc_rect.
TYPE_POINT
a point/coordinate, with the type cc_point.
TYPE_RGB
a RGB value, with the type rgbval_t.
TYPE_FOURCC
a FourCC, with the type fourcc_t.
TYPE_FILEPOS
a file position, with the type filepos_t.
TYPE_TICK
a tick value, with the type tick_t.
TYPE_PTR
a pointer, with the type void*.
TYPE_NOTIFY
a notify callback, with the type notify.
TYPE_INT8
an integer on 8 bits, with the type int8_t.
TYPE_INT16
an integer on 16 bits, with the type int16_t.
TYPE_INT32
an integer on 32 bits, with the type int32_t.
TYPE_INT64
an integer on 64 bits, with the type int64_t.
TYPE_BOOL_BIT
a boolean value that is internally mixed with other flags (to save memory), with the type bool_t.
TYPE_PIN
a pin, ie the combination of a node and a variable ID, with the type pin.
TYPE_EVENT
an event, see Actions.
TYPE_ARRAY
an array of values, with the type array.
TYPE_DATETIME
a date & time value, with the type datetime_t.

The possible variable flags include:

Default - TFLAG_DEFAULT
When reading data it's filled with a default empty value even if the data don't exist.
Read-Only - TFLAG_RDONLY
The value can only be read, not written.
Setup - TFLAG_SETUP
A variable that can be saved/restored into a XML file
Settings - TFLAG_SETTINGS
The variable can be displayed/changed in the user preferences.
Not Saved - TFLAG_NOSAVE
The value isn't kept when a node is copied.
Notify When Changed - TFLAG_NOTIFY
This variables can be monitored for changes using a notiyfunc callback.
Update Mode - TFLAG_UPDATEMODE
In CoreUI, forces the update of the display when an event is fired.
No Dump - TFLAG_NODUMP
The value of this variable is not dump when a crash occurs.
Hotkey - TFLAG_HOTKEY
Indicates that a hotkey can be assigned to toggle the value of this variable.
Hotkey - TFLAG_INPUT
Indicates that a the data with PIN_FORMAT flag is available as input source.
Display - TFLAG_DISPLAY
When reading a data as a string, indicates it's for displaying and not internal use.
Available - TFLAG_AVAILABLE
The pin includes an entry with DATA_AVAILABLE to tell if the pin is usable or not.

The possible variable unit modifiers are:

Checklist - TUNIT_CHECKLIST
The boolean value should be shown as a checklist.
Enumerate - TUNIT_ENUM
The pin includes various possible values that can be read with the DATA_ENUM flag.
Enumerate - TUNIT_NUMBER
The integer should be displayed with no type.
Hexadecimal - TUNIT_HEX
The integer should be displayed as a value in hexadecimal.
Percent - TUNIT_PERCENT
The integer should be displayed as a percentage.
KiloBytes - TUNIT_KBYTE
The integer should be displayed as a value in kilobytes.
Second - TUNIT_SECOND
The integer should be displayed as a value in seconds.
MegaHertz - TUNIT_MHZ
The integer should be displayed as a value in MHz.
BitRate - TUNIT_BYTERATE
The integer should be displayed as a bitrate.
X Coordinates - TUNIT_XCOORD
The integer value represents a X coordinate.
Y Coordinates - TUNIT_YCOORD
The integer value represents a Y coordinate.
UpperCase - TUNIT_UPPER
The string value should be shown and stored as uppercase.
Folder - TUNIT_FOLDER
The string value represents a path to a folder.
Hotkey - TUNIT_HOTKEY
The value is representing a hotkey.
AnyChar - TUNIT_ANYCHAR
The node value can have any char in the expression ???

Class Actions

An action are implemented like variables of type TYPE_EVENT. These variables are only set and take no parameter.
Node_Set(ClassInstance, ACTION_ID, NULL, 0)
Actions used to make instances perform actions without having to call a method. It is useful for scripting like in CoreUI.

Class Methods

Methods are functions that can be called directly on the class. A child class can override the methods of its parents, and add new methods.
The basic node class has 4 methods: Get(), Set(), Meta() and Enum().

Singleton Classes

Singleton classes are classes that can be used from anywhere in the code. They can be queried using NodeSingleton(<Class_FourCC>). They are created with the flag CFLAG_SINGLETON.
A singleton class has no parent and only has one instance created. It's equivalent to the singleton design pattern.

Singleton Events

Classes can have their own events, but in addition Core-C provides some generic singleton events that every singleton classes receive:
  • NODE_SINGLETON_STARTUP: called when a module is loaded or the program is started.
  • NODE_SINGLETON_CONFIGURED: called when all the modules are loaded and all the class are registered.
  • NODE_SINGLETON_SHUTDOWN: called when a module is unloaded or the program is shutting down.
  • NODE_SINGLETON_INSTALL: called when a CoreUI program is called with --install in the command-line.
  • NODE_SINGLETON_UNINSTALL: called when a CoreUI program is called with --uninstall in the command-line.

Copyright © 2008-2009 CoreCodec, Inc.

bcmatroska2-5.3.101/corec/corec/node/node.c000066400000000000000000002564541462133141200203120ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "node.h" #include "node_internal.h" #define NODE_MAGIC 0xF0DE0A6C #define DYNDATA_SHIFT 8 static const uint16_t ParamSize[MAX_PARAMTYPE] = { 0, //TYPE_NONE sizeof(bool_t), //TYPE_BOOLEAN sizeof(int), //TYPE_INT sizeof(cc_fraction),//TYPE_FRACTION MAXDATA, //TYPE_STRING sizeof(cc_rect), //TYPE_RECT sizeof(cc_point), //TYPE_POINT sizeof(rgbval_t), //TYPE_RGB sizeof(fourcc_t), //TYPE_FOURCC sizeof(filepos_t), //TYPE_FILEPOS sizeof(node*), //TYPE_NODE sizeof(metanotify), //TYPE_META sizeof(pin), //TYPE_PACKET sizeof(tick_t), //TYPE_TICK sizeof(nodenotify), //TYPE_NODENOTIFY sizeof(void*), //TYPE_PTR MAXDATA, //TYPE_BINARY sizeof(notify), //TYPE_NOTIFY sizeof(int8_t), //TYPE_INT8 sizeof(int16_t), //TYPE_INT16 sizeof(int32_t), //TYPE_INT32 sizeof(int64_t), //TYPE_INT64 sizeof(nodefunc), //TYPE_FUNC sizeof(node*), //TYPE_NODE_REF sizeof(bool_t), //TYPE_BOOL_BIT sizeof(pin), //TYPE_PIN 0, //TYPE_EVENT MAXDATA, //TYPE_EXPR sizeof(cc_point16), //TYPE_POINT16 sizeof(int16_t)*4, //TYPE_RECT16 sizeof(array), //TYPE_ARRAY MAXDATA, //TYPE_EXPRSTRING MAXDATA, //TYPE_EXPRPARAM sizeof(datetime_t), //TYPE_DATETIME sizeof(int_fast32_t), //TYPE_DBNO sizeof(cc_guid), //TYPE_GUID sizeof(int), //TYPE_FIX16 sizeof(int), //TYPE_LUA_REF sizeof(notifyex), //TYPE_NOTIFYEX sizeof(dataenum), //TYPE_ENUM sizeof(multi_enum_set), //TYPE_ENUM_MULTI_SET sizeof(size_t), //TYPE_SIZE }; static const tchar_t* ParamName[MAX_PARAMTYPE] = { T("none"), //TYPE_NONE T("boolean"), //TYPE_BOOLEAN T("integer"), //TYPE_INT T("fraction"), //TYPE_FRACTION T("string"), //TYPE_STRING T("rectangle"), //TYPE_RECT T("point"), //TYPE_POINT T("rgb"), //TYPE_RGB T("fourcc"), //TYPE_FOURCC T("filepos"), //TYPE_FILEPOS T("node"), //TYPE_NODE NULL, //TYPE_META T("packet"), //TYPE_PACKET T("tick"), //TYPE_TICK NULL, //TYPE_NODENOTIFY T("pointer"), //TYPE_PTR NULL, //TYPE_BINARY NULL, //TYPE_NOTIFY T("integer_8"), //TYPE_INT8 T("integer_16"), //TYPE_INT16 T("integer_32"), //TYPE_INT32 T("integer_64"), //TYPE_INT64 NULL, //TYPE_FUNC T("node_ref"), //TYPE_NODE_REF NULL, //TYPE_BOOL_BIT T("pin"), //TYPE_PIN T("event"), //TYPE_EVENT NULL, //TYPE_EXPR T("point_16"), //TYPE_POINT16 T("rect_16"), //TYPE_RECT16 NULL, //TYPE_ARRAY NULL, //TYPE_EXPRSTRING NULL, //TYPE_EXPRPARAM T("datetime"), //TYPE_DATETIME T("db_no"), //TYPE_DBNO T("guid"), //TYPE_GUID T("fix_16"), //TYPE_FIX16 NULL, //TYPE_LUA_REF NULL, //TYPE_NOTIFYEX NULL, //TYPE_ENUM NULL, //TYPE_ENUM_MULTI_SET T("size"), //TYPE_SIZE }; static const tchar_t* ParamFormat[(TUNIT_MASK>>TUNIT_SHIFT)+1] = { NULL, T("kbyte"), //TUNIT_KBYTE T("second"), //TUNIT_SECOND T("mhz"), //TUNIT_MHZ T("xcoord"), //TUNIT_XCOORD T("ycoord"), //TUNIT_YCOORD T("byterate"), //TUNIT_BYTERATE T("folder"), //TUNIT_FOLDER T("number"), //TUNIT_NUMBER T("fix16"), //TUNIT_FIX16 T("ip"), //TUNIT_IP T("coord"), //TUNIT_COORD T("password"), //TUNIT_PASSWORD T("upper"), //TUNIT_UPPER T("hotkey"), //TUNIT_HOTKEY T("checklist"), //TUNIT_CHECKLIST T("percent"), //TUNIT_PERCENT T("hex"), //TUNIT_HEX T("task"), //TUNIT_TASK }; static INLINE void Node_ValidatePtr(anynode* Node) { #ifdef CONFIG_DEBUGCHECKS assert(((node*)Node)->Magic==NODE_MAGIC); #endif } NOINLINE bool_t NodeClass_IsPartOf(const nodeclass* p, fourcc_t PartOfClass) { for (;p;p=p->ParentClass) if (NodeClass_ClassId(p) == PartOfClass) return 1; return 0; } static INLINE nodeclass* NodeGetClass(const node* p) { return ((nodeclass*)p->VMT)-1; } static INLINE bool_t CheckLoadModule(nodecontext* p,nodemodule* Module) { if (&p->Base!=Module && p->LoadModule && !Module->Module) return p->LoadModule(p,Module); return 0; } static NOINLINE int CmpClass(const void* UNUSED_PARAM(p), const nodeclass* const* a, const nodeclass* const* b) { fourcc_t AClass = NodeClass_ClassId(*a); fourcc_t BClass = NodeClass_ClassId(*b); if (AClass > BClass) return 1; if (AClass < BClass) return -1; if ((*a)->Module != (*b)->Module) return ((*a)->Module > (*b)->Module) ? 1:-1; return 0; } static NOINLINE int CmpClassNoModule(const void* UNUSED_PARAM(p), const nodeclass* const* a, const nodeclass* const* b) { fourcc_t AClass = NodeClass_ClassId(*a); fourcc_t BClass = NodeClass_ClassId(*b); if (AClass > BClass) return 1; if (AClass < BClass) return -1; return 0; } static NOINLINE int CmpClassPri(const void* UNUSED_PARAM(p), const nodeclass* const* a, const nodeclass* const* b) { int APriority = (*a)->Priority; int BPriority = (*b)->Priority; if (APriority > BPriority) return -1; if (APriority < BPriority) return 1; return CmpClass(NULL,a,b); } typedef struct nodeclassrated { const nodeclass *Class; int Rating; } nodeclassrated; static NOINLINE int CmpRatedClassPri(const void* UNUSED_PARAM(p), const nodeclassrated* a, const nodeclassrated* b) { if (a->Rating > b->Rating) return -1; if (a->Rating < b->Rating) return 1; return CmpClassPri(NULL,&a->Class,&b->Class); } static NOINLINE int CmpNode(const void* p, const node* const* a, const node* const* b) { const nodeclass* ca = NodeGetClass(*a); const nodeclass* cb = NodeGetClass(*b); return CmpClass(p,&ca,&cb); } static NOINLINE int CmpNodeClass(void* UNUSED_PARAM(p), const node* const* a, const fourcc_t* b) { fourcc_t AClass = NodeClass_ClassId(NodeGetClass(*a)); if (AClass > *b) return 1; if (AClass < *b) return -1; return 0; } NOINLINE const nodeclass* NodeContext_FindClass(anynode* Any,fourcc_t ClassId) { size_t Pos; bool_t Found; nodeclass_with_vmt Item; const nodeclass* Ptr; nodecontext* p = Node_Context(Any); if (ClassId == 0) return NULL; Ptr = (const nodeclass*)p->NodeCache; if (Ptr && NodeClass_ClassId(Ptr) == ClassId) return Ptr; LockEnter(p->NodeLock); Item.VMT.ClassId = ClassId; Ptr = &Item.Class; Pos = ArrayFind(&p->NodeClass,nodeclass*,&Ptr,(arraycmp)CmpClassNoModule, NULL, &Found); if (Found) { if (ARRAYBEGIN(p->NodeClass,const nodeclass*)[Pos]->StateNodeClass,const nodeclass*); // find first with same id for (;Pos>0 && NodeClass_ClassId(ARRAYBEGIN(p->NodeClass,const nodeclass*)[Pos-1]) == ClassId;--Pos) {} Ptr = NULL; for (;PosNodeClass,const nodeclass*)[Pos]) == ClassId;++Pos) if (ARRAYBEGIN(p->NodeClass,const nodeclass*)[Pos]->State>=CLASS_REGISTERED) { Ptr = ARRAYBEGIN(p->NodeClass,const nodeclass*)[Pos]; break; } } else Ptr = ARRAYBEGIN(p->NodeClass,const nodeclass*)[Pos]; p->NodeCache = Ptr; } else { Ptr = NULL; //DebugMessage(T("Class %c%c%c%c (%d) not found"),(ClassId>>0)&0xFF,(ClassId>>8)&0xFF,(ClassId>>16)&0xFF,(ClassId>>24)&0xFF,ClassId); } LockLeave(p->NodeLock); return Ptr; } static NOINLINE const nodeclass* FindModuleClass(nodecontext* p,fourcc_t ClassId,nodemodule* Module) { const nodeclass** i; for (i=ARRAYBEGIN(p->NodeClass,const nodeclass*);i!=ARRAYEND(p->NodeClass,const nodeclass*);++i) if (NodeClass_ClassId(*i) == ClassId && (*i)->Module == Module && (*i)->State>=CLASS_REGISTERED) return *i; return NULL; } NOINLINE const nodeclass* NodeContext_FindClassEx(anynode* AnyNode,fourcc_t ClassId,nodemodule* Module) { const nodeclass* Class = NULL; if (ClassId) { nodecontext* p = Node_Context(AnyNode); LockEnter(p->NodeLock); Class = FindModuleClass(p,ClassId,Module); if (!Class) Class = NodeContext_FindClass(p,ClassId); LockLeave(p->NodeLock); } return Class; } #if defined(CONFIG_DEBUG_LEAKS) extern void DebugMessage(const tchar_t*,...); typedef struct class_ref_t { const nodeclass* Class; size_t Count; } class_ref_t; static int CmpClassRef(void* UNUSED_PARAM(p), const class_ref_t *a, const class_ref_t *b) { return (a->Class->FourCC - b->Class->FourCC); } static void AddClassRef(const nodeclass* Class) { bool_t Found; intptr_t Pos=-1; array *Refs = &Class->Module->ClassRefs; class_ref_t Item; if (!Class->Module->LockRefs) Class->Module->LockRefs = LockCreate(); LockEnter(Class->Module->LockRefs); Item.Class = Class; Item.Count = 1; Pos = ArrayFind(Refs,class_ref_t,&Item,(arraycmp)CmpClassRef,NULL,&Found); if (Found) { ARRAYBEGIN(*Refs,class_ref_t)[Pos].Count++; } else if (ArrayAdd(Refs,class_ref_t,&Item,(arraycmp)CmpClassRef,NULL,0)==-1) { DebugMessage(T("AddClassRef %p class %r/%p could not be added !"),Refs,Class->FourCC,Class); } LockLeave(Class->Module->LockRefs); } static void DelClassRef(const nodeclass* Class) { bool_t Found; intptr_t Pos; array *Refs = &Class->Module->ClassRefs; class_ref_t Item; if (!Class->Module->LockRefs) Class->Module->LockRefs = LockCreate(); LockEnter(Class->Module->LockRefs); Item.Class = Class; Pos = ArrayFind(Refs,class_ref_t,&Item,(arraycmp)CmpClassRef,NULL,&Found); if (Found) { if (--ARRAYBEGIN(*Refs,class_ref_t)[Pos].Count==0) { //DebugMessage(T("class %r No more used !"),Class->FourCC); ArrayRemove(Refs,class_ref_t,&Item,(arraycmp)CmpClassRef,NULL); } } else { class_ref_t *r; DebugMessage(T("DelClassRef %p class %r/%p Not found !"),Refs,Class->FourCC,Class); for (r=ARRAYBEGIN(*Refs,class_ref_t);r!=ARRAYEND(*Refs,class_ref_t);++r) { DebugMessage(T("%r/%p=%d"),r->Class->FourCC,r->Class,r->Count); } Pos = ArrayFind(Refs,class_ref_t,&Item,(arraycmp)CmpClassRef,NULL,&Found); } LockLeave(Class->Module->LockRefs); } #else #define AddClassRef(c) #define DelClassRef(c) #endif static void UnInitClass(nodecontext* p,nodeclass* Class, bool_t IncludingModule); static void UnRegisterModule(nodecontext* p, nodemodule* Module, bool_t IncludingModule) { nodeclass** i; node** j; // release singleton objects for (j=ARRAYBEGIN(p->NodeSingleton,node*);j!=ARRAYEND(p->NodeSingleton,node*);++j) { if (NodeGetClass(*j)->Module == Module) { node* Node = *j; ArrayDelete(&p->NodeSingleton,(uint8_t*)j-ARRAYBEGIN(p->NodeSingleton,uint8_t),sizeof(node*)); Node_Release(Node); j = ARRAYBEGIN(p->NodeSingleton,node*)-1; } } // node memory leak in this module? (root module checked in NodeContext_Done) assert(Module==&p->Base || Module->Base.RefCount==1); for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) if ((*i)->Meta && (*i)->Module == Module) { if ((*i)->State>=CLASS_INITED) UnInitClass(p,(*i),IncludingModule); (*i)->Meta = NULL; } } NOINLINE bool_t NodeContext_Cleanup(nodecontext* p,bool_t Force) { // at the moment we only release modules without any object (not even singleton objects) // because cleanup and singleton object releasing could have multithreading issues... bool_t Found=0; if (p->FreeModule) { nodemodule* i; LockEnter(p->NodeLock); for (i=p->Base.Next;i;i=i->Next) if (i->Module && (Force || (!i->Config && i->Base.RefCount==1))) { if (!Force) NodeSingletonEvent(p,NODE_SINGLETON_SHUTDOWN,i); UnRegisterModule(p,i,0); p->FreeModule(p,i); Found = 1; } LockLeave(p->NodeLock); } return Found; } static NOINLINE void UnlockModules(const nodeclass* Class) { for (;Class;Class=Class->ParentClass) { DelClassRef(Class); --Class->Module->Base.RefCount; assert(Class->Module->Base.RefCount>=1); } } static void UnlockModulesWithLock(nodecontext* p,const nodeclass* Class) { LockEnter(p->NodeLock); UnlockModules(Class); LockLeave(p->NodeLock); } static NOINLINE bool_t DataFree(nodecontext* p, node* Node, nodedata** i, bool_t DeletingNode) { datatype Type; nodedata* Data = *i; nodenotify *n,*m; Type = Data->Code & TYPE_MASK; if (Type == TYPE_NODENOTIFY) { n=(nodenotify*)NodeData_Data(Data); if (n) { if (n->Func) // the notification list is being used { if (DeletingNode) n->Referer = &n->Referer; // mark the node to be removed after the notification else n->Referer = n; // mark all data to be freed after the notification return 0; } else { n=n->Next; while (n) { m=n; n=n->Next; MemHeap_Free(p->NodeHeap,m,sizeof(nodenotify)); } } } } else if (Type == TYPE_EXPR && p->ExprRelease) p->ExprRelease((nodeexpr*)NodeData_Data(Data)); #if defined(CONFIG_CORELUA) else if (Type == TYPE_LUA_REF && p->LuaRelease) p->LuaRelease(p->LuaCookie,(int*)NodeData_Data(Data)); #endif else if (Type == TYPE_NODE_REF && *(node**)NodeData_Data(Data)) Node_Release(*(node**)NodeData_Data(Data)); else if (Type == TYPE_NOTIFYEX) { notifyex *n=(notifyex*)NodeData_Data(Data); if (n->Free) n->Free(n->FreeCookie,n->This); } *i = Data->Next; MemHeap_Free(p->NodeHeap,Data,sizeof(nodedata)+Node_DataSize(Node,Data->Code>>8,Type,NodeData_Data(Data),META_PARAM_UNSET)); // META_PARAM_UNSET is neutral for the type return 1; } NOINLINE nodedata** Node_GetDataStart(node* Node, dataid Id, datatype Type) { uint_fast32_t Code = (Id<NodeLock); for (i=&Node->Data;*i;i=&(*i)->Next) if ((*i)->Code == Code) { LockLeave(p->NodeLock); return i; } LockLeave(p->NodeLock); return NULL; } NOINLINE void Node_RemoveData(node* Node, dataid Id, datatype Type) { uint_fast32_t Code = (Id<NodeLock); for (i=&Node->Data;*i;i=&(*i)->Next) if ((*i)->Code == Code) { DataFree(p,Node,i,0); break; } LockLeave(p->NodeLock); } NOINLINE void* Node_AddData(node* Node, dataid Id, datatype Type, const void* Data) { if (Node) { size_t Size = Node_DataSize(Node,Id,Type&TYPE_MASK,Data,META_PARAM_UNSET); // META_PARAM_UNSET is neutral for the type if (Size>0) { nodedata* Ptr; nodecontext* p = Node_Context(Node); LockEnter(p->NodeLock); Ptr = (nodedata*)MemHeap_Alloc(p->NodeHeap,sizeof(nodedata)+Size,0); if (!Ptr) { LockLeave(p->NodeLock); return NULL; } // Data list order is important. Evaluating TYPE_EXPRSTRING needs to be done in the order it was added // This function reverses the order, but we also use Node_Copy with templates so the final order it correct (hackish...) memcpy(NodeData_Data(Ptr),Data,Size); Ptr->Code = (Id<Next = Node->Data; Node->Data = Ptr; if (Type == TYPE_NODE_REF && *(node**)NodeData_Data(Ptr)) Node_AddRef(*(node**)NodeData_Data(Ptr)); #if defined(CONFIG_CORELUA) if (Type == TYPE_LUA_REF) p->LuaAddRef(p->LuaCookie,(int*)NodeData_Data(Ptr)); #endif LockLeave(p->NodeLock); return NodeData_Data(Ptr); } } return NULL; } static void* SetData(node* p, dataid Id, datatype Type, const void* Data) { size_t i,Size = Node_DataSize(p,Id,Type&TYPE_MASK,Data,META_PARAM_UNSET); // META_PARAM_UNSET is neutral for the type for (i=0;i Size) return ERR_INVALID_PARAM; memcpy(Data,Ptr,DataSize); } } else if ((Type & TYPE_MASK) == TYPE_STRING) *((tchar_t*)Data) = 0; else memset(Data,0,Size); return ERR_NONE; } const tchar_t* Node_GetDataStr(const node* p, dataid Id) { const tchar_t* s = Node_GetData(p,Id,TYPE_STRING); return s?s:T(""); } datetime_t Node_GetDataDatetime(const node* p, dataid Id) { datetime_t *d = Node_GetData(p,Id,TYPE_DATETIME); return d?*d:INVALID_DATETIME_T; } void* Node_GetData(const node* p, dataid Id, datatype Type) { uint_fast32_t Code = (Id<Data;i;i=i->Next) if (i->Code == Code) return NodeData_Data(i); return NULL; } static NOINLINE bool_t CallDelete(nodecontext* p,node* Node,const nodeclass* Class) { bool_t Result = 1; nodedata **ListItem; for (;Class;Class=Class->ParentClass) if (Class->Meta) { const nodemeta* m; for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) { if (m->Meta == META_CLASS_DELETE) ((void(*)(node*))m->Data)(Node); else if (m->Meta == META_PARAM_DATA_RELEASE) ((nodeupdatefunc)m->Data)(Node,0); else if (m->Meta == (META_MODE_DATA | TYPE_ARRAY) && (intptr_t)m->Data>=0) { array* Ptr = (array*)((uint8_t*)Node+m->Data); #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_FLAGS) { ++m; ++m; } if (m[2].Meta == META_PARAM_DATA_RELEASE) { ++m; ++m; ((nodeupdatefunc)m->Data)(Node,0); } #else if (m[1].Meta == META_PARAM_DATA_FLAGS) ++m; if (m[1].Meta == META_PARAM_DATA_RELEASE) { ++m; ((nodeupdatefunc)m->Data)(Node,0); } #endif ArrayClear(Ptr); } else if (m->Meta == (META_MODE_DATA | TYPE_NODE_REF) && (intptr_t)m->Data>=0) { node** Ptr = (node**)((uint8_t*)Node+m->Data); node* v = *Ptr; if (v) { #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_FLAGS) { ++m; ++m; } if (m[2].Meta == META_PARAM_DATA_RELEASE) { ++m; ++m; ((nodeupdatefunc)m->Data)(Node,0); } #else if (m[1].Meta == META_PARAM_DATA_FLAGS) ++m; if (m[1].Meta == META_PARAM_DATA_RELEASE) { ++m; ((nodeupdatefunc)m->Data)(Node,0); } #endif *Ptr = NULL; Node_Release(v); } } } } // no need to NodeLock around DataFree(), because object in deleting // (other threads should not touch this object anymore) ListItem = &Node->Data; while (*ListItem) if (!DataFree(p,Node,ListItem,1)) { ListItem = &(*ListItem)->Next; // will be deleted on Node_NotifyInternal exit Result = 0; } Node->VMT = NULL; return Result; } static NOINLINE const nodeclass* LockModules(nodecontext* p, const nodeclass* Class) { fourcc_t ClassId = NodeClass_ClassId(Class); nodemodule* Module = Class->Module; if (!Class->ParentClass) { if (Class->ParentId) return NULL; } else { int8_t State = Class->State; if (!LockModules(p,Class->ParentClass)) return NULL; if (StateBase.RefCount; if (CheckLoadModule(p,Module)) { NodeSingletonEvent(p,NODE_SINGLETON_STARTUP,Module); Class = FindModuleClass(p,ClassId,Module); // maybe have been reallocated } if (Class->StateNodeLock); Class = LockModules(p,Class); LockLeave(p->NodeLock); return Class; } static void MetaConst(const nodemeta* i,void* Data) { size_t Size = ParamSize[i->Meta & TYPE_MASK]; if (Size == sizeof(uintptr_t)) *(uintptr_t*)((uint8_t*)Data+i->Id) = i->Data; else { memset((uint8_t*)Data+i->Id,0,Size); memcpy((uint8_t*)Data+i->Id,&i->Data,min(sizeof(uintptr_t),Size)); } } static err_t CallCreate(nodecontext* p,node* Node,const nodeclass* Class) { if (Class) { const nodemeta* i; if (Class->ParentId && !Class->ParentClass) return ERR_NOT_SUPPORTED; if (CallCreate(p,Node,Class->ParentClass)!=ERR_NONE) return ERR_NOT_SUPPORTED; assert(Class->Meta && Class->State>=CLASS_INITED); for (i=Class->Meta;i->Meta != META_CLASS_PARENT_ID;++i) { if ((i->Meta & META_MODE_MASK)==META_MODE_CONST) MetaConst(i,Node); else if (i->Meta == (META_MODE_DATA | TYPE_ARRAY) && (intptr_t)i->Data>=0) { array* Ptr = (array*)((uint8_t*)Node+i->Data); ArrayInitEx(Ptr,p->NodeHeap); } else if (i->Meta == META_CLASS_CREATE && ((err_t(*)(node*))i->Data)(Node) != ERR_NONE) { CallDelete(p,Node,Class->ParentClass); return ERR_NOT_SUPPORTED; } } } return ERR_NONE; } static NOINLINE size_t NodeSize(const nodeclass* Class) { const nodeclass *j; const nodemeta* m; size_t Size = 0; if (NodeClass_ClassId(Class) == NODEMODULE_CLASS) return sizeof(nodemodule); // for NodeContext_Done when all classes are already released for (j=Class;j && !Size;j=j->ParentClass) for (m=j->Meta;m && m->Meta != META_CLASS_PARENT_ID;++m) if (m->Meta == META_CLASS_SIZE) { Size = (size_t)m->Data; break; } return Size; } void Node_Destructor(node* Node) { if (Node && Node->VMT) { const nodeclass* Class = NodeGetClass(Node); nodecontext* p = Node_Context(Node); Node_Notify(Node,NODE_DELETING); CallDelete(p,Node,Class); #ifdef CONFIG_DEBUGCHECKS Node->Magic = 0; #endif UnlockModulesWithLock(p,Class); } } static bool_t AddSingleton(nodecontext* p, node* Node) { bool_t Result; LockEnter(p->NodeLock); Result = ArrayAdd(&p->NodeSingleton,node*,&Node,(arraycmp)CmpNode,NULL,64)>=0; LockLeave(p->NodeLock); return Result; } err_t Node_Constructor(anynode* AnyNode, node* Node, size_t Size, fourcc_t ClassId) { err_t Err; const nodeclass* Class; nodecontext* p = Node_Context(AnyNode); memset(Node,0,Size); Node->RefCount = 1; Class = NodeContext_FindClass(p,ClassId); if (Class && (Class = LockModulesWithLock(p,Class)) != NULL) { #ifdef CONFIG_DEBUGCHECKS Node->FourCC = ClassId; Node->Magic = NODE_MAGIC; #endif Node->VMT = Class+1; Err = CallCreate(p,Node,Class); if (Err == ERR_NONE) { if (Class->Flags & CFLAG_SINGLETON) { assert(Class->Flags & CFLAG_OWN_MEMORY); if (!AddSingleton(p,Node)) { Node_Destructor(Node); return ERR_OUT_OF_MEMORY; } Node_AddRef(Node); } } else { Node->VMT = NULL; UnlockModulesWithLock(p,Class); } } else Err = ERR_NOT_SUPPORTED; return Err; } static node* NodeCreateFromClass(nodecontext* p, const nodeclass* Class, bool_t Singleton); static NOINLINE void ReleaseMetaLookup(nodecontext* p, nodeclass* Class) { if (Class->ParentClass) { if (Class->MetaGet==Class->ParentClass->MetaGet) Class->MetaGet=NULL; if (Class->MetaSet==Class->ParentClass->MetaSet) Class->MetaSet=NULL; if (Class->MetaUnSet==Class->ParentClass->MetaUnSet) Class->MetaUnSet=NULL; } if (Class->MetaGet) { MemHeap_Free(p->NodeConstHeap,Class->MetaGet,sizeof(nodemetalookuphead)+(Class->MetaGet->Upper+1)*sizeof(nodemetalookup)); Class->MetaGet = NULL; } if (Class->MetaSet) { MemHeap_Free(p->NodeConstHeap,Class->MetaSet,sizeof(nodemetalookuphead)+(Class->MetaSet->Upper+1)*sizeof(nodemetalookup)); Class->MetaSet = NULL; } if (Class->MetaUnSet) { MemHeap_Free(p->NodeConstHeap,Class->MetaUnSet,sizeof(nodemetalookuphead)+(Class->MetaUnSet->Upper+1)*sizeof(nodemetalookup)); Class->MetaUnSet = NULL; } } static void UnInitClass(nodecontext* p,nodeclass* Class, bool_t IncludingModule) { nodeclass** i; const nodemeta* m; if (!IncludingModule && NodeClass_IsPartOf(Class,NODEMODULE_CLASS)) return; // uninit all child classes for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) if ((*i)->State>=CLASS_INITED && (*i)->ParentClass == Class) UnInitClass(p,*i,IncludingModule); for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Meta == META_CLASS_VMT_DELETE) ((void(*)(fourcc_t,const void*))m->Data)(NodeClass_ClassId(Class),Class+1); if (Class->State>CLASS_REGISTERED) Class->State=CLASS_REGISTERED; ReleaseMetaLookup(p,Class); } static nodeclass* NodeClassResize(nodecontext* p,nodeclass* Old,size_t VMTSize) { nodeclass* New = MemHeap_ReAlloc(p->NodeHeap,Old,sizeof(nodeclass)+Old->VMTSize,sizeof(nodeclass)+VMTSize); if (New) { nodeclass** i; New->VMTSize = VMTSize; for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) { if (*i == Old) *i = New; if ((*i)->ParentClass == Old) (*i)->ParentClass = New; } } return New; } static bool_t FilterLookupGet(const nodemeta* m) { return m->Meta==META_PARAM_GET || (m->Meta & META_MODE_MASK)==META_MODE_DATA; } static bool_t FilterLookupSet(const nodemeta* m) { return m->Meta==META_PARAM_SET || m->Meta==META_PARAM_EVENT || #if defined(CONFIG_CORECDOC) ((m->Meta & META_MODE_MASK)==META_MODE_DATA && (m[2].Meta != META_PARAM_DATA_FLAGS || !((int)m[2].Data & DFLAG_RDONLY))); #else ((m->Meta & META_MODE_MASK)==META_MODE_DATA && (m[1].Meta != META_PARAM_DATA_FLAGS || !((int)m[1].Data & DFLAG_RDONLY))); #endif } static bool_t FilterLookupUnSet(const nodemeta* m) { return m->Meta==META_PARAM_UNSET || m->Meta==META_PARAM_EVENT || #if defined(CONFIG_CORECDOC) ((m->Meta & META_MODE_MASK)==META_MODE_DATA && (m[2].Meta != META_PARAM_DATA_FLAGS || !((int)m[2].Data & DFLAG_RDONLY))); #else ((m->Meta & META_MODE_MASK)==META_MODE_DATA && (m[1].Meta != META_PARAM_DATA_FLAGS || !((int)m[1].Data & DFLAG_RDONLY))); #endif } static const nodemeta* BitLookup(const nodeclass* Class,dataid Id) { const nodemeta* m; for (;Class;Class=Class->ParentClass) if (Class->Meta) for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Id == Id && m->Meta == META_PARAM_BIT) return m; return NULL; } static NOINLINE int CmpLookup(const nodemetalookup* p, const nodemetalookup* a, const nodemetalookup* b) { // sort by Id if (a->Id > b->Id) return 1; if (a->Id < b->Id) return -1; // make sure META_PARAM_BIT is after META_MODE_DATA if (a->Meta && b->Meta && a->Meta->Meta == META_PARAM_BIT) return 1; if (b->Meta && b->Meta && b->Meta->Meta == META_PARAM_BIT) return -1; // make sure META_PARAM_EVENT's are added in the order as they are found if (a==p) return 1; if (b==p) return -1; return 0; } static NOINLINE void AddLookup(nodeclass* Class, const nodemeta* m, array* List) { bool_t Found; nodemetalookup Lookup; Lookup.Id = m->Id; Lookup.Meta = NULL; ArrayFind(List,nodemetalookup,&Lookup,(arraycmp)CmpLookup,NULL,&Found); if (!Found || m->Meta == META_PARAM_EVENT) { if ((m->Meta & META_MODE_MASK)==META_MODE_DATA && (m->Meta & TYPE_MASK)==TYPE_BOOL_BIT) { Lookup.Meta = BitLookup(Class,m->Id); assert(Lookup.Meta); if (!Lookup.Meta) return; ArrayAdd(List,nodemetalookup,&Lookup,(arraycmp)CmpLookup,NULL,0); } Lookup.Meta = m; ArrayAdd(List,nodemetalookup,&Lookup,(arraycmp)CmpLookup,&Lookup,0); } } static NOINLINE nodemetalookuphead* BuildLookup(nodecontext* p,array* List) { nodemetalookuphead* v; nodemetalookuphead Head; Head.Upper = ARRAYCOUNT(*List,nodemetalookup)-1; v = MemHeap_Alloc(p->NodeConstHeap,sizeof(Head)+ARRAYCOUNT(*List,uint8_t),0); if (v) { MemHeap_Write(p->NodeConstHeap,v,&Head,0,sizeof(Head)); MemHeap_Write(p->NodeConstHeap,v,ARRAYBEGIN(*List,nodemetalookup),sizeof(Head),ARRAYCOUNT(*List,uint8_t)); } ArrayClear(List); return v; } static void BuildMetaLookup(nodecontext* p,nodeclass* Class) { const nodeclass* c; array List; bool_t NeedGet=0; bool_t NeedSet=0; bool_t NeedUnSet=0; const nodemeta* m; for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) { if (FilterLookupGet(m)) NeedGet = 1; if (FilterLookupSet(m)) NeedSet = 1; if (FilterLookupUnSet(m)) NeedUnSet = 1; } if (NeedGet) { ArrayInit(&List); for (c=Class;c;c=c->ParentClass) if (c->Meta) for (m=c->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (FilterLookupGet(m)) AddLookup(Class,m,&List); if (!ARRAYEMPTY(List)) Class->MetaGet = BuildLookup(p,&List); } else if (Class->ParentClass) Class->MetaGet = Class->ParentClass->MetaGet; if (NeedSet) { ArrayInit(&List); for (c=Class;c;c=c->ParentClass) if (c->Meta) for (m=c->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (FilterLookupSet(m)) AddLookup(Class,m,&List); if (!ARRAYEMPTY(List)) Class->MetaSet = BuildLookup(p,&List); } else if (Class->ParentClass) Class->MetaSet = Class->ParentClass->MetaSet; if (NeedUnSet) { ArrayInit(&List); for (c=Class;c;c=c->ParentClass) if (c->Meta) for (m=c->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (FilterLookupUnSet(m)) AddLookup(Class,m,&List); if (!ARRAYEMPTY(List)) Class->MetaUnSet = BuildLookup(p,&List); } else if (Class->ParentClass) Class->MetaUnSet = Class->ParentClass->MetaUnSet; } static void InitClass(nodecontext* p,nodeclass* Class) { const nodeclass* Parent = Class->ParentClass; if (Class->State==CLASS_REGISTERED && Class->Meta && (!Class->ParentId || (Parent && Parent->State>=CLASS_INITED))) { uintptr_t Data; const nodemeta* i; if (Parent) { fourcc_t ClassId; if (Class->VMTSize == DEFAULT_VMT && Parent->VMTSize > DEFAULT_VMT) { Class = NodeClassResize(p,Class,Parent->VMTSize); if (!Class) return; } assert(Parent->VMTSize >= DEFAULT_VMT); assert(Class->VMTSize >= Parent->VMTSize); assert(NodeClass_Context(Parent) == NodeClass_Context(Class)); ClassId = NodeClass_ClassId(Class); memcpy(Class+1,Parent+1,min(Class->VMTSize,Parent->VMTSize)); NodeClass_ClassId(Class) = ClassId; } BuildMetaLookup(p,Class); assert(Class->VMTSize >= DEFAULT_VMT); Class->State = CLASS_INITED; for (i=Class->Meta;i->Meta != META_CLASS_PARENT_ID;++i) { if ((i->Meta & META_MODE_MASK)==META_MODE_VMT) { #if defined(CONFIG_CORECDOC) if ((i->Meta & ~META_MODE_MASK)==TYPE_FUNC) // otherwise it might be some doc items #endif MetaConst(i,Class+1); } else switch (i->Meta) { case META_CLASS_VMT_CREATE: if (((int(*)(fourcc_t,void*))i->Data)(NodeClass_ClassId(Class),Class+1) != ERR_NONE) { ReleaseMetaLookup(p,Class); p->NodeCache = NULL; Class->State = CLASS_FAILED; } break; case META_CLASS_META: if (((bool_t(*)(nodecontext*,void*,datameta,uintptr_t*))i->Data)(p,Class+1,META_CLASS_FLAGS,&Data)) Class->Flags = (uint8_t)Data; if (((bool_t(*)(nodecontext*,void*,datameta,uintptr_t*))i->Data)(p,Class+1,META_CLASS_PRIORITY,&Data)) Class->Priority = (int16_t)(Data-PRI_DEFAULT); break; case META_CLASS_FLAGS: Class->Flags = (uint8_t)i->Data; break; case META_CLASS_PRIORITY: Class->Priority = (int16_t)(i->Data-PRI_DEFAULT); break; } } if (Class->State>=CLASS_INITED && (Class->Flags & (CFLAG_SINGLETON|CFLAG_OWN_MEMORY))==CFLAG_SINGLETON && !NodeCreateFromClass(p,Class,1)) { p->NodeCache = NULL; Class->State = CLASS_FAILED; UnInitClass(p,Class,0); // just to call META_CLASS_VMT_DELETE } if (Class->State>=CLASS_INITED) { nodeclass** i; for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) if ((*i)->ParentClass == Class) InitClass(p,*i); } } } void NodeContext_UpdateParents(nodecontext* p) { nodeclass** i; for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) { (*i)->ParentClass = NodeContext_FindClass(p,(*i)->ParentId); InitClass(p,*i); } } static node* NodeCreateFromClass(nodecontext* p, const nodeclass* Class, bool_t Singleton) { node* Node; size_t Size; if (!Class || (Class->Flags & CFLAG_ABSTRACT)) return NULL; if ((Class->Flags & CFLAG_SINGLETON) && (Node = NodeSingleton(p,NodeClass_ClassId(Class)))!=NULL) { if (!Singleton) Node_AddRef(Node); return Node; } Class = LockModulesWithLock(p,Class); if (!Class) return NULL; Size = NodeSize(Class); if (!Size) { UnlockModulesWithLock(p,Class); return NULL; } Node = (node*)MemHeap_Alloc(p->NodeHeap,Size,0); if (Node) { memset(Node,0,Size); #ifdef CONFIG_DEBUGCHECKS Node->FourCC = NodeClass_ClassId(Class); Node->Magic = NODE_MAGIC; #endif Node->RefCount = 1; Node->VMT = Class+1; if (Singleton && !AddSingleton(p,Node)) { UnlockModulesWithLock(p,Class); return NULL; } if (CallCreate(p,Node,Class) != ERR_NONE) { LockEnter(p->NodeLock); if (Singleton) ArrayRemove(&p->NodeSingleton,node*,&Node,NULL,NULL); // can't use CmpNode, because Node->VMT is NULL UnlockModules(Class); LockLeave(p->NodeLock); MemHeap_Free(p->NodeHeap,Node,Size); Node = NULL; } } return Node; } nodeclass* NodeContext_CreateClass(nodecontext* p, fourcc_t ClassId, size_t VMTSize, nodemodule* Module) { nodeclass* Class = NULL; nodeclass** i; size_t Size = sizeof(nodeclass)+VMTSize; assert(VMTSize>=DEFAULT_VMT); p->NodeCache = NULL; for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) if (NodeClass_ClassId(*i) == ClassId && (*i)->Module == Module) { Class = *i; break; } if (!Class) { nodeclass** i; Class = (nodeclass*) MemHeap_Alloc(p->NodeHeap,Size,0); if (!Class) return NULL; memset(Class,0,Size); #ifdef CONFIG_DEBUGCHECKS Class->FourCC = ClassId; #endif Class->VMTSize = VMTSize; NodeClass_Context(Class) = p; NodeClass_ClassId(Class) = ClassId; Class->Module = Module; if (ArrayAdd(&p->NodeClass,nodeclass*,&Class,(arraycmp)CmpClass,NULL,128)<0) { MemHeap_Free(p->NodeHeap,Class,Size); return NULL; } // update child classes for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) if ((*i)->ParentId == NodeClass_ClassId(Class) && (!(*i)->ParentClass || (*i)->ParentClass->StateModule == Class->Module)) (*i)->ParentClass = Class; } else { if (Class->Meta) return NULL; // already registered if (Class->VMTSize != VMTSize) { Class = NodeClassResize(p,Class,VMTSize); if (!Class) return NULL; } } if (Class->StateState=CLASS_REGISTERED; Class->Priority = 0; Class->Flags = 0; return Class; } void NodeRegisterClassEx(nodemodule* Module,const nodemeta* Meta) { nodeclass* Class; nodecontext* p = Node_Context(Module); LockEnter(p->NodeLock); while (Meta->Meta == META_CLASS_CLASS_ID) { const nodeclass* ParentClass; fourcc_t ParentId; fourcc_t ClassId = (fourcc_t)(Meta++)->Data; size_t VMTSize = DEFAULT_VMT; const nodemeta* i = Meta; if (!ClassId) ClassId = ++p->DynamicClass; for (;Meta->Meta != META_CLASS_PARENT_ID;++Meta) if (Meta->Meta == META_CLASS_VMT_SIZE) VMTSize = (size_t)(Meta->Data); ParentId = (fourcc_t)Meta->Data; ParentClass = NodeContext_FindClassEx(p,ParentId,Module); if (VMTSize == DEFAULT_VMT && ParentClass) VMTSize = ParentClass->VMTSize; Class = NodeContext_CreateClass(p,ClassId,VMTSize,Module); if (Class) { Class->Meta = i; Class->ParentId = ParentId; Class->ParentClass = ParentClass; InitClass(p,Class); } if (!(Meta++)->Id) // more classes? break; } LockLeave(p->NodeLock); } static void EraseNode(nodecontext* p,node* Node,const nodeclass* Class) { size_t Size = NodeSize(Class); #ifdef CONFIG_DEBUGCHECKS Node->Magic = 0; #endif UnlockModulesWithLock(p,Class); if (!(Class->Flags & CFLAG_OWN_MEMORY)) MemHeap_Free(p->NodeHeap,Node,Size); } void Node_AddRef(thisnode p) { assert(p); // we may switch to virtual reference functions later Node_ValidatePtr(p); ++((node*)p)->RefCount; } void Node_Release(thisnode p) { nodecontext* Context; assert(p); // we may switch to virtual reference functions later Node_ValidatePtr(p); Context = Node_Context(p); if (--((node*)p)->RefCount == 0) { const nodeclass* Class = NodeGetClass(p); Node_Notify((node*)p,NODE_DELETING); assert(((node*)p)->RefCount == 0); // the RefCount may increase during Node_Notify but it shouldn't if (CallDelete(Context,p,Class)) EraseNode(Context,p,Class); } } void NodeDelete(node* p) { if (p) Node_Release(p); } nodemodule* NodeClassModule(anynode* Any,fourcc_t ClassId) { nodecontext* p = Node_Context(Any); nodemodule* Module = NULL; const nodeclass* Class = NULL; if (ClassId) { LockEnter(p->NodeLock); Class = NodeContext_FindClass(p,ClassId); LockLeave(p->NodeLock); } if (Class) Module = Class->Module; else Module = &p->Base; return Module; } nodemodule* NodeModule(node* Node) { return NodeGetClass(Node)->Module; } NOINLINE bool_t Node_IsPartOf(const void* Node, fourcc_t PartOfClass) { Node_ValidatePtr(Node); return NodeClass_IsPartOf(NodeGetClass(Node),PartOfClass); } NOINLINE void NodeClassSetPriority(node* Node,int Priority) { NodeGetClass(Node)->Priority = (int16_t)(Priority - PRI_DEFAULT); } NOINLINE int NodeClassFlags(node* Node) { return NodeGetClass(Node)->Flags; } node* NodeCreate(anynode* Any, fourcc_t ClassId) { nodecontext* p = Node_Context(Any); return NodeCreateFromClass(p,NodeContext_FindClass(p,ClassId),0); } node* NodeSingleton(anynode* Any, fourcc_t Class) { node* Node = NULL; if (Any) { nodecontext* p = Node_Context(Any); size_t Pos; bool_t Found; LockEnter(p->NodeLock); Pos = ArrayFind(&p->NodeSingleton,node*,&Class,(arraycmp)CmpNodeClass,NULL,&Found); if (Found) Node = ARRAYBEGIN(p->NodeSingleton,node*)[Pos]; LockLeave(p->NodeLock); } return Node; } bool_t NodeIsClass(anynode* p,fourcc_t ClassId, fourcc_t PartOfClass) { return NodeClass_IsPartOf(NodeContext_FindClass(p,ClassId),PartOfClass); } fourcc_t NodeEnumClass(anynode* Any,array* ListId, fourcc_t ClassId) { return NodeEnumClassFilterRated(Any,ListId,ClassId,NULL,NULL); } typedef struct filterstr { int Id; const tchar_t* Str; } filterstr; static int FilterStr(filterstr* i, const nodeclass* Class) { //TODO: suppport rating return StrListIndex(i->Str,NodeClass_Str(NULL,Class,i->Id))>=0?1:0; } fourcc_t NodeEnumClassStr(anynode* Any,array* ListId, fourcc_t ClassId, int Id, const tchar_t* Str) { filterstr i; if (!Str || !Str[0]) { if (ListId) ArrayInit(ListId); return 0; } i.Id = Id; i.Str = Str; return NodeEnumClassFilterRated(Any,ListId,ClassId,(nodeenumclassfilterrated)FilterStr,&i); } static NOINLINE void NodeEnumSingletonsEx(anynode* Any,array* List, nodemodule* Module) { nodecontext* p = Node_Context(Any); node** i; ArrayInit(List); LockEnter(p->NodeLock); for (i=ARRAYBEGIN(p->NodeSingleton,node*);i!=ARRAYEND(p->NodeSingleton,node*);++i) if (*i && (!Module || NodeGetClass(*i)->Module == Module)) ArrayAppend(List,i,sizeof(*i),64); LockLeave(p->NodeLock); } void NodeEnumSingletons(anynode* Any,array* List) { NodeEnumSingletonsEx(Any,List,NULL); } static uintptr_t NOINLINE NodeParamMeta(const nodeclass* Class, uint_fast32_t Meta, dataid Id, const node* Node) { uintptr_t Data; const nodemeta* m; for (;Class;Class=Class->ParentClass) { if (Class->Meta) // should be registered, just fail safe for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Id == Id) { if (m->Meta == Meta) return m->Data; if (m->Meta == META_PARAM_META && ((bool_t(*)(const node*,dataid,datameta,uintptr_t*))m->Data)(Node,Id,Meta,&Data)) return Data; } if (Meta == META_PARAM_STRING) { const nodeclass* MainClass = Class; nodecontext* Context = NodeClass_Context(Class); // only check for META_PARAM_META... while ((Class=Class->ParentClass)!=NULL) { if (Class->Meta) // should be registered, just fail safe for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Id == Id && m->Meta == META_PARAM_META && ((bool_t(*)(const node*,dataid,datameta,uintptr_t*))m->Data)(Node,Id,Meta,&Data)) return Data; } Class = MainClass; if (Context->ExternalStr) { do { Data = (uintptr_t)Context->ExternalStr(Context,NodeClass_ClassId(Class),(int)Id); if (Data!=0 && *((const tchar_t*)Data)) return Data; } while ((Class=Class->ParentClass)!=NULL); return (uintptr_t)T(""); } } } return 0; } NOINLINE uintptr_t NodeClass_Meta(const nodeclass* Class,dataid Id,datameta Meta) { return NodeParamMeta(Class,Meta,Id,NULL); } NOINLINE int NodeClass_Priority(const nodeclass* Class) { return Class?Class->Priority:PRI_MINIMUM; } NOINLINE fourcc_t NodeClass_Parent(const nodeclass* Class) { return Class?Class->ParentId:0; } NOINLINE const tchar_t* NodeClass_Str(anynode* AnyNode, const nodeclass* Class,int No) { const tchar_t* s = (const tchar_t*)NodeParamMeta(Class,META_PARAM_STRING,No,AnyNode); return s?s:T(""); } const tchar_t* NodeParamStr(const node* p,int No) { return NodeClass_Str(p,NodeGetClass(p),No); } const tchar_t* NodeStr2(anynode* AnyNode,fourcc_t ClassId,int No) { nodecontext* Context = Node_Context(AnyNode); const nodeclass* Class = NodeContext_FindClass(Context,ClassId); if (Class) return NodeClass_Str(AnyNode,Class,No); if (Context->ExternalStr) return Context->ExternalStr(Context,ClassId,No); return T(""); } //TODO: check if this can be merged with NodeStr2 const tchar_t* NodeStrEx(anynode* AnyNode,fourcc_t ClassId,int No) { nodecontext* Context = Node_Context(AnyNode); if (Context->ExternalStr) return Context->ExternalStr(Context,ClassId,No); return T(""); } fourcc_t NodeEnumClassFilterRated(anynode* AnyContext, array* ListId, fourcc_t ClassId, nodeenumclassfilterrated Func, void* Param) { nodecontext* p; const nodeclass* v; const nodeclass **i; array List; fourcc_t BestId = 0; int BestPri = 0; int BestRate = 0; assert(AnyContext != NULL); p = Node_Context(AnyContext); ArrayInit(&List); LockEnter(p->NodeLock); for (i=ARRAYBEGIN(p->NodeClass,const nodeclass*);i!=ARRAYEND(p->NodeClass,const nodeclass*);++i) { if ((*i)->State>=CLASS_REGISTERED && !((*i)->Flags & CFLAG_ABSTRACT)) // skip abstract { for (v=*i;v;v=v->ParentClass) if (NodeClass_ClassId(v) == ClassId) { int Rating = Func ? Func(Param,*i):1; if (Rating > 0) { if (!ListId) { if (BestRate < Rating || (BestRate == Rating && BestPri < (*i)->Priority)) { BestId = NodeClass_ClassId(*i); BestPri = (*i)->Priority; BestRate = Rating; } } else { nodeclassrated Item; Item.Class = *i; Item.Rating = Rating; ArrayAppend(&List,&Item,sizeof(Item),64); } } break; } } } if (ListId) { fourcc_t* a; nodeclassrated* b; size_t Count = ARRAYCOUNT(List,nodeclassrated); ArraySort(&List,nodeclassrated,(arraycmp)CmpRatedClassPri, NULL, 0); ArrayInit(ListId); if (ArrayAppend(ListId,NULL,Count*sizeof(fourcc_t),64)) { for (a=ARRAYBEGIN(*ListId,fourcc_t),b=ARRAYBEGIN(List,nodeclassrated);b!=ARRAYEND(List,nodeclassrated);++b,++a) *a = NodeClass_ClassId(b->Class); } ArrayClear(&List); } LockLeave(p->NodeLock); return BestId; } static INLINE void Node_NotifyInternal(node* Node,dataid Id,nodedata** i,nodecontext* Context) { const nodeclass* Class = NodeGetClass(Node); nodenotify* Top = NodeData_Data(*i); nodeevt Pin; nodenotify *n,*m; bool_t PostDeleteNode = 0, PosDeleteList = 0; // Top->Referer = any: the item of the list being called / NULL: remove the item being called from the list / Top: delete all the notification / &Top->Referer: delete all the node // Top->Func = set if the notification is in use if (Top->Func!=NULL) { assert(Top->Func!=NULL); return; // already being notified, not supported } Top->Func = (notifyproc)Top; // mark the notification as in use Pin.Node = Node; Pin.Id = Id; n = Top->Next; // skip the dummy notify element assert(n!=NULL); // if there is a Top there should be at least one item in the list while (n) { Top->Referer = n; // tell the RemoveNotify that this item in the list is being used m=n; n->Func(n->Referer,&Pin); n=n->Next; if (Top->Referer==&Top->Referer) { PostDeleteNode = 1; } else if (Top->Referer==Top) { PosDeleteList = 1; } else if (Top->Referer==NULL) // the notification item has been (asked to be) removed { MemHeap_Free(Context->NodeHeap,m,sizeof(nodenotify)); // i may have changed i = Node_GetDataStart(Node,Id,TYPE_NODENOTIFY); } } Top->Referer = NULL; if (PostDeleteNode) { LockEnter(Context->NodeLock); DataFree(Context,Node,i,1); EraseNode(Context,Node,Class); LockLeave(Context->NodeLock); } else if (Id==NODE_DELETING || Top->Next==NULL || PosDeleteList) { LockEnter(Context->NodeLock); DataFree(Context,Node,i,0); // delete the notify data when it's not to be used anymore(NODE_DELETING) or empty LockLeave(Context->NodeLock); } Top->Func = NULL; } bool_t Node_Notify(node* Node,dataid Id) { nodedata** i = Node_GetDataStart(Node,Id,TYPE_NODENOTIFY); if (i && NodeData_Data(*i)) { Node_NotifyInternal(Node,Id,i,Node_Context(Node)); return 1; } return 0; } #if defined(CONFIG_MULTITHREAD) bool_t Node_PostNotify(node* Node,dataid Id) { nodedata** i = Node_GetDataStart(Node,Id,TYPE_NODENOTIFY); if (i && NodeData_Data(*i) && NodeData_Data(*i)->Next) // do not propagate empty events { nodecontext* Context = Node_Context(Node); register uintptr_t CurrentThreadId = ThreadId(); if (Context->PostNotify && Context->ThreadId != CurrentThreadId) // TODO: what about the other ones in the same thread ? { if (Context->PostNotify(Context->PostNotifyParam,Node,Id)) return 0; // fallback to the same thread as we don't want to lose any event sending } Node_NotifyInternal(Node,Id,i,Context); return 1; } return 0; } #endif NOINLINE void Node_AddNotify(node* Node, dataid Id, notifyproc Func, void* Referer) { if (Node) { nodecontext* p = Node_Context(Node); nodenotify* n; nodenotify* Ptr; LockEnter(p->NodeLock); Ptr = Node_GetData(Node,Id,TYPE_NODENOTIFY); if (!Ptr) { nodenotify Origin = {NULL,NULL,NULL}; Ptr = Node_AddData(Node,Id,TYPE_NODENOTIFY,&Origin); if (!Ptr) { // Something went wrong ! No more memory ? LockLeave(p->NodeLock); return; } } n = MemHeap_Alloc(p->NodeHeap,sizeof(nodenotify),0); if (!n) { LockLeave(p->NodeLock); return; } n->Func = Func; n->Referer = Referer; n->Next = Ptr->Next; Ptr->Next = n; LockLeave(p->NodeLock); } } void Node_AddNotify_Update(node* Node, dataid Id, notifyproc Func, void* Refered) { Node_AddNotify(Node,Id,Func,Refered); if (Func) { nodeevt Pin; Pin.Node = Node; Pin.Id = Id; Func(Refered,&Pin); } } void Node_RemoveNotify(node* Node, dataid Id, notifyproc Func, void* Referer) { if (Node) { nodecontext* p = Node_Context(Node); nodenotify* n; LockEnter(p->NodeLock); n = Node_GetData(Node,Id,TYPE_NODENOTIFY); if (n) { nodenotify** Ptr; nodenotify* Top = n; void *OldReferer = Top->Referer; n = Top->Next; // skip the first element which is just there to know if an item of the chain is being notified Ptr = &n; for (;(n=*Ptr)!=NULL;Ptr=&n->Next) { if (n->Func==Func && n->Referer==Referer) { // remove the item from the list if (*Ptr == Top->Next) Top->Next = n->Next; else *Ptr = n->Next; if (Top->Referer==n) // this notification item is being called Top->Referer = NULL; // tell the notifier that it should remove this element after the call else MemHeap_Free(p->NodeHeap,n,sizeof(nodenotify)); break; } } if (Top->Next==NULL && OldReferer==Top->Referer) Node_RemoveData(Node,Id,TYPE_NODENOTIFY); // the notification list is empty and it's not being called } LockLeave(p->NodeLock); } } size_t NodeTypeSize(datatype Type) { assert((Type & TYPE_MASK)>TUNIT_SHIFT]; } static const tchar_t NullString[] = T(""); static NOINLINE bool_t EqData(datatype Type, const void* a, const void* b, size_t Size) { size_t i; switch (Type) { case TYPE_EXPRSTRING: case TYPE_EXPRPARAM: case TYPE_STRING: if (!a) a = NullString; if (!b) b = NullString; return tcscmp(a,b)==0; case TYPE_ARRAY: return ArrayEq(a,b); case TYPE_FRACTION: if (a && b) return EqFrac((const cc_fraction*)a,(const cc_fraction*)b); break; } if (!a && !b) return 1; if (a && b) return memcmp(a,b,Size)==0; if (!a) a = b; for (i=0;iValue,uint8_t),IsSet=ARRAYBEGIN(Values->Name,int);v!=ARRAYEND(Values->Value,uint8_t);v+=Values->ValueSize,++IsSet) { if (EqData(Type & TYPE_MASK,a,v,Values->ValueSize)) return (*IsSet!=0); } return 0; } return EqData(Type & TYPE_MASK,a,b,Node_MaxDataSize(p,Id,Type,META_PARAM_GET)); } NOINLINE size_t Node_MaxDataSize(node* p, dataid Id, dataflags Flags, int QueryType) { size_t Size; assert(QueryType==META_PARAM_GET || QueryType==META_PARAM_SET || QueryType==META_PARAM_UNSET); Flags &= TYPE_MASK; //assert(Flags != 0); if (Flags == 0) return 0; if (Id < (DATA_ENUM_MULTI*2)) // a normal ID (instead of a class ID, sometimes) { if (Id & DATA_ENUM) { if (QueryType==META_PARAM_GET) Flags = TYPE_ENUM; else if (QueryType==META_PARAM_SET) Flags = TYPE_STRING; } if (Id & DATA_ENUM_MULTI) { if (QueryType==META_PARAM_GET) Flags = TYPE_ENUM; else if (QueryType==META_PARAM_SET) Flags = TYPE_ENUM_MULTI_SET; } } assert(Flags < MAX_PARAMTYPE); Size = ParamSize[Flags]; if (Size == MAXDATA && Flags != TYPE_STRING) // we don't care about how much space the non-dynamic string needs (except in MetaSet()) { Size = (size_t)Node_Meta(p,Id,META_PARAM_SIZE); if (!Size) Size = MAXDATA; } return Size; } NOINLINE size_t Node_DataSize(node* p, dataid Id, datatype Type, const void* Data, int QueryType) { size_t Size; assert(QueryType==META_PARAM_GET || QueryType==META_PARAM_SET || QueryType==META_PARAM_UNSET); if (!Data) return 0; switch (Type) { case TYPE_EXPR: Size = Node_Context(p)->ExprSize((nodeexpr*)Data); break; case TYPE_EXPRSTRING: case TYPE_EXPRPARAM: case TYPE_STRING: Size = tcsbytes((const tchar_t*)Data); break; default: Size = Node_MaxDataSize(p,Id,Type,QueryType); break; } return Size; } static NOINLINE void MetaEnumClass(const nodeclass* Class,array* List) { if (Class->ParentClass) MetaEnumClass(Class->ParentClass,List); if (Class->Meta) { const nodemeta* m; for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Meta == META_PARAM_TYPE) { dataid Id = m->Id; ArrayAppend(List,&Id,sizeof(Id),256); } } } static void MetaEnum(node* p,array* List) { const nodeclass* Class; ArrayInit(List); Class = NodeGetClass(p); if (Class) MetaEnumClass(Class,List); } static uintptr_t MetaMeta(node* p,dataid Id,datameta Meta) { return NodeParamMeta(NodeGetClass(p),Meta,Id,p); } static err_t MetaGet(node* p,dataid Id,void* Data,size_t Size) { const nodeclass* Class = NodeGetClass(p); nodemetalookuphead* Head = Class->MetaGet; if (Head) { nodemetalookup* Lookup = (nodemetalookup*)(Head+1); intptr_t Mid; intptr_t Lower = 0; intptr_t Upper = Head->Upper; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; if (Lookup[Mid].Id>Id) Upper = Mid-1; else if (Lookup[Mid].IdMeta == META_PARAM_GET) return ((err_t(*)(node*,dataid,void*,size_t))m->Data)(p,Id,Data,Size); if (m->Meta == META_PARAM_BIT) m = Lookup[--Mid].Meta; assert((m->Meta & META_MODE_MASK)==META_MODE_DATA); Type = (m->Meta & TYPE_MASK); if ((intptr_t)m->Data<0) { Ptr = Node_GetData(p,Id,Type); if (!Ptr) { #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_FLAGS && (m[2].Data & DFLAG_NODEFAULT)) #else if (m[1].Meta == META_PARAM_DATA_FLAGS && (m[1].Data & DFLAG_NODEFAULT)) #endif return ERR_INVALID_DATA; memset(Data,0,Size); return ERR_NONE; } } else Ptr = (const uint8_t*)p + (intptr_t)m->Data; if (Type == TYPE_STRING) tcscpy_s(Data,Size/sizeof(tchar_t),(const tchar_t*)Ptr); else if (Type == TYPE_BOOL_BIT) { uint32_t Bit; assert(Lookup[Mid+1].Id == Id && Lookup[Mid+1].Meta->Meta==META_PARAM_BIT); Bit = (uint32_t)Lookup[Mid+1].Meta->Data; if (Size != sizeof(bool_t)) return ERR_INVALID_DATA; *(bool_t*)Data = (*(const uint32_t*)Ptr & Bit) != 0; } else { size_t DataSize = Node_MaxDataSize(p,m->Id,Type,META_PARAM_GET); assert(Size == DataSize); if (DataSize != Size) return ERR_INVALID_DATA; if (DataSize==sizeof(int)) *(int*)Data = *(const int*)Ptr; else memcpy(Data,Ptr,DataSize); } return ERR_NONE; } } } return ERR_INVALID_PARAM; } static err_t MetaSet(node* p,dataid Id,const void* Data,size_t Size) { const nodeclass* Class = NodeGetClass(p); nodemetalookuphead* Head = Class->MetaSet; if (Head) { nodemetalookup* Lookup = (nodemetalookup*)(Head+1); intptr_t Mid; intptr_t Lower = 0; intptr_t Upper = Head->Upper; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; if (Lookup[Mid].Id>Id) Upper = Mid-1; else if (Lookup[Mid].IdMeta == META_PARAM_SET) return ((err_t(*)(node*,dataid,const void*,size_t))m->Data)(p,Id,Data,Size); if (m->Meta == META_PARAM_EVENT) { while (Mid>0 && Lookup[Mid-1].Id==Id) --Mid; do { assert(Lookup[Mid].Meta->Meta==META_PARAM_EVENT); Result = ((nodeupdatefunc)Lookup[Mid].Meta->Data)(p,Id); if (Result != ERR_NONE) return Result; ++Mid; } while (Mid<=(intptr_t)Head->Upper && Lookup[Mid].Id==Id); return ERR_NONE; } if (m->Meta == META_PARAM_BIT) m = Lookup[--Mid].Meta; assert((m->Meta & META_MODE_MASK)==META_MODE_DATA); // any variable needs either a SET method, be an event or have related DATA MetaData = m->Data; Type = m->Meta; DFlags = 0; #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_FLAGS) #else if (m[1].Meta == META_PARAM_DATA_FLAGS) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif DFlags = (int)m->Data; if (DFlags & DFLAG_RDONLY) continue; // TODO: pointer should not use DFLAG_CMP because it maybe a recreated different object (unless referencing is used) //assert(!(DFlags & DFLAG_CMP) || (Type & TYPE_MASK) != TYPE_NODE); if ((DFlags & DFLAG_VERIFY_CLASS) && ((Type & TYPE_MASK) == TYPE_NODE || (Type & TYPE_MASK) == TYPE_NODE_REF) && Data && Size==sizeof(node*) && *(const node**)Data && !Node_IsPartOf(*(const node**)Data,(fourcc_t)Node_Meta(p,Id,META_PARAM_CLASS))) return ERR_INVALID_DATA; } if (MetaData < 0) { // dynamic data size_t RealSize = Node_DataSize(p,Id,(Type & TYPE_MASK),Data,META_PARAM_SET); if ((Type & TYPE_MASK) != TYPE_STRING && RealSize > Size) return ERR_INVALID_DATA; if ((DFlags & DFLAG_CMP) && Node_EqData(p,Id,Type,Data,Node_GetData(p,Id,Type & TYPE_MASK))) return ERR_NONE; // we don't support release with dynamic, because object destructor or manually dynamic data manipulation would not trigger it #if defined(CONFIG_CORECDOC) assert(m[2].Meta != META_PARAM_DATA_RELEASE); #else assert(m[1].Meta != META_PARAM_DATA_RELEASE); #endif Node_SetData(p,Id,Type & TYPE_MASK,Data); } else { uint32_t Bit; uint8_t* Ptr = (uint8_t*)p + (intptr_t)MetaData; size_t DataSize = Node_MaxDataSize(p,Id,Type,META_PARAM_SET); assert((Type & TYPE_MASK) == TYPE_STRING || !Data || Size == DataSize); if (Data && Size != DataSize && (Type & TYPE_MASK) != TYPE_STRING) return ERR_INVALID_DATA; if (DFlags & DFLAG_CMP) { if ((Type & TYPE_MASK) == TYPE_BOOL_BIT) { bool_t v; uint32_t Bit; assert(Lookup[Mid+1].Id == Id && Lookup[Mid+1].Meta->Meta==META_PARAM_BIT); Bit = (uint32_t)Lookup[Mid+1].Meta->Data; v = (*(uint32_t*)Ptr & Bit) != 0; if (EqData(Type & TYPE_MASK,&v,Data,DataSize)) return ERR_NONE; } else { if (EqData(Type & TYPE_MASK,Ptr,Data,DataSize)) return ERR_NONE; } } #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_RELEASE) #else if (m[1].Meta == META_PARAM_DATA_RELEASE) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif ((nodeupdatefunc)m->Data)(p,Id); } switch (Type & TYPE_MASK) { case TYPE_STRING: DataSize = (size_t)Node_Meta(p,Id,META_PARAM_SIZE); assert(DataSize); if (!Data) Data = NullString; tcscpy_s((tchar_t*)Ptr,DataSize/sizeof(tchar_t),(const tchar_t*)Data); break; case TYPE_BOOL_BIT: assert(Lookup[Mid+1].Id == Id && Lookup[Mid+1].Meta->Meta==META_PARAM_BIT); Bit = (uint32_t)Lookup[Mid+1].Meta->Data; if (Data && *(const bool_t*)Data) *(uint32_t*)Ptr |= Bit; else *(uint32_t*)Ptr &= ~Bit; break; case TYPE_NODE_REF: { node* v = Data?*(node**)Data:NULL; node* v0 = *(node**)Ptr; if (v0 != v) { if (v) Node_AddRef(v); *(node**)Ptr = v; if (v0) Node_Release(v0); } break; } case TYPE_ARRAY: ArrayCopy((array*)Ptr,(const array*)Data); break; default: if (Data) memcpy(Ptr,Data,DataSize); else memset(Ptr,0,DataSize); break; } } Result = ERR_NONE; #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_UPDATE) #else if (m[1].Meta == META_PARAM_DATA_UPDATE) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif Result = ((nodeupdatefunc)m->Data)(p,Id); } if (DFlags & DFLAG_NOTIFY) Node_PostNotify(p,Id); return Result; } } } return ERR_INVALID_PARAM; } static err_t MetaUnSet(node* p,dataid Id,const void* Data,size_t Size) { const nodeclass* Class = NodeGetClass(p); nodemetalookuphead* Head = Class->MetaUnSet; if (Head) { nodemetalookup* Lookup = (nodemetalookup*)(Head+1); intptr_t Mid; intptr_t Lower = 0; intptr_t Upper = Head->Upper; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; if (Lookup[Mid].Id>Id) Upper = Mid-1; else if (Lookup[Mid].IdMeta == META_PARAM_UNSET) return ((err_t(*)(node*,dataid,const void*,size_t))m->Data)(p,Id,Data,Size); if (m->Meta == META_PARAM_EVENT) { while (Mid>0 && Lookup[Mid-1].Id==Id) --Mid; do { assert(Lookup[Mid].Meta->Meta==META_PARAM_EVENT); Result = ((nodeupdatefunc)Lookup[Mid].Meta->Data)(p,Id); if (Result != ERR_NONE) return Result; ++Mid; } while (Mid<=(intptr_t)Head->Upper && Lookup[Mid].Id==Id); return ERR_NONE; } if (m->Meta == META_PARAM_BIT) m = Lookup[--Mid].Meta; assert((m->Meta & META_MODE_MASK)==META_MODE_DATA); MetaData = m->Data; Type = m->Meta; DFlags = 0; #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_FLAGS) #else if (m[1].Meta == META_PARAM_DATA_FLAGS) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif DFlags = (int)m->Data; if (DFlags & DFLAG_RDONLY) continue; // TODO: pointer should not use DFLAG_CMP because it maybe a recreated different object (unless referencing is used) //assert(!(DFlags & DFLAG_CMP) || (Type & TYPE_MASK) != TYPE_NODE); if ((DFlags & DFLAG_VERIFY_CLASS) && ((Type & TYPE_MASK) == TYPE_NODE || (Type & TYPE_MASK) == TYPE_NODE_REF) && Data && Size==sizeof(node*) && *(const node**)Data && !Node_IsPartOf(*(const node**)Data,(fourcc_t)Node_Meta(p,Id,META_PARAM_CLASS))) return ERR_INVALID_DATA; } if (MetaData < 0) { size_t RealSize = Node_DataSize(p,Id,Type,Data,META_PARAM_UNSET); if ((Type & TYPE_MASK) != TYPE_STRING && RealSize > Size) return ERR_INVALID_DATA; if ((DFlags & DFLAG_CMP) && Node_EqData(p,Id,Type,Data,Node_GetData(p,Id,Type & TYPE_MASK))) return ERR_NONE; // we don't support release with dynamic, because object destructor or manually dynamic data manipulation would not trigger it #if defined(CONFIG_CORECDOC) assert(m[2].Meta != META_PARAM_DATA_RELEASE); #else assert(m[1].Meta != META_PARAM_DATA_RELEASE); #endif Node_SetData(p,Id,Type & TYPE_MASK,Data); } else { uint32_t Bit; uint8_t* Ptr = (uint8_t*)p + (intptr_t)MetaData; size_t DataSize = Node_MaxDataSize(p,Id,Type,META_PARAM_UNSET); assert((Type & TYPE_MASK) == TYPE_STRING || !Data || Size == DataSize); if (Data && Size != DataSize && (Type & TYPE_MASK) != TYPE_STRING) return ERR_INVALID_DATA; if (DFlags & DFLAG_CMP) { if ((Type & TYPE_MASK) == TYPE_BOOL_BIT) { bool_t v; uint32_t Bit; assert(Lookup[Mid+1].Id == Id && Lookup[Mid+1].Meta->Meta==META_PARAM_BIT); Bit = (uint32_t)Lookup[Mid+1].Meta->Data; v = (*(uint32_t*)Ptr & Bit) != 0; if (EqData(Type & TYPE_MASK,&v,Data,DataSize)) return ERR_NONE; } else { if (EqData(Type & TYPE_MASK,Ptr,Data,DataSize)) return ERR_NONE; } } #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_RELEASE) #else if (m[1].Meta == META_PARAM_DATA_RELEASE) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif ((nodeupdatefunc)m->Data)(p,Id); } switch (Type & TYPE_MASK) { case TYPE_STRING: DataSize = (size_t)Node_Meta(p,Id,META_PARAM_SIZE); assert(DataSize); if (!Data) Data = NullString; tcscpy_s((tchar_t*)Ptr,DataSize/sizeof(tchar_t),(const tchar_t*)Data); break; case TYPE_BOOL_BIT: assert(Lookup[Mid+1].Id == Id && Lookup[Mid+1].Meta->Meta==META_PARAM_BIT); Bit = (uint32_t)Lookup[Mid+1].Meta->Data; if (Data && *(const bool_t*)Data) *(uint32_t*)Ptr |= Bit; else *(uint32_t*)Ptr &= ~Bit; break; case TYPE_NODE_REF: { node* v = Data?*(node**)Data:NULL; node* v0 = *(node**)Ptr; if (v0 != v) { if (v) Node_AddRef(v); *(node**)Ptr = v; if (v0) Node_Release(v0); } break; } case TYPE_ARRAY: ArrayCopy((array*)Ptr,(const array*)Data); break; default: if (Data) memcpy(Ptr,Data,DataSize); else memset(Ptr,0,DataSize); break; } } Result = ERR_NONE; #if defined(CONFIG_CORECDOC) if (m[2].Meta == META_PARAM_DATA_UPDATE) #else if (m[1].Meta == META_PARAM_DATA_UPDATE) #endif { ++m; #if defined(CONFIG_CORECDOC) ++m; #endif Result = ((nodeupdatefunc)m->Data)(p,Id); } if (DFlags & DFLAG_NOTIFY) Node_PostNotify(p,Id); return Result; } } } return ERR_INVALID_PARAM; } static dataid MetaFindParam(node* p,const tchar_t* Token) { if (Token) { const nodeclass* c; const nodemeta* m; for (c = NodeGetClass(p);c;c=c->ParentClass) if (c->Meta) // should be registered, just fail safe for (m=c->Meta;m->Meta != META_CLASS_PARENT_ID;++m) if (m->Meta == META_PARAM_NAME && tcsisame_ascii(Token,(const tchar_t*)m->Data)) { return m->Id; } } return 0; } META_START(Node_Class,NODE_CLASS) META_CLASS(SIZE,sizeof(node)) META_VMT(TYPE_FUNC,node_vmt,Enum,MetaEnum) META_VMT(TYPE_FUNC,node_vmt,Get,MetaGet) META_VMT(TYPE_FUNC,node_vmt,Set,MetaSet) META_VMT(TYPE_FUNC,node_vmt,UnSet,MetaUnSet) META_VMT(TYPE_FUNC,node_vmt,Meta,MetaMeta) META_VMT(TYPE_FUNC,node_vmt,FindParam,MetaFindParam) META_VMT(TYPE_FUNC,node_vmt,SetData,SetData) META_PARAM(TYPE,NODE_DELETING,TYPE_EVENT|TFLAG_NOTIFY|TFLAG_RDONLY) META_END_CONTINUE(0) META_START_CONTINUE(NODEMODULE_CLASS) META_CLASS(SIZE,sizeof(nodemodule)) META_END_CONTINUE(NODE_CLASS) META_START_CONTINUE(NODECONTEXT_CLASS) META_CLASS(SIZE,sizeof(nodecontext)) META_PARAM(NAME,NODECONTEXT_PROJECT_NAME,T("ProjName")) META_PARAM(TYPE,NODECONTEXT_PROJECT_NAME,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_NAME) META_PARAM(NAME,NODECONTEXT_PROJECT_VENDOR,T("ProjVendor")) META_PARAM(TYPE,NODECONTEXT_PROJECT_VENDOR,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_VENDOR) META_PARAM(NAME,NODECONTEXT_PROJECT_VERSION,T("ProjVersion")) META_PARAM(TYPE,NODECONTEXT_PROJECT_VERSION,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_VERSION) META_PARAM(NAME,NODECONTEXT_PROJECT_HELP,T("HelpFile")) META_PARAM(TYPE,NODECONTEXT_PROJECT_HELP,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_HELP) #if defined(TARGET_PALMOS) META_PARAM(NAME,NODECONTEXT_PROJECT_FOURCC,T("ProjFourCC")) META_PARAM(TYPE,NODECONTEXT_PROJECT_FOURCC,TYPE_FOURCC|TFLAG_SETUP|TFLAG_RDONLY) META_DATA(TYPE_FOURCC,NODECONTEXT_PROJECT_FOURCC,nodecontext,ProjFourCC) #endif META_PARAM(NAME,NODECONTEXT_PROJECT_BUILD,T("BuildVersion")) META_PARAM(TYPE,NODECONTEXT_PROJECT_BUILD,TYPE_INT|TFLAG_SETUP|TFLAG_RDONLY) META_DATA(TYPE_INT,NODECONTEXT_PROJECT_BUILD,nodecontext,Build) META_PARAM(NAME,NODECONTEXT_PROJECT_MIME,T("AppMime")) META_PARAM(TYPE,NODECONTEXT_PROJECT_MIME,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_MIME) META_PARAM(NAME,NODECONTEXT_PROJECT_PATH,T("ProjPath")) META_PARAM(TYPE,NODECONTEXT_PROJECT_PATH,TYPE_STRING|TFLAG_SETUP|TFLAG_RDONLY) META_DYNAMIC_RDONLY(TYPE_STRING,NODECONTEXT_PROJECT_PATH) META_PARAM(TYPE,NODECONTEXT_PROJECT_APPID,TYPE_INT16|TFLAG_SETUP|TFLAG_RDONLY) META_DATA(TYPE_INT16,NODECONTEXT_PROJECT_APPID,nodecontext,AppId) META_END(NODEMODULE_CLASS) MEMHEAP_DEFAULT void NodeContext_Init(nodecontext* p,const nodemeta* Custom, const cc_memheap* Heap, const cc_memheap* ConstHeap) { fourcc_t ClassId = NODECONTEXT_CLASS; node_vmt Tmp; memset(p,0,sizeof(nodecontext)); if (Heap) { ArrayInitEx(&p->Collect,Heap); ArrayInitEx(&p->NodeSingleton,Heap); ArrayInitEx(&p->NodeClass,Heap); } else Heap = &MemHeap_Default; if (!ConstHeap) ConstHeap=Heap; #if defined(CONFIG_MULTITHREAD) p->PostNotifyParam = p; #endif p->NodeLock = LockCreate(); p->NodeHeap = Heap; p->NodeConstHeap = ConstHeap; Tmp.Context = p; p->Base.Base.VMT = &Tmp; p->Base.Found = 1; p->Base.Func = (void*)(uintptr_t)NodeContext_Init; NodeRegisterClassEx(&p->Base,Node_Class); NodeRegisterClassEx(&p->Base,NodeTree_Class); if (Custom) { NodeRegisterClassEx(&p->Base,Custom); ClassId = (fourcc_t)Custom->Data; } Node_Constructor(p,(node*)p,0,ClassId); } void NodeContext_Done(nodecontext* p) { nodeclass **i; NodeSingletonEvent(p,NODE_SINGLETON_SHUTDOWN,NULL); NodeContext_Cleanup(p,1); // first unregister all plugins UnRegisterModule(p,&p->Base,1); // unregister common.dll classes // free modules while (p->Base.Next) { node* v = (node*)p->Base.Next; p->Base.Next = p->Base.Next->Next; Node_Release(v); } Node_Destructor((node*)p); #if defined(CONFIG_DEBUG_LEAKS) if (p->Base.Base.RefCount!=1) { class_ref_t *Item; for (Item=ARRAYBEGIN(p->Base.ClassRefs,class_ref_t);Item!=ARRAYEND(p->Base.ClassRefs,class_ref_t);++Item) { DebugMessage(T("remaining class %r (%d times)"),Item->Class->FourCC,Item->Count); } } #endif assert(p->Base.Base.RefCount==1); // node memory leaking? // free classes for (i=ARRAYBEGIN(p->NodeClass,nodeclass*);i!=ARRAYEND(p->NodeClass,nodeclass*);++i) { assert(!(*i)->Meta && !(*i)->MetaGet && !(*i)->MetaSet && !(*i)->MetaUnSet); MemHeap_Free(p->NodeHeap,*i,sizeof(nodeclass)+(*i)->VMTSize); } assert(ARRAYEMPTY(p->Collect)); ArrayClear(&p->Collect); ArrayClear(&p->NodeSingleton); ArrayClear(&p->NodeClass); LockDelete(p->NodeLock); p->NodeLock = NULL; } void NodeEnumDef(node* p,array* List) { ArrayInit(List); if (p) { dataid* i; datadef Def; array Id; Node_Enum(p,&Id); for (i=ARRAYBEGIN(Id,dataid);i!=ARRAYEND(Id,dataid);++i) if (NodeDataDef(p,*i,&Def)) ArrayAppend(List,&Def,sizeof(Def),256); ArrayClear(&Id); } } bool_t NodeDataDef(node* p, dataid Id, datadef* DataDef) { uintptr_t Flags = Node_Meta(p,Id,META_PARAM_TYPE); if (!Flags) return 0; //assert((Flags & TYPE_MASK)!=0); DataDef->Id = Id; DataDef->Flags = (dataflags)Flags; return 1; } err_t Node_Toggle(void* Node,dataid Id) { bool_t Bool = 0; Node_GET(Node,Id,&Bool); Bool = !Bool; return Node_SET(Node,Id,&Bool); } NOINLINE void NodeDup_Replace(array* Dup, node** Ptr) { if (Dup) { node* p = *Ptr; nodedup* i; for (i=ARRAYBEGIN(*Dup,nodedup);i!=ARRAYEND(*Dup,nodedup);++i) if (i->Orig == p) { *Ptr = i->Dup; return; } } } static NOINLINE void CopyData(const nodeclass* Class, node* p, node* Src, array* Dup, uint8_t* Data) { if (Class->ParentClass) CopyData(Class->ParentClass,p,Src,Dup,Data); if (Class->Meta) { const nodemeta* m; for (m=Class->Meta;m->Meta != META_CLASS_PARENT_ID;++m) { uintptr_t Type; if (m->Meta == META_PARAM_TYPE) Type = m->Data; else if (m->Meta != META_PARAM_META || !((bool_t(*)(node*,dataid,datameta,uintptr_t*))m->Data)(Src,m->Id,META_PARAM_TYPE,&Type)) // we need to use the Src because dynamic flags (like UIButton_Value) continue; if (!(Type & (TFLAG_RDONLY|TFLAG_NOSAVE)) && (Type & TYPE_MASK)) { dataid Id = m->Id; Type &= TYPE_MASK; if (Type != TYPE_EXPR) // batch expressions are already copied { size_t Size = Node_MaxDataSize(Src,Id,Type,META_PARAM_GET); assert((Id & ~DATA_ENUM)==Id); if (Size && Node_Get(Src,Id,Data,Size) == ERR_NONE) { if (Type == TYPE_PIN) NodeDup_Replace(Dup,&((pin*)Data)->Node); if (Type == TYPE_NODE) NodeDup_Replace(Dup,(node**)Data); Node_Set(p,Id,Data,Size); } } } } } } void Node_Copy(node* p, node* Src, array* Dup) { nodedata* i; const nodeclass* Class = NodeGetClass(p); uint8_t Data[MAXDATA]; // at moment only same ClassId will be copied if (Class != NodeGetClass(Src)) return; for (i=Src->Data;i;i=i->Next) { datatype Type = i->Code & TYPE_MASK; if (Type == TYPE_EXPRSTRING || Type == TYPE_EXPRPARAM || Type == TYPE_EXPR) { void* Data = Node_AddData(p,i->Code>>8,Type,NodeData_Data(i)); if (Type == TYPE_EXPR && Data) NodeClass_Context(Class)->ExprDup(p,(nodeexpr*)Data,Dup); } } CopyData(Class,p,Src,Dup,Data); } const void* Node_InheritedVMT(node* p,fourcc_t ClassId) { const nodeclass* Class = NodeGetClass(p); while (NodeClass_ClassId(Class) != ClassId) { assert(Class->ParentClass); Class=Class->ParentClass; } assert(Class->ParentClass); return Class->ParentClass+1; } void NodeReportError(anynode* AnyNode, node* Sender, fourcc_t Class, int No,...) { nodecontext* Context = Node_Context(AnyNode); if (Context->ReportError) { va_list Args; va_start(Args,No); Context->ReportError(Context,Sender,Class,No,Args); va_end(Args); } } void NodeSingletonEvent(anynode* Any, dataid Cmd, nodemodule* Module) { array List; node** i; NodeEnumSingletonsEx(Any,&List,Module); for (i=ARRAYBEGIN(List,node*);i!=ARRAYEND(List,node*);++i) Node_Trigger(*i,Cmd); ArrayClear(&List); } void* NodeHeap_Alloc(anynode* AnyNode, size_t Size) { return MemHeap_Alloc(Node_Context(AnyNode)->NodeHeap,Size,0); } void NodeHeap_Free(anynode* AnyNode, void* Ptr, size_t Size) { MemHeap_Free(Node_Context(AnyNode)->NodeHeap,Ptr,Size); } typedef struct memcollectitem { memcollect Func; void* Cookie; } memcollectitem; bool_t NodeHibernate(anynode* AnyNode) { nodecontext* p = Node_Context(AnyNode); bool_t Changed = 0; if (!p->InCollect) { int Level; int NextLevel; memcollectitem* i; p->InCollect = 1; for (Level=COLLECT_UNUSED;!Changed;Level=NextLevel) { NextLevel = INT_MAX; for (i=ARRAYBEGIN(p->Collect,memcollectitem);i!=ARRAYEND(p->Collect,memcollectitem);++i) { int v=i->Func(i->Cookie,Level); if (v==COLLECT_FOUND) Changed=1; else if (NextLevel>v && v>Level) NextLevel=v; } if (NextLevel==INT_MAX) break; } if (!Changed && NodeContext_Cleanup(p,0)) Changed = 1; p->InCollect = 0; } return Changed; } void Mem_AddCollector(anynode* AnyNode, memcollect Func, void* Cookie) { memcollectitem Item; Item.Func = Func; Item.Cookie = Cookie; ArrayAppend(&Node_Context(AnyNode)->Collect,&Item,sizeof(Item),0); } void Mem_RemoveCollector(anynode* AnyNode, memcollect Func, void* Cookie) { memcollectitem Item; Item.Func = Func; Item.Cookie = Cookie; ArrayRemove(&Node_Context(AnyNode)->Collect,memcollectitem,&Item,NULL,NULL); } bcmatroska2-5.3.101/corec/corec/node/node.h000066400000000000000000000043321462133141200203010ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODE_H #define __NODE_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #include "corec/array/array.h" #include "corec/multithread/multithread.h" #include "corec/str/str.h" #include "corec/memheap.h" #if defined(NODE_EXPORTS) #define NODE_DLL DLLEXPORT #elif defined(NODE_IMPORTS) #define NODE_DLL DLLIMPORT #else #define NODE_DLL #endif #include "nodebase.h" #include "nodetree.h" #include "nodetools.h" #ifdef __cplusplus } #endif #if defined(TARGET_SYMBIAN) #include "node_symbian.h" #endif #endif /* __NODE_H */ bcmatroska2-5.3.101/corec/corec/node/node.proj000066400000000000000000000004051462133141200210210ustar00rootroot00000000000000GROUP node { USE corec USE array USE multithread USE str SOURCE node.c SOURCE nodetree.c HEADER node.h HEADER nodebase.h HEADER nodetree.h HEADER nodetools.h HEADER(TARGET_SYMBIAN) node_symbian.h INSTALL(CONFIG_CORECDOC) corec.html } bcmatroska2-5.3.101/corec/corec/node/node_internal.h000066400000000000000000000057551462133141200222070ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODE_INTERNAL_H #define __NODE_INTERNAL_H #define DEFAULT_VMT sizeof(node_vmt) #define CLASS_FAILED -2 #define CLASS_NOT_FOUND -1 #define CLASS_REGISTERED 0 #define CLASS_INITED 1 typedef struct nodemetalookup { dataid Id; const nodemeta* Meta; } nodemetalookup; typedef struct nodemetalookuphead { size_t Upper; //nodemetalookup Lookup[] } nodemetalookuphead; struct nodeclass { fourcc_t FourCC; // help figure out memory leak const nodemeta* Meta; nodemodule* Module; const nodeclass* ParentClass; nodemetalookuphead* MetaGet; nodemetalookuphead* MetaSet; nodemetalookuphead* MetaUnSet; fourcc_t ParentId; uint8_t Flags; int8_t State; int16_t Priority; size_t VMTSize; }; typedef struct nodeclass_with_vmt { nodeclass Class; node_vmt VMT; } nodeclass_with_vmt; #define NodeClass_Context(Class) ((nodeclass_with_vmt*)Class)->VMT.Context #define NodeClass_ClassId(Class) ((nodeclass_with_vmt*)Class)->VMT.ClassId nodeclass* NodeContext_CreateClass(nodecontext* p, fourcc_t ClassId, size_t VMTSize, nodemodule* Module); void NodeContext_UpdateParents(nodecontext* p); extern const nodemeta NodeTree_Class[]; typedef struct nodenotify nodenotify; struct nodenotify { nodenotify* Next; notifyproc Func; void* Referer; }; #endif bcmatroska2-5.3.101/corec/corec/node/node_symbian.h000066400000000000000000000067561462133141200220370ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef NODE_SYMBIAN__H #define NODE_SYMBIAN__H /* the symbian headers are not compatible with C */ #if defined(__cplusplus) #undef T #undef NULL #include #include #include #include #include #include #include #include #include #ifdef SYMBIAN90 #include #endif #include #include #include #include #include #include #include #include #include #if !defined(SERIES90) #include #endif #if defined(SERIES60) #include #include #include #include #include #include #define CAppUi CAknAppUi #define CDocument CEikDocument typedef CAknApplication CApplication; #elif defined(SERIES80) || defined(SERIES90) #include #include #include #include #include #define CAppUi CEikAppUi #define CDocument CEikDocument typedef CEikApplication CApplication; #elif defined(UIQ) #include #include #include #if defined(SYMBIAN90) #include #include #endif #define CAppUi CQikAppUi #define CDocument CQikDocument typedef CQikApplication CApplication; #else #error Unknown Symbian SDK #endif #ifdef UNICODE #define T(a) L ## a #else #define T(a) a #endif #ifndef SYMBIAN90 static INLINE int64_t FromInt64(const TInt64& i) { return i.Low() | ((int64_t)i.High() << 32); } static INLINE TInt64 ToInt64(int64_t i) { return TInt64((int32_t)(i>>32),(uint32_t)i); } #else #define FromInt64(a) (a) #define ToInt64(a) (a) #endif #endif /* __cplusplus */ #endif /* NODE_SYMBIAN__H */ bcmatroska2-5.3.101/corec/corec/node/nodebase.h000066400000000000000000000635431462133141200211450ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODEBASE_H #define __NODEBASE_H #define MAXDATA (MAXPATH*sizeof(tchar_t)) //---------------------------------------------------------------- // data types #define TYPE_BOOLEAN 1 // bool_t #define TYPE_INT 2 // int #define TYPE_FRACTION 3 // cc_fraction #define TYPE_STRING 4 // null terminated tchar_t[] #define TYPE_RECT 5 // rect #define TYPE_POINT 6 // point #define TYPE_RGB 7 // rgbval_t #define TYPE_FOURCC 8 // fourcc_t #define TYPE_FILEPOS 9 // filepos_t #define TYPE_NODE 10 // node* (format1: node class) #define TYPE_META 11 // metanotify #define TYPE_PACKET 12 // flow packet pin #define TYPE_TICK 13 // tick_t #define TYPE_NODENOTIFY 14 // nodenotify (private) #define TYPE_PTR 15 // void* #define TYPE_BINARY 16 // binary data (format1: size) #define TYPE_NOTIFY 17 // notify #define TYPE_INT8 18 // int8_t #define TYPE_INT16 19 // int16_t #define TYPE_INT32 20 // int32_t #define TYPE_INT64 21 // int64_t #define TYPE_FUNC 22 // nodefunc #define TYPE_NODE_REF 23 // node* #define TYPE_BOOL_BIT 24 // bool_t #define TYPE_PIN 25 // pin #define TYPE_EVENT 26 // void #define TYPE_EXPR 27 #define TYPE_POINT16 28 // cc_point16 #define TYPE_RECT16 29 // int16_t[4] #define TYPE_ARRAY 30 #define TYPE_EXPRSTRING 31 #define TYPE_EXPRPARAM 32 #define TYPE_DATETIME 33 // datetime_t #define TYPE_DBNO 34 // db_no #define TYPE_GUID 35 // cc_guid #define TYPE_FIX16 36 // int #define TYPE_LUA_REF 37 // int #define TYPE_NOTIFYEX 38 #define TYPE_ENUM 39 // dataenum #define TYPE_ENUM_MULTI_SET 40 // multi_enum_set #define TYPE_SIZE 41 // size_t #define MAX_PARAMTYPE 42 #define TYPE_MASK 0x3F #define PERCENT_ONE 1024 #define FIX16_SHIFT 16 #define FIX16_UNIT (1<= ExtensionStart && Id < ExtensionStart+ExtensionSize); } typedef struct dataenum { size_t ValueSize; array Name; // tchar_t array Value; // any type } dataenum; typedef struct multi_enum_set { void *Element; size_t ElementSize; int Value; } multi_enum_set; //--------------------------------------------------------------- // node #define NODE_CLASS FOURCC('N','O','D','E') // strings #define NODE_NAME 0 #define NODE_CONTENTTYPE 1 #define NODE_EXTS 2 #define NODE_PROBE 3 #define NODE_PROTOCOL 4 #define NODE_ID 5 // events for singleton objects #define NODE_SINGLETON_INSTALL 6 #define NODE_SINGLETON_UNINSTALL 7 #define NODE_SINGLETON_STARTUP 8 // after the module's classes registered and singleton objects are created #define NODE_SINGLETON_CONFIGURED 9 // after configuration loaded for CFLAG_CONFIG objects #define NODE_SINGLETON_SHUTDOWN 10 // before the module's singleton objects are deleted // events for any class #define NODE_DELETING 11 // can be used as notify #define NODE_SETTINGS_CHANGED 12 // can be used as notify // settings #define NODE_GAP 13 #define NODE_SELECT_ALL 14 //TODO: remove #define NODE_SELECT_NONE 15 //TODO: remove // for debug/dump (array) #define NODE_CHILDREN 13 // default param #define NODE_DEFAULT_DATA 14 //TODO: fix collision with NODE_SELECT_ALL typedef err_t (*nodefunc)(void* This); typedef err_t (*nodeupdatefunc)(void* This,dataid Id); typedef bool_t (*nodeenumfilter)(void* This,dataid Id,const void* Value,size_t Size); typedef const void anynode; typedef void* thisnode; typedef struct nodecontext nodecontext; typedef struct node { fourcc_t FourCC; // help figure out memory leak uint32_t Magic; const void* VMT; nodedata* Data; size_t RefCount; } node; typedef struct node_vmt { nodecontext* Context; fourcc_t ClassId; void (*Enum)(thisnode,array* List); err_t (*Get)(thisnode,dataid Id,void* Data,size_t Size); err_t (*Set)(thisnode,dataid Id,const void* Data,size_t Size); err_t (*UnSet)(thisnode,dataid Id,const void* Data,size_t Size); uintptr_t (*Meta)(thisnode,dataid Id,datameta Meta); dataid (*FindParam)(thisnode,const tchar_t* Token); void* (*SetData)(thisnode,dataid Id, datatype Type,const void* Data); } node_vmt; #define Node_Enum(p,a) VMT_FUNC(p,node_vmt)->Enum(p,a) #define Node_Get(p,a,b,c) VMT_FUNC(p,node_vmt)->Get(p,a,b,c) #define Node_GET(p,a,b) VMT_FUNC(p,node_vmt)->Get(p,a,b,sizeof(*(b))) #define Node_Set(p,a,b,c) VMT_FUNC(p,node_vmt)->Set(p,a,b,c) #define Node_SET(p,a,b) VMT_FUNC(p,node_vmt)->Set(p,a,b,sizeof(*(b))) #define Node_Trigger(p,a) VMT_FUNC(p,node_vmt)->Set(p,a,NULL,0) #define Node_UnSet(p,a,b,c) VMT_FUNC(p,node_vmt)->UnSet(p,a,b,c) #define Node_Meta(p,a,b) VMT_FUNC(p,node_vmt)->Meta(p,a,b) #define Node_FindParam(p,a) VMT_FUNC(p,node_vmt)->FindParam(p,a) #define Node_SetData(p,i,t,d) VMT_FUNC(p,node_vmt)->SetData(p,i,t,d) //----------------------------------------------------------------- typedef struct pin { node* Node; dataid Id; } pin; typedef pin nodeevt; typedef err_t (*notifyproc)(void* This, nodeevt* Evt); typedef void (*metafunc)(void* Referer, fourcc_t Meta, int32_t Stream, const tchar_t* Value); typedef struct metanotify { metafunc Func; void* Referer; int Stream; } metanotify; typedef err_t (*notifyfunc)(void* This,intptr_t Param,intptr_t Param2); typedef void (*freefunc)(void* This,void *Ptr); typedef struct notify { notifyfunc Func; void* This; } notify; typedef struct notifyex { notifyfunc Func; void* This; freefunc Free; void* FreeCookie; } notifyex; typedef struct nodeexpr nodeexpr; //--------------------------------------------------------------- // node priority classes #define PRI_MINIMUM 1 #define PRI_DEFAULT 1000 #define PRI_MAXIMUM 10000 //--------------------------------------------------------------- // functions managing node meta information #define NODEMODULE_CLASS FOURCC('N','M','O','D') #define NODEMODULE_PATH 0x80 typedef struct nodeclass nodeclass; typedef struct nodemodule nodemodule; struct nodemodule { node Base; nodemodule* Next; void* Module; void* Db; void* Func; uint8_t* Min; uint8_t* Max; datetime_t Stamp; array ClassRefs; void *LockRefs; uint8_t Found; uint8_t Config; uint8_t Changed; }; struct nodecontext { nodemodule Base; void* NodeLock; const void* NodeCache; array NodeSingleton; array NodeClass; // ordered by id const cc_memheap* NodeHeap; const cc_memheap* NodeConstHeap; bool_t (*LoadModule)(nodecontext*,nodemodule*); void (*FreeModule)(nodecontext*,nodemodule*); #if defined(CONFIG_MULTITHREAD) uintptr_t ThreadId; void* PostNotifyParam; bool_t (*PostNotify)(nodecontext*,node*,dataid); // returns if the message has been queued #endif const tchar_t* (*ExternalStr)(nodecontext*,fourcc_t,int); //TODO: runtime datatype meta information handling... void (*ExprRelease)(nodeexpr*); size_t (*ExprSize)(nodeexpr*); void (*ExprDup)(node* Node, nodeexpr*, array* Dup); #if defined(CONFIG_CORELUA) void *LuaCookie; void (*LuaRelease)(void* Cookie, int* Ref); void (*LuaAddRef)(void* Cookie, int* Ref); #endif void (*ReportError)(nodecontext*, node* Node, fourcc_t MsgClass, int MsgNo, va_list Args); #if defined(TARGET_PALMOS) fourcc_t ProjFourCC; #endif int Build; int Revision; array Collect; bool_t InCollect; fourcc_t DynamicClass; #if defined(TARGET_SYMBIAN) void *FsSession; #endif uint16_t AppId; }; #define NODECONTEXT_CLASS FOURCC('N','C','T','X') #define NODECONTEXT_PROJECT_NAME 0x100 #define NODECONTEXT_PROJECT_VENDOR 0x101 #define NODECONTEXT_PROJECT_VERSION 0x102 #define NODECONTEXT_PROJECT_FOURCC 0x103 #define NODECONTEXT_PROJECT_HELP 0x104 #define NODECONTEXT_PROJECT_BUILD 0x105 #define NODECONTEXT_PROJECT_MIME 0x106 #define NODECONTEXT_PROJECT_APPID 0x107 #define NODECONTEXT_PROJECT_PATH 0x108 // notify #define NODECONTEXT_CRASH 0x201 NODE_DLL void NodeContext_Init(nodecontext*,const nodemeta* Custom, const cc_memheap* Heap, const cc_memheap* ConstHeap); NODE_DLL void NodeContext_Done(nodecontext*); NODE_DLL bool_t NodeContext_Cleanup(nodecontext* p,bool_t Force); NODE_DLL dataflags NodeContext_FindDataType(const tchar_t* Type, const tchar_t* Format); NODE_DLL size_t NodeTypeSize(datatype); // TODO: use nodecontext* when switching to runtime datatype meta information handling... NODE_DLL const tchar_t *NodeContext_TypeName(datatype Type); NODE_DLL const tchar_t *NodeContext_UnitName(datatype Unit); NODE_DLL void NodeRegisterClassEx(nodemodule*,const nodemeta*); NODE_DLL fourcc_t NodeEnumClass(anynode*,array* List, fourcc_t Class); // List=NULL just returns the first class NODE_DLL fourcc_t NodeEnumClassStr(anynode*,array* ListId, fourcc_t ClassId, int Id, const tchar_t* Str); NODE_DLL void NodeEnumSingletons(anynode*,array* List); NODE_DLL void NodeSingletonEvent(anynode*, dataid Cmd, nodemodule* Module); // Module = NULL for all modules typedef int (*nodeenumclassfilterrated)(void* Cookie, const nodeclass* Class); NODE_DLL fourcc_t NodeEnumClassFilterRated(anynode*,array* List, fourcc_t Class, nodeenumclassfilterrated Func, void* Cookie); NODE_DLL bool_t NodeIsClass(anynode*,fourcc_t Class, fourcc_t PartOfClass); NODE_DLL const tchar_t* NodeStr2(anynode*,fourcc_t ClassId,int No); NODE_DLL const tchar_t* NodeStrEx(anynode*,fourcc_t ClassId,int No); NODE_DLL node* NodeCreate(anynode*,fourcc_t Class); NODE_DLL node* NodeSingleton(anynode*,fourcc_t Class); NODE_DLL const tchar_t* NodeClass_Str(anynode* AnyNode, const nodeclass*, int No); NODE_DLL uintptr_t NodeClass_Meta(const nodeclass*,dataid Id,datameta Meta); NODE_DLL int NodeClass_Priority(const nodeclass*); NODE_DLL fourcc_t NodeClass_Parent(const nodeclass*); NODE_DLL const nodeclass* NodeContext_FindClass(anynode*, fourcc_t Class); NODE_DLL const nodeclass* NodeContext_FindClassEx(anynode*, fourcc_t Class, nodemodule* Prefered); // functions for existing nodes NODE_DLL void NodeDelete(node*); //TODO: use Node_Release() instead (but Node_Release doesn't support NULL) NODE_DLL void Node_AddRef(thisnode This); NODE_DLL void Node_Release(thisnode This); NODE_DLL int NodeClassFlags(node*); NODE_DLL void NodeClassSetPriority(node*,int Priority); NODE_DLL nodemodule* NodeModule(node*); NODE_DLL nodemodule* NodeClassModule(anynode*,fourcc_t Class); NODE_DLL bool_t NodeFindDef(node*,const tchar_t* Token,datadef* Out); NODE_DLL bool_t NodeDataDef(node* p, dataid Id, datadef* Out); NODE_DLL void NodeEnumDef(node*,array* Out); NODE_DLL void NodeParamName(node* p, dataid Id, tchar_t* Name, size_t NameLen); NODE_DLL const tchar_t* NodeParamStr(const node* p,int No); NODE_DLL void NodeReportError(anynode*, node* Node,fourcc_t MsgClass,int MsgNo,...); NODE_DLL err_t Node_Constructor(anynode*,node* Node,size_t Size, fourcc_t ClassId); NODE_DLL void Node_Destructor(node* Node); NODE_DLL bool_t Node_Notify(node* Node, dataid Id); /// returns wether there were some receivers #if defined(CONFIG_MULTITHREAD) NODE_DLL bool_t Node_PostNotify(node* Node, dataid Id); // supports threading #else #define Node_PostNotify(x,y) Node_Notify(x,y) #endif NODE_DLL void Node_AddNotify(node*, dataid Id, notifyproc Func, void* Refered); NODE_DLL void Node_AddNotify_Update(node*, dataid Id, notifyproc Func, void* Refered); NODE_DLL void Node_RemoveNotify(node*, dataid Id, notifyproc Func, void* Refered); NODE_DLL size_t Node_MaxDataSize(node*, dataid Id, dataflags Flags, int QueryType); NODE_DLL bool_t Node_EqData(node*, dataid Id, dataflags Flags, const void* a, const void* b); NODE_DLL size_t Node_DataSize(node*, dataid Id, datatype Type, const void* Data, int QueryType); NODE_DLL void Node_RemoveData(node*, dataid Id, datatype Type); NODE_DLL void* Node_AddData(node*, dataid Id, datatype Type, const void* Data); NODE_DLL void* Node_GetData(const node*, dataid Id, datatype Type); NODE_DLL err_t Node_ReadData(node* p, dataid Id, datatype Type, void* Data, size_t Size); /// fills with 0 if the dynamic data doesn't exist NODE_DLL const tchar_t* Node_GetDataStr(const node*, dataid Id); NODE_DLL datetime_t Node_GetDataDatetime(const node*, dataid Id); // functions which should be exported in node DLLs DLLEXPORT err_t DLLRegister(nodemodule*); DLLEXPORT void DLLUnRegister(nodemodule*); DLLEXPORT void DLLTest(void); DLLEXPORT void DLLTest2(void); NODE_DLL bool_t Node_IsPartOf(const void*, fourcc_t PartOfClass); NODE_DLL err_t Node_Toggle(void* Node,dataid Id); NODE_DLL void Node_Copy(node* Dst,node* Src,array* Dup); typedef struct nodedup { node* Orig; node* Dup; } nodedup; void NodeDup_Replace(array* Dup, node** Ptr); #ifdef CONFIG_DEBUGCHECKS #define VMT_FUNC(p,class_vmt) (assert((const void*)(p)!=NULL),(class_vmt*)((node*)(p))->VMT) #else #define VMT_FUNC(p,class_vmt) ((class_vmt*)((node*)(p))->VMT) #endif #define Node_Context(p) (VMT_FUNC(p,node_vmt)->Context) #define Node_ClassId(p) (VMT_FUNC(p,node_vmt)->ClassId) NODE_DLL const void* Node_InheritedVMT(node* p,fourcc_t ClassId); #define INHERITED(p,class_vmt,classid) ((const class_vmt*)Node_InheritedVMT((node*)(p),classid)) void* NodeHeap_Alloc(anynode*, size_t Size); void NodeHeap_Free(anynode*, void* Ptr, size_t Size); typedef int (*memcollect)(void* Cookie, int Level); // collect levels #define COLLECT_UNUSED 0 #define COLLECT_SOFT 100 #define COLLECT_HARD 200 #define COLLECT_FOUND -1 // return value when memory was collected on that level NODE_DLL bool_t NodeHibernate(anynode*); //TODO: rename NODE_DLL void Mem_AddCollector(anynode*, memcollect Func, void* Cookie); NODE_DLL void Mem_RemoveCollector(anynode*, memcollect Func, void* Cookie); #endif bcmatroska2-5.3.101/corec/corec/node/nodetools.h000066400000000000000000000113061462133141200213610ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODETOOLS_H #define __NODETOOLS_H //some helper functions static INLINE tchar_t* tcsdup(const tchar_t* s) { size_t n = tcslen(s)+1; tchar_t* p = (tchar_t*)malloc(n*sizeof(tchar_t)); if (p) tcscpy_s(p,n,s); return p; } static INLINE bool_t EqInt(const int* a, const int* b) { return *a == *b; } static INLINE bool_t EqTick(const tick_t* a, const tick_t* b) { return *a == *b; } static INLINE bool_t EqBool(const bool_t* a, const bool_t* b) { return *a == *b; } static INLINE bool_t EqPtr(void** a, void** b) { return *a == *b; } static INLINE bool_t EqFrac(const cc_fraction* a, const cc_fraction* b) { if (a->Den == b->Den && a->Num == b->Num) return 1; if (!a->Den) return b->Den==0; if (!b->Den) return 0; return (int64_t)b->Den * a->Num == (int64_t)a->Den * b->Num; } // variable names: Result, Data, Size #define GETVALUE(Value,Type) \ { \ assert(Size == sizeof(Type)); \ *(Type*)Data = Value; \ Result = ERR_NONE; \ } #define GETVALUECOND(Value,Type,Cond) \ { \ assert(Size == sizeof(Type)); \ if (Cond) \ { \ *(Type*)Data = Value; \ Result = ERR_NONE; \ } \ } #define SETVALUE(Value,Type,Update) \ { \ assert(Size == sizeof(Type)); \ Value = *(Type*)Data; \ Result = Update; \ } #define SETVALUENULL(Value,Type,Update,Null) \ { \ if (Data) \ { \ assert(Size == sizeof(Type)); \ Value = *(Type*)Data; \ } \ else \ Null; \ Result = Update; \ } #define SETVALUECOND(Value,Type,Update,Cond) \ { \ assert(Size == sizeof(Type)); \ if (Cond) \ { \ Value = *(Type*)Data; \ Result = Update; \ } \ } #define SETVALUECMP(Value,Type,Update,EqFunc) \ { \ assert(Size == sizeof(Type)); \ Result = ERR_NONE; \ if (!EqFunc(&Value,(Type*)Data)) \ { \ Value = *(Type*)Data; \ Result = Update; \ } \ } #define SETPACKETFORMAT(Value,Type,Update) \ { \ assert(Size == sizeof(Type) || !Data); \ Result = PacketFormatCopy(&Value,(Type*)Data); \ if (Result == ERR_NONE) \ Result = Update; \ } #define SETPACKETFORMATCMP(Value,Type,Update) \ { \ assert(Size == sizeof(Type) || !Data); \ Result = ERR_NONE; \ if (!EqPacketFormat(&Value,(Type*)Data)) \ { \ Result = PacketFormatCopy(&Value,(Type*)Data);\ if (Result == ERR_NONE) \ Result = Update; \ } \ } static INLINE tick_t ScaleTick(int64_t v, int64_t Num, int64_t Den) { return (tick_t)Scale64(v,Num,Den); } static INLINE filepos_t ScalePos(int64_t v, int64_t Num, int64_t Den) { return (filepos_t)Scale64(v,Num,Den); } NODE_DLL int ScaleRound(int_fast32_t v,int_fast32_t Num,int_fast32_t Den); #endif bcmatroska2-5.3.101/corec/corec/node/nodetree.c000066400000000000000000000141421462133141200211540ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "node.h" static NOINLINE err_t SetParent(nodetree* p,nodetree* Parent,nodetree* Before) { err_t Result = ERR_NONE; assert(!Before || Before->Parent == Parent); // make sure Before is in the right tree if (p!=Before && (p->Parent != Parent || p->Next != Before)) { if (p->Parent) VMT_FUNC(p->Parent,nodetree_vmt)->RemoveChild(p->Parent,p); if (Parent) Result = VMT_FUNC(Parent,nodetree_vmt)->AddChild(Parent,p,Before); assert(p->Next != p); } return Result; } nodetree* NodeTree_DetachAndRelease(void* p) { nodetree* Next = NodeTree_Next(p); NodeTree_SetParent(p,NULL,NULL); Node_Release(p); return Next; } void NodeTree_Clear(nodetree* p) { while (p->Children) NodeTree_DetachAndRelease(p->Children); SetParent(p,NULL,NULL); } static err_t AddChild(nodetree* p,nodetree* Child, nodetree* Before) { nodetree** i; LockEnter(Node_Context(p)->NodeLock); for (i=&p->Children;*i;i=&(*i)->Next) if (*i == Before) break; Child->Parent = p; Child->Next = Before; *i = Child; LockLeave(Node_Context(p)->NodeLock); return ERR_NONE; } static void RemoveChild(nodetree* p,nodetree* Child) { nodetree** i; LockEnter(Node_Context(p)->NodeLock); for (i=&p->Children;*i;i=&(*i)->Next) if (*i==Child) { *i=Child->Next; break; } Child->Next = NULL; Child->Parent = NULL; LockLeave(Node_Context(p)->NodeLock); } void NodeTree_MoveBefore(void* p, void* Before) { if (p != Before) { nodetree* Parent; LockEnter(Node_Context(p)->NodeLock); Parent = NodeTree_Parent(p); RemoveChild(Parent,p); AddChild(Parent,p,Before); LockLeave(Node_Context(p)->NodeLock); } } nodetree* NodeTree_ChildByName(const void* p,const tchar_t* Name, fourcc_t Class, bool_t Recursive) { if (p && Name && Name[0]) { nodetree* i; for (i=NodeTree_Children(p);i;i=NodeTree_Next(i)) if (Node_IsPartOf(i,Class)) { const tchar_t* s = (const tchar_t*)Node_GetData((node*)i,NODE_ID,TYPE_STRING); if (s && tcsisame_ascii(s,Name)) return i; } if (Recursive) { nodetree* j; for (i=NodeTree_Children(p);i;i=NodeTree_Next(i)) if ((j = NodeTree_ChildByName(i,Name,Class,1))!=NULL) return j; } } return NULL; } NOINLINE nodetree* NodeTree_CreateChild(void* p, const tchar_t* Name, fourcc_t ClassId, void* Before) { nodetree* Child = (nodetree*)NodeCreate(p,ClassId); if (Child) { NodeTree_SetParent(Child,p,Before); if (Name && Name[0]) Node_SetData((node*)Child,NODE_ID,TYPE_STRING,Name); } return Child; } NOINLINE nodetree* NodeTree_ChildByClass(const void *p, fourcc_t Class) { if (Node_IsPartOf(p,Class)) return (nodetree*)p; for (p=NodeTree_Children(p);p;p=NodeTree_Next(p)) { nodetree *Result = NodeTree_ChildByClass(p,Class); if (Result) return Result; } return NULL; } static nodetree* FindChild(nodetree* p, const tchar_t* Name) { nodetree* Result; for (p=NodeTree_Children(p);p;p=NodeTree_Next(p)) { const tchar_t* s = Node_GetData((node*)p,NODE_ID,TYPE_STRING); if (s) { if (tcsisame_ascii(Name,s)) return p; } else if ((Result = NodeTree_FindChild(p,Name))!=NULL) return Result; } return NULL; } static nodetree* AddData(nodetree* UNUSED_PARAM(i), const tchar_t* UNUSED_PARAM(Token), dataflags UNUSED_PARAM(Flags)) { return NULL; } META_START(NodeTree_Class,NODETREE_CLASS) META_CLASS(VMT_SIZE,sizeof(nodetree_vmt)) META_CLASS(SIZE,sizeof(nodetree)) META_CLASS(DELETE,NodeTree_Clear) META_PARAM(NAME,NODETREE_PARENT,T("Parent")) META_PARAM(TYPE,NODETREE_PARENT,TYPE_NODE|TFLAG_DEFAULT|TFLAG_RDONLY) META_DATA_RDONLY(TYPE_NODE,NODETREE_PARENT,nodetree,Parent) META_PARAM(NAME,NODETREE_NEXT,T("Next")) META_PARAM(TYPE,NODETREE_NEXT,TYPE_NODE|TFLAG_DEFAULT|TFLAG_RDONLY) META_DATA_RDONLY(TYPE_NODE,NODETREE_NEXT,nodetree,Next) META_VMT(TYPE_FUNC,nodetree_vmt,SetParent,SetParent) META_VMT(TYPE_FUNC,nodetree_vmt,AddChild,AddChild) META_VMT(TYPE_FUNC,nodetree_vmt,RemoveChild,RemoveChild) META_VMT(TYPE_FUNC,nodetree_vmt,AddData,AddData) META_VMT(TYPE_FUNC,nodetree_vmt,FindChild,FindChild) META_END(NODE_CLASS) bcmatroska2-5.3.101/corec/corec/node/nodetree.h000066400000000000000000000064621462133141200211670ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __NODETREE_H #define __NODETREE_H #define NODETREE_CLASS FOURCC('T','R','E','E') #define NODETREE_PARENT 20 #define NODETREE_NEXT 21 typedef struct nodetree nodetree; typedef struct nodetree_vmt { node_vmt Base; err_t (*SetParent)(thisnode,void* Parent,void* Before); err_t (*AddChild)(thisnode,void* Child,void* Before); //private void (*RemoveChild)(thisnode,void* Child); //private nodetree* (*AddData)(thisnode,const tchar_t* Name,dataflags Flags); nodetree* (*FindChild)(thisnode,const tchar_t* Name); } nodetree_vmt; struct nodetree { node Base; nodetree* Parent; nodetree* Next; nodetree* Children; }; #define NodeTree_SetParent(p,a,b) VMT_FUNC(p,nodetree_vmt)->SetParent(p,a,b) #define NodeTree_AddData(p,a,b) VMT_FUNC(p,nodetree_vmt)->AddData(p,a,b) #define NodeTree_FindChild(p,a) VMT_FUNC(p,nodetree_vmt)->FindChild(p,a) #define NodeTree_Parent(p) ((nodetree*)(p))->Parent #define NodeTree_Children(p) ((nodetree*)(p))->Children #if defined(NDEBUG) #define NodeTree_Next(p) ((nodetree*)(p))->Next #else #define NodeTree_Next(p) (assert((nodetree*)(p) != ((nodetree*)(p))->Next),((nodetree*)(p))->Next) #endif NODE_DLL nodetree* NodeTree_CreateChild(void* p, const tchar_t* Name, fourcc_t ClassId, void* Before); NODE_DLL nodetree* NodeTree_ChildByName(const void* p,const tchar_t* Name, fourcc_t Class, bool_t Recursive); NODE_DLL nodetree* NodeTree_ChildByClass(const void* p,fourcc_t Class); NODE_DLL nodetree* NodeTree_DetachAndRelease(void* p); NODE_DLL void NodeTree_MoveBefore(void* p, void* Before); NODE_DLL void NodeTree_Clear(nodetree* p); #endif bcmatroska2-5.3.101/corec/corec/portab.h000066400000000000000000000427601462133141200177250ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __PORTAB_H #define __PORTAB_H #if defined(__GNUC__) && defined(__palmos__) #undef __WCHAR_TYPE__ #define __WCHAR_TYPE__ unsigned short #endif #include #include #include #include #include #undef INLINE #undef NOINLINE #undef IS_LITTLE_ENDIAN #undef IS_BIG_ENDIAN #if defined(__palmos__) #define TARGET_PALMOS #define NO_FLOATINGPOINT #define CONFIG_BLOCK_RDONLY #elif defined(_EE) #define TARGET_PS2SDK #define TARGET_DESKTOP #define RESOURCE_COREC #elif defined(__SYMBIAN32__) #if defined(__SERIES60_3X__) #define SYMBIAN90 #define SERIES60 #elif defined(__SERIES60_10__) #define SYMBIAN60 #define SERIES60 #elif defined(__SERIES60_20__) #define SYMBIAN70 #define SERIES60 #elif defined(__SERIES80__) #define SYMBIAN70 #define SERIES80 #elif defined(__SERIES90__) #define SYMBIAN70 #define SERIES90 #elif defined(__UIQ3__) #define SYMBIAN90 #define UIQ #elif defined(__UIQ__) #define SYMBIAN70 #define UIQ #endif #define TARGET_SYMBIAN #ifndef UNICODE #define UNICODE #endif #ifdef __MARM__ #define ARM #endif #elif defined(_WIN32_WCE) #if !defined(CONFIG_WINCE2) && (_WIN32_WCE>=200 && _WIN32_WCE<300) #define CONFIG_WINCE2 #endif #if defined(WIN32_PLATFORM_WFSP) #define TARGET_SMARTPHONE #endif #define TARGET_WINCE #define TARGET_WIN #ifndef UNICODE #define UNICODE #endif #elif defined(_WIN64) #define TARGET_WIN64 #define TARGET_WIN #define TARGET_DESKTOP #elif defined(_WIN32) #define TARGET_WIN32 #define TARGET_WIN #define TARGET_DESKTOP #elif defined(__APPLE__) #ifndef TARGET_IPHONE #include // iPhone information is defined within the SDK in which Xcode is pointed to #endif #define TARGET_OSX #undef UNICODE // tchar_t is UTF-8 for OS X #ifdef TARGET_OS_IPHONE // defined in TargetConditionals.h #define TARGET_IPHONE #define TARGET_IPHONE_SDK #if !TARGET_IPHONE_SIMULATOR #define TARGET_IPHONE_DEVICE #endif #if defined(__arm__) #define ARM #endif #endif #ifndef TARGET_IPHONE #define TARGET_DESKTOP // only for dekstop (not iPhone or Apple TV) #endif #elif defined(__QNXNTO__) #if defined(__arm__) #define ARM #endif #define TARGET_QNX #elif defined(__ANDROID__) #define TARGET_ANDROID #if defined(__arm__) #define ARM #endif #elif defined(__linux__) || defined(__CYGWIN__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #define TARGET_LINUX #ifndef TARGET_QTOPIA // qtopia defines desktop manually #define TARGET_DESKTOP // not necessarily #endif #else #error Platform not supported by Core-C! #endif #if defined(__powerpc__) || defined(__PPC__) || defined(__POWERPC__) #define POWERPC #define IS_BIG_ENDIAN #endif #if defined(__sparc) #if defined(_LP64) #define SPARC64 #define CPU_64BITS #else #define SPARC32 #endif #define IS_BIG_ENDIAN #endif #if defined(TARGET_LINUX) || defined(TARGET_ANDROID) #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #include #else #include #endif #if __BYTE_ORDER == __LITTLE_ENDIAN #define IS_LITTLE_ENDIAN #elif __BYTE_ORDER == __BIG_ENDIAN #define IS_BIG_ENDIAN #endif #endif #if defined(_M_X64) || defined(__amd64__) #define IX86_64 #define CPU_64BITS #endif #if defined(_M_IA64) #define IA64 #define CPU_64BITS #endif #if defined(__mips) && !defined(MIPS) #define MIPS #endif #ifdef MIPS #if defined(__mips64) || defined(CONFIG_MIPS64) #define MIPS64 #else #define MIPS32 #endif #endif #if defined(_M_IX86) || defined(__i386) || defined(__i686) #define IX86 #endif #if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN) #define IS_LITTLE_ENDIAN #endif #define TICKSPERSEC 16384 #define TIMEPERSEC (TICKSPERSEC>>4) #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif #ifdef _MSC_VER #define _CRTDBG_MAP_ALLOC #include #include #ifndef TARGET_WINCE #include #endif #ifndef strncasecmp #define strncasecmp(x,y,z) _strnicmp(x,y,z) #endif #ifndef strcasecmp #define strcasecmp(x,y) _stricmp(x,y) #endif #ifndef stricmp #define stricmp(x,y) _stricmp(x,y) #endif #ifndef strnicmp #define strnicmp(x,y,z) _strnicmp(x,y,z) #endif #if _MSC_VER >= 1400 #pragma comment(linker, "/nodefaultlib:libc.lib") #pragma comment(linker, "/nodefaultlib:libcd.lib") //#pragma comment(linker, "/nodefaultlib:oldnames.lib") #elif defined(_WIN32_WCE) // allow evc3/evc4 compiling with vs2005 object files #pragma comment(linker, "/nodefaultlib:libcmt.lib") #pragma comment(linker, "/nodefaultlib:oldnames.lib") #endif #ifndef alloca #define alloca _alloca #endif //#ifndef inline //#define inline __inline //#endif #ifndef _UINTPTR_T_DEFINED typedef unsigned int uintptr_t; #define _UINTPTR_T_DEFINED #endif #ifndef _INTPTR_T_DEFINED typedef signed int intptr_t; #define _INTPTR_T_DEFINED #endif #if _MSC_VER >= 1400 #define NOINLINE __declspec(noinline) #else #define NOINLINE #endif #define INLINE __forceinline #ifndef STDCALL #define STDCALL __stdcall #endif #ifndef CDECL #define CDECL __cdecl #endif #if !defined(COMPILER_MSVC) #define COMPILER_MSVC #endif #if defined(__cplusplus) #define SORTPP_PASS // to avoid a problem if winnt.h is included after us #define NOMINMAX // conflict with #endif #else /* _MSC_VER */ #include #if defined(TARGET_SYMBIAN) typedef signed long int32_t; typedef unsigned long uint32_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed long long int64_t; typedef unsigned long long uint64_t; typedef uint32_t uintptr_t; typedef int32_t intptr_t; typedef signed int int_fast32_t; typedef unsigned int uint_fast32_t; typedef signed int int_fast16_t; typedef unsigned int uint_fast16_t; typedef signed char int_fast8_t; typedef unsigned char uint_fast8_t; typedef signed long long int_fast64_t; typedef unsigned long long uint_fast64_t; #elif !defined(__GLIBC__) && !defined(__MINGW32__) && !defined(TARGET_PS2SDK) && !defined(TARGET_IPHONE) && !defined(TARGET_ANDROID) && !defined(__FreeBSD__) && !defined(__QNXNTO__) #include #ifdef SPARC64 typedef int64_t int_fast32_t; typedef uint64_t uint_fast32_t; typedef int64_t int_fast16_t; typedef uint64_t uint_fast16_t; #else typedef int32_t int_fast32_t; typedef uint32_t uint_fast32_t; # ifndef __APPLE__ typedef int32_t int_fast16_t; typedef uint32_t uint_fast16_t; # endif #endif typedef int8_t int_fast8_t; typedef uint8_t uint_fast8_t; typedef int64_t int_fast64_t; typedef uint64_t uint_fast64_t; #else #include #endif #if defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ > 0) && !defined(always_inline) #define INLINE __attribute__((always_inline)) inline #else #define INLINE inline #endif #if __GNUC__ >= 3 #define NOINLINE __attribute__((noinline)) #else #define NOINLINE #endif #if !defined(IX86) || defined(__CW32__) #define __stdcall #define __cdecl #define STDCALL #define CDECL #else #ifndef STDCALL #define STDCALL __attribute__((stdcall)) #endif #ifndef CDECL #define CDECL __attribute__((cdecl)) #endif #endif #if !defined(COMPILER_GCC) && defined(__GNUC__) #define COMPILER_GCC #endif #endif /* _MSC_VER */ #if !defined(_STDINT_H) && !defined(_STDINT_H_) && !defined(_STDINT) && !defined(_UINT64_T_DECLARED) && !defined(_STDINT_H_INCLUDED) // could be used elsewhere typedef signed int int32_t; typedef unsigned int uint32_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #if defined(IX86_64) || defined(IA64) typedef signed __int64 int_fast32_t; typedef unsigned __int64 uint_fast32_t; typedef signed __int64 int_fast16_t; typedef unsigned __int64 uint_fast16_t; typedef signed char int_fast8_t; typedef unsigned char uint_fast8_t; typedef signed __int64 int_fast64_t; typedef unsigned __int64 uint_fast64_t; #else #if _MSC_VER >= 1400 typedef __w64 signed int int_fast32_t; typedef __w64 unsigned int uint_fast32_t; typedef __w64 signed int int_fast16_t; typedef __w64 unsigned int uint_fast16_t; #else typedef signed int int_fast32_t; typedef unsigned int uint_fast32_t; typedef signed int int_fast16_t; typedef unsigned int uint_fast16_t; #endif typedef signed char int_fast8_t; typedef unsigned char uint_fast8_t; typedef signed __int64 int_fast64_t; typedef unsigned __int64 uint_fast64_t; #endif #endif #ifdef _MSC_VER #define LL(x) x##i64 #define ULL(x) x##ui64 #define PRId64 "I64d" #define PRIu64 "I64u" #define PRIx64 "I64x" #define TPRId64 L"I64d" #define TPRIu64 L"I64u" #define TPRIx64 L"I64x" #else #define LL(x) x##ll #define ULL(x) x##ull #ifndef PRId64 #define PRId64 "lld" #endif #ifndef PRIu64 #define PRIu64 "llu" #endif #ifndef PRIx64 #define PRIx64 "llx" #endif #define TPRId64 PRId64 #define TPRIu64 PRIu64 #define TPRIx64 PRIx64 #endif #define MAX_INT64 LL(0x7fffffffffffffff) #define MAX_TICK INT_MAX typedef int_fast32_t err_t; typedef int_fast32_t bool_t; typedef int_fast32_t tick_t; typedef uint8_t boolmem_t; /* unsigned so ":1" bitmode should work */ typedef uint32_t fourcc_t; typedef uint32_t rgbval_t; typedef struct cc_guid { uint32_t v1; uint16_t v2; uint16_t v3; uint8_t v4[8]; } cc_guid; typedef struct cc_fraction { int_fast32_t Num; int_fast32_t Den; } cc_fraction; typedef struct cc_fraction64 { int_fast64_t Num; int_fast64_t Den; } cc_fraction64; typedef struct cc_point { int x; int y; } cc_point; typedef struct cc_point16 { int16_t x; int16_t y; } cc_point16; typedef struct cc_rect { int x; int y; int Width; int Height; } cc_rect; #ifndef ZLIB_INTERNAL #undef T #define TSIZEOF(name) (sizeof(name)/sizeof(tchar_t)) #if defined(UNICODE) #if defined(__GNUC__) && !defined(TARGET_SYMBIAN) && !defined(TARGET_PALMOS) #include #endif #if defined(__GNUC__) && (__GNUC__<3) && defined(__cplusplus) typedef __wchar_t tchar_t; #else typedef wchar_t tchar_t; #endif #define tcsstr wcsstr #define tcslen wcslen #define tcschr wcschr #define tcsrchr wcsrchr #define tcscoll wcscoll #define tcstod wcstod #define tcscspn wcscspn #define tcspbrk wcspbrk #define tcstoul wcstoul #define tcsftime wcsftime #define T(a) L ## a #else /* UNICODE */ typedef char tchar_t; #define tcsstr strstr #define tcslen strlen #define tcschr strchr #define tcsrchr strrchr #define tcscoll strcoll #define tcstod strtod #define tcscspn strcspn #define tcspbrk strpbrk #define tcstoul strtoul #define tcsftime strftime #define T(a) a #endif /* UNICODE */ #define T__(x) T(x) #endif #ifndef SIZEOF_WCHAR #if defined(TARGET_OSX) || defined(TARGET_LINUX) || defined(TARGET_PS2SDK) #define SIZEOF_WCHAR 4 #else #define SIZEOF_WCHAR 2 #endif #endif #if SIZEOF_WCHAR==2 typedef wchar_t utf16_t; #else typedef uint16_t utf16_t; #endif #define tcscpy !UNSAFE! #define tcscat !UNSAFE! #define stprintf !UNSAFE! #define vstprintf !UNSAFE! #if defined(_WIN32) || defined(TARGET_SYMBIAN) #define DLLEXPORT __declspec(dllexport) #define DLLIMPORT __declspec(dllimport) #define DLLHIDDEN #elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 340) #define DLLEXPORT __attribute__ ((visibility("default"))) #define DLLIMPORT __attribute__ ((visibility("default"))) #define DLLHIDDEN __attribute__ ((visibility("hidden"))) #else #define DLLEXPORT #define DLLIMPORT #define DLLHIDDEN #endif #ifdef __cplusplus #define INTERNAL_C_API extern "C" #else #define INTERNAL_C_API extern #endif #if defined(TARGET_WINCE) && (defined(SH3) || defined(SH4) || defined(MIPS)) #define _INLINE #define _CONST #else #define _INLINE INLINE #define _CONST const #endif /* todo: needs more testing, that nothing broke... */ #if defined(MAX_PATH) #define MAXPATH MAX_PATH #elif defined(PATH_MAX) #define MAXPATH PATH_MAX #else #define MAXPATH 256 #endif #define MAXPROTOCOL 16 #if MAXPATH < 1024 #define MAXPATHFULL 1024 #else #define MAXPATHFULL MAXPATH #endif #define MAXPLANES 4 typedef void* planes[MAXPLANES]; typedef const void* constplanes[MAXPLANES]; #define CONST_CONSTPLANES(name) const void* const (name)[MAXPLANES] #define CONSTPLANES(name) const void* (name)[MAXPLANES] #define CONST_PLANES(name) void* const (name)[MAXPLANES] #define FOURCCBE(a,b,c,d) \ (((uint8_t)(a) << 24) | ((uint8_t)(b) << 16) | \ ((uint8_t)(c) << 8) | ((uint8_t)(d) << 0)) #define FOURCCLE(a,b,c,d) \ (((uint8_t)(a) << 0) | ((uint8_t)(b) << 8) | \ ((uint8_t)(c) << 16) | ((uint8_t)(d)<< 24)) #ifdef IS_BIG_ENDIAN #define FOURCC(a,b,c,d) (fourcc_t)FOURCCBE(a,b,c,d) #else #define FOURCC(a,b,c,d) (fourcc_t)FOURCCLE(a,b,c,d) #endif #if defined(TARGET_WINCE) #undef strdup #define strdup(x) _strdup(x) #define wcscoll(x,y) tcscmp(x,y) #endif #if defined(__CW32__) void * __alloca(size_t size); #ifndef alloca #define alloca(size) __alloca(size) #endif #endif #if defined(__GNUC__) #ifndef alloca #define alloca(size) __builtin_alloca(size) #endif #if defined(TARGET_PALMOS) extern int rand(); extern void srand(unsigned int); extern void qsort(void* const base,size_t,size_t,int(*cmp)(const void*,const void*)); #endif #if defined(ARM) && !defined(TARGET_WINCE) //fixed size stack: // symbian // palm os #define SWAPSP static INLINE void* SwapSP(void* in) { void* out; asm volatile( "mov %0, sp\n\t" "mov sp, %1\n\t" : "=&r"(out) : "r"(in) : "cc"); return out; } #endif #endif /* __GNUC__ */ #if defined(TARGET_PALMOS) && defined(IX86) extern void* malloc_palmos(size_t); extern void* realloc_palmos(void*,size_t); extern void free_palmos(void*); #define malloc(n) malloc_palmos(n) #define realloc(p,n) realloc_palmos(p,n) #define free(p) free_palmos(p) #endif #if defined(_MSC_VER) && defined(TARGET_WIN) #if _MSC_VER >= 1800 #include #endif #if !defined(WINAPI_FAMILY_PARTITION) || !defined(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_FAMILY_PARTITION) #if defined(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_PARTITION_PHONE_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #define WINDOWS_PHONE 1 #elif defined(WINAPI_PARTITION_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define WINDOWS_UNIVERSAL 1 #endif #endif #ifdef WINDOWS_UNIVERSAL #undef strdup #define strdup _strdup #endif #endif #if defined(_MSC_VER) && defined(TARGET_WIN) #define TRY_BEGIN __try { #define TRY_END ;} __except (1) {} #define TRY_END_FUNC(func) ;} __except (1) { func; } #else #define TRY_BEGIN { #define TRY_END } #define TRY_END_FUNC(func) } #endif #ifndef NDEBUG #if defined(TARGET_OSX) #include #elif !defined(TARGET_WINCE) && !defined(TARGET_PALMOS) #include #else #ifdef LIBC_EXPORTS #define ASSERT_DLL DLLEXPORT #else #define ASSERT_DLL #endif ASSERT_DLL void _Assert(const char* Exp, const char* File, int Line); #define assert(x) ((x) ? (void)0 : _Assert(#x, __FILE__, __LINE__)) #endif #else // NDEBUG #ifndef assert #define assert(x) ((void)0) #endif #endif // NDEBUG #if defined(__palmos__) #if _MSC_VER > 1000 #pragma warning( disable:4068 4204 ) #endif #undef BIG_ENDIAN #define USE_TRAPS 0 #endif #if defined(COMPILER_GCC) && (!defined(TARGET_SYMBIAN) || defined(SYMBIAN90)) #define UNUSED_PARAM(x) (x) __attribute__ ((unused)) #elif (defined(TARGET_SYMBIAN) && !defined(ARM)) || defined(__cplusplus) #define UNUSED_PARAM(x) #else #define UNUSED_PARAM(x) (x) #endif #include "bcmatroska2_config.h" #if defined(COREMAKE_CONFIG_HELPER) #include "config_helper.h" #else /* COREMAKE_CONFIG_HELPER */ #include "confhelper.h" #endif /* COREMAKE_CONFIG_HELPER */ #if defined(TARGET_IPHONE) && !defined(__ARM_NEON__) #undef CONFIG_NEON #endif #ifdef CONFIG_FILEPOS_64 typedef int_fast64_t filepos_t; #define MAX_FILEPOS MAX_INT64 #else typedef int_fast32_t filepos_t; #define MAX_FILEPOS INT_MAX #endif #define INVALID_FILEPOS_T ((filepos_t)-1) typedef int systick_t; #define INVALID_SYSTICK_T ((int)-1) #if defined(CONFIG_SAFE_C) // change the low level APIs to be safer on windows and other OSes #include "banned.h" #endif /* CONFIG_SAFE_C */ #endif bcmatroska2-5.3.101/corec/corec/str/000077500000000000000000000000001462133141200170645ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/corec/str/str.c000066400000000000000000000537361462133141200200560ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #if defined(COREC_PARSER) #include "corec/helpers/parser/parser.h" #endif static INLINE int ascii_upper(int ch) { if (ch>='a' && ch<='z') ch += 'A'-'a'; return ch; } size_t tcsbytes(const tchar_t* p) { if (p) return (tcslen(p)+1)*sizeof(tchar_t); else return 0; } #define icmp_ascii(a,b,i) \ ca=a[i]; \ cb=b[i]; \ cb ^= ca; \ if (cb) /* not equal? */\ { \ cb &= ~0x20; /* only allow the 0x20 bit to be different */ \ ca &= ~0x20; /* and only in the 'A'..'Z' range */ \ if (cb || ca<'A' || ca>'Z') \ { \ ca=a[i]; \ cb=b[i]; \ break; \ } \ } \ if (!ca) /* both zero? */ \ return 0; int tcsicmp_ascii(const tchar_t* a,const tchar_t* b) { int ca,cb; for (;;a+=4,b+=4) { icmp_ascii(a,b,0) icmp_ascii(a,b,1) icmp_ascii(a,b,2) icmp_ascii(a,b,3) } return ascii_upper(ca)-ascii_upper(cb); } #define isame_ascii(a,b,i) \ ca=a[i]; \ cb=b[i]; \ cb ^= ca; \ if (cb) /* not equal? */\ { \ cb &= ~0x20; /* only allow the 0x20 bit to be different */ \ ca &= ~0x20; /* and only in the 'A'..'Z' range */ \ if (cb || ca<'A' || ca>'Z') \ return 0; \ } \ if (!ca) /* both zero? */ \ break; bool_t tcsisame_ascii(const tchar_t* a,const tchar_t* b) { int ca,cb; for (;;a+=4,b+=4) { isame_ascii(a,b,0) isame_ascii(a,b,1) isame_ascii(a,b,2) isame_ascii(a,b,3) } return 1; } int tcsnicmp_ascii(const tchar_t* a,const tchar_t* b,size_t n) { int ca,cb; for (;;++a,++b) { if (!n--) return 0; icmp_ascii(a,b,0) } return ascii_upper(ca)-ascii_upper(cb); } tchar_t* tcscpy_s(tchar_t* Out,size_t OutLen,const tchar_t* In) { assert(In != NULL); if (OutLen>0) { size_t n = min(tcslen(In),OutLen-1); memcpy(Out,In,n*sizeof(tchar_t)); Out[n] = 0; } return Out; } tchar_t* tcsncpy_s(tchar_t* Out,size_t OutLen,const tchar_t* In,size_t n) { assert(In != NULL); if (OutLen>0) { n = min(min(tcslen(In),n),OutLen-1); memcpy(Out,In,n*sizeof(tchar_t)); Out[n] = 0; } return Out; } tchar_t* tcscat_s(tchar_t* Out,size_t OutLen,const tchar_t* In) { assert(In != NULL); if (OutLen>0) { size_t n = tcslen(Out); if (OutLen>n) tcscpy_s(Out+n,OutLen-n,In); } return Out; } tchar_t* tcsncat_s(tchar_t* Out,size_t OutLen,const tchar_t* In,size_t InLen) { assert(In != NULL); if (OutLen>0) { size_t n = tcslen(Out); if (OutLen>n) tcsncpy_s(Out+n,OutLen-n,In,InLen); } return Out; } void stprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask, ...) { va_list Arg; va_start(Arg, Mask); vstprintf_s(Out,OutLen,Mask,Arg); va_end(Arg); } void stcatprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask, ...) { size_t n = tcslen(Out); if (OutLen>n) { va_list Arg; va_start(Arg, Mask); vstprintf_s(Out+n,OutLen-n,Mask,Arg); va_end(Arg); } } static int get_integers(int64_t IntValue) { int Result = 0; int64_t TmpVal = 1; while (IntValue >= TmpVal && TmpVal < MAX_INT64/10) { TmpVal *= 10; Result++; } return Result; } static int get_decimals(int Decimals, int64_t IntValue) { int Result = 0; int64_t TmpVal = IntValue+1; while (TmpVal < MAX_INT64/10) { TmpVal *= 10; Result++; } return min(Decimals,Result); } void vstprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask,va_list Arg) { int64_t vl; int vs; double dvs, _dvs; intptr_t Width,ptr; unsigned int v,w,q,w0; bool_t ZeroFill; bool_t Unsigned; bool_t Sign; bool_t AlignLeft; bool_t Long; int Decimals; const tchar_t *In; const char *InA; size_t n; int64_t lvs,_lvs,ww; while (OutLen>1 && *Mask) { switch (*Mask) { case '%': ++Mask; if (*Mask == '%') { *(Out++) = *(Mask++); --OutLen; break; } AlignLeft = *Mask=='-'; if (AlignLeft) ++Mask; ZeroFill = *Mask=='0'; if (ZeroFill) ++Mask; Width = -1; if (IsDigit(*Mask)) { Width = 0; for (;IsDigit(*Mask);++Mask) Width = Width*10 + (*Mask-'0'); } Decimals = *Mask=='.'; if (Decimals) { ++Mask; Decimals = 0; if (IsDigit(*Mask)) { for (;IsDigit(*Mask);++Mask) Decimals = Decimals*10 + (*Mask-'0'); } } Long = 0; if (*Mask == '*') { ++Mask; Width = va_arg(Arg,int); } while (*Mask == 'l') { Long=1; ++Mask; // long } if (*Mask=='I' && *(Mask+1)=='6' && *(Mask+2)=='4') { Long=1; Mask += 3; } Unsigned = *Mask=='u'; if (Unsigned) ++Mask; switch (*Mask) { case 'd': case 'i': case 'X': case 'x': if (Long) vl = va_arg(Arg,int64_t); else vl = va_arg(Arg,int); if (*Mask=='x' || *Mask=='X') { Unsigned = 1; q = 16; ww = 0x10000000; } else { q = 10; ww = 100000000000; } Sign = vl<0 && !Unsigned; if (Sign) { vl=-vl; --Width; } w0 = 1; for (;Width>1;--Width) w0 *= q; v = vl; while (vlw0) ww/=q; while (ww>0) { unsigned int i = (unsigned int)(vl/ww); // between 0 and q-1 vl-=i*ww; if (OutLen>1 && Sign && (ww==1 || ZeroFill || i>0)) { *(Out++) = '-'; --OutLen; Sign = 0; } if (OutLen>1) { if (i==0 && !ZeroFill && ww!=1) i = ' '; else { ZeroFill = 1; if (i>=10) { if (*Mask == 'X') i += 'A'-10; else i += 'a'-10; } else i+='0'; } *(Out++) = (tchar_t)i; --OutLen; } ww/=q; } break; case 'c': Width -= 1; if (!AlignLeft) while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } *(Out++) = (tchar_t)va_arg(Arg,int); --OutLen; while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } break; case 's': In = va_arg(Arg,const tchar_t*); if (In) { n = min(tcslen(In),OutLen-1); Width -= n; if (!AlignLeft) while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } memcpy(Out,In,n*sizeof(tchar_t)); Out += n; OutLen -= n; while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } } break; case 'S': InA = va_arg(Arg,const char*); n = min(strlen(InA),OutLen-1); Width -= n; if (!AlignLeft) while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } for (;n>0 && OutLen>1 && *InA;++InA,++Out,--OutLen,--n) *Out = *InA; while (--Width>=0 && OutLen>1) { *Out++ = ' '; --OutLen; } break; case 'g': case 'G': case 'f': dvs = va_arg(Arg,double); if (OutLen) { Sign = dvs<0; if (Sign && OutLen>1) dvs = -dvs; if (Width >= 0) { // count integer digits and decimal digits to adjust the alignment int max_integer_digits = get_integers((int64_t)dvs); int max_decimal_digits = get_decimals(Width - max_integer_digits - 1 - (Sign?1:0),(int64_t)dvs); int max_total_chars; vs = (int)dvs; lvs = 1; _lvs = vs; w = w0 = 0; // decimals in use while (max_decimal_digits-->0) { lvs *= 10; _lvs *= 10; q = (int)(dvs * lvs - (double)_lvs); _lvs += q; w0++; if (q) w = w0; } if (Decimals>0) max_decimal_digits = max(Decimals,(int)w); else max_decimal_digits = w; max_total_chars = max_integer_digits + max_decimal_digits + (Sign?1:0) + (max_decimal_digits?1:0); if (max_integer_digits + (Sign?1:0) + (max_decimal_digits?1:0) > Width) goto do_exponent; while (!AlignLeft && Width > max_total_chars && OutLen > 1) { *Out++ = ' '; --Width; --OutLen; } } // integer part vs = (int)dvs; v = vs; if (Sign && dvs!=0.0 && OutLen > 1) { *Out++ = '-'; --OutLen; } w = 1000000000; while (w>v && w>1) w/=10; // integer filling while (w>0) { unsigned int i = v/w; v-=i*w; if (OutLen>1 && (Width<0 || Width-->0)) { i+='0'; *(Out++) = (tchar_t)i; --OutLen; } w/=10; } // decimal part // dry run to count the number of necessary decimals v = Decimals; if (!Decimals) Decimals=30; Decimals = get_decimals(Decimals,vs); lvs = 1; _lvs = vs; w = w0 = 0; // decimals in use while (Decimals-->0) { lvs *= 10; _lvs *= 10; q = (int)(dvs * lvs - (double)_lvs); _lvs += q; w0++; if (q) w = w0; } if (*Mask==T('f') && w) w = max(w,6); if (w && OutLen>1) { *Out++ = T('.'); --OutLen; --Width; v -= w; lvs = 1; _lvs = vs; while (w-->0 && OutLen>1) { lvs *= 10; _lvs *= 10; q = (int)(dvs * lvs - (double)_lvs); _lvs += q; if (w==0) // last one, do some rounding { if ((dvs * lvs - (double)_lvs) >= 5) q++; } *Out++ = (tchar_t)(q + '0'); --OutLen; --Width; } while (Width-- > 0 && OutLen > 1) { *Out++ = ' '; --OutLen; } } break; do_exponent: // TODO *Out++ = T('e'); OutLen--; } break; case 'e': case 'E': dvs = va_arg(Arg,double); Sign = dvs<0; if (Sign && OutLen>1) { *Out++ = '-'; OutLen--; dvs = -dvs; } vs = 0; // exponent _dvs = 1.0; // factor if (dvs >= 1.0) { while (dvs*_dvs > 1.0) { _dvs *= 10.0; vs++; } dvs *= 10.0; vs--; } else { while (dvs*_dvs < 1.0) { _dvs *= 10.0; vs--; } } dvs *= _dvs; if (OutLen > 4) { *Out++ = (tchar_t)((int)dvs + T('0')); *Out++ = T('.'); dvs -= (int)dvs; dvs *= 10.0; if (dvs - (int)dvs > 0.5) *Out++ = (tchar_t)((int)(dvs+1) + T('0')); else *Out++ = (tchar_t)((int)(dvs) + T('0')); *Out++ = *Mask; OutLen -= 4; } if (OutLen > 1 && vs < 0) { *Out++ = T('-'); OutLen--; vs = -vs; } if (OutLen > 3) { *Out++ = (tchar_t)((vs / 100) + T('0')); vs %= 100; *Out++ = (tchar_t)((vs / 10) + T('0')); vs %= 10; *Out++ = (tchar_t)(vs + T('0')); OutLen -= 3; } break; case 'p': while (Width > 8 && !AlignLeft && OutLen > 1) { Width--; *Out++ = ' '; OutLen--; } ptr = va_arg(Arg,intptr_t); for (vs=28;OutLen>1 && vs>=0;vs-=4) { q = (ptr>>vs) & 0x0F; if (q<10) *Out++ = (tchar_t)(q+T('0')); else *Out++ = (tchar_t)(q+T('A')-10); OutLen--; } while (Width > 8 && OutLen > 1) { Width--; *Out++ = ' '; OutLen--; } break; case 'r': { #if !defined(COREC_PARSER) va_arg(Arg,fourcc_t); // skip the param #else fourcc_t FourCC = va_arg(Arg,fourcc_t); if (OutLen > 4) { size_t Written = FourCCToString(Out,OutLen,FourCC); Out+=Written; OutLen+=Written; } #endif } break; } ++Mask; break; default: *(Out++) = *(Mask++); --OutLen; break; } } assert(OutLen>0); if (OutLen>0) *Out=0; } static int var_stscanf_s(const tchar_t* In, size_t *InLen, const tchar_t* Mask, va_list Arg) { int n = 0; int Sign; bool_t Long=0; size_t inlen = *InLen; int64_t v; int Width; const tchar_t* In0; while (inlen && In && *Mask) { switch (*Mask) { case '%': ++Mask; Width = -1; if (IsDigit(*Mask)) { Width = 0; for (;IsDigit(*Mask);++Mask) Width = Width*10 + (*Mask-'0'); } while (*Mask=='l') { ++Long; ++Mask; } switch (*Mask) { case 'X': case 'x': for (;inlen && IsSpace(*In);++In,--inlen) {} Sign = *In == '-'; In0 = In; if (Sign) { ++In; --inlen; --Width; } v = 0; for (;inlen && Width!=0 && *In;++In,--inlen,--Width) { int h = Hex(*In); if (h<0) break; v=v*16+h; } if (Sign) v=-v; if (In != In0) { *va_arg(Arg,int*) = v; ++n; } else In = NULL; break; case 'd': case 'i': for (;inlen && IsSpace(*In);++In,--inlen) {} Sign = *In == '-'; In0 = In; if (Sign) {++In; --inlen;} v = 0; for (;inlen && Width!=0 && IsDigit(*In);++In,--inlen,--Width) v=v*10+(*In-'0'); if (Sign) v=-v; if (In != In0) { if (Long) *va_arg(Arg,int64_t*) = v; else *va_arg(Arg,int*) = v; ++n; } else In = NULL; break; case 'o': for (;inlen && IsSpace(*In);++In,--inlen) {} Sign = *In == '-'; In0 = In; if (Sign) {++In; --inlen;} v = 0; for (;inlen && Width!=0 && *In;++In,--inlen,--Width) { if (*In >= '0' && *In <= '7') v=v*8+(*In-'0'); else break; } if (Sign) v=-v; if (In != In0) { *va_arg(Arg,int*) = v; ++n; } else In = NULL; break; case 'f': for (;inlen && IsSpace(*In);++In,--inlen) {} Sign = *In == '-'; In0 = In; if (Sign) {++In; --inlen;} v = 0; for (;inlen && IsDigit(*In);++In,--inlen) v=v*10+(*In-'0'); if (Sign) v=-v; if (In != In0) { int64_t Decimal=0; double Decimals=1.0; if (inlen && *In=='.') { ++In; --inlen; for (;inlen && IsDigit(*In);++In,--inlen,Decimals/=10.0) Decimal=Decimal*10+(*In-'0'); } if (Long) *va_arg(Arg,double*) = (double)v + (double)(Decimal*Decimals); else *va_arg(Arg,float*) = (float)v + (float)(Decimal*Decimals); ++n; } else In = NULL; break; } break; case 9: case ' ': for (;inlen && IsSpace(*In);++In,--inlen) {} break; default: if (*Mask == *In) { ++In; --inlen; } else In = NULL; } ++Mask; } *InLen -= inlen; return n; } int stscanf_s(const tchar_t* In, size_t *InLen, const tchar_t* Mask, ...) { int n; va_list Arg; va_start(Arg, Mask); n = var_stscanf_s(In,InLen,Mask,Arg); va_end(Arg); return n; } int stscanf(const tchar_t* In, const tchar_t* Mask, ...) { int n; size_t InLen = tcslen(In); va_list Arg; va_start(Arg, Mask); n = var_stscanf_s(In,&InLen,Mask,Arg); va_end(Arg); return n; } bool_t IsSpace(int ch) { return ch==' ' || ch==9 || ch == 13 || ch == 10; } bool_t IsAlpha(int ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } bool_t IsDigit(int ch) { return ch>='0' && ch<='9'; } int Hex(int ch) { if (IsDigit(ch)) return ch-'0'; if (ch >= 'a' && ch <= 'f') return ch-'a'+10; if (ch >= 'A' && ch <= 'F') return ch-'A'+10; return -1; } tchar_t* tcsupr(tchar_t* p) { tchar_t* i=p; for (;*i;++i) *i = (tchar_t)toupper(*i); return p; } tchar_t* tcslwr(tchar_t* p) { tchar_t* i=p; for (;*i;++i) *i = (tchar_t)tolower(*i); return p; } int StrListIndex(const tchar_t* s, const tchar_t* List) { if (List && *List) { size_t n = tcslen(s); if (n) { int i=0; while (List) { if (tcsnicmp_ascii(List,s,n)==0 && (!List[n] || List[n]==',' || List[n]==' ')) return i; List = tcschr(List,T(',')); if (List) ++List; ++i; } } } return -1; } size_t utf16len(const utf16_t *In) { size_t Result=0; while (*In++) ++Result; return Result; } tchar_t* tcsreplace(tchar_t* Out, size_t OutLen, const tchar_t *Src, const tchar_t *Dst) { tchar_t *s = tcsstr(Out,Src); if (s) { size_t SrcLen,DstLen,Remain; SrcLen = tcslen(Src); DstLen = tcslen(Dst); do { Remain = tcslen(s); if (SrcLen < DstLen) { if (Remain + (DstLen-SrcLen) >= OutLen - (s-Out)) return 0; // not enough room memmove(s+DstLen-SrcLen,s,(Remain+1)*sizeof(tchar_t)); } else memmove(s,s+SrcLen-DstLen,(Remain+1)*sizeof(tchar_t)); memcpy(s,Dst,DstLen*sizeof(tchar_t)); s += DstLen; } while ((s=tcsstr(s,Src))); } return Out; } tchar_t* tcsreplacechar(tchar_t *ts, tchar_t From, tchar_t To) { tchar_t *p; for (p=ts;*p;++p) if (*p == From) *p = To; return ts; } bcmatroska2-5.3.101/corec/corec/str/str.h000066400000000000000000000103341462133141200200460ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __STR_H #define __STR_H #include "corec/corec.h" #ifdef __cplusplus extern "C" { #endif #if defined(STR_EXPORTS) #define STR_DLL DLLEXPORT #elif defined(STR_IMPORTS) #define STR_DLL DLLIMPORT #else #define STR_DLL #endif STR_DLL bool_t IsSpace(int); STR_DLL bool_t IsAlpha(int); STR_DLL bool_t IsDigit(int); STR_DLL int Hex(int); STR_DLL int StrListIndex(const tchar_t* s, const tchar_t* List); STR_DLL bool_t tcsisame_ascii(const tchar_t* a,const tchar_t* b); STR_DLL int tcsicmp_ascii(const tchar_t* a,const tchar_t* b); STR_DLL int tcsnicmp_ascii(const tchar_t* a,const tchar_t* b,size_t n); STR_DLL tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In); STR_DLL int tcsicmp(const tchar_t* a,const tchar_t* b); STR_DLL int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n); STR_DLL int tcscmp(const tchar_t* a,const tchar_t* b); STR_DLL int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n); STR_DLL tchar_t* tcsupr(tchar_t* a); // only for ascii! STR_DLL tchar_t* tcslwr(tchar_t* a); // only for ascii! STR_DLL tchar_t* tcscpy_s(tchar_t* Out,size_t OutLen,const tchar_t* In); STR_DLL tchar_t* tcsncpy_s(tchar_t* Out,size_t OutLen,const tchar_t* In,size_t n); STR_DLL tchar_t* tcscat_s(tchar_t* Out,size_t OutLen,const tchar_t* In); STR_DLL tchar_t* tcsncat_s(tchar_t* Out,size_t OutLen,const tchar_t* In,size_t n); STR_DLL int stscanf(const tchar_t* In, const tchar_t* Mask, ...); STR_DLL int stscanf_s(const tchar_t* In, size_t *InLen, const tchar_t* Mask, ...); STR_DLL void stprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask, ...); STR_DLL void stcatprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask, ...); STR_DLL void vstprintf_s(tchar_t* Out,size_t OutLen,const tchar_t* Mask,va_list Arg); STR_DLL tchar_t* tcsreplace(tchar_t* Out,size_t OutLen, const tchar_t *Src, const tchar_t *Dst); STR_DLL tchar_t* tcsreplacechar(tchar_t *ts, tchar_t From, tchar_t To); static INLINE tchar_t* tcsclr_s(tchar_t *ts, size_t len) { if (ts && len) *ts = 0; return ts; } STR_DLL size_t utf16len(const utf16_t *); #ifndef stricmp #if defined(TARGET_WIN) #define stricmp(x,y) _stricmp(x,y) #elif defined(TARGET_PALMOS) #define stricmp(x,y) tcsicmp(x,y) #else #define stricmp(x,y) strcasecmp(x,y) #endif #endif #ifdef TARGET_SYMBIAN STR_DLL int wcsncmp(const tchar_t *,const tchar_t *,size_t); STR_DLL tchar_t* wcschr(const tchar_t *, tchar_t); STR_DLL tchar_t* wcsrchr(const tchar_t *, tchar_t); STR_DLL tchar_t* wcsstr(const tchar_t*,const tchar_t*); #endif STR_DLL size_t tcsbytes(const tchar_t*); #ifdef __cplusplus } #endif #endif bcmatroska2-5.3.101/corec/corec/str/str.proj000066400000000000000000000004371462133141200205740ustar00rootroot00000000000000GROUP str { USE corec SOURCE str.c SOURCE(TARGET_WIN) str_win32.c SOURCE(TARGET_LINUX || TARGET_ANDROID) str_linux.c SOURCE(TARGET_PALMOS) str_palmos.c SOURCE(TARGET_SYMBIAN) str_symbian.cpp SOURCE(TARGET_OSX) str_osx.c SOURCE(TARGET_PS2SDK) str_utf8.c HEADER str.h } bcmatroska2-5.3.101/corec/corec/str/str_linux.c000066400000000000000000000043641462133141200212660ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #include int tcscmp(const tchar_t* a,const tchar_t* b) { return strcmp(a, b); } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { return strncmp(a, b, n); } int tcsicmp(const tchar_t* a,const tchar_t* b) { return strcasecmp(a, b); } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { return strncasecmp(a, b, n); } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { if (OutLen) { tcscpy_s(Out,OutLen,In); tcsupr(Out); //todo: doesn't support multibyte } return Out; } bcmatroska2-5.3.101/corec/corec/str/str_osx.c000066400000000000000000000051041462133141200207310ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #if defined(TARGET_OSX) #include int tcscmp(const tchar_t* a,const tchar_t* b) { #ifdef UNICODE return wcscmp(a,b); #else return strcmp(a, b); #endif } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { #ifdef UNICODE return wcsncmp(a,b,n); #else return strncmp(a, b, n); #endif } int tcsicmp(const tchar_t* a,const tchar_t* b) { #ifdef UNICODE fprintf(stderr, "Not supported yet: %s\n", __FUNCTION__); return 0; #else return strcasecmp(a, b); #endif } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { #ifdef UNICODE fprintf(stderr, "Not supported yet: %s\n", __FUNCTION__); return 0; #else return strncasecmp(a, b, n); #endif } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { if (OutLen) { tcscpy_s(Out,OutLen,In); tcsupr(Out); //TODO: doesn't support multibyte } return Out; } #endif bcmatroska2-5.3.101/corec/corec/str/str_palmos.c000066400000000000000000000055701462133141200214220ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #if defined(TARGET_PALMOS) #include int tcsicmp(const tchar_t* a,const tchar_t* b) { UInt16 na = (UInt16)tcslen(a); UInt16 nb = (UInt16)tcslen(b); return TxtCaselessCompare(a,na,&na,b,nb,&nb); } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { UInt16 na = (UInt16)(min(tcslen(a),n)); UInt16 nb = (UInt16)(min(tcslen(b),n)); return TxtCaselessCompare(a,na,&na,b,nb,&nb); } int tcscmp(const tchar_t* a,const tchar_t* b) { UInt16 na = (UInt16)tcslen(a); UInt16 nb = (UInt16)tcslen(b); return TxtCompare(a,na,&na,b,nb,&nb); } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { UInt16 na = (UInt16)(min(tcslen(a),n)); UInt16 nb = (UInt16)(min(tcslen(b),n)); return TxtCompare(a,na,&na,b,nb,&nb); } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { if (OutLen) { UInt16 n = (UInt16)(OutLen-1); if (TxtTransliterate(In,(UInt16)tcslen(In),Out,&n,translitOpUpperCase) == errNone) { Out[min(n,OutLen-1)]=0; return Out; } // fallback for (;*In && OutLen>1;++In,++Out,--OutLen) *Out = (tchar_t)toupper(*In); *Out = 0; } return Out; } #endif bcmatroska2-5.3.101/corec/corec/str/str_symbian.cpp000066400000000000000000000062551462133141200221320ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #if defined(TARGET_SYMBIAN) #undef T #undef NULL #include tchar_t* wcsstr(const tchar_t* s,const tchar_t* p) { size_t sn = wcslen(s); size_t pn = wcslen(p); for (;sn>=pn;++s,--sn) if (memcmp(s,p,pn*sizeof(tchar_t))==0) return (tchar_t*)s; return NULL; } tchar_t* wcschr(const tchar_t *p, tchar_t i) { for (;*p;++p) if (*p == i) return (tchar_t*)p; return NULL; } tchar_t* wcsrchr(const tchar_t *p, tchar_t i) { int n; for (n=wcslen(p);--n>=0;) if (p[n] == i) return (tchar_t*)(p+n); return NULL; } int tcsicmp(const tchar_t* a,const tchar_t* b) { TPtrC _a((TText*)a); TPtrC _b((TText*)b); return _a.CompareF(_b); } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { size_t na = tcslen(a); size_t nb = tcslen(b); TPtrC _a((TText*)a,min(na,n)); TPtrC _b((TText*)b,min(nb,n)); return _a.CompareF(_b); } int tcscmp(const tchar_t* a,const tchar_t* b) { TPtrC _a((TText*)a); TPtrC _b((TText*)b); return _a.Compare(_b); } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { size_t na = tcslen(a); size_t nb = tcslen(b); TPtrC _a((TText*)a,min(na,n)); TPtrC _b((TText*)b,min(nb,n)); return _a.Compare(_b); } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { if (OutLen) { TPtr _Out((TText*)Out,OutLen-1); TPtrC _In((TText*)In,tcslen(In)); _Out.CopyUC(_In); Out[_Out.Length()]=0; } return Out; } #endif bcmatroska2-5.3.101/corec/corec/str/str_utf8.c000066400000000000000000000271571462133141200210220ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" static const uint16_t utf_sort_en[] = { 0x0000,0x0020,0x0030,0x0040,0x0050,0x0060,0x0070,0x0080,0x0090,0x05e0,0x05f0,0x0600,0x0610,0x0620,0x00a0,0x00b0, 0x00c0,0x00d0,0x00e0,0x00f0,0x0100,0x0110,0x0120,0x0130,0x0140,0x0150,0x0160,0x0170,0x0180,0x0190,0x01a0,0x01b0, 0x05c0,0x0630,0x0640,0x0650,0x0660,0x0670,0x0680,0x03d0,0x0690,0x06a0,0x06b0,0x09c0,0x06c0,0x03e0,0x06d0,0x06e0, 0x0b80,0x0bc0,0x0be0,0x0c00,0x0c20,0x0c30,0x0c40,0x0c50,0x0c60,0x0c70,0x06f0,0x0700,0x09d0,0x09e0,0x09f0,0x0710, 0x0720,0x0c81,0x0d41,0x0d51,0x0d91,0x0dd1,0x0e61,0x0e81,0x0eb1,0x0ec1,0x0f51,0x0f61,0x0f81,0x0fd1,0x0fe1,0x1041, 0x10f1,0x1101,0x1111,0x1151,0x11a1,0x11f1,0x1281,0x1291,0x12a1,0x12b1,0x12e1,0x0730,0x0740,0x0750,0x0760,0x0780, 0x0790,0x0c80,0x0d40,0x0d50,0x0d90,0x0dd0,0x0e60,0x0e80,0x0eb0,0x0ec0,0x0f50,0x0f60,0x0f80,0x0fd0,0x0fe0,0x1040, 0x10f0,0x1100,0x1110,0x1150,0x11a0,0x11f0,0x1280,0x1290,0x12a0,0x12b0,0x12e0,0x07a0,0x07b0,0x07c0,0x07d0,0x01c0, 0x01d0,0x01e0,0x01f0,0x0200,0x0210,0x0220,0x0230,0x0240,0x0250,0x0260,0x0270,0x0280,0x0290,0x02a0,0x02b0,0x02c0, 0x02d0,0x02e0,0x02f0,0x0300,0x0310,0x0320,0x0330,0x0340,0x0350,0x0360,0x0370,0x0380,0x0390,0x03a0,0x03b0,0x03c0, 0x05d0,0x07e0,0x0a50,0x0a60,0x0a70,0x0a80,0x07f0,0x0a90,0x0800,0x0aa0,0x0c90,0x0a10,0x0ab0,0x03f0,0x0ac0,0x0810, 0x0ad0,0x0a00,0x0bf0,0x0c10,0x0820,0x0ae0,0x0af0,0x0b00,0x0830,0x0bd0,0x1050,0x0a20,0x0b90,0x0ba0,0x0bb0,0x0840, 0x0cb1,0x0ca1,0x0cc1,0x0d01,0x0cd1,0x0d11,0x0d31,0x0d81,0x0df1,0x0de1,0x0e11,0x0e21,0x0ef1,0x0ee1,0x0f11,0x0f21, 0x0dc1,0x1011,0x1071,0x1061,0x1081,0x10b1,0x1091,0x0a30,0x10d1,0x1211,0x1201,0x1221,0x1231,0x12c1,0x11d1,0x1190, 0x0cb0,0x0ca0,0x0cc0,0x0d00,0x0cd0,0x0d10,0x0d30,0x0d80,0x0df0,0x0de0,0x0e10,0x0e20,0x0ef0,0x0ee0,0x0f10,0x0f20, 0x0dc0,0x1010,0x1070,0x1060,0x1080,0x10b0,0x1090,0x0a40,0x10d0,0x1210,0x1200,0x1220,0x1230,0x12c0,0x11d0,0x12d0, 0x0100,0x0cf1,0x0101,0x0cf0,0x0102,0x0ce1,0x0103,0x0ce0,0x0104,0x0d21,0x0105,0x0d20,0x0106,0x0d61,0x0107,0x0d60, 0x010c,0x0d71,0x010d,0x0d70,0x010e,0x0da1,0x010f,0x0da0,0x0110,0x0db1,0x0111,0x0db0,0x0112,0x0e41,0x0113,0x0e40, 0x0116,0x0e01,0x0117,0x0e00,0x0118,0x0e51,0x0119,0x0e50,0x011a,0x0e31,0x011b,0x0e30,0x011e,0x0e91,0x011f,0x0e90, 0x0122,0x0ea1,0x0123,0x0ea0,0x012a,0x0f31,0x012b,0x0f30,0x012e,0x0f41,0x012f,0x0f40,0x0130,0x0f00,0x0131,0x0ed0, 0x0136,0x0f71,0x0137,0x0f70,0x0139,0x0f91,0x013a,0x0f90,0x013b,0x0fb1,0x013c,0x0fb0,0x013d,0x0fa1,0x013e,0x0fa0, 0x0141,0x0fc1,0x0142,0x0fc0,0x0143,0x0ff1,0x0144,0x0ff0,0x0145,0x1021,0x0146,0x1020,0x0147,0x1001,0x0148,0x1000, 0x014c,0x10a1,0x014d,0x10a0,0x0150,0x10c1,0x0151,0x10c0,0x0152,0x10e1,0x0153,0x10e0,0x0154,0x1121,0x0155,0x1120, 0x0156,0x1141,0x0157,0x1140,0x0158,0x1131,0x0159,0x1130,0x015a,0x1161,0x015b,0x1160,0x015e,0x1181,0x015f,0x1180, 0x0160,0x1171,0x0161,0x1170,0x0162,0x11c1,0x0163,0x11c0,0x0164,0x11b1,0x0165,0x11b0,0x016a,0x1241,0x016b,0x1240, 0x016e,0x1251,0x016f,0x1250,0x0170,0x1271,0x0171,0x1270,0x0172,0x1261,0x0173,0x1260,0x0178,0x12d1,0x0179,0x12f1, 0x017a,0x12f0,0x017b,0x1301,0x017c,0x1300,0x017d,0x1311,0x017e,0x1310,0x0192,0x0e70,0x02c6,0x0770,0x02c7,0x0850, 0x02d8,0x0860,0x02d9,0x0870,0x02db,0x0880,0x02dc,0x0890,0x02dd,0x08a0,0x0384,0x08b0,0x0385,0x08c0,0x0386,0x1331, 0x0388,0x1381,0x0389,0x13b1,0x038a,0x13e1,0x038c,0x1471,0x038e,0x14d1,0x038f,0x1541,0x0390,0x1400,0x0391,0x1321, 0x0392,0x1341,0x0393,0x1351,0x0394,0x1361,0x0395,0x1371,0x0396,0x1391,0x0397,0x13a1,0x0398,0x13c1,0x0399,0x13d1, 0x039a,0x1411,0x039b,0x1421,0x039c,0x1431,0x039d,0x1441,0x039e,0x1451,0x039f,0x1461,0x03a0,0x1481,0x03a1,0x1491, 0x03a3,0x14a2,0x03a4,0x14b1,0x03a5,0x14c1,0x03a6,0x1501,0x03a7,0x1511,0x03a8,0x1521,0x03a9,0x1531,0x03aa,0x13f1, 0x03ab,0x14e1,0x03ac,0x1330,0x03ad,0x1380,0x03ae,0x13b0,0x03af,0x13e0,0x03b0,0x14f0,0x03b1,0x1320,0x03b2,0x1340, 0x03b3,0x1350,0x03b4,0x1360,0x03b5,0x1370,0x03b6,0x1390,0x03b7,0x13a0,0x03b8,0x13c0,0x03b9,0x13d0,0x03ba,0x1410, 0x03bb,0x1420,0x03bc,0x1430,0x03bd,0x1440,0x03be,0x1450,0x03bf,0x1460,0x03c0,0x1480,0x03c1,0x1490,0x03c2,0x14a1, 0x03c3,0x14a0,0x03c4,0x14b0,0x03c5,0x14c0,0x03c6,0x1500,0x03c7,0x1510,0x03c8,0x1520,0x03c9,0x1530,0x03ca,0x13f0, 0x03cb,0x14e0,0x03cc,0x1470,0x03cd,0x14d0,0x03ce,0x1540,0x0401,0x15e1,0x0402,0x15c1,0x0403,0x15a1,0x0404,0x15f1, 0x0405,0x1621,0x0406,0x1641,0x0407,0x1651,0x0408,0x1671,0x0409,0x16b1,0x040a,0x16e1,0x040b,0x1741,0x040c,0x1691, 0x040e,0x1761,0x040f,0x17b1,0x0410,0x1551,0x0411,0x1561,0x0412,0x1571,0x0413,0x1581,0x0414,0x15b1,0x0415,0x15d1, 0x0416,0x1601,0x0417,0x1611,0x0418,0x1631,0x0419,0x1661,0x041a,0x1681,0x041b,0x16a1,0x041c,0x16c1,0x041d,0x16d1, 0x041e,0x16f1,0x041f,0x1701,0x0420,0x1711,0x0421,0x1721,0x0422,0x1731,0x0423,0x1751,0x0424,0x1771,0x0425,0x1781, 0x0426,0x1791,0x0427,0x17a1,0x0428,0x17c1,0x0429,0x17d1,0x042a,0x17e1,0x042b,0x17f1,0x042c,0x1801,0x042d,0x1811, 0x042e,0x1821,0x042f,0x1831,0x0430,0x1550,0x0431,0x1560,0x0432,0x1570,0x0433,0x1580,0x0434,0x15b0,0x0435,0x15d0, 0x0436,0x1600,0x0437,0x1610,0x0438,0x1630,0x0439,0x1660,0x043a,0x1680,0x043b,0x16a0,0x043c,0x16c0,0x043d,0x16d0, 0x043e,0x16f0,0x043f,0x1700,0x0440,0x1710,0x0441,0x1720,0x0442,0x1730,0x0443,0x1750,0x0444,0x1770,0x0445,0x1780, 0x0446,0x1790,0x0447,0x17a0,0x0448,0x17c0,0x0449,0x17d0,0x044a,0x17e0,0x044b,0x17f0,0x044c,0x1800,0x044d,0x1810, 0x044e,0x1820,0x044f,0x1830,0x0451,0x15e0,0x0452,0x15c0,0x0453,0x15a0,0x0454,0x15f0,0x0455,0x1620,0x0456,0x1640, 0x0457,0x1650,0x0458,0x1670,0x0459,0x16b0,0x045a,0x16e0,0x045b,0x1740,0x045c,0x1690,0x045e,0x1760,0x045f,0x17b0, 0x0490,0x1591,0x0491,0x1590,0x05b0,0x04b0,0x05b1,0x04c0,0x05b2,0x04d0,0x05b3,0x04e0,0x05b4,0x04f0,0x05b5,0x0500, 0x05b6,0x0510,0x05b7,0x0520,0x05b8,0x0530,0x05b9,0x0540,0x05ba,0x0010,0x05bb,0x0550,0x05bc,0x0560,0x05bd,0x0570, 0x05be,0x08d0,0x05bf,0x0580,0x05c0,0x0590,0x05c1,0x05a0,0x05c2,0x05b0,0x05c3,0x08e0,0x05d0,0x1840,0x05d1,0x1850, 0x05d2,0x1860,0x05d3,0x1870,0x05d4,0x1880,0x05d5,0x1890,0x05d6,0x18c0,0x05d7,0x18d0,0x05d8,0x18e0,0x05d9,0x18f0, 0x05da,0x1910,0x05db,0x1911,0x05dc,0x1920,0x05dd,0x1930,0x05de,0x1931,0x05df,0x1940,0x05e0,0x1941,0x05e1,0x1950, 0x05e2,0x1960,0x05e3,0x1970,0x05e4,0x1971,0x05e5,0x1980,0x05e6,0x1981,0x05e7,0x1990,0x05e8,0x19a0,0x05e9,0x19b0, 0x05ea,0x19c0,0x05f0,0x18a0,0x05f1,0x18b0,0x05f2,0x1900,0x05f3,0x08f0,0x05f4,0x0900,0x060c,0x0910,0x061b,0x0920, 0x061f,0x0930,0x0621,0x19d0,0x0622,0x1a10,0x0623,0x1a20,0x0624,0x19e0,0x0625,0x1a30,0x0626,0x19f0,0x0627,0x1a00, 0x0628,0x1a40,0x0629,0x1a60,0x062a,0x1a61,0x062b,0x1a70,0x062c,0x1a80,0x062d,0x1aa0,0x062e,0x1ab0,0x062f,0x1ac0, 0x0630,0x1ad0,0x0631,0x1ae0,0x0632,0x1af0,0x0633,0x1b10,0x0634,0x1b20,0x0635,0x1b30,0x0636,0x1b40,0x0637,0x1b50, 0x0638,0x1b60,0x0639,0x1b70,0x063a,0x1b80,0x0640,0x0015,0x0641,0x1b90,0x0642,0x1ba0,0x0643,0x1bb0,0x0644,0x1be0, 0x0645,0x1bf0,0x0646,0x1c00,0x0647,0x1c10,0x0648,0x1c20,0x0649,0x1c30,0x064a,0x1c40,0x064b,0x0430,0x064c,0x0440, 0x064d,0x0450,0x064e,0x0460,0x064f,0x0470,0x0650,0x0480,0x0651,0x04a0,0x0652,0x0490,0x0679,0x1c50,0x067e,0x1a50, 0x0686,0x1a90,0x0688,0x1c60,0x0691,0x1c70,0x0698,0x1b00,0x06a9,0x1bc0,0x06af,0x1bd0,0x06ba,0x1c80,0x06be,0x1c90, 0x06c1,0x1ca0,0x06d2,0x1cb0,0x200c,0x0013,0x200d,0x0014,0x200e,0x0011,0x200f,0x0012,0x2013,0x0400,0x2014,0x0410, 0x2015,0x0420,0x2018,0x0940,0x2019,0x0950,0x201a,0x0960,0x201c,0x0970,0x201d,0x0980,0x201e,0x0990,0x2020,0x0b10, 0x2021,0x0b20,0x2022,0x0b30,0x2026,0x0b40,0x2030,0x0b50,0x2039,0x09a0,0x203a,0x09b0,0x20aa,0x0b60,0x20ac,0x0b70, 0x2116,0x1030,0x2122,0x11e0,0xf88d,0x1cc0,0xf88e,0x1cd0,0xf88f,0x1ce0,0xf890,0x1cf0,0xf891,0x1d00,0xf892,0x1d10, 0xf893,0x1d20,0xf894,0x1d30,0xf895,0x1d40,0xf896,0x1d50,0xf8f9,0x1d60,0xf8fa,0x1d70,0xf8fb,0x1d80,0xf8fc,0x1d90, 0xf8fd,0x1da0 }; static NOINLINE uint_fast32_t sortvalue(const tchar_t** InPtr) { uint_fast32_t ch; const uint8_t* In=(const uint8_t*)*InPtr; if ((In[0]&0x80)==0) // most of the time { ++(*InPtr); return utf_sort_en[In[0]]; } if ((In[0]&0xe0)==0xc0 && (In[1]&0xc0)==0x80) { ch=((In[0]&0x1f)<<6)+(In[1]&0x3f); In+=2; } else if ((In[0]&0xf0)==0xe0 && (In[1]&0xc0)==0x80 && (In[2]&0xc0)==0x80) { ch=((In[0]&0x0f)<<12)+((In[1]&0x3f)<<6)+(In[2]&0x3f); In+=3; } else if ((In[0]&0xf8)==0xf0 && (In[1]&0xc0)==0x80 && (In[2]&0xc0)==0x80 && (In[3]&0xc0)==0x80) { ch=((In[0]&0x07)<<18)+((In[1]&0x3f)<<12)+((In[2]&0x3f)<<6)+(In[3]&0x3f); In+=4; } else { ch=In[0]; ++In; } *InPtr=(const tchar_t*)In; if (ch<0x100) return utf_sort_en[ch]; else { intptr_t Mid; intptr_t Lower = 128; intptr_t Upper = sizeof(utf_sort_en)/(sizeof(uint16_t)*2)-1; while (Upper >= Lower) { Mid = (Upper + Lower) >> 1; if (utf_sort_en[Mid*2]>ch) Upper = Mid-1; else if (utf_sort_en[Mid*2]vb)?1:-1; } while (va); return 0; } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { uint_fast32_t va,vb; do { if (!n) break; --n; va=sortvalue(&a); vb=sortvalue(&b); if (va!=vb) return (va>vb)?1:-1; } while (va); return 0; } int tcsicmp(const tchar_t* a,const tchar_t* b) { uint_fast32_t va,vb; do { va=sortvalue(&a) & ~15; vb=sortvalue(&b) & ~15; if (va!=vb) return (va>vb)?1:-1; } while (va); return 0; } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { uint_fast32_t va,vb; do { if (!n) break; --n; va=sortvalue(&a) & ~15; vb=sortvalue(&b) & ~15; if (va!=vb) return (va>vb)?1:-1; } while (va); return 0; } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { if (OutLen) { tcscpy_s(Out,OutLen,In); tcsupr(Out); //todo: doesn't support multibyte } return Out; } bcmatroska2-5.3.101/corec/corec/str/str_win32.c000066400000000000000000000107311462133141200210640ustar00rootroot00000000000000/***************************************************************************** * * Copyright (c) 2008-2010, CoreCodec, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CoreCodec, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CoreCodec, Inc. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CoreCodec, Inc. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "str.h" #if defined(TARGET_WIN) #ifdef _MSC_VER #define wcsicmp _wcsicmp #define wcsnicmp _wcsnicmp #endif #ifndef STRICT #define STRICT #endif #define WIN32_LEAN_AND_MEAN #include #if defined(__MINGW32__) || !defined(WINAPI_FAMILY_PARTITION) || !defined(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_FAMILY_PARTITION) #if defined(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define WINDOWS_DESKTOP 1 #elif defined(WINAPI_PARTITION_PHONE_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #define WINDOWS_PHONE 1 #elif defined(WINAPI_PARTITION_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define WINDOWS_UNIVERSAL 1 #endif #endif int tcsicmp(const tchar_t* a,const tchar_t* b) { #ifndef WINDOWS_DESKTOP int i = CompareStringEx(LOCALE_NAME_USER_DEFAULT, NORM_IGNORECASE, a, -1, b, -1, NULL, NULL, 0); #else int i = CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,a,-1,b,-1); #endif if (i) return i-CSTR_EQUAL; // fallback #ifdef UNICODE return wcsicmp(a,b); #else return stricmp(a,b); #endif } int tcsnicmp(const tchar_t* a,const tchar_t* b,size_t n) { #ifndef WINDOWS_DESKTOP int i = CompareStringEx(LOCALE_NAME_USER_DEFAULT, NORM_IGNORECASE, a, min(tcslen(a), n), b, min(tcslen(b), n), NULL, NULL, 0); #else int i = CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,a,min(tcslen(a),n),b,min(tcslen(b),n)); #endif if (i) return i-CSTR_EQUAL; // fallback #ifdef UNICODE return wcsnicmp(a,b,n); #else return strnicmp(a,b,n); #endif } int tcscmp(const tchar_t* a,const tchar_t* b) { #ifndef WINDOWS_DESKTOP int i = CompareStringEx(LOCALE_NAME_USER_DEFAULT, 0, a, -1, b, -1, NULL, NULL, 0); #else int i = CompareString(LOCALE_USER_DEFAULT,0,a,-1,b,-1); #endif if (i) return i-CSTR_EQUAL; // fallback #ifdef UNICODE return wcscmp(a,b); #else return strcmp(a,b); #endif } int tcsncmp(const tchar_t* a,const tchar_t* b,size_t n) { #ifndef WINDOWS_DESKTOP int i = CompareStringEx(LOCALE_NAME_USER_DEFAULT, 0, a, min(tcslen(a), n), b, min(tcslen(b), n), NULL, NULL, 0); #else int i = CompareString(LOCALE_USER_DEFAULT,0,a,min(tcslen(a),n),b,min(tcslen(b),n)); #endif if (i) return i-CSTR_EQUAL; // fallback #ifdef UNICODE return wcsncmp(a,b,n); #else return strncmp(a,b,n); #endif } tchar_t* TcsToUpper(tchar_t* Out,size_t OutLen,const tchar_t* In) { #ifndef WINDOWS_DESKTOP if (LCMapStringEx(LOCALE_NAME_USER_DEFAULT, LCMAP_UPPERCASE, In, -1, Out, OutLen, NULL, NULL, 0)) #else if (LCMapString(LOCALE_USER_DEFAULT,LCMAP_UPPERCASE,In,-1,Out,OutLen)) #endif return Out; // fallback if (OutLen) { for (;*In && OutLen>1;++In,++Out,--OutLen) *Out = (tchar_t)toupper(*In); *Out = 0; } return Out; } #endif bcmatroska2-5.3.101/corec/default_config.h000066400000000000000000000002431462133141200203020ustar00rootroot00000000000000#define COREMAKE_STATIC //#define COREMAKE_UNICODE #define COREMAKE_CONFIG_HELPER //#define CONFIG_MULTITHREAD #define CONFIG_DEBUGCHECKS //#define CONFIG_SAFE_C bcmatroska2-5.3.101/corec/tests/000077500000000000000000000000001462133141200163235ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tests/file_test.c000066400000000000000000000003001462133141200204360ustar00rootroot00000000000000#include "corec/helpers/file/file.h" int main(int argc,char** argv) { nodecontext Context; NodeContext_Init(&Context,NULL,NULL,NULL); NodeContext_Done(&Context); return 0; } bcmatroska2-5.3.101/corec/tests/node_test.c000066400000000000000000000006511462133141200204550ustar00rootroot00000000000000#include "corec/node/node.h" int main(int argc,char** argv) { node* p[10000]; int i; nodecontext Context; NodeContext_Init(&Context,NULL,NULL,NULL); for (i=0;i<10000;++i) p[i] = NodeCreate(&Context,NODE_CLASS); for (i=0;i<1000000;++i) NodeDelete(NodeCreate(&Context,NODE_CLASS)); for (i=0;i<10000;++i) NodeDelete(p[i]); NodeContext_Done(&Context); return 0; } bcmatroska2-5.3.101/corec/tests/string_test.c000066400000000000000000000077371462133141200210520ustar00rootroot00000000000000#include "corec/str/str.h" #if defined(UNICODE) #include "corec/helpers/charconvert/charconvert.h" charconv *ToStr; charconv *FromStr; #endif #include void test_float(const char *Format, double Value) { char String[512]; tchar_t tString[512]; const tchar_t *format; char *corec; #if defined(UNICODE) tchar_t tFormat[64]; char corecString[512]; #endif sprintf(String,Format,Value); #if defined(UNICODE) CharConvTS(FromStr,tFormat,TSIZEOF(tFormat),Format); format = tFormat; #else format = Format; #endif stprintf_s(tString,TSIZEOF(tString),format,Value); #if defined(UNICODE) CharConvST(ToStr,corecString,sizeof(corecString),tString); corec = corecString; #else corec = tString; #endif printf("Format %-8s: ",Format); if (stricmp(String,corec) != 0) printf("failed '%s' != '%s'\n",String,corec); else printf("passed '%s'\n",String); } void test_integer(const char *Format, int Value) { char String[512]; tchar_t tString[512]; const tchar_t *format; char *corec; #if defined(UNICODE) tchar_t tFormat[64]; char corecString[512]; #endif sprintf(String,Format,Value); #if defined(UNICODE) CharConvTS(FromStr,tFormat,TSIZEOF(tFormat),Format); format = tFormat; #else format = Format; #endif stprintf_s(tString,TSIZEOF(tString),format,Value); #if defined(UNICODE) CharConvST(ToStr,corecString,sizeof(corecString),tString); corec = corecString; #else corec = tString; #endif printf("Format %-8s: ",Format); if (stricmp(String,corec) != 0) printf("failed '%s' != '%s'\n",String,corec); else printf("passed '%s'\n",String); } void test_ptr(const char *Format, intptr_t Value) { char String[512]; tchar_t tString[512]; const tchar_t *format; char *corec; #if defined(UNICODE) tchar_t tFormat[64]; char corecString[512]; #endif sprintf(String,Format,Value); #if defined(UNICODE) CharConvTS(FromStr,tFormat,TSIZEOF(tFormat),Format); format = tFormat; #else format = Format; #endif stprintf_s(tString,TSIZEOF(tString),format,Value); #if defined(UNICODE) CharConvST(ToStr,corecString,sizeof(corecString),tString); corec = corecString; #else corec = tString; #endif printf("Format %-8s: ",Format); if (stricmp(String,corec) != 0) printf("failed '%s' != '%s'\n",String,corec); else printf("passed '%s'\n",String); } int main(int argc,char** argv) { #if defined(UNICODE) ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); FromStr = CharConvOpen(CHARSET_DEFAULT,NULL); #endif test_ptr("%p",(intptr_t)argv); test_ptr("%p",0xA1234); test_ptr("%10p",0xA1234); test_ptr("%-10p",0xA1234); test_float("%g",100.25); test_float("%f",100.25); test_float("%f",0.25); test_float("%.014g",100.25); test_float("%14g",100.25); test_float("%15f",99.2500000000001); // fail test_float("%15g",10.2500000000001); // fail test_float("%14g",-0.25); // fail test_float("%14.4g",0.25); // fail test_float("%14.4g",0.2512345); // fail test_float("%14.0g",0.25); // fail test_float("%015.5g",0.25); // fail test_float("%.014g",1000000000.25); test_float("%03.014g",10.25); test_float("%.14f",10.250000000000005); // fail test_float("%.15f",10.250000000000005); // fail test_float("%.1f",.99); // fail test_float("%03.1f",10.25); // fail test_float("%03.1f",-10.25); // fail test_float("%03.1g",-10.25); // fail test_integer("%6d",25); test_integer("%06d",25); test_integer("%06d",-25); #if 0 // integer too long test_integer("%15d",25); test_integer("%015d",25); #endif #if 0 // length align not supported with numbers test_integer("%-6d",25); test_integer("%-15d",25); test_float("%-14g",0.25); #endif #if 0 // infinite loops ! test_float("%e",100.25); test_float("%E",100.25); #endif #if defined(UNICODE) CharConvClose(ToStr); CharConvClose(FromStr); #endif return 0; } bcmatroska2-5.3.101/corec/tests/tests.proj000066400000000000000000000005101462133141200203550ustar00rootroot00000000000000workspace corec_test { use node_test use file_test use string_test } CON node_test { USE node SOURCE node_test.c } CON string_test { USE str USE(COREMAKE_UNICODE) charconvert SOURCE string_test.c } CON file_test { USE file SOURCE file_test.c } CON parser_test { USE parser SOURCE parser_test.c } bcmatroska2-5.3.101/corec/tools/000077500000000000000000000000001462133141200163215ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/branch/000077500000000000000000000000001462133141200175565ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/branch/Makefile000066400000000000000000000001261462133141200212150ustar00rootroot00000000000000all: branch # make has all the default built-ins to build this for the current system bcmatroska2-5.3.101/corec/tools/branch/branch.c000066400000000000000000000323711462133141200211650ustar00rootroot00000000000000/* Copyright (c) 2006-2010, CoreCodec, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CoreCodec, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #define MAX_REDIRECT 1024 #define MAX_HEADER 4096 #ifndef MAX_PATH #define MAX_PATH 1024 #endif #if !defined(_MSC_VER) && !defined(__MINGW32__) # ifndef strcmpi # define strcmpi strcasecmp # endif # ifndef stricmp # define stricmp strcasecmp # endif # ifndef strncmpi # define strncmpi strncasecmp # endif # ifndef strnicmp # define strnicmp strncasecmp # endif # define make_dir(x) mkdir(x,S_IRWXU) # define tmpnam_safe(x) tmpnam(x) #else static const char *tmpnam_safe(char *str) { char *res = tmpnam(str); if (res && res[0] == '\\') ++res; return res; } # define make_dir(x) mkdir(x) #endif int verbose = 0; #ifdef _WIN32 #include #include #ifndef _INTPTR_T_DEFINED typedef signed int intptr_t; #define _INTPTR_T_DEFINED #endif struct dirent { char d_name[MAX_PATH]; }; typedef struct DIR { intptr_t h; int first; struct _finddata_t file; struct dirent entry; } DIR; DIR* opendir(const char* name) { DIR* p = malloc(sizeof(DIR)); if (p) { sprintf(p->entry.d_name,"%s\\*",name); p->h = _findfirst(p->entry.d_name,&p->file); p->first = 1; if (p->h == -1) { free(p); p = NULL; } } return p; } struct dirent* readdir(DIR* p) { if (p->first || _findnext(p->h,&p->file)==0) { p->first = 0; strcpy(p->entry.d_name,p->file.name); return &p->entry; } return NULL; } void closedir(DIR* p) { _findclose(p->h); free(p); } #else #include #include #include #endif void trim(char* s) { while (s[0] && isspace(s[strlen(s)-1])) s[strlen(s)-1]=0; } void addendpath(char* path) { if (path[0] && path[strlen(path)-1]!='/') strcat(path,"/"); } void delendpath(char* path) { if (path[0] && path[strlen(path)-1]=='/') path[strlen(path)-1] = 0; } void create_missing_dirs(const char *path) { size_t strpos = 0, strpos_i; char new_path[MAX_PATH]; char orig_path[MAX_PATH]; int ret; struct stat dir_stats; getcwd(orig_path, sizeof(new_path)); for (;;) { strpos_i = strcspn(&path[strpos], "/\\"); if (strpos_i == strlen(&path[strpos])) break; strpos += strpos_i+1; strcpy(new_path,orig_path); strcat(new_path,"/"); strncat(new_path, path, strpos-1); if (stat(new_path, &dir_stats) == 0) { if ((dir_stats.st_mode & S_IFDIR) != S_IFDIR) { printf("%s is not a directory\n",new_path); exit(1); } } else { ret = make_dir(new_path); if (ret != 0 && ret != EEXIST) { printf("can't create directory %s\n",new_path); exit(1); } } } } static char header[3][MAX_HEADER]; static char header_magic[MAX_HEADER]; static size_t redirect_count; static char redirect_src[MAX_REDIRECT][MAX_PATH]; static char redirect_dst[MAX_REDIRECT][MAX_PATH]; static char redirect_process[MAX_REDIRECT][MAX_PATH]; int gethead(const char* line, int prev) { if (prev<0 && strncmp(line,"/*",2)==0) return 3; if (prev==3) { const char* s = strrchr(line,'*'); if (s && s[1]=='/') return 0; return 3; } if (strncmp(line,";*",2)==0) return 1; if (strncmp(line,"@*",2)==0) return 2; return -1; } int stristr(const char* s, const char* sub) { size_t n = strlen(sub); for (;*s;++s) if (strnicmp(s,sub,n)==0) return 1; return 0; } int preprocess(const char* srcname, const char* dstname, const char* process) { char line[MAX_HEADER]; FILE* src; FILE* dst; int head=-1; int ret=0; src = fopen(srcname,"r"); if (!src) return 0; fgets(line,sizeof(line),src); if (header[0][0]) { int i; if ((i = gethead(line,-1))>=0) { int magic=0; do { head = i; if (!fgets(line,sizeof(line),src)) break; i = gethead(line,i); if (stristr(line,header_magic)) magic = 1; } while (i>=0); if (magic) ret = 1; } } if (process[0]) ret = 1; if (!ret) { fclose(src); return 0; } dst = fopen(dstname,"w"); if (!dst) { printf("file create error (%s)!\n",dstname); exit(1); } if (head>=0) fputs(header[head],dst); for (;;) { const char* i1; const char* i2; const char* i3; char* j; for (i1=process;(i1=strchr(i1,'{'))!=NULL && (i2=strchr(i1,'|'))!=NULL && (i3=strchr(i2,'}'))!=NULL;i1=i3) { size_t n=i2-(++i1); for (j=line;*j;) if (strncmp(j,i1,n)==0) { char* k; memmove(j,j+n,strlen(j+n)+1); n=i3-(++i2); memmove(j+n,j,strlen(j)+1); memcpy(j,i2,n); for (k=j;k %s\n",srcname,dstname); stat(srcname,&s); if (header[0][0] || process[0]) { tmpname = tmpnam_safe(NULL); if (preprocess(srcname,tmpname,process)) srcname = tmpname; else tmpname = NULL; } src = fopen(srcname,"rb"); if (!src) { printf("file open error (%s)!\n",srcname); exit(1); } create_missing_dirs(dstname); dst = fopen(dstname,"wb+"); if (!dst) { printf("file create error (%s)!\n",dstname); exit(1); } for (;;) { size_t n = fread(buf,1,sizeof(buf),src); if (!n) break; fwrite(buf,1,n,dst); } fclose(src); fclose(dst); chmod(dstname,s.st_mode); if (tmpname) remove(tmpname); } int same_ch(int a, int b) { #ifdef _WIN32 return toupper(a) == toupper(b); #else return a==b; #endif } int match(const char* name, const char* mask) { if (*mask=='*') { ++mask; for (;!match(name,mask);++name) { if (*name==0) return 0; } return 1; } else { if (*mask==0) return *name==0; if (*name==0) return 0; return (mask[0]=='?' || same_ch(name[0],mask[0])) && match(name+1,mask+1); } } void refresh(const char* src, const char* dst, int force, const char* process) { DIR* dir; size_t i; if (strcmp(dst,"-")==0 || strchr(src,'*') || strchr(src,'?')) return; if (!force) for (i=0;id_name[0]!='.') { char src2[MAX_PATH]; char dst2[MAX_PATH]; strcpy(dst2,dst); strcpy(src2,src); addendpath(dst2); addendpath(src2); strcat(src2,entry->d_name); strcat(dst2,entry->d_name); refresh(src2,dst2,0,""); } } } closedir(dir); } else { if (compare(src,dst,process)) copy(src,dst,process); } } int main(int argc, char** argv) { FILE* f; char base[MAX_PATH]; char line[MAX_PATH*2]; int head=0; size_t i; if (argc<=1) { printf("usage: branch \n"); return 1; } strcpy(base,argv[1]); for (i=strlen(base);i>0;) { --i; if (base[i]=='/' || base[i]=='\\') break; base[i]=0; } memset(header,0,sizeof(header)); f = fopen(argv[1],"r"); if (!f) { printf("%s not found!\n",argv[1]); return 1; } redirect_count=0; for (;;) { char* s, *t; if (!fgets(line,sizeof(line),f)) break; if (line[0]=='#') continue; if (!head && line[0]=='/' && line[1]=='*') head = 1; if (head) { strcat(header[0],line); s = strrchr(line,'*'); if (s && s[1]=='/') { s[1]='*'; head = 0; fgets(header_magic,sizeof(header_magic),f); trim(header_magic); } line[0]=';'; strcat(header[1],line); line[0]='@'; strcat(header[2],line); } else { trim(line); strcpy(redirect_src[redirect_count],(line[0]!='/')?base:""); strcat(redirect_src[redirect_count],line); s = redirect_src[redirect_count]; s += (line[0]!='/')?strlen(base):0; while (*s && isspace(*s)) ++s; if (*s == '\"') { memmove(s,s+1,strlen(s)+1); t = strchr(s+1,'\"'); if (t) *t=0; s = t+1; } else { s = strchr(redirect_src[redirect_count],' '); } if (s) { while (*s && isspace(*s)) *(s++)=0; if (*s == '\"') { t = strchr(++s,'\"'); if (t) *t=' '; strcpy(redirect_dst[redirect_count],s); s = strchr(t+1,' '); } else { strcpy(redirect_dst[redirect_count],s); s = strchr(redirect_dst[redirect_count],' '); } redirect_process[redirect_count][0]=0; if (s) { while (*s && isspace(*s)) *(s++)=0; if (*s) strcpy(redirect_process[redirect_count],s); } ++redirect_count; } } } fclose(f); for (i=0;i bcmatroska2-5.3.101/corec/tools/coremake/000077500000000000000000000000001462133141200201075ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/Makefile000066400000000000000000000315431462133141200215550ustar00rootroot00000000000000all: coremake corerc # make has all the default built-ins to build this for the current system install: coremake corerc install -c coremake /usr/local/bin/coremake install -c corerc /usr/local/bin/corerc install -c -m 644 -D android_armv5.build /usr/local/share/coremake/android_armv5.build install -c -m 644 -D android_armv6.build /usr/local/share/coremake/android_armv6.build install -c -m 644 -D android_armv7.build /usr/local/share/coremake/android_armv7.build install -c -m 644 -D automake.build /usr/local/share/coremake/automake.build install -c -m 644 -D clean.build /usr/local/share/coremake/clean.build install -c -m 644 -D distclean.build /usr/local/share/coremake/distclean.build install -c -m 644 -D evc_arm.build /usr/local/share/coremake/evc_arm.build install -c -m 644 -D evc_arm_pocketpc.build /usr/local/share/coremake/evc_arm_pocketpc.build install -c -m 644 -D evc_arm_smartphone.build /usr/local/share/coremake/evc_arm_smartphone.build install -c -m 644 -D evc_armv4.build /usr/local/share/coremake/evc_armv4.build install -c -m 644 -D evc_armv4i.build /usr/local/share/coremake/evc_armv4i.build install -c -m 644 -D evc_armv4_pocketpc.build /usr/local/share/coremake/evc_armv4_pocketpc.build install -c -m 644 -D evc_armv4_smartphone.build /usr/local/share/coremake/evc_armv4_smartphone.build install -c -m 644 -D evc_emulator.build /usr/local/share/coremake/evc_emulator.build install -c -m 644 -D evc_mips.build /usr/local/share/coremake/evc_mips.build install -c -m 644 -D evc_mipsii.build /usr/local/share/coremake/evc_mipsii.build install -c -m 644 -D evc_sh3.build /usr/local/share/coremake/evc_sh3.build install -c -m 644 -D evc_sh4.build /usr/local/share/coremake/evc_sh4.build install -c -m 644 -D evc_x86.build /usr/local/share/coremake/evc_x86.build install -c -m 644 -D gcc_linux_arm.build /usr/local/share/coremake/gcc_linux_arm.build install -c -m 644 -D gcc_linux.build /usr/local/share/coremake/gcc_linux.build install -c -m 644 -D gcc_linux_debug.build /usr/local/share/coremake/gcc_linux_debug.build install -c -m 644 -D gcc_linux_mips.build /usr/local/share/coremake/gcc_linux_mips.build install -c -m 644 -D gcc_linux_ppc.build /usr/local/share/coremake/gcc_linux_ppc.build install -c -m 644 -D gcc_linux_qt_x86.build /usr/local/share/coremake/gcc_linux_qt_x86.build install -c -m 644 -D gcc_linux_qt_x86_debug.build /usr/local/share/coremake/gcc_linux_qt_x86_debug.build install -c -m 644 -D gcc_linux_x64.build /usr/local/share/coremake/gcc_linux_x64.build install -c -m 644 -D gcc_linux_x64_debug.build /usr/local/share/coremake/gcc_linux_x64_debug.build install -c -m 644 -D gcc_osx.build /usr/local/share/coremake/gcc_osx.build install -c -m 644 -D gcc_osx_iphone_dev.build /usr/local/share/coremake/gcc_osx_iphone_dev.build install -c -m 644 -D gcc_osx_ppc.build /usr/local/share/coremake/gcc_osx_ppc.build install -c -m 644 -D gcc_osx_x64.build /usr/local/share/coremake/gcc_osx_x64.build install -c -m 644 -D gcc_osx_x86.build /usr/local/share/coremake/gcc_osx_x86.build install -c -m 644 -D gcc_osx_x86_pic.build /usr/local/share/coremake/gcc_osx_x86_pic.build install -c -m 644 -D gcc_palmos.build /usr/local/share/coremake/gcc_palmos.build install -c -m 644 -D gcc_ps2sdk.build /usr/local/share/coremake/gcc_ps2sdk.build install -c -m 644 -D gcc_qtcore_arm.build /usr/local/share/coremake/gcc_qtcore_arm.build install -c -m 644 -D gcc_qtcore_mips.build /usr/local/share/coremake/gcc_qtcore_mips.build install -c -m 644 -D gcc_qtcore_x86.build /usr/local/share/coremake/gcc_qtcore_x86.build install -c -m 644 -D gcc_qtphone_arm.build /usr/local/share/coremake/gcc_qtphone_arm.build install -c -m 644 -D gcc_qtphone_x86.build /usr/local/share/coremake/gcc_qtphone_x86.build install -c -m 644 -D gcc_sparc32.build /usr/local/share/coremake/gcc_sparc32.build install -c -m 644 -D gcc_sparc64.build /usr/local/share/coremake/gcc_sparc64.build install -c -m 644 -D gcc_win32.build /usr/local/share/coremake/gcc_win32.build install -c -m 644 -D gcc_wince_arm.build /usr/local/share/coremake/gcc_wince_arm.build install -c -m 644 -D gcc_x_win32.build /usr/local/share/coremake/gcc_x_win32.build install -c -m 644 -D icl_2005.build /usr/local/share/coremake/icl_2005.build install -c -m 644 -D kdevelop.build /usr/local/share/coremake/kdevelop.build install -c -m 644 -D kdevelop_qtcore_arm_debug.build /usr/local/share/coremake/kdevelop_qtcore_arm_debug.build install -c -m 644 -D kdevelop_qtphone_arm.build /usr/local/share/coremake/kdevelop_qtphone_arm.build install -c -m 644 -D kdevelop_qtphone_arm_debug.build /usr/local/share/coremake/kdevelop_qtphone_arm_debug.build install -c -m 644 -D kdevelop_qtphone_x86.build /usr/local/share/coremake/kdevelop_qtphone_x86.build install -c -m 644 -D kdevelop_qtphone_x86_debug.build /usr/local/share/coremake/kdevelop_qtphone_x86_debug.build install -c -m 644 -D s60_1st.build /usr/local/share/coremake/s60_1st.build install -c -m 644 -D s60_1st_wins.build /usr/local/share/coremake/s60_1st_wins.build install -c -m 644 -D s60_2nd_fp3.build /usr/local/share/coremake/s60_2nd_fp3.build install -c -m 644 -D s60_2nd_fp3_debug.build /usr/local/share/coremake/s60_2nd_fp3_debug.build install -c -m 644 -D s60_2nd_fp3_winscw.build /usr/local/share/coremake/s60_2nd_fp3_winscw.build install -c -m 644 -D s60_3rd_fp1.build /usr/local/share/coremake/s60_3rd_fp1.build install -c -m 644 -D s60_3rd_fp1_debug.build /usr/local/share/coremake/s60_3rd_fp1_debug.build install -c -m 644 -D s60_3rd_fp1_winscw.build /usr/local/share/coremake/s60_3rd_fp1_winscw.build install -c -m 644 -D s60_3rd_mr.build /usr/local/share/coremake/s60_3rd_mr.build install -c -m 644 -D s60_3rd_mr_debug.build /usr/local/share/coremake/s60_3rd_mr_debug.build install -c -m 644 -D s60_3rd_mr_winscw.build /usr/local/share/coremake/s60_3rd_mr_winscw.build install -c -m 644 -D s60_5th.build /usr/local/share/coremake/s60_5th.build install -c -m 644 -D s60_5th_winscw.build /usr/local/share/coremake/s60_5th_winscw.build install -c -m 644 -D s80_dp2.build /usr/local/share/coremake/s80_dp2.build install -c -m 644 -D s80_dp2_wins.build /usr/local/share/coremake/s80_dp2_wins.build install -c -m 644 -D s90_7710.build /usr/local/share/coremake/s90_7710.build install -c -m 644 -D s90_7710_wins.build /usr/local/share/coremake/s90_7710_wins.build install -c -m 644 -D script.build /usr/local/share/coremake/script.build install -c -m 644 -D uiq_21.build /usr/local/share/coremake/uiq_21.build install -c -m 644 -D uiq_21_wins.build /usr/local/share/coremake/uiq_21_wins.build install -c -m 644 -D uiq_30.build /usr/local/share/coremake/uiq_30.build install -c -m 644 -D uiq_30_debug.build /usr/local/share/coremake/uiq_30_debug.build install -c -m 644 -D uiq_30_winscw.build /usr/local/share/coremake/uiq_30_winscw.build install -c -m 644 -D uiq_31.build /usr/local/share/coremake/uiq_31.build install -c -m 644 -D uiq_31_winscw.build /usr/local/share/coremake/uiq_31_winscw.build install -c -m 644 -D vc6.build /usr/local/share/coremake/vc6.build install -c -m 644 -D vc6_palmos.build /usr/local/share/coremake/vc6_palmos.build install -c -m 644 -D vs_2003.build /usr/local/share/coremake/vs_2003.build install -c -m 644 -D vs_2005.build /usr/local/share/coremake/vs_2005.build install -c -m 644 -D vs9_ce5_armv4i.build /usr/local/share/coremake/vs9_ce5_armv4i.build install -c -m 644 -D vs9_ce5_mips32_gcc.build /usr/local/share/coremake/vs9_ce5_mips32_gcc.build install -c -m 644 -D vs9_ce5_mipsii.build /usr/local/share/coremake/vs9_ce5_mipsii.build install -c -m 644 -D vs9_ce5_x86.build /usr/local/share/coremake/vs9_ce5_x86.build install -c -m 644 -D vs9_express.build /usr/local/share/coremake/vs9_express.build install -c -m 644 -D vs9_ic_x64.build /usr/local/share/coremake/vs9_ic_x64.build install -c -m 644 -D vs9_ic_x86.build /usr/local/share/coremake/vs9_ic_x86.build install -c -m 644 -D vs9_ppc2003_armv4.build /usr/local/share/coremake/vs9_ppc2003_armv4.build install -c -m 644 -D vs9_smart2003_armv4.build /usr/local/share/coremake/vs9_smart2003_armv4.build install -c -m 644 -D vs9_win32.build /usr/local/share/coremake/vs9_win32.build install -c -m 644 -D vs9_wm5_armv4i.build /usr/local/share/coremake/vs9_wm5_armv4i.build install -c -m 644 -D vs9_wm5s_armv4i.build /usr/local/share/coremake/vs9_wm5s_armv4i.build install -c -m 644 -D vs9_wm6p_armv4i.build /usr/local/share/coremake/vs9_wm6p_armv4i.build install -c -m 644 -D vs9_x64.build /usr/local/share/coremake/vs9_x64.build install -c -m 644 -D vs_ce5_armv4i.build /usr/local/share/coremake/vs_ce5_armv4i.build install -c -m 644 -D vs_ce5_mips32.build /usr/local/share/coremake/vs_ce5_mips32.build install -c -m 644 -D vs_ce5_mips32_gcc.build /usr/local/share/coremake/vs_ce5_mips32_gcc.build install -c -m 644 -D vs_ce5_mipsii.build /usr/local/share/coremake/vs_ce5_mipsii.build install -c -m 644 -D vs_ce5_x86.build /usr/local/share/coremake/vs_ce5_x86.build install -c -m 644 -D vs_ce6_krs_armv4i.build /usr/local/share/coremake/vs_ce6_krs_armv4i.build install -c -m 644 -D vs_express.build /usr/local/share/coremake/vs_express.build install -c -m 644 -D vs_palmos.build /usr/local/share/coremake/vs_palmos.build install -c -m 644 -D vs_ppc2003_armv4.build /usr/local/share/coremake/vs_ppc2003_armv4.build install -c -m 644 -D vs_s60_3rd_mr.build /usr/local/share/coremake/vs_s60_3rd_mr.build install -c -m 644 -D vs_smart2003_armv4.build /usr/local/share/coremake/vs_smart2003_armv4.build install -c -m 644 -D vs_wm5_armv4i.build /usr/local/share/coremake/vs_wm5_armv4i.build install -c -m 644 -D vs_wm5s_armv4i.build /usr/local/share/coremake/vs_wm5s_armv4i.build install -c -m 644 -D vs_wm6p_armv4i.build /usr/local/share/coremake/vs_wm6p_armv4i.build install -c -m 644 -D vs_wm6s_armv4i.build /usr/local/share/coremake/vs_wm6s_armv4i.build install -c -m 644 -D vs_x64.build /usr/local/share/coremake/vs_x64.build install -c -m 644 -D xcode24_universal.build /usr/local/share/coremake/xcode24_universal.build install -c -m 644 -D xcode.build /usr/local/share/coremake/xcode.build install -c -m 644 -D xcode_ios4.build /usr/local/share/coremake/xcode_ios4.build install -c -m 644 -D xcode_ios4_simu.build /usr/local/share/coremake/xcode_ios4_simu.build install -c -m 644 -D xcode_iphone.build /usr/local/share/coremake/xcode_iphone.build install -c -m 644 -D xcode_iphone_dev.build /usr/local/share/coremake/xcode_iphone_dev.build install -c -m 644 -D xcode_iphone_ipad.build /usr/local/share/coremake/xcode_iphone_ipad.build install -c -m 644 -D xcode_iphone_ipad_simu.build /usr/local/share/coremake/xcode_iphone_ipad_simu.build install -c -m 644 -D xcode_iphone_simulator.build /usr/local/share/coremake/xcode_iphone_simulator.build install -c -m 644 -D xcode_iphone_uni.build /usr/local/share/coremake/xcode_iphone_uni.build install -c -m 644 -D xcode_uni64.build /usr/local/share/coremake/xcode_uni64.build install -c -m 644 -D xcode_uni.build /usr/local/share/coremake/xcode_uni.build install -c -m 644 -D xcode_x86.build /usr/local/share/coremake/xcode_x86.build install -c -m 644 -D android_arm.inc /usr/local/share/coremake/android_arm.inc install -c -m 644 -D android.inc /usr/local/share/coremake/android.inc install -c -m 644 -D android_mk.inc /usr/local/share/coremake/android_mk.inc install -c -m 644 -D automake.inc /usr/local/share/coremake/automake.inc install -c -m 644 -D carbide.inc /usr/local/share/coremake/carbide.inc install -c -m 644 -D carbide_vs.inc /usr/local/share/coremake/carbide_vs.inc install -c -m 644 -D evc.inc /usr/local/share/coremake/evc.inc install -c -m 644 -D gcc_conf.inc /usr/local/share/coremake/gcc_conf.inc install -c -m 644 -D gcc.inc /usr/local/share/coremake/gcc.inc install -c -m 644 -D gcc_mak.inc /usr/local/share/coremake/gcc_mak.inc install -c -m 644 -D gcc_osx.inc /usr/local/share/coremake/gcc_osx.inc install -c -m 644 -D gcc_qtopia.inc /usr/local/share/coremake/gcc_qtopia.inc install -c -m 644 -D kdevelop_qtopia_arm.inc /usr/local/share/coremake/kdevelop_qtopia_arm.inc install -c -m 644 -D kdevelop_qtopia_x86.inc /usr/local/share/coremake/kdevelop_qtopia_x86.inc install -c -m 644 -D osx_plist.inc /usr/local/share/coremake/osx_plist.inc install -c -m 644 -D qmake.inc /usr/local/share/coremake/qmake.inc install -c -m 644 -D qtopia_desktop.inc /usr/local/share/coremake/qtopia_desktop.inc install -c -m 644 -D qtopia_resource.inc /usr/local/share/coremake/qtopia_resource.inc install -c -m 644 -D symbian.inc /usr/local/share/coremake/symbian.inc install -c -m 644 -D symbian_pkg.inc /usr/local/share/coremake/symbian_pkg.inc install -c -m 644 -D vc6.inc /usr/local/share/coremake/vc6.inc install -c -m 644 -D vs.inc /usr/local/share/coremake/vs.inc install -c -m 644 -D vsproj.inc /usr/local/share/coremake/vsproj.inc install -c -m 644 -D vsproj-user.inc /usr/local/share/coremake/vsproj-user.inc install -c -m 644 -D wincab.inc /usr/local/share/coremake/wincab.inc install -c -m 644 -D winrc.inc /usr/local/share/coremake/winrc.inc install -c -m 644 -D xcode.inc /usr/local/share/coremake/xcode.inc bcmatroska2-5.3.101/corec/tools/coremake/android.inc000066400000000000000000000256001462133141200222250ustar00rootroot00000000000000#define TARGET_ANDROID #define COMPILER_GCC #define NO_MAKE_EXE #define NO_MAKE_EXE_JAVA #define OUTPUT_EXE %(NAME) #define OUTPUT_JAVA %(NAME).apk #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a CONFIG ANDROID_LIBC_DIR = %(§CONFIG_ANDROID_NDK)/build/platforms/android-%(CONFIG_ANDROID_VERSION)/%(ANDROID_ARCH)/usr ANDROID_GCC_DIR = %(§CONFIG_ANDROID_NDK)/build/prebuilt/%(CONFIG_ANDROID_PLATFORM)/%(ANDROID_GCC)/bin IFNDEF CONFIG_ANDROID_NDK ECHO Android NDK path not defined ! (CONFIG_ANDROID_NDK) ENDIF IFNDEF CONFIG_ANDROID_VERSION ECHO Android target version not defined ! (CONFIG_ANDROID_VERSION) ENDIF IFNDEF CONFIG_ANDROID_PLATFORM ECHO Android NDK build platform not defined ! (CONFIG_ANDROID_PLATFORM) ENDIF FOR EACH WORKSPACE FOR EACH USE IF %(TYPE)==EXE_JAVA IFDEF ANDROID_NDK_PROJ FILE %(§CONFIG_ANDROID_NDK)/apps/%(:``|§BUILDDIR)/Application.mk PRINTNL # DO NOT EDIT, FILE GENERATED BY COREMAKE PRINTNL APP_PROJECT_PATH := $(call my-dir)/%(!§OUTPUTPATH) PRINTNL APP_OPTIM := %(TARGOPTIM) MODULES = // LIBs first FOR EACH USE IF %(TYPE)==LIB ../MODULES += %(NAME) FOR EACH SOURCE FOR EACH MIME_TYPE ../../../MIME_TYPES += %(NAME) ENDFOR ENDFOR ENDIF FOR EACH USE IF %(TYPE)==LIB ../../MODULES += %(NAME) ENDIF ENDFOR ENDFOR // DLLs next FOR EACH USE IF %(TYPE)==DLL ../MODULES += %(NAME) FOR EACH SOURCE FOR EACH MIME_TYPE ../../../MIME_TYPES += %(NAME) ENDFOR ENDFOR ENDIF FOR EACH USE IF %(TYPE)==DLL ../../MODULES += %(NAME) ENDIF ENDFOR ENDFOR PRINTNL APP_MODULES := %(MODULES) PRINTNL APP_BUILD_SCRIPT := $(call my-dir)/Android.mk FILE %(§CONFIG_ANDROID_NDK)/apps/%(:``|§BUILDDIR)/Android.mk PRINTNL # DO NOT EDIT, FILE GENERATED BY COREMAKE PRINTNL LOCAL_PATH := $(call my-dir) FOR EACH USE // LIBs first IF %(TYPE)==LIB #include "android_mk.inc" ENDIF FOR EACH USE IF %(TYPE)==LIB #include "android_mk.inc" ENDIF ENDFOR // DLLs next IF %(TYPE)==DLL #include "android_mk.inc" ENDIF FOR EACH USE IF %(TYPE)==DLL #include "android_mk.inc" ENDIF ENDFOR ENDFOR FILEBIN %(¯BUILDDIR)build_ndk.sh SCRIPT PRINTNL #!/bin/sh PRINTNL PRINTNL # you can use V=1 for more traces and -B to force a rebuild PRINTNL PRINTNL (cd %(CONFIG_ANDROID_NDK); make APP=%(:``|§BUILDDIR) $1 $2 $3 $4 $5 $6) ENDIF IF %(PROJECT_VENDOR)=="" PROJECT_VENDOR = CoreCodec ENDIF IF %(PROJECT_NAME)=="" PROJECT_NAME = %(NAME) ENDIF MKDIR %(¯BUILDDIR)gen/ MKDIR %(¯BUILDDIR)res/ MKDIR %(¯BUILDDIR)res/raw/ FOR EACH INSTALL COPY %(!NAME) %(¯BUILDDIR)res/raw/%(NAME) ENDFOR FOR EACH USE FOR EACH INSTALL COPY %(!NAME) %(¯BUILDDIR)res/raw/%(NAME) ENDFOR ENDFOR IF %(ANDROID_VALUE)!="" MKDIR %(¯BUILDDIR)res/values/ FOR EACH ANDROID_VALUE COPY %(!NAME) %(¯BUILDDIR)res/values/%(NAME) ENDFOR ENDIF IF %(ICON)!="" MKDIR %(BUILDDIR)res/drawable/ COPY %(!ICON)_64x64.png %(¯BUILDDIR)res/drawable/%( PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL MKDIR %(OUTPUTPATH) FILE %(¯BUILDDIR).project PRINTNL PRINTNL PRINTNL %(NAME) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL com.android.ide.eclipse.adt.ResourceManagerBuilder PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL com.android.ide.eclipse.adt.PreCompilerBuilder PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL org.eclipse.jdt.core.javabuilder PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL com.android.ide.eclipse.adt.ApkBuilder PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL com.android.ide.eclipse.adt.AndroidNature PRINTNL org.eclipse.jdt.core.javanature PRINTNL PRINTNL PRINTNL PRINTNL src PRINTNL 2 PRINTNL %(|§PATH) PRINTNL PRINTNL PRINTNL srcgen PRINTNL 2 PRINTNL %(¯|BUILDDIR)%(§PATH) PRINTNL PRINTNL PRINTNL FILE %(¯BUILDDIR)default.properties PRINTNL # DO NOT EDIT, FILE GENERATED BY COREMAKE PRINTNL PRINTNL # Indicates whether an apk should be generated for each density. PRINTNL split.density=false PRINTNL # Project target. PRINTNL target=android-4 FILE %(¯BUILDDIR).settings/org.eclipse.jdt.core.prefs PRINTNL #Mon Jan 25 12:20:43 CET 2010 PRINTNL eclipse.preferences.version=1 PRINTNL org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 PRINTNL org.eclipse.jdt.core.compiler.compliance=1.5 PRINTNL org.eclipse.jdt.core.compiler.source=1.5 // TODO: there should be one per EXE FILE %(¯BUILDDIR)AndroidManifest.xml PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF %(MIME_TYPES)!="" FOR EACH MIME_TYPES PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR ENDIF PRINTNL FOR EACH SOURCE IF %(ACTIVITY)!="" DIRPUSH %(!PATH) PRINTNL DIRPOP ENDIF IF %(SERVICE)!="" DIRPUSH %(!PATH) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL DIRPOP ENDIF ENDFOR PRINTNL FOR EACH ANDROID_PERMISSION PRINTNL ENDFOR PRINTNL ENDIF ENDFOR ENDFOR CC = %(ANDROID_GCC_DIR)/%(ANDROID_GCC_PREFIX)gcc STRIP = %(ANDROID_GCC_DIR)/%(ANDROID_GCC_PREFIX)strip STRIPFLAGS = --strip-debug OS_INCLUDE += %(ANDROID_LIBC_DIR)/include CCFLAGS += -DANDROID SHFLAGS += %(ANDROID_LIBC_DIR)/lib/libc.so %(ANDROID_LIBC_DIR)/lib/libstdc++.so %(ANDROID_LIBC_DIR)/lib/libm.so -Wl,--no-undefined -Wl,-rpath-link=%(ANDROID_LIBC_DIR)/lib -L%(ANDROID_LIBC_DIR)/lib IF %(ANDROID_GCC_LIB)!="" SHFLAGS1 += %(ANDROID_GCC_DIR)/../lib/%(ANDROID_GCC_LIB) ENDIF #include "gcc_conf.inc" bcmatroska2-5.3.101/corec/tools/coremake/android_arm.inc000066400000000000000000000007561462133141200230710ustar00rootroot00000000000000#define TARGARCH arm #define TARGARCH_ABI arm #define TARGOPTIM release #define ARM CCFLAGS += -pipe -msoft-float -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -O2 -fomit-frame-pointer -fstrict-aliasing -funswitch-loops -finline-limit=300 -g SFLAGS += -march=armv7-a ANDROID_ABI += armeabi ANDROID_ARCH = arch-arm ANDROID_GCC_PREFIX = arm-eabi- ANDROID_GCC = arm-eabi-4.4.0 ANDROID_GCC_LIB = gcc/arm-eabi/4.4.0/libgcc.a #include "android.inc" bcmatroska2-5.3.101/corec/tools/coremake/android_armv5.build000066400000000000000000000001031462133141200236540ustar00rootroot00000000000000CCFLAGS = -march=armv5te -mtune=xscale #include "android_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/android_armv6.build000066400000000000000000000001071462133141200236610ustar00rootroot00000000000000CCFLAGS = -march=armv6 -mtune=arm1176jzf-s #include "android_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/android_armv7.build000066400000000000000000000002001462133141200236540ustar00rootroot00000000000000CCFLAGS = -march=armv7-a -mtune=cortex-a8 -mfloat-abi=softfp -mfpu=neon //ANDROID_ABI = armeabi-v7a #include "android_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/android_mk.inc000066400000000000000000000035061462133141200227150ustar00rootroot00000000000000IF %(TYPE)==DLL || %(TYPE)==LIB PRINTNL PRINTNL include $(CLEAR_VARS) PRINTNL LOCAL_MODULE := %(NAME) PRINTNL TARGET_ARCH := %(TARGARCH) PRINTNL TARGET_ARCH_ABI := %(TARGARCH_ABI) IFNDEF ARM_THUMB PRINTNL LOCAL_ARM_MODE := arm ENDIF PRINTNL LOCAL_SRC_FILES := \ FOR EACH SOURCE IF %(FOR_LAST) PRINTNL %(!NAME) ELSE PRINTNL %(!NAME) \ ENDIF ENDFOR PRINTNL DLL_DEPS = LIB_DEPS = FOR EACH USE IF %(TYPE)==DLL ../DLL_DEPS += %(NAME) ELSE ../LIB_DEPS += %(NAME) ENDIF ENDFOR IF %(DLL_DEPS)!="" PRINTNL LOCAL_SHARED_LIBRARIES := \ FOR EACH DLL_DEPS IF %(FOR_LAST) PRINTNL %(NAME) ELSE PRINTNL %(NAME) \ ENDIF ENDFOR PRINTNL ENDIF IF %(LIB_DEPS)!="" PRINTNL LOCAL_STATIC_LIBRARIES := \ FOR EACH LIB_DEPS IF %(NAME)!="" IF %(FOR_LAST) PRINTNL %(NAME) ELSE PRINTNL %(NAME) \ ENDIF ENDIF ENDFOR PRINTNL ENDIF IF %(SYSLIBS)!="" && %(TYPE)==DLL PRINTNL LOCAL_LDLIBS := \ FOR EACH SYSLIBS IF %(NAME)!="" IF %(FOR_LAST) PRINTNL -l%(NAME) ELSE PRINTNL -l%(NAME) \ ENDIF ENDIF ENDFOR PRINTNL ENDIF // the include folders are relative to the root of the NDK DIRPUSH %(!CONFIG_ANDROID_NDK) PRINTNL LOCAL_C_INCLUDES := \ FOR EACH INCLUDE PRINTNL %(!§NAME) \ ENDFOR FOR EACH CONFIG_INCLUDE IF %(FOR_LAST) PRINTNL %(!§NAME) ELSE PRINTNL %(!§NAME) \ ENDIF ENDFOR DIRPOP PRINTNL IF %(DEFINE)!="" PRINTNL LOCAL_CFLAGS := %(DEFINE:%=-D%) ENDIF IF %(TYPE)==DLL PRINTNL include $(BUILD_SHARED_LIBRARY) ELSE PRINTNL include $(BUILD_STATIC_LIBRARY) ENDIF PRINTNL ENDIF bcmatroska2-5.3.101/corec/tools/coremake/automake.build000066400000000000000000000004301462133141200227330ustar00rootroot00000000000000#define TARGET_LINUX #define IX86 #define GLIBC #define COMPILER_GCC #define RESOURCE_COREC #define ASM yasm #define ASMFLAGS -f elf #define OUTPUT_EXE %(NAME) #define OUTPUT_DLL lib%(NAME).la #define OUTPUT_LIB lib%(NAME).la #define OUTPUT_CON %(NAME) #include "automake.inc" bcmatroska2-5.3.101/corec/tools/coremake/automake.inc000066400000000000000000000077471462133141200224270ustar00rootroot00000000000000CONFIG // make sure to use fixed output names for lib and dll FOR EACH LIB,DLL OUTPUT = lib%(NAME).la ENDFOR ALLDIRS = ./ AC_OUTPUT = ./Makefile FOR EACH WORKSPACE FOR REVERSE EACH USE x = %(PATH) WHILE "%(x)"!="./" ../../ALLDIRS += %(|x) ../../AC_OUTPUT += %(|x)Makefile x = %(?x) ENDWHILE IF "%(../../ACTIVETARGET)"=="" && (%(TYPE)=="exe" || %(TYPE)=="con") ../../ACTIVETARGET = %(PATH)%(OUTPUT) ENDIF ENDFOR ENDFOR FILE %(¯)Makefile.cvs PRINTNL default: all PRINTNL all: PRINTNL aclocal PRINTNL libtoolize --force PRINTNL autoheader PRINTNL automake --add-missing --foreign PRINTNL autoconf FILE %(¯)configure.in PRINTNL AC_INIT(root,1.0) PRINTNL PRINTNL AC_CONFIG_SRCDIR(configure.in) PRINTNL AM_CONFIG_HEADER(%(@BUILDPATH)/config.h) PRINTNL AC_CONFIG_AUX_DIR(%(@BUILDPATH)) PRINTNL PRINTNL AM_INIT_AUTOMAKE PRINTNL PRINTNL AC_LANG_C PRINTNL AC_PROG_CC PRINTNL AM_PROG_LIBTOOL PRINTNL PRINTNL AC_OUTPUT(%(AC_OUTPUT)) PRINTNL FOR EACH ALLDIRS FILE %(¯NAME)Makefile.am PRINTNL AUTOMAKE_OPTIONS = foreign PRINTNL INCLUDES= $(all_includes) FOR EACH ../ALLDIRS IF "%(?NAME)"=="%(../NAME)" ../SUBDIRS += %(|@NAME) ENDIF ENDFOR IF "%(SUBDIRS)"!="" PRINTNL SUBDIRS = %(SUBDIRS) ENDIF FOR EACH ../LIB,../DLL,../EXE,../CON IF "%(PATH)"=="%(../NAME)" IF %(TYPE)==LIB || %(TYPE)==DLL OUTPUT2 = %(OUTPUT) OUTPUT2_LDADD = %(OUTPUT2)_LIBADD ../noinst_LTLIBRARIES += %(OUTPUT) IF %(TYPE)==LIB LDFLAGS = -static ENDIF IF %(TYPE)==DLL LDFLAGS = -module ENDIF ELSE IF "%(../ACTIVE)"=="" ../ACTIVE = %(!PATH)%(OUTPUT) ENDIF OUTPUT2 = %(OUTPUT) OUTPUT2_LDADD = %(OUTPUT2)_LDADD ../noinst_PROGRAMS += %(OUTPUT) ENDIF LDADD += %(NAME)"=="c" || "%(>NAME)"=="cpp" ../SOURCES += %(!NAME) ENDIF IF (%(ASM)!="") && "%(>NAME)"=="asm" ../LDADD += %(NAME)"=="asm" PRINTNL %( PRINTNL PRINTNL %(NAME) PRINTNL PRINTNL IF %(TYPE)==EXE RSS += %(¯MAKEPATH)%(PROJECT_PATH).rss RSS += %(¯MAKEPATH)%(PROJECT_PATH)_reg.rss ENDIF IF (%(TYPE)!=LIB) FOR EACH USE IF (!%(NOLIB)) PRINTNL %(NAME) ENDIF ENDFOR ENDIF PRINTNL PRINTNL IF !DEFINED(CARBIDE_12) && !DEFINED(CARBIDE_20) PRINTNL PRINTNL org.eclipse.cdt.managedbuilder.core.genmakebuilder PRINTNL PRINTNL PRINTNL ELSE PRINTNL PRINTNL com.nokia.carbide.cdt.builder.carbideCPPBuilder PRINTNL PRINTNL PRINTNL IF DEFINED(CARBIDE_12) PRINTNL PRINTNL com.nokia.carbide.cdt.rombuilder.carbideRomBuilder PRINTNL PRINTNL PRINTNL ENDIF ENDIF PRINTNL PRINTNL PRINTNL org.eclipse.cdt.core.cnature PRINTNL org.eclipse.cdt.core.ccnature IF DEFINED(CARBIDE_12) || DEFINED(CARBIDE_20) PRINTNL com.nokia.carbide.cdt.builder.carbideCPPBuilderNature IF DEFINED(CARBIDE_12) PRINTNL com.nokia.carbide.cdt.rombuilder.carbideRomBuildNature ENDIF ELSE PRINTNL org.eclipse.cdt.managedbuilder.core.managedBuildNature PRINTNL com.symbian.cdt.core.symbiannature ENDIF PRINTNL PRINTNL FOR EACH SOURCE,HEADER IF %(>NAME)!=rss PRINTNL PRINTNL %(NAME) PRINTNL 1 PRINTNL %(|NAME) PRINTNL ENDIF ENDFOR FOR EACH RSS PRINTNL PRINTNL %(NAME) PRINTNL 1 PRINTNL %(|NAME) PRINTNL ENDFOR PRINTNL PRINTNL IF (%(TYPE)==LIB) CARBIDE_TYPE = lib CARBIDE_PTYPE = lib CARBIDE_CTYPE = Lib IF %(CARBIDE_TOOLCHAIN)==winscw CARBIDE_TTYPE = SLib CARBIDE_TTYPE2 = SLib ELSE CARBIDE_TTYPE = Slib CARBIDE_TTYPE2 = Slib ENDIF CARBIDE_TTYPE3 = slib CARBIDE_TYPE_NAME = Static Library ENDIF IF (%(TYPE)==DLL) CARBIDE_TYPE = dll CARBIDE_PTYPE = pdll CARBIDE_CTYPE = PDll CARBIDE_TTYPE = Pdll CARBIDE_TTYPE2 = PDll CARBIDE_TTYPE3 = pdll CARBIDE_TYPE_NAME = Static !!!! ENDIF IF (%(TYPE)==EXE) CARBIDE_TYPE = exe CARBIDE_PTYPE = exe CARBIDE_CTYPE = Exe CARBIDE_TTYPE = Exe CARBIDE_TTYPE2 = Exe CARBIDE_TTYPE3 = exe CARBIDE_TYPE_NAME = Static Executable ENDIF POSTBUILDCMD = IF %(INSTALL) && %(PROJECT_UID_3rd) && (%(CARBIDE_TOOLCHAIN)==winscw) POSTBUILDCMD = postannouncebuildStep="Install dependent files" postbuildStep="..\install.bat" FILE %(¯MAKEPATH)install.bat PRINTNL @set PRINTNL if not exist %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\private\%(#PROJECT_UID_3rd) mkdir %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\private\%(#PROJECT_UID_3rd) FOR EACH INSTALL PRINTNL copy /b /y "%(~|NAME)" %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\private\%(#PROJECT_UID_3rd) ENDFOR ENDIF IF !DEFINED(CARBIDE_12) && !DEFINED(CARBIDE_20) FILE %(¯MAKEPATH).cdtbuild PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF (%(TYPE)==EXE) PRINTNL ELSE PRINTNL ENDIF PRINTNL PRINTNL PRINTNL IF %(CARBIDE_TOOLCHAIN)==winscw IF (%(TYPE)==EXE) PRINTNL FOR EACH RSS PRINTNL PRINTNL IFDEF SYMBIAN90 PRINTNL PRINTNL ENDFOR ENDIF IF %(CARBIDE_TOOLCHAIN)==gcce IF (%(TYPE)==EXE) PRINTNL PRINTNL PRINTNL PRINTNL ENDIF FILE %(¯MAKEPATH)bld.inf PRINTNL PRJ_PLATFORMS PRINTNL %(TARGPLATFORM) PRINTNL PRINTNL PRJ_MMPFILES IF %(TYPE)==exe IF defined(SYMBIAN90) && defined(SERIES60) && %(ICON)!="" PRINTNL gnumakefile %(¯~!PATH)%(PROJECT_PATH)_icon.mak ENDIF ENDIF PRINTNL %(NAME).mmp IF %(CARBIDE_TOOLCHAIN)==winscw CONFIG_STRING = Emulator Debug (WINSCW) [%(CARBIDE_SDK)] ELIF %(TARGMODE)=="UDEB" CONFIG_STRING = Phone Debug (%(TARGPLATFORM)) [%(CARBIDE_SDK)] ELSE CONFIG_STRING = Phone Release (%(TARGPLATFORM)) [%(CARBIDE_SDK)] ENDIF IF DEFINED(CARBIDE_20) FILE %(¯MAKEPATH).cproject PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF (%(TYPE)==EXE) && %(CARBIDE_TOOLCHAIN)!=winscw IF DEFINED(SYMBIAN90) && %(SYMBIAN_CERT) && %(SYMBIAN_KEY) PRINTNL ELSE PRINTNL ENDIF ELSE PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL FILE %(¯MAKEPATH).settings/org.eclipse.cdt.ui.prefs PRINTNL eclipse.preferences.version=1 PRINTNL formatter_profile=org.eclipse.cdt.ui.default.allman_profile PRINTNL formatter_settings_version=1 ELSE FILE %(¯MAKEPATH).cdtproject PRINTNL PRINTNL PRINTNL IF DEFINED(CARBIDE_12) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL // PRINTNL PRINTNL /* FOR EACH USE IF !%(NOLIB) && (%(TYPE)!=DLL) PRINTNL ENDIF ENDFOR FOR EACH USELIB PRINTNL ENDFOR */ FOR EACH USE PRINTNL ENDFOR PRINTNL PRINTNL PRINTNL ELSE PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF FILE %(¯MAKEPATH).settings/.carbide_build_settings PRINTNL PRINTNL PRINTNL IF %(CARBIDE_TOOLCHAIN)==winscw IF (%(TYPE)==EXE) PRINTNL ENDIF ELSE IF (%(TYPE)==EXE) IF DEFINED(SYMBIAN90) && %(SYMBIAN_CERT) && %(SYMBIAN_KEY) PRINTNL ELSE PRINTNL ENDIF ENDIF ENDIF PRINTNL PRINTNL PRINTNL ENDIF IF %(TYPE)==exe && %(CARBIDE_TOOLCHAIN)!=winscw IF %(ICON)!="" FILE %(¯MAKEPATH)%(PROJECT_PATH).mifdef PRINTNL c32|%(|ICON)_s60.svg ENDIF TARGEPOC = $(EPOCROOT) TARGPLATFORM = $(PLATFORM) TARGETMODE = $(TARGET) FILE %(¯MAKEPATH)%(PROJECT_PATH).pkg FILEABS #include "symbian_pkg.inc" ENDIF ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/carbide_vs.inc000066400000000000000000000062651462133141200227140ustar00rootroot00000000000000#define TARGET_SYMBIAN #define ARM #define COMPILER_GCC #define MSVC_SEE_DEPRECATE #define CARBIDE_VS DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 USE_DLL_RUNTIME = 1 TARGNAME = Win32 TARGCFLAGS = /QIfist /NDSProjectFile "$(ProjectPath)" /NDSSDKShortName %(SDKNAME) TARGLFLAGS = /FORCE:MULTIPLE,UNRESOLVED TARGINC = $(EPOCROOT)\epoc32\include TARGINC += ;"$(EPOCROOT)\epoc32\include\libc" IF defined(SYMBIAN90) TARGINC += ;"$(EPOCROOT)\epoc32\include\ecom" ENDIF IF defined(SERIES60) IF defined(SYMBIAN90) TARGINC += ;"$(EPOCROOT)\epoc32\include\mmf\plugin" ENDIF ENDIF TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 PRECOMMAND_DEB = RCMake.exe "$(ProjectPath)" %(SDKNAME) WINSCW UDEB PRECOMMAND_REL = RCMake.exe "$(ProjectPath)" %(SDKNAME) GCCE UREL TARGDEF += _UNICODE TARGDEF += __SYMBIAN32__ TARGDEF += __SUPPORT_CPP_EXCEPTIONS__ DEFINE_RELEASE += __EPOC32__ DEFINE_RELEASE += __MARM__ DEFINE_RELEASE += __EABI__ DEFINE_RELEASE += __MARM_ARMV5__ DEFINE_RELEASE += __GCCE__ DEFINE_DEBUG += __WINSCW__ DEFINE_DEBUG += __WINS__ DEFINE_DEBUG += __CW32__ #include "vs.inc" EXECUTABLE_DEBUG = C:\Nokia\Tools\Carbide_vs30\EpocWrapper.exe ARGUMENTS_DEBUG = $(EPOCROOT)\\Epoc32\release\winscw\udeb\eshell.exe #include "symbian.inc" FOR EACH EXE,DLL,LIB FILE %(¯PATH)%(NAME)-SymbianOS-properties.xml PRINTNL PRINTNL PRINTNL %(NAME).mmp PRINTNL false PRINTNL false IF %(TYPE)==EXE PRINTNL %(NAME).pkg PRINTNL true PRINTNL true PRINTNL ELIF %(TYPE)==DLL PRINTNL ELIF %(TYPE)==LIB PRINTNL ENDIF PRINTNL EN PRINTNL false PRINTNL FILE %(¯PATH)%(NAME).uid.cpp PRINTNL #include PRINTNL #pragma data_seg(".SYMBIAN") IF %(TYPE)==EXE PRINTNL __EMULATOR_IMAGE_HEADER2(0x1000007a,0x100039ce,%(PROJECT_UID_3RD),EPriorityForeground,0x0u,0x00000000u,%(PROJECT_UID_3RD),0,0,0) ELIF %(TYPE)==DLL PRINTNL __EMULATOR_IMAGE_HEADER2(0x10000079,0x1000008d,%(PROJECT_UID_3RD),EPriorityForeground,0x0u,0x00000000u,%(PROJECT_UID_3RD),0,0,0) ELIF %(TYPE)==LIB PRINTNL __EMULATOR_IMAGE_HEADER2(0x00000000,0x0,0xe611bdef,EPriorityForeground,0x0u,0x00000000u,0,0,0,0) ENDIF PRINTNL #pragma data_seg() FILE %(¯PATH)%(NAME).vcproj.user #include "vsproj-user.inc" ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/clean.build000066400000000000000000000124301462133141200222120ustar00rootroot00000000000000FOR EACH WORKSPACE REMOVE %(¯PATH)Makefile REMOVE %(¯PATH)GNUmakefile REMOVE %(¯PATH)Makefile.evc REMOVE %(¯PATH)Makefile.vc6 REMOVE %(¯PATH)Makefile.vs REMOVE %(¯PATH)bld.inf REMOVE %(¯PATH)make.bat REMOVE %(¯PATH)abld.bat REMOVE %(¯PATH)%(NAME).dsw REMOVE %(¯PATH)%(NAME)_wins.dsw REMOVE %(¯PATH)%(NAME).sln REMOVE %(¯PATH)%(NAME).vcw REMOVE %(¯PATH)%(NAME).log REMOVE %(¯PATH)%(NAME)_nsi.log REMOVE %(¯PATH)%(NAME).log.tmp REMOVE %(¯PATH)%(NAME).kdevelop_gdbscript REMOVEDIR %(¯PATH)%(NAME).xcodeproj FOR EACH USE IF (%(TYPE)==EXE) || (%(TYPE)==DLL) REMOVE %(¯../PATH)%(NAME).plist ENDIF IF %(PMDOC)!="" REMOVEDIR %(¯PATH)%(NAME).pmdoc ENDIF ENDFOR ENDFOR REMOVE %(¯)Makefile.cvs REMOVE %(¯)libtool REMOVE %(¯)aclocal.m4 REMOVE %(¯)config.h.in REMOVE %(¯)config.status REMOVE %(¯)config.log REMOVE %(¯)Doxyfile REMOVEDIR %(¯)autom4te.cache REMOVE %(¯)root.kdevelop ALLDIRS = ./ FOR EACH LIB,DLL,EXE,CON,CAB,LIB_CSHARP,DLL_CSHARP,EXE_CSHARP,CON_CSHARP,EXE_JAVA x = %(PATH) WHILE "%(x)"!="./" ../ALLDIRS += %(|x) x = %(?x) ENDWHILE REMOVE %(¯PATH)%(NAME)_stdafx.c REMOVE %(¯PATH)%(NAME)_stdafx.h REMOVE %(¯PATH)%(NAME)_win32.rc REMOVE %(¯PATH)%(NAME)_win32.nsi REMOVE %(¯PATH)%(NAME)_project.h REMOVE %(¯PATH)%(NAME)_host.h REMOVE %(¯PATH)%(NAME)_split.sh REMOVE %(¯PATH)%(NAME)_palmos.rcp REMOVE %(¯PATH)%(NAME)_palmos.def REMOVE %(¯PATH)%(NAME)_wince.inf REMOVE %(¯PATH)%(NAME)_wince.ini REMOVE %(¯PATH)%(NAME)_rsg.h REMOVE %(¯PATH)%(NAME).dsp REMOVE %(¯PATH)%(NAME).vcproj REMOVE %(¯PATH)%(NAME).icproj REMOVE %(!ROOTPATH)%(PATH)%(NAME).csproj REMOVEDIR %(!ROOTPATH)%(PATH)%(NAME)/obj REMOVE %(¯PATH)%(NAME)_cab.vddproj REMOVE %(¯PATH)%(NAME).mak REMOVE %(¯PATH)%(NAME).tmp.pro REMOVE %(¯PATH)%(NAME).vcp REMOVE %(¯PATH)%(NAME).mmp REMOVE %(¯PATH)%(NAME).mmp.bak REMOVE %(¯PATH)%(NAME).GCCE REMOVE %(¯PATH)%(NAME).uid.cpp REMOVE %(¯PATH)%(NAME).plg REMOVE %(¯PATH)%(NAME).desktop REMOVE %(¯PATH)%(PROJECT_NAME).doxyfile REMOVE %(¯PATH)%(NAME)-SymbianOS-properties.xml REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/%(NAME).mmp REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/.project REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/.cdtbuild REMOVEDIR %(BUILDPATH)../carbide/%(PATH)%(NAME)/.settings REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/bld.inf REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/.cdtproject REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/.rnd REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/%(PROJECT_PATH).mifdef REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/%(PROJECT_PATH).pkg REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/.settings/.carbide_build_settings REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/%(NAME).mmp REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.project REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.cdtbuild REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/bld.inf REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.cdtproject REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.rnd REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/%(PROJECT_PATH).mifdef REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/%(PROJECT_PATH).pkg REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.settings/.carbide_build_settings REMOVEDIR %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/.settings REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/%(NAME).mmp REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.project REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.cdtbuild REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/bld.inf REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.cproject REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.rnd REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/%(PROJECT_PATH).mifdef REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/%(PROJECT_PATH).pkg REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.settings/.carbide_build_settings REMOVEDIR %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/.settings REMOVE %(¯BUILDDIR)build_ndk.sh REMOVE %(¯BUILDDIR).classpath REMOVE %(¯BUILDDIR).project REMOVE %(¯BUILDDIR)default.properties REMOVE %(¯BUILDDIR)AndroidManifest.xml REMOVE %(¯BUILDDIR).settings/org.eclipse.jdt.core.prefs REMOVEDIR %(¯BUILDDIR).settings REMOVEDIR %(¯BUILDDIR)gen REMOVEDIR %(¯BUILDDIR)res REMOVEDIR %(¯BUILDDIR)libs IF "%(PRECOMPILED_HEADER)"!="" REMOVE %(!PATH)%(PRECOMPILED_HEADER).gch REMOVE %(¯PATH)%(PRECOMPILED_HEADER).gch.%(NAME) ENDIF IF "%(PROJECT_PATH)"=="" PROJECT_PATH = %(NAME) ENDIF FOR EACH PROJECT_PATH REMOVE %(¯PATH)%(NAME).pkg REMOVE %(¯PATH)%(NAME).rss REMOVE %(BUILDPATH)../carbide/%(PATH)%(NAME)/%(NAME).rss REMOVE %(BUILDPATH)../carbide_12/%(PATH)%(NAME)/%(NAME).rss REMOVE %(BUILDPATH)../carbide_20/%(PATH)%(NAME)/%(NAME).rss REMOVE %(¯PATH)%(NAME)_icon.mak REMOVE %(¯PATH)%(NAME)_dll.txt REMOVE %(¯PATH)%(NAME)_aif.rss REMOVE %(¯PATH)%(NAME)_reg.rss REMOVE %(¯PATH)%(NAME)_caption.rss REMOVE %(¯PATH)%(NAME)_backup.xml ENDFOR ENDFOR FOR EACH LIB_CSHARP,DLL_CSHARP,EXE_CSHARP,CON_CSHARP REMOVEDIR %(PATH)obj ENDFOR FOR EACH ALLDIRS REMOVEDIR %(NAME).deps REMOVEDIR %(NAME).libs REMOVE %(NAME)Makefile REMOVE %(NAME)GNUmakefile REMOVE %(NAME)Makefile.in REMOVE %(NAME)Makefile.am ENDFOR REMOVEDIR release REMOVEDIR build bcmatroska2-5.3.101/corec/tools/coremake/config.h000066400000000000000000000001531462133141200215240ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE #define CONFIG_MULTITHREAD #define COREMAKE_CONFIG_HELPER bcmatroska2-5.3.101/corec/tools/coremake/config_helper.h000066400000000000000000000074041462133141200230710ustar00rootroot00000000000000/* $Id: config_helper.h 25 2010-07-07 14:49:45Z robux4 $ Copyright (c) 2010, CoreCodec, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CoreCodec, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __CONFIG_HELPER_H #define __CONFIG_HELPER_H /* force some defines */ #if defined(TARGET_WINCE) || defined(TARGET_SYMBIAN) #undef COREMAKE_UNICODE #define COREMAKE_UNICODE /* platforms where Unicode is mandatory */ #endif #if (defined(TARGET_PALMOS) && defined(IX86)) || defined(TARGET_SYMBIAN) #undef COREMAKE_STATIC /* platforms where dynamic libraries are not supported */ #define COREMAKE_STATIC #endif #if (defined(ARM) || defined(MIPS) || defined(SH3) || defined(SH4)) && !defined(TARGET_IPHONE_SDK) #undef CONFIG_DYNCODE #define CONFIG_DYNCODE /* platforms when dynamic code can be used */ #endif #if defined(IX86) || defined(IX86_64) #undef CONFIG_UNALIGNED_ACCESS #define CONFIG_UNALIGNED_ACCESS /* pointers can use unaligned memory */ #endif #if defined(TARGET_WIN32) || defined(TARGET_WIN64) || defined(TARGET_WINCE) || defined(TARGET_OSX) || defined(TARGET_LINUX) #define CONFIG_FILEPOS_64 /* platforms where 64 bits file position/size should be favoured */ #endif #if defined(TARGET_WINCE) || defined(TARGET_SYMBIAN) || defined(TARGET_PALMOS) || defined(ARM) || defined(MIPS) #define CONFIG_FIXED_POINT /* platforms where fixed point arithmetic processing should favoured */ #endif /* forbid some defines */ #if defined(TARGET_PALMOS) || defined(TARGET_LINUX) || defined(TARGET_PS2SDK) #undef COREMAKE_UNICODE /* platforms where Unicode is handled via UTF-8 strings */ #endif #if defined(TARGET_PALMOS) #undef CONFIG_FILEPOS_64 /* platforms where 64 bits file position/size should not be used */ #endif #if !defined(ARM) || defined(TARGET_SYMBIAN) || defined(TARGET_IPHONE) #undef CONFIG_WMMX /* platforms that don't support Wireless MMX CPUs/instructions */ #endif #if !defined(ARM) || defined(TARGET_SYMBIAN) || defined(TARGET_PALMOS) #undef CONFIG_ARMV6 /* platforms that don't support ARMv6 CPUs/instructions */ #endif #if !defined(IX86) || defined(TARGET_SYMBIAN) #undef CONFIG_MMX /* platforms that don't support MMX CPUs/instructions */ #endif #if !defined(ARM) || (!defined(TARGET_IPHONE) && !defined(TARGET_ANDROID)) #undef CONFIG_NEON /* platforms that don't support NEON/ARMv7 instructions */ #endif #if !defined(POWERPC) #undef CONFIG_ALTIVEC #endif #endif /* __CONFIG_HELPER_H */ bcmatroska2-5.3.101/corec/tools/coremake/coremake.c000066400000000000000000004476571462133141200220700ustar00rootroot00000000000000/* $Id: coremake.c 42 2011-07-03 08:25:54Z robux4 $ Copyright (c) 2006-2010, CoreCodec, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CoreCodec, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #define MAX_LINE 8192 #if !defined(_MSC_VER) && !defined(__MINGW32__) # ifndef strcmpi # define strcmpi strcasecmp # endif # ifndef stricmp # define stricmp strcasecmp # endif # ifndef strncmpi # define strncmpi strncasecmp # endif # ifndef strnicmp # define strnicmp strncasecmp # endif # define make_dir(x) mkdir(x,S_IRWXU) #else # define make_dir(x) mkdir(x) #endif int verbose = 0; #ifdef _WIN32 #include #include #include #ifndef _INTPTR_T_DEFINED typedef signed int intptr_t; #define _INTPTR_T_DEFINED #endif #ifndef MAX_PATH #define MAX_PATH 1024 #endif struct dirent { char d_name[MAX_PATH]; }; typedef struct DIR { intptr_t h; int first; struct _finddata_t file; struct dirent entry; } DIR; DIR* opendir(const char* name) { DIR* p = malloc(sizeof(DIR)); if (p) { sprintf(p->entry.d_name,"%s\\*",name); p->h = _findfirst(p->entry.d_name,&p->file); p->first = 1; if (p->h == -1) { free(p); p = NULL; } } return p; } struct dirent* readdir(DIR* p) { if (p->first || _findnext(p->h,&p->file)==0) { p->first = 0; strcpy(p->entry.d_name,p->file.name); return &p->entry; } return NULL; } void closedir(DIR* p) { _findclose(p->h); free(p); } #else #include #include #include #ifndef MAX_PATH #define MAX_PATH 1024 #endif #endif typedef struct reader_static { FILE* f; int comment; int no; int flags; int filename_kind; int filepos; } reader_static; typedef struct reader { reader_static r; char *pos; char *line; char *token; char *filename; } reader; typedef struct item item; typedef struct itemcond itemcond; typedef struct build_pos build_pos; struct build_pos { build_pos* prev; item* p; }; #define FLAG_PATH_NOT_PATH 0 #define FLAG_PATH_SOURCE 1 #define FLAG_PATH_GENERATED 2 #define FLAG_PATH_COREMAKE 3 #define FLAG_PATH_SYSTEM 4 #define FLAG_PATH_MASK 0x0F #define FLAG_PATH_SET_ABSOLUTE 0x10 #define FLAG_DEFINED 0x20 #define FLAG_REMOVED 0x40 #define FLAG_PROCESSED 0x80 #define FLAG_ATTRIB 0x100 #define FLAG_READY 0x200 #define FLAG_CONFIG_FILE_SET 0x400 char src_root[MAX_PATH] = ""; char proj_root[MAX_PATH] = ""; char coremake_root[MAX_PATH] = ""; size_t src_root_len = 0; size_t proj_root_len = 0; size_t coremake_root_len = 0; char proj[MAX_PATH] = "root.proj"; char platform[MAX_PATH] = ""; enum { COND_GET, COND_OR, COND_AND, COND_NOT, COND_1, COND_0, }; struct itemcond { int refcount; int func; item* value; itemcond* a; itemcond* b; }; struct item { char* value; itemcond* cond; item* parent; item** child; item** childend; item** childalloc; int flags; int stamp; }; int stamp=1; void upr(char* s) { for (;*s;++s) *s = toupper(*s); } void lwr(char* s) { for (;*s;++s) *s = tolower(*s); } void syntax(reader* p) { printf("syntax error %s:%d\n%s\r\n",p->filename,p->r.no,p->line); exit(1); } void* zalloc(int size) { void* p = malloc(size); if (!p) { printf("out of memory!\r\n"); exit(1); } memset(p,0,size); return p; } void set_path_type(item *i, int type) { assert((type & FLAG_PATH_MASK)==type); i->flags &= ~FLAG_PATH_MASK; i->flags |= type; } size_t item_childcount(const item* p) { if (!p) return 0; return (size_t)(p->childend - p->child); } void item_remove(item* i) { item** child; item* p = i->parent; for (child = p->child;child != p->childend;++child) if (*child == i) { memmove(child,child+1,(p->childend-child-1)*sizeof(item*)); --p->childend; break; } i->parent = NULL; } void item_add(item* p,item* child) { if (!child) return; if (child->parent) item_remove(child); if (p->childalloc == p->childend) { intptr_t count = p->childend - p->child; intptr_t alloc = count+16; p->child = realloc(p->child,sizeof(item*)*alloc); if (!p->child) { printf("out of memory!\r\n"); exit(1); } p->childend = p->child+count; p->childalloc = p->child+alloc; } *(p->childend++) = child; child->parent = p; } item* item_find(const item* parent,const char* value) { if (parent) { item** child; for (child = parent->child;child != parent->childend;++child) if (stricmp((*child)->value,value)==0) return *child; } return NULL; } int compare_name(const item* a, const item* b) { return stricmp(a->value,b->value)>0; } item* item_get(item* parent,const char* value,int defined); item* getroot(const item* p,const char* name) { while (p->parent) p = p->parent; return item_get((item*)p,name,0); } item* getconfig(item* p) { return getroot(p,"config"); } item* getvalue(item* p) { if (p) { item** child; for (child=p->child;child!=p->childend;++child) if (!((*child)->flags & FLAG_REMOVED)) return *child; } return NULL; } void setvalue(item* p,const char* value) { item* v = getvalue(p); if (v) { if (strcmp(v->value,value)==0) return; v->flags |= FLAG_REMOVED; } item_get(p,value,1); } item* findref(const item* p) { if (p->parent && (stricmp(p->parent->value,"project")==0 || stricmp(p->parent->value,"dep")==0 || stricmp(p->parent->value,"use")==0 || stricmp(p->parent->value,"useinclude")==0 || stricmp(p->parent->value,"usemerge")==0 || stricmp(p->parent->value,"usebuilt")==0)) { item* v = item_find(getroot(p,"exe"),p->value); if (!v) v = item_find(getroot(p,"con"),p->value); if (!v) v = item_find(getroot(p,"lib"),p->value); if (!v) v = item_find(getroot(p,"dll"),p->value); if (!v) v = item_find(getroot(p,"group"),p->value); if (!v) v = item_find(getroot(p,"dll_csharp"),p->value); if (!v) v = item_find(getroot(p,"con_csharp"),p->value); if (!v) v = item_find(getroot(p,"exe_csharp"),p->value); if (!v) v = item_find(getroot(p,"lib_csharp"),p->value); if (!v) v = item_find(getroot(p,"exe_java"),p->value); return v; } return NULL; } item* findref2(item* p) { item* ref = findref(p); return ref?ref:p; } int compare_use(const item* a, const item* b) { item* refa = findref(a); item* refb = findref(b); if (refa && refb) { size_t i; item* use; use = item_get(refb,"use",0); for (i=0;ichild[i])) { use = item_get(refa,"use",0); for (i=0;ichild[i])) { // circular reference return compare_name(refa,refb); } return 1; } } return 0; } int precompare_use(const item* refa, const item* refb) { size_t i; item* use; use = item_get((item*)refb,"use",0); for (i=0;ichild[i])) { use = item_get((item*)refa,"use",0); for (i=0;ichild[i])) { // circular reference return compare_name(refa,refb); } return 1; } return 0; } void item_sort(item* p,int(*compare)(const item*, const item*)) { if (item_childcount(p)>=2) { int changed; do { size_t i,j,n=item_childcount(p); changed=0; for (i=0;ichild[i],p->child[j])) { item* tmp = p->child[i]; p->child[i] = p->child[j]; p->child[j] = tmp; changed=1; } } while (changed); } } item* item_get(item* parent,const char* value,int defined) { item* p = item_find(parent,value); if (!p) { p = zalloc(sizeof(item)); if (value) p->value = strdup(value); if (parent) item_add(parent,p); } if (defined) p->flags |= FLAG_DEFINED; return p; } void itemcond_delete(itemcond* p) { if (p && --p->refcount==0) { itemcond_delete(p->a); itemcond_delete(p->b); free(p); } } void item_delete(item* p) { item** child; if (!p) return; if (p->parent) item_remove(p); for (child = p->child;child != p->childend;++child) { (*child)->parent = NULL; item_delete(*child); } itemcond_delete(p->cond); free(p->value); free(p); } itemcond* itemcond_new(int func, item* value) { itemcond* p = zalloc(sizeof(itemcond)); p->refcount = 1; p->func = func; p->value = value; return p; } int itemcond_same(itemcond* a,itemcond* b) { if (!a && !b) return 1; if (!a || !b) return 0; if (a->func != b->func) return 0; switch (a->func) { case COND_GET: return a->value == b->value; case COND_AND: case COND_OR: return (itemcond_same(a->a,b->a) && itemcond_same(a->b,b->b)) || (itemcond_same(a->b,b->a) && itemcond_same(a->a,b->b)); case COND_NOT: return itemcond_same(a->a,b->a); default: return 1; } } int itemcond_contains(itemcond* cond,item* has) { if (cond->func == COND_AND && has) { if (cond->a->value == has) return 1; if (cond->b->value == has) return 1; } return 0; } void itemcond_reduce(itemcond* cond) { if (cond->func == COND_OR) { itemcond_reduce(cond->a); itemcond_reduce(cond->b); if (cond->a->value) { if (itemcond_same(cond->a,cond->b)) { cond->func = COND_GET; cond->value = cond->a->value; } } if (cond->a->func == COND_GET && itemcond_contains(cond->b,cond->a->value)) { cond->func = COND_GET; cond->value = cond->a->value; } if (cond->b->func == COND_GET && itemcond_contains(cond->a,cond->b->value)) { cond->func = COND_GET; cond->value = cond->b->value; } } else if (cond->func == COND_AND) { itemcond_reduce(cond->a); itemcond_reduce(cond->b); if (cond->a->value) { if (itemcond_same(cond->a,cond->b)) { cond->func = COND_GET; cond->value = cond->a->value; } } } } int itemcond_partof(itemcond* a,itemcond* b) { if (itemcond_same(a,b)) return 1; if (a && a->func == COND_OR) return itemcond_partof(a->a,b) || itemcond_partof(a->b,b); return 0; } itemcond* itemcond_dup(itemcond* p) { if (p) ++p->refcount; return p; } void preprocess_condeval(item* p); int itemcond_eval(itemcond* p) { switch (p->func) { case COND_GET: if (!(p->value->flags & FLAG_PROCESSED)) preprocess_condeval(p->value); return (p->value->flags & FLAG_DEFINED)==FLAG_DEFINED; case COND_AND: return itemcond_eval(p->a) && itemcond_eval(p->b); case COND_OR: return itemcond_eval(p->a) || itemcond_eval(p->b); case COND_NOT: return !itemcond_eval(p->a); case COND_0: return 0; case COND_1: return 1; default: return 1; } } itemcond* itemcond_and(itemcond* p,itemcond* cond) { if (cond) { if (p) { itemcond* v = itemcond_new(COND_AND,NULL); v->a = itemcond_dup(cond); v->b = p; p = v; } else p = itemcond_dup(cond); } return p; } itemcond* itemcond_or(itemcond* p,itemcond* cond) { if (cond && p) { itemcond* v = itemcond_new(COND_OR,NULL); v->a = itemcond_dup(cond); v->b = p; p = v; } else { itemcond_delete(p); p = NULL; } return p; } item* item_getmerge(item* p,const item* child,int removed,int *exists) { item* dup; *exists = item_find(p,child->value) != NULL; dup = item_get(p,child->value,(child->flags & FLAG_DEFINED)==FLAG_DEFINED); if (((child->flags & FLAG_REMOVED) || removed) && (!*exists || (dup->flags & FLAG_REMOVED))) dup->flags |= FLAG_REMOVED; else dup->flags &= ~FLAG_REMOVED; dup->flags |= (child->flags & ~FLAG_REMOVED); return dup; } void item_merge2(item* p,item* group,itemcond* cond0,int removed,int exists) { if (group) { item** child; itemcond* cond = itemcond_and(itemcond_dup(group->cond),cond0); for (child = group->child;child != group->childend;++child) { int child_exists; item* dup = item_getmerge(p,*child,removed,&child_exists); item_merge2(dup,*child,cond,removed,child_exists); } if (!item_childcount(group) || (p->flags & FLAG_ATTRIB)) { if (exists) p->cond = itemcond_or(p->cond,cond); else { itemcond_delete(p->cond); p->cond = itemcond_dup(cond); } } itemcond_delete(cond); } } void item_merge(item* p,item* group,item* plus) { if (group) { int removed=0; item* i; itemcond* cond = NULL; for (i=group->parent;i;i=i->parent) cond = itemcond_and(cond,i->cond); if (plus) { removed = (plus->flags & FLAG_REMOVED)==FLAG_REMOVED; cond = itemcond_and(cond,plus->cond); } item_merge2(p,group,cond,removed,1); itemcond_delete(cond); } } void reader_init(reader *p) { memset(p,0,sizeof(reader)); p->filename = malloc(MAX_PATH); p->line = malloc(MAX_LINE); p->token = malloc(MAX_LINE); memset(p->filename,0,MAX_PATH); memset(p->line,0,MAX_LINE); memset(p->token,0,MAX_LINE); } void reader_free(reader *p) { free(p->filename); free(p->line); free(p->token); } void reader_save(reader *p,reader* save) { p->r.filepos = ftell(p->r.f); memcpy(save,p,sizeof(reader_static)); save->filename = strdup(p->filename); save->line = strdup(p->line); save->token = strdup(p->token); save->pos = save->line + (p->pos - p->line); } void reader_restore(reader *p,reader* save) { memcpy(p,save,sizeof(reader_static)); strcpy(p->filename,save->filename); strcpy(p->line,save->line); strcpy(p->token,save->token); p->pos = p->line + (save->pos - save->line); fseek(p->r.f,p->r.filepos,SEEK_SET); } int reader_line(reader* p) { size_t i; p->line[0] = 0; fgets(p->line,MAX_LINE,p->r.f); if (feof(p->r.f) && p->line[0]==0) return 0; i=strlen(p->line); while (i && isspace(p->line[--i])) p->line[i]=0; p->pos = p->line; ++p->r.no; return 1; } char* strins(char* s,const char* begin,const char* end) { size_t n = end?end-begin:strlen(begin); memmove(s+n,s,strlen(s)+1); memcpy(s,begin,n); return s; } char* strdel(char* s,const char* end) { memmove(s,end,strlen(end)+1); return s; } void reader_comment(reader* p) { char* s = p->line; while (*s) { if (p->r.comment) { char* s0 = s; for (;*s;++s) if (s[0]=='*' && s[1]=='/') { s = strdel(s0,s); p->r.comment = 0; break; } if (p->r.comment) { s = s0; *s = 0; } } else { for (;*s;++s) { if (s[0]=='/' && s[1]=='*') { s = strdel(s,s+2); p->r.comment = 1; break; } if (s[0]=='/' && s[1]=='/') { *s = 0; break; } } } } } int iscond(int ch) { return strchr("<>[]&|=+-!",ch) != NULL; } int isname(int ch) { return isalpha(ch) || isdigit(ch) || ch=='_' || ch=='-' || ch=='#' || ch=='/' || ch=='\\' || ch=='.' || ch=='%' || ch=='\''; } int reader_read(reader* p) { char* s = p->pos; for (;;) { if (!*s) { if (!reader_line(p)) { p->token[0] = 0; return 0; } s = p->pos; } if (p->r.comment) { char* s0 = s; for (;*s;++s) if (s[0]=='*' && s[1]=='/') { s = strdel(s0,s+2); p->r.comment = 0; break; } } else { while (*s && isspace(*s)) ++s; if (s[0]=='/' && s[1]=='*') { s = strdel(s,s+2); p->r.comment = 1; } else if (s[0]=='/' && s[1]=='/') *s = 0; else if (isname(*s)) { int i; for (i=0;*s && isname(*s);++s,++i) p->token[i] = *s; p->token[i] = 0; break; } else if (*s=='"') { int i; ++s; for (i=0;*s && (s[0]!='"' || s[1]=='"');++s,++i) { if (s[0]=='"') ++s; p->token[i] = *s; } p->token[i] = 0; if (*s=='"') ++s; break; } else if (*s) { p->token[0] = *(s++); p->token[1] = 0; if (*s && iscond(s[-1]) && iscond(*s)) { p->token[1] = *(s++); p->token[2] = 0; } break; } } } p->pos = s; p->r.flags |= FLAG_READY; return 1; } int reader_eof(reader* p) { if (p->r.flags & FLAG_READY) return 0; return !reader_read(p); } int reader_istoken(reader* p,const char* token) { if (!(p->r.flags & FLAG_READY) && !reader_read(p)) return 0; if (stricmp(p->token,token)!=0) return 0; p->r.flags &= ~FLAG_READY; return 1; } int reader_istoken_n(reader* p,const char* token, int n) { if (!(p->r.flags & FLAG_READY) && !reader_read(p)) return 0; if (strnicmp(p->token,token,n)!=0) return 0; return 1; } void reader_token_skip(reader* p, int n) { strdel(p->token,p->token+n); if (!p->token[0]) p->r.flags &= ~FLAG_READY; } int reader_tokenline(reader* p,int onespace) { char* s = p->pos; assert(!(p->r.flags & FLAG_READY)); if (onespace >= 0) { while (*s && isspace(*s)) { ++s; if (onespace) break; } } strcpy(p->token,s); p->pos = s + strlen(s); return p->token[0]!=0; } void reader_token(reader* p) { if (!(p->r.flags & FLAG_READY) && !reader_read(p)) syntax(p); p->r.flags &= ~FLAG_READY; } void reader_name(reader* p) { reader_token(p); if (!isalpha(p->token[0]) && p->token[0]!='_' && p->token[0]!='.' && p->token[0]!='\\') syntax(p); } char* getfilename(const char* path) { char* i = strrchr(path,'/'); if (i) return i+1; return (char*)path; } void removedrive(char *path) { if (((path[0]>='a' && path[0]<='z') || (path[0]>='A' && path[0]<='Z')) && path[1]==':') memmove(path,path+2,strlen(path)); } void truncfilename(char* path) { char* i = getfilename(path); memmove(path,i,strlen(i)+1); i = strrchr(path,'.'); if (i) *i=0; } void truncfilefourcc(char* path) { char* i = getfilename(path); memmove(path,i,strlen(i)+1); path[4] = 0; while (strlen(path)<4) strcat(path,"_"); } void truncfileext(char* path) { char* i = getfilename(path); char* ext = strrchr(i,'.'); if (ext) memmove(path,ext+1,strlen(ext+1)+1); else path[0]=0; } void truncfourcc(char* s) { size_t len = strlen(s); if (len>2 && s[0]=='\'' && s[len-1]=='\'') { strdel(s+len-1,s+len); strdel(s,s+1); } } void trunchex(char* s) { if (s[0]=='0' && s[1]=='x') strdel(s,s+2); } char* nextlevel(const char* path) { char* i = strchr(path,'/'); if (i) return i+1; return NULL; } void addendpath(char* path) { if (path[0] && path[strlen(path)-1]!='/') strcat(path,"/"); } void delendpath(char* path) { if (path[0] && path[strlen(path)-1]=='/') path[strlen(path)-1] = 0; } void truncfilepath(char* path,int delend) { char* i = getfilename(path); if (i) *i=0; if (delend) { delendpath(path); if (!path[0]) strcpy(path,"."); } else addendpath(path); } void truncfileupper(char* path) { delendpath(path); truncfilepath(path,0); if (!path[0]) strcpy(path,"./"); } void pathunix(char* path) { int i; for (i=0;path[i];++i) if (path[i]=='\\') path[i]='/'; } void pathdos(char* path) { int i; for (i=0;path[i];++i) if (path[i]=='/') path[i]='\\'; } void reversestr(char *value) { char tmpstr[MAX_LINE]; size_t i,len=strlen(value); for (i=0;itoken,p->r.flags); } void reader_filename(reader* p, int dst_flags) { assert((dst_flags & FLAG_PATH_MASK) != FLAG_PATH_NOT_PATH); if (stricmp(p->token,".")==0) p->token[0]='\0'; if ((dst_flags & FLAG_PATH_SET_ABSOLUTE)==0 && ((p->token[0] != '$' || p->token[1] != '(') && p->token[0] != '/')) { char* end = getfilename(p->filename); while (p->token[0]=='.' && p->token[1]=='.' && end != p->filename) { char* i; for (i=end-1;i>p->filename;--i) if (i[-1]=='/') break; strdel(p->token,p->token+2); if (p->token[0]=='/') strdel(p->token,p->token+1); end = i; } strins(p->token,p->filename,end); p->r.flags &= ~FLAG_PATH_MASK; p->r.flags |= p->r.filename_kind & FLAG_PATH_MASK; // adjust the pathes according to their modifier if ((dst_flags & FLAG_PATH_MASK) != (p->r.filename_kind & FLAG_PATH_MASK)) { if (coremake_root_len || (dst_flags & FLAG_PATH_MASK) != FLAG_PATH_COREMAKE) // keep the full path to get the coremake_root reader_strip_abs(p); switch (dst_flags & FLAG_PATH_MASK) { case FLAG_PATH_GENERATED: strins(p->token,proj_root,NULL); break; case FLAG_PATH_COREMAKE: strins(p->token,coremake_root,NULL); break; case FLAG_PATH_SOURCE: strins(p->token,src_root,NULL); break; } p->r.flags &= ~FLAG_PATH_MASK; p->r.flags |= (dst_flags & FLAG_PATH_MASK); } } pathunix(p->token); } itemcond* load_cond0(reader* file,item* config); itemcond* load_cond2(reader* file,item* config) { itemcond* p; if (reader_istoken(file,"(")) { p = load_cond0(file,config); if (!reader_istoken(file,")")) syntax(file); } else { if (reader_istoken(file,")")) syntax(file); reader_name(file); p = itemcond_new(COND_GET,item_get(config,file->token,0)); } return p; } itemcond* load_cond1(reader* file,item* config) { if (reader_istoken(file,"!")) { itemcond* p = itemcond_new(COND_NOT,NULL); p->a = load_cond1(file,config); return p; } else return load_cond2(file,config); } itemcond* load_cond0(reader* file,item* config) { itemcond* a = load_cond1(file,config); if (reader_istoken(file,"||")) { itemcond* p = itemcond_new(COND_OR,NULL); p->a = a; p->b = load_cond0(file,config); return p; } if (reader_istoken(file,"&&")) { itemcond* p = itemcond_new(COND_AND,NULL); p->a = a; p->b = load_cond0(file,config); return p; } return a; } itemcond* load_cond(item* item, reader* file, int force) { itemcond* p = NULL; if (reader_istoken(file,"(")) { p = load_cond0(file,getconfig(item)); if (!reader_istoken(file,")")) syntax(file); } else if (force) p = load_cond0(file,getconfig(item)); return p; } int load_file(item* p,const char* filename, int file_kind, itemcond* cond0); int load_item(item* p,reader* file,int sub,itemcond* cond0) { int result=0; item *i,*j=NULL; while (!reader_eof(file)) { if (reader_istoken(file,"#include")) { if (reader_istoken(file,"*/*.proj")) { char path[MAX_PATH]; DIR* dir; path[0] = 0; strins(path,file->filename,getfilename(file->filename)); delendpath(path); dir = opendir(path[0]?path:"."); if (dir) { struct dirent* entry; struct stat entrystats; addendpath(path); while ((entry = readdir(dir)) != NULL) { sprintf(file->token,"%s%s",path,entry->d_name); stat(file->token,&entrystats); if ((entrystats.st_mode & S_IFDIR) && entry->d_name[0]!='.') { sprintf(file->token,"%s%s/%s.proj",path,entry->d_name,entry->d_name); if (!load_file(p,file->token,FLAG_PATH_SOURCE,cond0) && strrchr(entry->d_name,'-')) { // if it's a UNIX library name, try without the version char *empty = strrchr(file->token,'-'); *empty = 0; strcat(file->token,".proj"); load_file(p,file->token,FLAG_PATH_SOURCE,cond0); } } } closedir(dir); } } else { reader_token(file); reader_filename(file,0); load_file(p,file->token,FLAG_PATH_SOURCE,cond0); } } else if (reader_istoken(file,"if")) { itemcond* condextra = NULL; int mode; do { itemcond* cond = load_cond(p,file,1); itemcond* cond1 = itemcond_and(itemcond_and(itemcond_dup(cond),cond0),condextra); mode = load_item(p,file,2,cond1); itemcond_delete(cond1); if (mode==1) { itemcond* not = itemcond_new(COND_NOT,NULL); not->a = itemcond_dup(cond); not = itemcond_and(itemcond_and(not,cond0),condextra); load_item(p,file,3,not); itemcond_delete(not); } else if (mode==2) { itemcond* not = itemcond_new(COND_NOT,NULL); not->a = itemcond_dup(cond); condextra = itemcond_and(condextra,not); itemcond_delete(not); } itemcond_delete(cond); } while (mode==2); itemcond_delete(condextra); } else if (reader_istoken(file,"else")) { if (sub != 2) syntax(file); result = 1; break; } else if (reader_istoken(file,";")) { //nothing to do } else if (reader_istoken(file,"elif")) { if (sub != 2) syntax(file); result = 2; break; } else if (reader_istoken(file,"endif")) { if (sub != 2 && sub != 3) syntax(file); break; } else if (reader_istoken(file,"}")) { if (sub != 1) syntax(file); break; } else { int config = 0; int need_path; int filename; int uselib; int deepercond; int attrib; int generated_dir; int coremake_dir; int system_dir; itemcond* cond; reader_name(file); deepercond = !p->parent && stricmp(file->token,"project")==0; need_path = !p->parent && ( stricmp(file->token,"con")==0 || stricmp(file->token,"exe")==0 || stricmp(file->token,"group")==0 || stricmp(file->token,"lib")==0 || stricmp(file->token,"dll")==0 || stricmp(file->token,"lib_csharp")==0 || stricmp(file->token,"dll_csharp")==0 || stricmp(file->token,"exe_csharp")==0 || stricmp(file->token,"con_csharp")==0 || stricmp(file->token,"exe_java")==0 || stricmp(file->token,"workspace")==0); uselib = stricmp(file->token,"uselib")==0 || stricmp(file->token,"builtlib")==0; filename = stricmp(file->token,"config_file")==0 || stricmp(file->token,"config_include")==0 || stricmp(file->token,"config_cleaner")==0 || stricmp(file->token,"platform_files")==0 || stricmp(file->token,"expinclude")==0 || stricmp(file->token,"subinclude")==0 || stricmp(file->token,"sysinclude")==0 || stricmp(file->token,"include")==0 || stricmp(file->token,"include_debug")==0 || stricmp(file->token,"include_release")==0 || stricmp(file->token,"os_include")==0 || stricmp(file->token,"libinclude")==0 || stricmp(file->token,"libinclude_debug")==0 || stricmp(file->token,"libinclude_release")==0 || stricmp(file->token,"def")==0 || stricmp(file->token,"icon")==0 || stricmp(file->token,"header")==0 || stricmp(file->token,"header_qt4")==0 || stricmp(file->token,"ui_form_qt4")==0 || stricmp(file->token,"resource_qt4")==0 || stricmp(file->token,"install_zip")==0 || stricmp(file->token,"install_cab")==0 || stricmp(file->token,"install")==0 || stricmp(file->token,"android_value")==0 || stricmp(file->token,"nsi")==0 || stricmp(file->token,"pmdoc")==0 || stricmp(file->token,"osx_icon")==0 || stricmp(file->token,"source_m68k")==0 || stricmp(file->token,"export_svn")==0 || stricmp(file->token,"source")==0 || stricmp(file->token,"compile")==0 || stricmp(file->token,"linkfile")==0 || stricmp(file->token,"crt0")==0 || stricmp(file->token,"symbian_cert")==0 || stricmp(file->token,"symbian_key")==0 || stricmp(file->token,"doxygen")==0 || stricmp(file->token,"project_svn_revision")==0 || stricmp(file->token,"project_help")==0 || stricmp(file->token,"config_android_ndk")==0; generated_dir = stricmp(file->token,"config_file")==0 || stricmp(file->token,"config_include")==0; coremake_dir = stricmp(file->token,"platform_files")==0; system_dir = stricmp(file->token,"config_android_ndk")==0 || stricmp(file->token,"os_include")==0; attrib = filename || stricmp(file->token,"register_cab")==0 || stricmp(file->token,"reg")==0 || stricmp(file->token,"class")==0; // we need this because priority would mess up conditions if (stricmp(file->token,"config")==0) { config = 1; j = getconfig(p); } else j = item_get(p,file->token,0); cond = load_cond(p,file,0); cond = itemcond_and(cond,cond0); if (cond && config) { item* v; for (v=p;v;v=v->parent) cond = itemcond_and(cond,v->cond); } if (reader_istoken(file,"}")) { if (sub != 1) syntax(file); item_get(j,"1",1); break; } if (reader_istoken(file,",") || reader_istoken(file,";")) { item_get(j,"1",1); } else if (reader_istoken(file,"{")) { if (config) syntax(file); load_item(j,file,1,cond); } else { do { int exists; int is_abs=0; reader_token(file); if (filename) { int file_flags = generated_dir?FLAG_PATH_GENERATED:(coremake_dir?FLAG_PATH_COREMAKE:(system_dir?FLAG_PATH_SYSTEM:FLAG_PATH_SOURCE)); if (ispathabs(file->token)) { is_abs = 1; file_flags |= FLAG_PATH_SET_ABSOLUTE; } reader_filename(file,file_flags); } exists = item_find(j,file->token)!=NULL; i = item_get(j,file->token,0); if (attrib) i->flags |= FLAG_ATTRIB; if (is_abs) i->flags |= FLAG_PATH_SET_ABSOLUTE; if (coremake_dir) set_path_type(i,FLAG_PATH_COREMAKE); else if (generated_dir) set_path_type(i,FLAG_PATH_GENERATED); else if (filename || need_path) set_path_type(i,FLAG_PATH_SOURCE); else set_path_type(i,FLAG_PATH_NOT_PATH); if (need_path) { char path[MAX_PATH]; item *v = item_get(i,"PATH",0); item *j; if (exists) { item* existing = getvalue(v); printf("project already defined at %s!\n%s:%d\n%s\r\n",existing?existing->value:"?",file->filename,file->r.no,file->line); exit(1); } path[0]=0; strins(path,file->filename,getfilename(file->filename)); strip_path_abs(path,file->r.filename_kind); if (generated_dir) strins(path,proj_root,NULL); else if (coremake_dir) strins(path,coremake_root,NULL); else strins(path,src_root,NULL); j = item_get(v,path,1); if (generated_dir) set_path_type(j,FLAG_PATH_GENERATED); else if (coremake_dir) set_path_type(j,FLAG_PATH_COREMAKE); else set_path_type(j,FLAG_PATH_SOURCE); // pre-define some items item_get(i,"OUTPUT",0); item_get(i,"EXPINCLUDE",0); item_get(i,"SUBINCLUDE",0); item_get(i,"SYSINCLUDE",0); item_get(i,"LIBINCLUDE",0); item_get(i,"LIBINCLUDE_DEBUG",0); item_get(i,"LIBINCLUDE_RELEASE",0); item_get(i,"INCLUDE",0); item_get(i,"INCLUDE_DEBUG",0); item_get(i,"INCLUDE_RELEASE",0); item_get(i,"EXPDEFINE",0); item_get(i,"DEFINE",0); item_get(i,"LIBS",0); item_get(i,"LIBS_DEBUG",0); item_get(i,"LIBS_RELEASE",0); item_get(i,"SYSLIBS",0); } if (!deepercond) { if (exists) i->cond = itemcond_or(i->cond,cond); else i->cond = itemcond_dup(cond); } if (uselib) { int exists; item *incs; item* i; char path[MAX_PATH]; path[0]=0; strins(path,file->filename,getfilename(file->filename)); incs = item_get(p,"libinclude",0); exists = item_find(incs,path)!=NULL; i = item_get(incs,path,0); i->flags = file->r.filename_kind; if (exists) i->cond = itemcond_or(i->cond,cond); else i->cond = itemcond_dup(cond); } if (reader_istoken(file,":")) { int pri; reader_token(file); if (sscanf(file->token,"%d",&pri)!=1) syntax(file); item_get(item_get(i,"priority",0),file->token,1); } if (reader_istoken(file,"{")) { if (config) syntax(file); load_item(i,file,1,deepercond?cond:NULL); } } while (reader_istoken(file,",")); } itemcond_delete(cond); } } return result; } int load_file(item* p,const char* filename, int file_kind, itemcond* cond) { reader r; reader_init(&r); strcpy(r.filename,filename); pathunix(r.filename); r.r.f = fopen(filename,"r"); r.pos = r.line; if (r.r.f) { r.r.filename_kind = file_kind; load_item(p,&r,0,cond); fclose(r.r.f); reader_free(&r); return 1; } reader_free(&r); return 0; } void dumpcond(FILE* f,itemcond* p,int first,int prev,int* startpos,int nobreak) { int pos = ftell(f); if (startpos && !nobreak && pos>*startpos+200) { fprintf(f,"\\\n "); *startpos = pos; } itemcond_reduce(p); if (!first && (p->func==COND_OR || p->func==COND_AND) && p->func!=prev) fprintf(f,"("); switch (p->func) { case COND_GET: fprintf(f,"defined(%s)",p->value->value); break; case COND_NOT: if (p->a->func == COND_NOT) dumpcond(f,p->a->a,0,COND_NOT,startpos,0); else { fprintf(f,"!"); dumpcond(f,p->a,0,p->func,startpos,1); } break; case COND_OR: dumpcond(f,p->a,0,p->func,startpos,0); fprintf(f," || "); dumpcond(f,p->b,0,p->func,startpos,0); break; case COND_AND: dumpcond(f,p->a,0,p->func,startpos,0); fprintf(f," && "); dumpcond(f,p->b,0,p->func,startpos,0); break; case COND_0: fprintf(f,"0"); break; case COND_1: fprintf(f,"1"); break; } if (!first && (p->func==COND_OR || p->func==COND_AND) && p->func!=prev) fprintf(f,")"); } void dumpitem(item* p,int deep) { item** child; printf("%*c%s",deep*2,' ',p->value); if (p->cond) { printf(" ("); dumpcond(stdout,p->cond,1,COND_GET,NULL,0); printf(")"); } printf("\r\n"); for (child=p->child;child!=p->childend;++child) dumpitem(*child,deep+1); } void usage() { printf("usage: coremake [] \r\n\r\n"); printf(" -h : help\r\n"); printf(" -v : verbose\r\n"); printf(" -r : root folder (default is current dir)\r\n"); printf(" -f : specify project file (default is root.proj)\r\n"); printf(" -d : dump project\r\n"); printf(" -p : dump project at the end\r\n"); // TODO: add support for using another config file than config.h } void preprocess_setremoved(item* p) { item** child; p->flags |= FLAG_REMOVED; p->flags &= ~FLAG_DEFINED; for (child=p->child;child!=p->childend;++child) preprocess_setremoved(*child); } void preprocess_condeval(item* p) { item** child; p->flags |= FLAG_PROCESSED; if (p->cond) { if (!itemcond_eval(p->cond)) preprocess_setremoved(p); } if (!(p->flags & FLAG_REMOVED)) for (child=p->child;child!=p->childend;++child) preprocess_condeval(*child); } void preprocess_condstart(item* p) { item** child; p->flags &= ~FLAG_PROCESSED; p->flags &= ~FLAG_REMOVED; for (child=p->child;child!=p->childend;++child) preprocess_condstart(*child); } void preprocess_config(item* p) { item** child; for (child=p->child;child!=p->childend;++child) if (!((*child)->flags & FLAG_DEFINED)) (*child)->flags |= FLAG_REMOVED; } void preprocess_condend(item* p) { item** child; if (p->cond) { itemcond_delete(p->cond); p->cond = NULL; } for (child=p->child;child!=p->childend;++child) { if ((*child)->flags & FLAG_REMOVED) { item_delete(*child); --child; } else preprocess_condend(*child); } } void item_merge_name(item* dst,item* src,const char* value,item* cond) { src = item_find(src,value); if (src) { int exists; item_merge(item_getmerge(dst,src,0,&exists),src,cond); } } void preprocess_dependency_project(item* p) { if (!(p->flags & FLAG_PROCESSED)) { // remove not exising dependencies size_t i; item* use = item_get(p,"use",0); p->flags |= FLAG_PROCESSED; for (i=0;ichild[i]); if (!ref || (ref->flags & FLAG_REMOVED) || ref==p) { preprocess_setremoved(use->child[i]); } else if (stricmp(ref->parent->value,"lib")==0) { preprocess_dependency_project(ref); // copy use of lib's item_merge(use,item_find(ref,"use"),use->child[i]); item_merge_name(p,ref,"uselib",use->child[i]); item_merge_name(p,ref,"framework",use->child[i]); item_merge_name(p,ref,"framework_lib",use->child[i]); item_merge_name(p,ref,"privateframework",use->child[i]); item_merge_name(p,ref,"libinclude",use->child[i]); item_merge_name(p,ref,"libinclude_debug",use->child[i]); item_merge_name(p,ref,"libinclude_release",use->child[i]); item_merge_name(p,ref,"rpath",use->child[i]); item_merge_name(p,ref,"android_permission",use->child[i]); } } } } void preprocess_dependency(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) preprocess_dependency_project(*child); } void file_finalize(char* name) { char tmp[MAX_PATH]; char* i = strrchr(name,'.'); if (i && stricmp(i,".tmp")==0) { FILE* a; FILE* b; int same=0; strcpy(tmp,name); *i = 0; a = fopen(tmp,"rb"); b = fopen(name,"rb"); if (a && b) { char bufa[1024]; char bufb[1024]; for (;;) { size_t na = fread(bufa,1,sizeof(bufa),a); size_t nb = fread(bufb,1,sizeof(bufb),b); if (na != nb || memcmp(bufa,bufb,na)!=0) break; if (feof(a) || feof(b)) { same=1; break; } } } if (a) fclose(a); if (b) fclose(b); if (!same) { if (verbose) printf("updating %s\r\n",name); remove(name); rename(tmp,name); } else remove(tmp); } } itemcond* itemcond_print(FILE* f,itemcond* p,itemcond* cond) { if (!itemcond_same(p,cond)) { if (p) { itemcond_delete(p); fprintf(f,"#endif\n"); } p = itemcond_dup(cond); if (p) { int pos = ftell(f); fprintf(f,"#if "); dumpcond(f,p,1,COND_GET,&pos,0); fprintf(f,"\n"); } } return p; } int is_project_data(item* p) { char name[MAX_LINE]; strcpy(name,p->value); name[8]=0; return stricmp(name,"PROJECT_")==0; } int is_host_data(item* p) { char name[MAX_LINE]; strcpy(name,p->value); name[5]=0; return stricmp(name,"HOST_")==0; } #define MAX_PRI (1<<20) int getpri(item* p) { int i; item* v = item_find(p,"priority"); if (v && item_childcount(v) && sscanf(v->child[0]->value,"%d",&i)==1) return i; return MAX_PRI; } int tokeneval(char* s,int skip,build_pos* pos,reader* error, int extra_cmd); void create_missing_dirs(const char *path); void getabspath(char* path, int path_flags, const char *rel_path, int rel_flags); void preprocess_stdafx_includes(item* p,int lib) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { size_t i; int prj = 0, host = 0; char gen_path[MAX_PATH]; item* plugin = getvalue(item_find(*child,"plugin")); item* no_stdafx = getvalue(item_find(*child,"no_stdafx")); item* no_project = getvalue(item_find(*child,"no_project")); item* cls = item_get(*child,"class",0); item* reg = item_get(*child,"reg",0); item* path = getvalue(item_get(*child,"path",0)); item *include = item_get(*child,"include",0); if (!path) continue; strcpy(gen_path,path->value); strip_path_abs(gen_path,path->flags); getabspath(gen_path,FLAG_PATH_GENERATED,"",FLAG_PATH_GENERATED); if (!plugin) for (i=0;ichild[i]) && is_project_data((*child)->child[i])) { prj = 1; break; } for (i=0;ichild[i]) && is_host_data((*child)->child[i])) { host = 1; break; } if (prj && !no_project) { /* add _project.h */ item *src; char file[MAX_PATH]; item *add_inc; sprintf(file,"%s%s_project.h",gen_path,(*child)->value); src = item_get(item_get(*child,"header",0),file,1); set_path_type(src,FLAG_PATH_GENERATED); add_inc = item_get(include,gen_path,0); set_path_type(add_inc,FLAG_PATH_GENERATED); add_inc->flags |= FLAG_ATTRIB; } if (host && !lib) { /* add _host.h */ item *src; char file[MAX_PATH]; item *add_inc; sprintf(file,"%s%s_host.h",gen_path,(*child)->value); src = item_get(item_get(*child,"header",0),file,1); set_path_type(src,FLAG_PATH_GENERATED); add_inc = item_get(include,gen_path,0); set_path_type(add_inc,FLAG_PATH_GENERATED); add_inc->flags |= FLAG_ATTRIB; } if ((item_childcount(reg) || item_childcount(cls) || prj) && !lib && !no_stdafx) { /* add _stdafx.c */ item *src; char file[MAX_PATH]; item *add_inc; src = item_get(item_get(*child,"expinclude",0),gen_path,1); set_path_type(src,FLAG_PATH_GENERATED); sprintf(file,"%s%s_stdafx.c",gen_path,(*child)->value); src = item_get(item_get(*child,"source",0),file,1); set_path_type(src,FLAG_PATH_GENERATED); src = item_get(src,"NO_PCH",1); item_get(src,".",1); add_inc = item_get(include,gen_path,0); set_path_type(add_inc,FLAG_PATH_GENERATED); add_inc->flags |= FLAG_ATTRIB; /* add _stdafx.h */ sprintf(file,"%s%s_stdafx.h",gen_path,(*child)->value); src = item_get(item_get(*child,"header",0),file,1); set_path_type(src,FLAG_PATH_GENERATED); } } } void preprocess_stdafx(item* p,int lib) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { size_t i,j; int prj = 0, host = 0; char gen_path[MAX_PATH]; item* plugin = getvalue(item_find(*child,"plugin")); item* no_stdafx = getvalue(item_find(*child,"no_stdafx")); item* cls = item_get(*child,"class",0); item* reg = item_get(*child,"reg",0); item* use = item_find(*child,"use"); item* usebuilt = item_find(*child,"usebuilt"); item* path = getvalue(item_get(*child,"path",0)); item* src = item_get(*child,"source",0); item* libs = item_get(*child,"libs",0); item* syslibs = item_get(*child,"syslibs",0); item* install = item_get(*child,"install",0); item* uselib = item_find(*child,"uselib"); if (path) { strcpy(gen_path,path->value); strip_path_abs(gen_path,path->flags); getabspath(gen_path,FLAG_PATH_GENERATED,"",FLAG_PATH_GENERATED); } if (!plugin) for (i=0;ichild[i]) && is_project_data((*child)->child[i])) { prj = 1; if (stricmp((*child)->child[i]->value,"project_svn_revision")==0) { item** k; for (k=((*child)->child[i])->child;k!=((*child)->child[i])->childend;++k) { // open the /.svn/entries file reader r; reader_init(&r); r.pos = r.line; strcpy(r.filename,(*k)->value); pathunix(r.filename); addendpath(r.filename); strcat(r.filename,".svn/entries"); r.r.f = fopen(r.filename,"r"); if (r.r.f) { if (reader_line(&r)) { if (stricmp(r.line,"8")!=0 && stricmp(r.line,"9")!=0 && stricmp(r.line,"10")!=0) printf("unknown .svn/entries version '%s'\r\n",r.line); else { if (reader_line(&r) && reader_line(&r) && reader_line(&r)) { item* build=item_get(*child,"PROJECT_BUILD",1); item** j; for (j=build->child;j!=build->childend;++j) if (itemcond_partof((*k)->cond,(*j)->cond)) { itemcond_delete((*j)->cond); (*j)->cond = itemcond_new(COND_0,NULL); (*j)->flags |= FLAG_REMOVED; } if (j==build->childend) { item* line = item_get(build,r.line,1); line->cond = itemcond_dup((*k)->cond); preprocess_condeval(line); } } } } fclose(r.r.f); } reader_free(&r); } } } for (i=0;ichild[i]) && is_host_data((*child)->child[i])) { host = 1; break; } // copy register from source for (i=0;ichild[i],"reg"),NULL); item_merge(cls,item_find(src->child[i],"class"),NULL); } if (uselib) for (i=0;ichild[i],"reg"),NULL); item_merge(cls,item_find(uselib->child[i],"class"),NULL); } // register libraries as well from use for (i=0;ichild[i]); if (ref && stricmp(ref->parent->value,"lib")==0) { item* src = item_get(ref,"source",0); item* uselib = item_find(*child,"uselib"); for (j=0;jchild[j],"reg"),use->child[i]); item_merge(cls,item_find(src->child[j],"class"),use->child[i]); } if (uselib) for (j=0;jchild[j],"reg"),use->child[i]); item_merge(cls,item_find(uselib->child[j],"class"),use->child[i]); } item_merge(reg,item_find(ref,"reg"),use->child[i]); item_merge(cls,item_find(ref,"class"),use->child[i]); item_merge(libs,item_find(ref,"libs"),use->child[i]); item_merge(syslibs,item_find(ref,"syslibs"),use->child[i]); item_merge(install,item_find(ref,"install"),use->child[i]); } } // register libraries as well from usebuilt for (i=0;ichild[i]); if (ref && stricmp(ref->parent->value,"lib")==0) { item* src = item_get(ref,"source",0); item* uselib = item_find(*child,"uselib"); for (j=0;jchild[j],"reg"),usebuilt->child[i]); item_merge(cls,item_find(src->child[j],"class"),usebuilt->child[i]); } if (uselib) for (j=0;jchild[j],"reg"),usebuilt->child[i]); item_merge(cls,item_find(uselib->child[j],"class"),usebuilt->child[i]); } item_merge(reg,item_find(ref,"reg"),usebuilt->child[i]); item_merge(cls,item_find(ref,"class"),usebuilt->child[i]); item_merge(libs,item_find(ref,"libs"),usebuilt->child[i]); item_merge(syslibs,item_find(ref,"syslibs"),usebuilt->child[i]); item_merge(install,item_find(ref,"install"),usebuilt->child[i]); } } if (item_find(getconfig(p),"RESOURCE_COREC")) { if (item_get(getconfig(p),"COREMAKE_STATIC",0)->flags & FLAG_DEFINED) { // make resource out of plugin/driver dll files for (i=0;ichild[i]); if (ref && stricmp(ref->parent->value,"dll")==0 && getvalue(item_find(ref,"nolib"))) { item* outputpath = getvalue(getroot(ref,"outputpath")); item* output = getvalue(item_get(ref,"output",0)); if (outputpath && outputpath->value && output && output->value) { item* tmp, *out; char path[MAX_PATH]; strcpy(path,outputpath->value); addendpath(path); strcat(path,output->value); tmp = item_get(ref,"__tmp",1); out = item_get(tmp,path,1); set_path_type(out,outputpath->flags & FLAG_PATH_MASK); item_merge(install,tmp,use->child[i]); } } } } if (item_childcount(install)) { itemcond* cond = itemcond_new(COND_GET,item_find(getconfig(p),"RESOURCE_COREC")); item* v = item_get(*child,"install_resource",0); item_merge(v,install,NULL); for (i=0;ichild[i]->value); truncfilename(name); strins(name,"Resource_",NULL); strcat(name,"_Class"); free(v->child[i]->value); v->child[i]->value = strdup(name); v->child[i]->flags |= FLAG_ATTRIB; item_get(item_get(v->child[i],"priority",1),"1",1); v->child[i]->cond = itemcond_and(v->child[i]->cond,cond); } item_merge(cls,v,NULL); itemcond_delete(cond); } } if (path) { preprocess_stdafx_includes(p,lib); if (prj) { FILE* f; char file[MAX_PATH]; sprintf(file,"%s%s_project.h",gen_path,(*child)->value); strcat(file,".tmp"); create_missing_dirs(file); f = fopen(file,"w"); if (f) { itemcond* cond = NULL; fprintf(f,"/* DO NOT EDIT, FILE GENERATED BY COREMAKE */\n\n"); fprintf(f,"#ifndef T\n"); fprintf(f,"#define T(x) x\n"); fprintf(f,"#define HAS_DEFINED_T\n"); fprintf(f,"#endif /* T */\n\n"); for (i=0;ichild[i])) { for (j=0;jchild[i]);++j) { build_pos pos; reader r; item* value = (*child)->child[i]->child[j]; cond = itemcond_print(f,cond,value->cond); reader_init(&r); strcpy(r.filename,file); r.r.filename_kind = FLAG_PATH_GENERATED; r.r.no = 0; strcpy(r.line,value->value); strcpy(r.token,value->value); pos.p = value; pos.prev = NULL; tokeneval(r.token,0,&pos,&r,0); upr((*child)->child[i]->value); if (stricmp((*child)->child[i]->value,"project_svn_revision")!=0) { if (r.token[0]=='\'' || (isdigit(r.token[0]) && !strchr(r.token,'.') && !strchr(r.token,' '))) fprintf(f,"#define %s %s\n",(*child)->child[i]->value,r.token); else fprintf(f,"#define %s T(\"%s\")\n",(*child)->child[i]->value,r.token); } if (stricmp((*child)->child[i]->value,"project_version")==0 && ((*child)->child[i])->child) { char proj_name[256]; int major=1, minor=0, revision=0; sscanf(r.token,"%d.%d.%d",&major,&minor,&revision); fprintf(f,"#define PROJECT_VERSION_MAJOR %d\n",major); fprintf(f,"#define PROJECT_VERSION_MINOR %d\n",minor); fprintf(f,"#define PROJECT_VERSION_REVISION %d\n",revision); strcpy(proj_name,(*child)->value); upr(proj_name); fprintf(f,"#define %s_PROJECT_VERSION 0x%02x%02x%02x\n",proj_name,major,minor,revision); } reader_free(&r); } } cond = itemcond_print(f,cond,NULL); fprintf(f,"\n"); fprintf(f,"#ifdef HAS_DEFINED_T\n"); fprintf(f,"#undef T\n"); fprintf(f,"#undef HAS_DEFINED_T\n"); fprintf(f,"#endif /* HAS_DEFINED_T */\n\n"); fclose(f); file_finalize(file); } } if (host && !lib) { FILE* f; char file[MAX_PATH]; sprintf(file,"%s%s_host.h",gen_path,(*child)->value); strcat(file,".tmp"); create_missing_dirs(file); f = fopen(file,"w"); if (f) { itemcond* cond = NULL; fprintf(f,"/* DO NOT EDIT, FILE GENERATED BY COREMAKE */\n\n"); fprintf(f,"#include \"config.h\"\n\n"); for (i=0;ichild[i])) { for (j=0;jchild[i]);++j) { item* value = (*child)->child[i]->child[j]; cond = itemcond_print(f,cond,value->cond); if (value->value[0]=='\'' || (isdigit(value->value[0]) && !strchr(value->value,'.'))) fprintf(f,"#define %s %s\n",(*child)->child[i]->value,value->value); else fprintf(f,"#define %s T(\"%s\")\n",(*child)->child[i]->value,value->value); } } cond = itemcond_print(f,cond,NULL); fprintf(f,"\n"); fclose(f); file_finalize(file); } } if ((item_childcount(reg) || item_childcount(cls) || prj) && !lib && !no_stdafx) { /* generate stdafx.c */ FILE* f; char file[MAX_PATH]; sprintf(file,"%s%s_stdafx.c",gen_path,(*child)->value); strcat(file,".tmp"); create_missing_dirs(file); f = fopen(file,"w"); if (f) { itemcond* cond = NULL; fprintf(f,"/* DO NOT EDIT, FILE GENERATED BY COREMAKE */\n\n"); fprintf(f,"#include \"%s_stdafx.h\"\n",(*child)->value); if (prj) fprintf(f,"#include \"%s_project.h\"\n",(*child)->value); fprintf(f,"\n\n"); if (item_childcount(reg) || item_childcount(cls)) { item* found; int found_reg = 0; int found_pri; for (i=0;ichild[i]->flags &= ~FLAG_PROCESSED; fprintf(f,"extern const nodemeta %s[];\n",cls->child[i]->value); } for (i=0;ichild[i]->flags &= ~FLAG_PROCESSED; fprintf(f,"extern void %s_Init(nodemodule* Module);\n",reg->child[i]->value); fprintf(f,"extern void %s_Done(nodemodule* Module);\n",reg->child[i]->value); } fprintf(f,"\nerr_t %s(nodemodule* Module)\n",plugin?"DLLRegister":"StdAfx_Init"); fprintf(f,"{\n"); do { found = NULL; found_pri = MAX_PRI+1; for (i=0;ichild[i]->flags & FLAG_PROCESSED)) { int pri = getpri(reg->child[i]); if (found_pri > pri) { found_pri = pri; found_reg = 1; found = reg->child[i]; } } } for (i=0;ichild[i]->flags & FLAG_PROCESSED)) { int pri = getpri(cls->child[i]); if (found_pri > pri) { found_pri = pri; found_reg = 0; found = cls->child[i]; } } } if (found) { found->flags |= FLAG_PROCESSED; cond = itemcond_print(f,cond,found->cond); if (found_reg) fprintf(f,"\t%s_Init(Module);\n",found->value); else fprintf(f,"\tNodeRegisterClassEx(Module,%s);\n",found->value); } } while (found); cond = itemcond_print(f,cond,NULL); fprintf(f,"\treturn ERR_NONE;\n"); fprintf(f,"}\n\n"); fprintf(f,"void %s(nodemodule* Module)\n",plugin?"DLLUnRegister":"StdAfx_Done"); fprintf(f,"{\n"); for (i=0;ichild[i]->cond); fprintf(f,"\t%s_Done(Module);\n",reg->child[i]->value); } cond = itemcond_print(f,cond,NULL); fprintf(f,"}\n\n"); } if (prj) { fprintf(f,"\nvoid ProjectSettings(nodecontext* p)\n"); fprintf(f,"{\n"); fprintf(f,"#ifdef PROJECT_FOURCC\n"); fprintf(f," fourcc_t FourCC = PROJECT_FOURCC;\n"); fprintf(f," Node_Set(p,NODECONTEXT_PROJECT_FOURCC,&FourCC,sizeof(FourCC));\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_NAME\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_NAME,TYPE_STRING,PROJECT_NAME);\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_VENDOR\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_VENDOR,TYPE_STRING,PROJECT_VENDOR);\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_HELP\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_HELP,TYPE_STRING,PROJECT_HELP);\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_VERSION\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_VERSION,TYPE_STRING,PROJECT_VERSION);\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_BUILD\n"); fprintf(f," {\n"); fprintf(f," int BuildVersion = PROJECT_BUILD;\n"); fprintf(f," Node_Set(p,NODECONTEXT_PROJECT_BUILD,&BuildVersion,sizeof(BuildVersion));\n"); fprintf(f," }\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_MIME\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_MIME,TYPE_STRING,PROJECT_MIME);\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_APPID\n"); fprintf(f," {\n"); fprintf(f," uint16_t AppId = PROJECT_APPID;\n"); fprintf(f," Node_Set(p,NODECONTEXT_PROJECT_APPID,&AppId,sizeof(AppId));\n"); fprintf(f," }\n"); fprintf(f,"#endif\n"); fprintf(f,"#ifdef PROJECT_PATH\n"); fprintf(f," Node_SetData((node*)p,NODECONTEXT_PROJECT_PATH,TYPE_STRING,PROJECT_PATH);\n"); fprintf(f,"#endif\n"); fprintf(f,"}\n"); } fclose(f); file_finalize(file); } /* generate _stdafx.h */ sprintf(file,"%s%s_stdafx.h",gen_path,(*child)->value); strcat(file,".tmp"); f = fopen(file,"w"); if (f) { fprintf(f,"/* DO NOT EDIT, FILE GENERATED BY COREMAKE */\n\n"); fprintf(f,"#include \"corec/node/node.h\"\n"); fprintf(f,"\n"); fprintf(f,"#ifdef __cplusplus\n"); fprintf(f,"extern \"C\" {\n"); fprintf(f,"#endif\n"); fprintf(f,"\n"); if (item_childcount(reg) || item_childcount(cls)) { fprintf(f,"extern err_t %s(nodemodule* Module);\n",plugin?"DLLRegister":"StdAfx_Init"); fprintf(f,"extern void %s(nodemodule* Module);\n",plugin?"DLLUnRegister":"StdAfx_Done"); } if (prj) fprintf(f,"extern void ProjectSettings(nodecontext* p);\n"); fprintf(f,"\n#ifdef __cplusplus\n"); fprintf(f,"}\n"); fprintf(f,"#endif\n"); fclose(f); file_finalize(file); } } } } } void preprocess_dependency_include(item* base, item* list, int keep_exp_inc, int discard_exp_def) { size_t i; for (i=0;ichild[i]); if (ref && ref->stamp != stamp) { ref->stamp = stamp; // add to "expinclude" to "include" or "expinclude" item_merge(item_get(base,keep_exp_inc?"expinclude":"include",0),item_find(ref,"expinclude"),list->child[i]); // also merge "subinclude" item_merge(item_get(base,"subinclude",0),item_find(ref,"subinclude"),list->child[i]); // also merge "sysinclude" item_merge(item_get(base,"sysinclude",0),item_find(ref,"sysinclude"),list->child[i]); // also merge "linkfile" item_merge(item_get(base,"linkfile",0),item_find(ref,"linkfile"),list->child[i]); // also merge "crt0" item_merge(item_get(base,"crt0",0),item_find(ref,"crt0"),list->child[i]); // also merge "expdefine" to "define" or "expdefine" if (!discard_exp_def) item_merge(item_get(base,"define",0),item_find(ref,"expdefine"),list->child[i]); preprocess_dependency_include(base,item_get(ref,"useinclude",0),keep_exp_inc,1); preprocess_dependency_include(base,item_get(ref,"use",0),keep_exp_inc,0); } } } void preprocess_dependency_init(item* p,int onlysource) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { size_t i; item* list; int empty = 1; (*child)->flags &= ~FLAG_PROCESSED; ++stamp; preprocess_dependency_include(*child,item_get(*child,"useinclude",0),0,1); preprocess_dependency_include(*child,item_get(*child,"use",0),0,0); list = item_find(*child,"source"); for (i=0;ichild[i]->flags & FLAG_REMOVED) && !item_find(list->child[i],"sys")) { empty = 0; break; } if (!onlysource) { list = item_find(*child,"use"); for (i=0;ichild[i]->flags & FLAG_REMOVED)) { item* ref = findref(list->child[i]); if (ref && !(ref->flags & FLAG_REMOVED) && stricmp(ref->parent->value,"lib")==0) { empty = 0; break; } } } if (empty) preprocess_setremoved(*child); // empty project } } void preprocess_workspace_adddep(item* workspace_use,item* p) { item* ref = findref(p); p->flags |= FLAG_PROCESSED; if (ref && !(ref->flags & FLAG_REMOVED)) { size_t i; item* use = item_get(ref,"use",0); for (i=0;ichild[i]->flags & FLAG_REMOVED)) { item* dep = item_get(workspace_use,use->child[i]->value,1); if (!(dep->flags & FLAG_PROCESSED)) preprocess_workspace_adddep(workspace_use,dep); } use = item_get(ref,"dep",0); for (i=0;ichild[i]->flags & FLAG_REMOVED)) { item* dep = item_get(workspace_use,use->child[i]->value,1); if (!(dep->flags & FLAG_PROCESSED)) preprocess_workspace_adddep(workspace_use,dep); } } } void preprocess_workspace_init(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) (*child)->flags &= ~FLAG_PROCESSED; } void preprocess_workspace(item* p) { item** child; for (child=p->child;child!=p->childend;++child) { item* use = item_get(*child,"use",0); size_t i; for (i=0;ichild[i]->flags &= ~FLAG_PROCESSED; for (i=0;ichild[i]->flags & FLAG_PROCESSED)) preprocess_workspace_adddep(use,use->child[i]); for (i=0;ichild[i]); if (!ref || (ref->flags & FLAG_REMOVED)) { item_delete(use->child[i]); --i; } } if (!item_childcount(use)) { item_delete(*child); --child; } #if 0 else { // copy all the FRAMEWORK of each (use) into the WORKSPACE (*child) item *frameworks = item_get(*child,"framework",0); for (i=0;ichild[i]); if (ref) { item_merge(frameworks,item_find(ref,"framework"),NULL); } } } #endif } } void merge_project(item* target,item* source,item* filter) { size_t j; item* tmp = item_get(NULL,"tmp",0); item_add(tmp,item_find(source,"path")); item_merge(target,source,filter); for (j=0;jchild[j]); item_delete(tmp); } void replace_use(item* p,const char* remove,item* set) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { item* use = item_get(*child,"use",0); item* a = item_find(use,remove); if (a && !(a->flags & FLAG_REMOVED)) { // remove old use item_delete(a); if (stricmp((*child)->value,set->value)!=0) { item* setuse = item_find(item_find(set,"use"),(*child)->value); if (setuse) { if ((*child)->parent && stricmp((*child)->parent->value,"lib")==0) continue; item_get(item_get(set,"dep",0),(*child)->value,1); item_delete(setuse); } // replace use item_get(use,set->value,1); } } } } void preprocess_usemerge(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { size_t i; item* merge = item_get(*child,"usemerge",0); for (i=0;ichild[i]); if (dll && stricmp(dll->parent->value,"dll")==0 && !(merge->child[i]->flags & FLAG_REMOVED)) { item* use; item* lib = item_get(getroot(p,"lib"),dll->value,0); item_delete(item_find(dll,"nolib")); item_delete(item_find(dll,"output")); item_merge(lib,dll,merge->child[i]); item_delete(dll); use = item_find(item_get(lib,"use",0),(*child)->value); if (use) item_delete(use); use = item_find(item_get(lib,"usebuilt",0),(*child)->value); if (use) item_delete(use); replace_use(getroot(p,"dll"),lib->value,*child); replace_use(getroot(p,"lib"),lib->value,*child); replace_use(getroot(p,"con"),lib->value,*child); replace_use(getroot(p,"exe"),lib->value,*child); item_get(item_get(*child,"use",0),lib->value,1)->flags &= ~FLAG_REMOVED; } else if (dll && stricmp(dll->parent->value,"dll_csharp")==0 && !(merge->child[i]->flags & FLAG_REMOVED)) { item* use; item* lib = item_get(getroot(p,"lib_csharp"),dll->value,0); item_delete(item_find(dll,"nolib")); item_delete(item_find(dll,"output")); item_merge(lib,dll,merge->child[i]); item_delete(dll); use = item_find(item_get(lib,"use",0),(*child)->value); if (use) item_delete(use); use = item_find(item_get(lib,"usebuilt",0),(*child)->value); if (use) item_delete(use); replace_use(getroot(p,"dll_csharp"),lib->value,*child); replace_use(getroot(p,"lib_csharp"),lib->value,*child); replace_use(getroot(p,"con_csharp"),lib->value,*child); replace_use(getroot(p,"exe_csharp"),lib->value,*child); item_get(item_get(*child,"use",0),lib->value,1)->flags &= ~FLAG_REMOVED; } } } } void preprocess_outputname(item* p,const char* outputname) { item* output; item** child; if (!p) return; output = getvalue(item_find(getconfig(p),outputname)); for (child=p->child;child!=p->childend;++child) { if (!output) preprocess_setremoved(*child); else if (!getvalue(item_find(*child,"output"))) item_get(item_get(*child,"output",0),output->value,1); } } void preprocess_project(item* p) { size_t i; if (!p) return; for (i=0;ichild[i]); if (ref) { merge_project(ref,p->child[i],p->child[i]); item_delete(p->child[i]); --i; } } } // replace the "use" of a "group" by the content of the "group" void preprocess_group(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { size_t i; item* use = item_get(*child,"use",0); for (i=0;ichild[i]->value); if (group) { merge_project(*child,group,use->child[i]); item_delete(use->child[i]); --i; // process the same item again until there is no more 'group' } } } } void preprocess_uselib(item* p,item* ref,item* uselib) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) if (!((*child)->flags & FLAG_REMOVED)) { size_t i; item* use = item_get(*child,"use",0); for (i=0;ichild[i]->value,ref->value)==0) { size_t j; item* src = item_get(ref,"source",0); for (j=0;jchild[j]->value); truncfileext(path); if (stricmp(path,"rc")==0) item_merge(item_get(item_get(*child,"source",0),src->child[j]->value,1),src->child[j],use->child[i]); item_merge(item_get(*child,"reg",0),item_find(src->child[j],"reg"),use->child[i]); item_merge(item_get(*child,"class",0),item_find(src->child[j],"class"),use->child[i]); } item_merge(item_get(*child,"reg",0),item_find(ref,"reg"),use->child[i]); item_merge(item_get(*child,"class",0),item_find(ref,"class"),use->child[i]); item_merge(item_get(*child,"libs",0),item_find(ref,"libs"),use->child[i]); item_merge(item_get(*child,"syslibs",0),item_find(ref,"syslibs"),use->child[i]); item_merge(item_get(*child,"install",0),item_find(ref,"install"),use->child[i]); // add to "include" item_merge(item_get(*child,"include",0),item_find(ref,"expinclude"),use->child[i]); // also merge "subinclude" item_merge(item_get(*child,"subinclude",0),item_find(ref,"subinclude"),use->child[i]); // also merge "sysinclude" item_merge(item_get(*child,"sysinclude",0),item_find(ref,"sysinclude"),use->child[i]); // also merge "libinclude" item_merge(item_get(*child,"libinclude",0),item_find(ref,"libinclude"),use->child[i]); // also merge "uselib" item_merge(item_get(*child,"uselib",0),item_find(ref,"uselib"),use->child[i]); // also merge "rpath" item_merge(item_get(*child,"rpath",0),item_find(ref,"rpath"),use->child[i]); // add to "define" item_merge(item_get(*child,"define",0),item_find(ref,"expdefine"),use->child[i]); item_get(item_get(*child,"uselib",1),uselib->value,1); item_delete(use->child[i]); --i; } } } } void preprocess_builtlib(item* p) { size_t i; if (!p) return; for (i=0;ichild[i],"builtlib",0); item* value = getvalue(builtlib); if (value) { ++stamp; preprocess_dependency_include(p->child[i],item_get(p->child[i],"useinclude",0),1,1); preprocess_dependency_include(p->child[i],item_get(p->child[i],"use",0),1,0); preprocess_uselib(getroot(p,"group"),p->child[i],value); preprocess_uselib(getroot(p,"exe"),p->child[i],value); preprocess_uselib(getroot(p,"dll"),p->child[i],value); preprocess_uselib(getroot(p,"con"),p->child[i],value); preprocess_uselib(getroot(p,"lib"),p->child[i],value); preprocess_uselib(getroot(p,"dll_csharp"),p->child[i],value); preprocess_uselib(getroot(p,"exe_csharp"),p->child[i],value); preprocess_uselib(getroot(p,"con_csharp"),p->child[i],value); preprocess_uselib(getroot(p,"lib_csharp"),p->child[i],value); preprocess_uselib(getroot(p,"exe_java"),p->child[i],value); item_delete(p->child[i]); --i; } } } void generate_xcodeuid(char *xcodeuid,const char *srcstr) { int i; union { unsigned int d[3]; unsigned char b[12]; } code; for (i=0;i<3;++i) code.d[i] = 1; for (i=0;srcstr[i];++i) { unsigned char ch = (unsigned char)srcstr[i]; code.d[0] = (code.d[0] + 0x33299112 + code.d[0] * ch) ^ code.d[2]; code.d[1] = (code.d[1] + 0x1345AF22 + code.d[2] * ch) ^ code.d[1]; code.d[2] = (code.d[2] + 0x73A92332 + code.d[1] * ch) ^ code.d[0]; } sprintf(xcodeuid,"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", code.b[0],code.b[1],code.b[2],code.b[3], code.b[4],code.b[5],code.b[6],code.b[7], code.b[8],code.b[9],code.b[10],code.b[11]); } void generate_msmuid(char *msmuid,const char *srcstr) { int i; union { unsigned int d[4]; unsigned char b[16]; } code; for (i=0;i<4;++i) code.d[i] = 1; for (i=0;srcstr[i];++i) { unsigned char ch = (unsigned char)srcstr[i]; code.d[0] = (code.d[0] + 0x33299112 + code.d[2] * ch) ^ code.d[3]; code.d[1] = (code.d[1] + 0x1345AF22 + code.d[3] * ch) ^ code.d[2]; code.d[2] = (code.d[2] + 0x73A92332 + code.d[0] * ch) ^ code.d[1]; code.d[3] = (code.d[3] + 0x5123ABC1 + code.d[1] * ch) ^ code.d[0]; } sprintf(msmuid,"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", code.b[0],code.b[1],code.b[2],code.b[3], code.b[4],code.b[5],code.b[6],code.b[7], code.b[8],code.b[9],code.b[10],code.b[11], code.b[12],code.b[13],code.b[14],code.b[15]); } void generate_msuid(char *msuid,const char *srcstr) { int i; union { unsigned int d[4]; unsigned char b[16]; } code; for (i=0;i<4;++i) code.d[i] = 1; for (i=0;srcstr[i];++i) { unsigned char ch = (unsigned char)srcstr[i]; code.d[0] = (code.d[0] + 0x33299112 + code.d[2] * ch) ^ code.d[3]; code.d[1] = (code.d[1] + 0x1345AF22 + code.d[3] * ch) ^ code.d[2]; code.d[2] = (code.d[2] + 0x73A92332 + code.d[0] * ch) ^ code.d[1]; code.d[3] = (code.d[3] + 0x5123ABC1 + code.d[1] * ch) ^ code.d[0]; } sprintf(msuid,"{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}", code.b[0],code.b[1],code.b[2],code.b[3], code.b[4],code.b[5],code.b[6],code.b[7], code.b[8],code.b[9],code.b[10],code.b[11], code.b[12],code.b[13],code.b[14],code.b[15]); } void preprocess_sort_workspace(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { #if 0 size_t i; item *frameworks = item_find(*child,"framework"); for (i=0;ichild[i]->value); item_get(item_get(frameworks->child[i],"xcodegrpuid",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(frameworks->child[i],"xcodegrpuid2",0),xcodeuid,1); } #endif item_sort(item_get(*child,"use",0),compare_use); // for automake "subdirs" } } void preprocess_presort(item* p) { // before builtlib removes projects if (!p) return; item_sort(p,precompare_use); // symbian libary linking madness... } void preprocess_sort(item* p) { item** child; if (!p) return; for (child=p->child;child!=p->childend;++child) { item* prjname; item* prjpath; item* src; int major,minor,revision; size_t i; char ver[64]; char msuid[64]; char xcodeuid[25]; char msmuid[40]; char projfile[MAX_PATH]; generate_msuid(msuid,(*child)->value); item_get(item_get(*child,"guid",0),msuid,1); generate_msuid(msuid,msuid); item_get(item_get(*child,"guidbis",0),msuid,1); generate_msuid(msuid,msuid); item_get(item_get(*child,"guid2",0),msuid,1); generate_msuid(msuid,msuid); item_get(item_get(*child,"guid3",0),msuid,1); generate_msmuid(msmuid,msuid); item_get(item_get(*child,"msmuid",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(*child,"msmuid2",0),msmuid,1); generate_xcodeuid(xcodeuid,(*child)->value); item_get(item_get(*child,"xcodegrpuid",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid2",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid3",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid4",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid5",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid6",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid7",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid8",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid9",0),xcodeuid,1); generate_xcodeuid(xcodeuid, xcodeuid); item_get(item_get(*child,"xcodegrpuid10",0),xcodeuid,1); item_sort(item_get(*child,"source",0),compare_name); item_sort(item_get(*child,"use",0),compare_use); // symbian libary linking madness... src = item_get(*child,"source",0); for (i=0;ivalue); strcat(projfile,"source"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"header",0); for (i=0;ivalue); strcat(projfile,"header"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"osx_strings",0); for (i=0;ivalue); strcat(projfile,"osx_strings"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"osx_icon",0); for (i=0;ivalue); strcat(projfile,"osx_icon"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"icon",0); for (i=0;ivalue); strcat(projfile,"icon"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"install",0); for (i=0;ivalue); strcat(projfile,"install"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodeuid",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"framework",0); for (i=0;ivalue); strcat(projfile,"framework"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodefrwfile",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"framework_lib",0); for (i=0;ivalue); strcat(projfile,"framework_lib"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodefrwfile",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"privateframework",0); for (i=0;ivalue); strcat(projfile,"privateframework"); strcat(projfile,src->child[i]->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodefrwfile",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } src = item_get(*child,"use",0); for (i=0;ichild[i]); if (ref) { strcpy(projfile,(*child)->value); strcat(projfile,"lib"); strcat(projfile,ref->value); generate_xcodeuid(xcodeuid, projfile); item_get(item_get(src->child[i],"xcodefrwfile",0),xcodeuid,1); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); } } src = item_get(*child,"install_cab",0); for (i=0;ivalue); strcat(projfile,"install_cab"); strcat(projfile,src->child[i]->value); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); generate_msmuid(msmuid, msmuid); item_get(item_get(src->child[i],"msmuid2",0),msmuid,1); } src = item_get(*child,"register_cab",0); for (i=0;ivalue); strcat(projfile,"register_cab"); strcat(projfile,src->child[i]->value); generate_msmuid(msmuid, projfile); item_get(item_get(src->child[i],"msmuid",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid2",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid3",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid4",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid5",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid6",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid7",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid8",0),msmuid,1); generate_msmuid(msmuid,msmuid); item_get(item_get(src->child[i],"msmuid9",0),msmuid,1); } prjname = getvalue(item_get(*child,"project_name",0)); if (!prjname) prjname = item_get(item_get(*child,"project_name",0),(*child)->value,1); prjpath = getvalue(item_get(*child,"project_path",0)); if (!prjpath) prjpath = item_get(item_get(*child,"project_path",0),(*child)->value,1); if (!getvalue(item_get(*child,"project_version",0))) item_get(item_get(*child,"project_version",0),"1.0.0",1); if ((item_get(getconfig(*child),"TARGET_PALMOS",0)->flags & FLAG_DEFINED) && !getvalue(item_get(*child,"project_fourcc",0))) item_get(item_get(*child,"project_fourcc",0),"'CMAK'",1); major=1; minor=0; revision=0; sscanf(getvalue(item_get(*child,"project_version",0))->value,"%d.%d.%d",&major,&minor,&revision); sprintf(ver,"%d",major); item_get(item_get(*child,"project_version_major",0),ver,1); sprintf(ver,"%d",minor); item_get(item_get(*child,"project_version_minor",0),ver,1); sprintf(ver,"%d",revision); item_get(item_get(*child,"project_version_revision",0),ver,1); } } void preprocess(item* p) { item* i; item* con_to_exe; char config_path[MAX_PATH]; item *config_file; i = getvalue(item_find(p,"platformlib")); if (i) { char path[MAX_PATH]; sprintf(path,"lib/%s/",i->value); item_get(item_get(p,"libpath",1),path,1); } preprocess_condstart(p); preprocess_config(getconfig(p)); preprocess_condeval(p); // add the path with config.h to CONFIG_INCLUDE i = item_get(p,"config_include",0); config_file = getvalue(getroot(p,"config_file")); if (config_file) strcpy(config_path,config_file->value); else config_path[0]=0; truncfilepath(config_path,0); i = item_get(i,config_path,0); set_path_type(i,FLAG_PATH_GENERATED); i->flags |= FLAG_ATTRIB; i->flags |= FLAG_PATH_GENERATED; // add the path of the CONFIG_CLEANER file to CONFIG_INCLUDE i = getroot(p,"config_cleaner"); if (getvalue(i)) { strcpy(config_path,getvalue(i)->value); truncfilepath(config_path,0); i = item_get(item_get(p,"config_include",0),config_path,1); set_path_type(i,FLAG_PATH_SOURCE); } // add the path of PLATFORM_FILES to CONFIG_INCLUDE if COREMAKE_CONFIG_HELPER is set if (item_get(getconfig(p),"COREMAKE_CONFIG_HELPER",0)->flags & FLAG_DEFINED) { i = item_get(item_get(p,"config_include",0),coremake_root,1); set_path_type(i,FLAG_PATH_SOURCE); } // "GROUP con_to_exe": replaces all "con" by "exe" and add "USE con_to_exe" con_to_exe = getvalue(item_find(item_find(getroot(p,"group"),"con_to_exe"),"source")); if (con_to_exe) { i = item_find(p,"con"); if (i) { item** child; for (child=i->child;child!=i->childend;++child) if (!((*child)->flags & FLAG_REMOVED)) { item* j = item_get(item_get(p,"exe",0),(*child)->value,1); item_merge(j,*child,NULL); item_get(item_get(j,"use",0),"con_to_exe",1); item_delete(*child); --child; } } } else if (item_get(getconfig(p),"COREMAKE_CONSOLE",0)->flags & FLAG_DEFINED) { // repleace all "exe" by "con" i = item_find(p,"exe"); if (i) { item** child; for (child=i->child;child!=i->childend;++child) if (!((*child)->flags & FLAG_REMOVED)) { item* j = item_get(item_get(p,"con",0),(*child)->value,1); item_merge(j,*child,NULL); item_delete(*child); --child; } } } preprocess_group(item_find(p,"lib")); preprocess_group(item_find(p,"exe")); preprocess_group(item_find(p,"con")); preprocess_group(item_find(p,"dll")); preprocess_group(item_find(p,"lib_csharp")); preprocess_group(item_find(p,"exe_csharp")); preprocess_group(item_find(p,"con_csharp")); preprocess_group(item_find(p,"dll_csharp")); preprocess_group(item_find(p,"exe_java")); preprocess_group(item_find(p,"workspace")); // COREMAKE_STATIC and TARGET_ALWAYS_STATIC: replaces all "dll" by "lib" if ((item_get(getconfig(p),"COREMAKE_STATIC",0)->flags & FLAG_DEFINED) || (item_get(getconfig(p),"TARGET_ALWAYS_STATIC",0)->flags & FLAG_DEFINED)) { i = item_find(p,"dll"); if (i) { item** child; for (child=i->child;child!=i->childend;++child) if (!((*child)->flags & FLAG_REMOVED) && ((item_get(getconfig(*child),"TARGET_ALWAYS_STATIC",0)->flags & FLAG_DEFINED) || !getvalue(item_find(*child,"never_static")))) { item_merge(item_get(item_get(p,"lib",0),(*child)->value,1),*child,NULL); item_delete(*child); --child; } } i = item_find(p,"dll_csharp"); if (i) { item** child; for (child=i->child;child!=i->childend;++child) if (!((*child)->flags & FLAG_REMOVED) && ((item_get(getconfig(*child),"TARGET_ALWAYS_STATIC",0)->flags & FLAG_DEFINED) || !getvalue(item_find(*child,"never_static")))) { item_merge(item_get(item_get(p,"lib_csharp",0),(*child)->value,1),*child,NULL); item_delete(*child); --child; } } } preprocess_presort(item_find(p,"lib")); preprocess_presort(item_find(p,"con")); preprocess_presort(item_find(p,"exe")); preprocess_presort(item_find(p,"dll")); preprocess_presort(item_find(p,"lib_csharp")); preprocess_presort(item_find(p,"con_csharp")); preprocess_presort(item_find(p,"exe_csharp")); preprocess_presort(item_find(p,"dll_csharp")); preprocess_presort(item_find(p,"exe_java")); preprocess_builtlib(item_find(p,"project")); preprocess_builtlib(item_find(p,"lib")); preprocess_builtlib(item_find(p,"lib_csharp")); preprocess_usemerge(item_find(p,"dll")); preprocess_usemerge(item_find(p,"exe")); preprocess_usemerge(item_find(p,"dll_csharp")); preprocess_usemerge(item_find(p,"exe_csharp")); preprocess_usemerge(item_find(p,"exe_java")); // the .build (or .inc) file needs to define these preprocess_outputname(item_find(p,"lib"),"output_lib"); preprocess_outputname(item_find(p,"exe"),"output_exe"); preprocess_outputname(item_find(p,"con"),"output_con"); preprocess_outputname(item_find(p,"dll"),"output_dll"); preprocess_outputname(item_find(p,"lib_csharp"),"output_lib"); preprocess_outputname(item_find(p,"exe_csharp"),"output_exe"); preprocess_outputname(item_find(p,"con_csharp"),"output_con"); preprocess_outputname(item_find(p,"dll_csharp"),"output_dll"); preprocess_outputname(item_find(p,"exe_java"),"output_java"); preprocess_stdafx_includes(item_find(p,"con"),0); preprocess_stdafx_includes(item_find(p,"exe"),0); preprocess_stdafx_includes(item_find(p,"dll"),0); preprocess_stdafx_includes(item_find(p,"lib"),1); preprocess_stdafx_includes(item_find(p,"con_csharp"),0); preprocess_stdafx_includes(item_find(p,"exe_csharp"),0); preprocess_stdafx_includes(item_find(p,"dll_csharp"),0); preprocess_stdafx_includes(item_find(p,"lib_csharp"),1); preprocess_stdafx_includes(item_find(p,"exe_java"),0); preprocess_dependency_init(item_find(p,"lib"),1); preprocess_dependency_init(item_find(p,"exe"),0); preprocess_dependency_init(item_find(p,"con"),0); preprocess_dependency_init(item_find(p,"dll"),0); preprocess_dependency_init(item_find(p,"lib_csharp"),1); preprocess_dependency_init(item_find(p,"exe_csharp"),0); preprocess_dependency_init(item_find(p,"con_csharp"),0); preprocess_dependency_init(item_find(p,"dll_csharp"),0); preprocess_dependency_init(item_find(p,"exe_java"),0); preprocess_dependency(item_find(p,"lib")); preprocess_dependency(item_find(p,"con")); preprocess_dependency(item_find(p,"exe")); preprocess_dependency(item_find(p,"dll")); preprocess_dependency(item_find(p,"lib_csharp")); preprocess_dependency(item_find(p,"con_csharp")); preprocess_dependency(item_find(p,"exe_csharp")); preprocess_dependency(item_find(p,"dll_csharp")); preprocess_dependency(item_find(p,"exe_java")); preprocess_stdafx(item_find(p,"con"),0); preprocess_stdafx(item_find(p,"exe"),0); preprocess_stdafx(item_find(p,"dll"),0); preprocess_stdafx(item_find(p,"lib"),1); preprocess_stdafx(item_find(p,"con_csharp"),0); preprocess_stdafx(item_find(p,"exe_csharp"),0); preprocess_stdafx(item_find(p,"dll_csharp"),0); preprocess_stdafx(item_find(p,"lib_csharp"),1); preprocess_stdafx(item_find(p,"exe_java"),0); preprocess_workspace_init(item_find(p,"lib")); preprocess_workspace_init(item_find(p,"exe")); preprocess_workspace_init(item_find(p,"con")); preprocess_workspace_init(item_find(p,"dll")); preprocess_workspace_init(item_find(p,"lib_csharp")); preprocess_workspace_init(item_find(p,"exe_csharp")); preprocess_workspace_init(item_find(p,"con_csharp")); preprocess_workspace_init(item_find(p,"dll_csharp")); preprocess_workspace_init(item_find(p,"exe_java")); preprocess_workspace(item_get(p,"workspace",0)); preprocess_condend(p); preprocess_sort(item_find(p,"lib")); preprocess_sort(item_find(p,"con")); preprocess_sort(item_find(p,"exe")); preprocess_sort(item_find(p,"dll")); preprocess_sort(item_find(p,"lib_csharp")); preprocess_sort(item_find(p,"con_csharp")); preprocess_sort(item_find(p,"exe_csharp")); preprocess_sort(item_find(p,"dll_csharp")); preprocess_sort(item_find(p,"exe_java")); preprocess_sort_workspace(item_find(p,"workspace")); } #define MAX_PUSHED_PATH 8 FILE* build; char buildpath[MAX_PUSHED_PATH][MAX_PATH]; int buildflags[MAX_PUSHED_PATH]; int curr_build = 0; void simplifypath(char* path, int head) { char* s; for (s=path;*s;++s) { if (strncmp(s,"/../",4)==0 && s!=path) { char* end = s+4; while (--s!=path) if (*s == '/' || *s == '\\') { ++s; break; } s = strdel(s,end); if (s != path) --s; --s; } if (strncmp(s,"/./",3)==0 && s!=path) memmove(s+1,s+3,strlen(s+3)+1); if (strncmp(s,"/.",3)==0 && s!=path) s[1]=0; } if (head) { while (path[0] == '.' && path[1] == '/') memmove(path,path+2,strlen(path+2)); } } void getabspath(char* path, int path_flags, const char *rel_path, int rel_flags) { assert((path_flags & FLAG_PATH_MASK) != FLAG_PATH_NOT_PATH); if (!(path_flags & FLAG_PATH_SET_ABSOLUTE)) { char base[3*MAX_PATH]; if (rel_path[0]) { base[0] = '\0'; strins(base,rel_path,getfilename(rel_path)); } else switch (rel_flags & FLAG_PATH_MASK) { case FLAG_PATH_SOURCE: strcpy(base,src_root); break; case FLAG_PATH_GENERATED: strcpy(base,proj_root); break; case FLAG_PATH_COREMAKE: strcpy(base,coremake_root); break; default: base[0] = '\0'; // safety } addendpath(base); strcat(base,path); simplifypath(base,0); strcpy(path,base); } } char* getname(char* s,char* name) { for (;*s && isspace(*s);++s); for (;*s && isname(*s);++s) *(name++) = *s; *name = 0; return s; } void urlquote(char *name,int no_backslash) { char *q = strrchr(name,'\"'); while (q) { strdel(q,q+1); strins(q,""",NULL); if (!no_backslash) strins(q,"\\",NULL); q = strrchr(name,'\"'); } } int tokeneval(char* s,int skip,build_pos* pos,reader* error, int extra_cmd) { size_t maskpos,maskend; char mask[MAX_LINE]; size_t outpos; char out[MAX_LINE]; char name[MAX_LINE]; char value[MAX_LINE]; int result = FLAG_PATH_NOT_PATH; int has_forced_generated = 0; for (;*s;++s) { char* s0 = s; if (extra_cmd && s[0]=='%' && s[1]=='%') { s +=2; s = getname(s,name); if (stricmp(name,"DIRPUSH")==0) { int flags; s = strdel(s0,s); s = strins(s,"cd ",NULL); s +=2; while (isspace(*s)) ++s; s0 = s; flags = tokeneval(s,skip,pos,error,extra_cmd); if (++curr_build > MAX_PUSHED_PATH) { printf("can't push directory %s, limit reached\r\n",s); exit(1); } strcpy(name,s); getabspath(name,flags,buildpath[curr_build-1],buildflags[curr_build-1]); addendpath(name); strcpy(buildpath[curr_build],name); buildflags[curr_build] = flags; getrelpath(name,flags,buildpath[curr_build-1],buildflags[curr_build-1],0,0); truncfilepath(name,1); s = strcpy(s0,name); continue; } else if (stricmp(name,"DIRPOP")==0) { int flags; s = strdel(s0,s); s = strins(s,"cd ",NULL); s +=3; while (isspace(*s)) ++s; s0 = s; flags = tokeneval(s,skip,pos,error,extra_cmd); if (--curr_build < 0) { printf("can't pop directory limit reached\r\n"); exit(1); } strcpy(name,buildpath[curr_build]); getrelpath(name,buildflags[curr_build],buildpath[curr_build+1],buildflags[curr_build+1],0,0); truncfilepath(name,1); s = strcpy(s0,name); continue; } } if (s[0]=='%' && s[1]=='(') { int in_generated; int count; int upper; int delhex; int relpath; int filepath; int filefourcc; int filename; int fileext; int fileupper; int fourcc; int levelup; int delend; int deltrail; int addend; int dos; int reverse; int abspath; int getused; int escape; int nodrive; int findfile; int quote; int no_backslash; int only_abspath; int only_relpath; item** child; size_t n; const char* iname; build_pos* ipos; item* i; s += 2; in_generated = *s=='¯'; if (in_generated) ++s; if (*s=='¯' && ++in_generated) ++s; nodrive = *s==':'; if (nodrive) ++s; count = *s=='='; if (count) ++s; dos = *s=='~'; if (dos) ++s; fourcc = *s=='\''; if (fourcc) ++s; fileupper = *s=='?'; if (fileupper) ++s; filename = *s=='<'; if (filename) ++s; filefourcc = *s==','; if (filefourcc) ++s; fileext = *s=='>'; if (fileext) ++s; only_abspath = *s=='º'; if (only_abspath) ++s; only_relpath = *s=='º'; if (only_relpath) { ++s; only_abspath=0; } relpath = *s=='!'; if (relpath) ++s; escape = *s=='`'; if (escape) ++s; while (*s=='`' && ++escape) ++s; upper = *s=='^'; if (upper) ++s; filepath = *s=='/'; if (filepath) { ++s; if (*s=='!') ++s; else relpath=1; } abspath = *s=='|'; if (abspath) { ++s; relpath=1; } levelup = 0; while (*s==';' && ++levelup) s++; delend = *s=='@'; if (delend) { ++s; relpath=1; } deltrail = *s=='§'; if (deltrail) ++s; addend = *s=='+'; if (addend) { ++s; } delhex = *s=='#'; if (delhex) ++s; reverse = *s=='_'; if (reverse) ++s; getused = *s=='*'; if (getused) ++s; findfile = *s=='÷'; if (findfile) ++s; quote = *s=='&'; if (quote) ++s; no_backslash = *s=='&'; if (no_backslash) ++s; if (!filename) { if (in_generated==1) { has_forced_generated = 1; result |= FLAG_PATH_GENERATED; } else if (in_generated) { has_forced_generated = 2; result |= FLAG_PATH_SYSTEM; } } if (relpath && (buildflags[curr_build] & FLAG_PATH_SET_ABSOLUTE)) abspath = 1; s = getname(s,name); ipos = pos; iname = name; while (iname[0]=='.' && iname[1]=='.' && iname[2]=='/') { if (ipos->prev) ipos = ipos->prev; iname += 3; } i = ipos->p; if (stricmp(iname,"type")==0) { if (!skip) { if ((!i->parent || relpath)) syntax(error); strcpy(name,i->parent->value); if (upper) upr(name); } } else { item* i2; item* j; int usename=0; if (stricmp(iname,"name")==0) { j = i; usename = 1; } else { item *ii=i; if (getused && ipos->prev) { size_t k; ii = ipos->prev->p; j = item_find(ii,"use"); for (k=0;kchild[k]->value,i->value)==0) { ii = j->child[k]; break; } } } j = item_find(ii,iname); for (i2=ii;!skip && !j && i2->parent;) { // search in parents i2=i2->parent; j = item_find(i2,iname); } if (!skip && !j) j = item_find(getconfig(i),iname); } if (count) { sprintf(name,"%d",j?(int)item_childcount(j):0); } else if (s[0]==':') { int checkquote; int deep; ++s; maskpos=0; for (n=0;*s && *s!='=';++s) if (*s=='%') maskpos=n; else mask[n++]=*s; mask[n]=0; maskend=n-maskpos; if (*s != '=') syntax(error); ++s; outpos=0; deep=0; for (n=0;*s;++s) { if (*s==')' && --deep<0) break; if (*s=='(') ++deep; if (*s=='%') { if (s[1]=='(') { for (;*s!=')';++s) out[n++]=*s; out[n++]=*s; } else outpos=n; } else out[n++]=*s; } out[n]=0; checkquote = outpos>0 && out[outpos-1]=='\'' && out[outpos]=='\''; if (checkquote) { out[outpos-1]='"'; out[outpos]='"'; } if (*s != ')') syntax(error); name[0]=0; if (j) { for (child=j->child;usename || child!=j->childend;++child) { item *Item = usename?j:(*child); int value_flags = Item->flags; relpath = 1; if (only_abspath || only_relpath) { int isabs = (Item->flags & FLAG_PATH_SET_ABSOLUTE) == FLAG_PATH_SET_ABSOLUTE; if (isabs && !only_abspath) continue; if (!isabs && !only_relpath) continue; } strcpy(value,Item->value); // force a relative path by default if ((value_flags & FLAG_PATH_MASK) != FLAG_PATH_NOT_PATH) strip_path_abs(value, value_flags); if (in_generated==1) { value_flags &= ~FLAG_PATH_MASK; value_flags |= FLAG_PATH_GENERATED; } else if (in_generated) { value_flags &= ~FLAG_PATH_MASK; value_flags |= FLAG_PATH_SYSTEM; } if (relpath) getrelpath(value,value_flags,buildpath[curr_build],buildflags[curr_build],delend,levelup); if (abspath) getabspath(value,value_flags,buildpath[curr_build],buildflags[curr_build]); if (filepath) truncfilepath(value,delend); if (fileupper) truncfileupper(value); if (filename) truncfilename(value); if (filefourcc) truncfilefourcc(value); if (fileext) truncfileext(value); if (addend) addendpath(value); if (delhex) trunchex(value); if (fourcc) truncfourcc(value); if (deltrail) delendpath(value); if (dos) pathdos(value); if (upper) upr(value); if (reverse) reversestr(value); if (nodrive) removedrive(value); if (escape==1) escapestr(value); else if (escape) escapepath(value,escape); if (quote) urlquote(value,no_backslash); n = strlen(value); if (n>strlen(mask) && memcmp(value,mask,maskpos)==0 && strcmp(value+n-maskend,mask+maskpos)==0) { int skipquote=0; char* name0 = name+strlen(name); if (name[0]) strcat(name," "); if (checkquote) { char* i=value+maskpos; char* ie=value+n-maskend; skipquote=1; for (;i!=ie;++i) { char ch=*i; if (!isalpha(ch) && !isdigit(ch) && ch!='_' && ch!='-' && ch!='.' && ch!='/') { skipquote=0; break; } } } strins(name+strlen(name),out,out+outpos-skipquote); strins(name+strlen(name),value+maskpos,value+n-maskend); strins(name+strlen(name),out+outpos+skipquote,out+strlen(out)); if (findfile && !skip) { char path[MAX_PATH]; struct stat s; char* filename = name0; while (isspace(*filename)) ++filename; strcpy(path,filename); tokeneval(path,0,pos,error,extra_cmd); pathunix(path); getabspath(path,FLAG_PATH_SOURCE,buildpath[curr_build],buildflags[curr_build]); if (stat(path,&s)!=0) name0[0]=0; } } if (usename) break; } } } else { int name_flags = 0; int is_relpath = 1; name[0]=0; if (usename) { strcpy(name,j->value); name_flags = j->flags; } else if (j) { name_flags |= j->flags; for (child=j->child;child!=j->childend;++child) { if (findfile && !skip) { struct stat s; char path[MAX_PATH]; strcpy(path,(*child)->value); tokeneval(path,0,pos,error,extra_cmd); pathunix(path); getabspath(path,FLAG_PATH_SOURCE,buildpath[curr_build],buildflags[curr_build]); if (stat(path,&s)!=0) continue; } if (name[0]) strcat(name," "); strcat(name,(*child)->value); name_flags |= (*child)->flags; } } // force a relative path by default if (!filename && (name_flags & FLAG_PATH_MASK) != FLAG_PATH_NOT_PATH) { if (!escape && (!has_forced_generated || (name_flags & FLAG_PATH_MASK)==FLAG_PATH_SYSTEM)) { result &= ~FLAG_PATH_MASK; result |= name_flags & FLAG_PATH_MASK; } if (skip || !abspath) strip_path_abs(name, name_flags); else is_relpath = 0; } if (in_generated==1) { name_flags &= ~FLAG_PATH_MASK; name_flags |= FLAG_PATH_GENERATED; } else if (in_generated) { name_flags &= ~FLAG_PATH_MASK; name_flags |= FLAG_PATH_SYSTEM; } if (is_relpath && relpath) getrelpath(name,name_flags,buildpath[curr_build],buildflags[curr_build],delend,levelup); if (!skip && abspath && is_relpath) getabspath(name,name_flags,buildpath[curr_build],buildflags[curr_build]); if (filepath) truncfilepath(name,delend); if (fileupper) truncfileupper(name); if (filename) truncfilename(name); if (filefourcc) truncfilefourcc(name); if (fileext) truncfileext(name); if (addend) addendpath(name); if (delhex) trunchex(name); if (fourcc) truncfourcc(name); if (deltrail) delendpath(name); if (dos) pathdos(name); if (upper) upr(name); if (reverse) reversestr(name); if (nodrive) removedrive(name); if (escape==1) escapestr(name); else if (escape) escapepath(name,escape); if (quote) urlquote(name,no_backslash); } } for (;*s && isspace(*s);++s); if (*s != ')') syntax(error); ++s; s = strdel(s0,s); s = strins(s,name,NULL); --s; } } return result; } int reader_tokeneval(reader* p,int skip,int onespace,build_pos* pos,int extra_cmd) { reader_tokenline(p,onespace); return tokeneval(p->token,skip,pos,p,extra_cmd); } int str2bool(const char* s) { return s[0] && strcmp(s,"0")!=0; } char* bool2str(int v) { return strdup(v?"1":"0"); } void evalspace(const char** s) { for (;(*s)[0] && isspace((*s)[0]);++(*s)); } char* eval0(const char** s,item* config,reader* file); char* eval3(const char** s,item* config,reader* file) { int n; char* a; const char* s0; evalspace(s); if ((*s)[0] == '(') { char* a; *s += 1; a = eval0(s,config,file); evalspace(s); if ((*s)[0] != ')') syntax(file); *s += 1; return a; } else if ((*s)[0] == '"') { *s += 1; s0 = *s; for (n=0;(*s)[0] && (*s)[0]!='"';(*s)++,++n); if ((*s)[0]!='"') syntax(file); *s += 1; a = zalloc(n+1); memcpy(a,s0,n); } else if (isname((*s)[0])) { s0 = *s; for (n=0;(*s)[0] && isname((*s)[0]);(*s)++,++n); a = zalloc(n+1); memcpy(a,s0,n); if (stricmp(a,"defined")==0 && (*s)[0]=='(') { item* i; free(a); *s += 1; s0 = *s; for (n=0;(*s)[0] && (*s)[0]!=')';(*s)++,++n); a = zalloc(n+1); memcpy(a,s0,n); i = item_find(config,a); free(a); if ((*s)[0] != ')') syntax(file); *s += 1; a = bool2str(i && (i->flags & FLAG_DEFINED)); } } else a = strdup(""); return a; } char* eval2(const char** s,item* config,reader* file) { evalspace(s); if ((*s)[0] == '!' && (*s)[1] != '=') { int value; char* a; *s += 1; a = eval2(s,config,file); value = !str2bool(a); free(a); return bool2str(value); } else return eval3(s,config,file); } char* eval1(const char** s,item* config,reader* file) { int value; char* b; char* a = eval2(s,config,file); evalspace(s); if ((*s)[0] == '=' && (*s)[1] == '=') { *s += 2; b = eval1(s,config,file); value = stricmp(a,b)==0; free(a); free(b); a = bool2str(value); } else if ((*s)[0] == '!' && (*s)[1] == '=') { *s += 2; b = eval1(s,config,file); value = stricmp(a,b)!=0; free(a); free(b); a = bool2str(value); } return a; } char* eval0(const char** s,item* config,reader* file) { int value; char* b; char* a = eval1(s,config,file); evalspace(s); if ((*s)[0] == '&' && (*s)[1] == '&') { *s += 2; b = eval0(s,config,file); value = str2bool(a) && str2bool(b); free(a); free(b); a = bool2str(value); } else if ((*s)[0] == '|' && (*s)[1] == '|') { *s += 2; b = eval0(s,config,file); value = str2bool(a) || str2bool(b); free(a); free(b); a = bool2str(value); } return a; } int eval(const char* s,item* config,reader* file) { int result; char* a = eval0(&s,config,file); result = str2bool(a); free(a); return result; } int same_ch(int a, int b) { #ifdef _WIN32 return toupper(a) == toupper(b); #else return a==b; #endif } int match(const char* name, const char* mask) { if (*mask=='*') { ++mask; for (;!match(name,mask);++name) { if (*name==0) return 0; } return 1; } else { if (*mask==0) return *name==0; if (*name==0) return 0; return (mask[0]=='?' || same_ch(name[0],mask[0])) && match(name+1,mask+1); } } void remove_file(const char* name) { if (strchr(name,'*') == NULL && strchr(name,'?') == NULL) remove(name); else { DIR* dir; const char* mask = getfilename(name); char path[MAX_PATH]; strncpy(path,name,MAX_PATH); truncfilepath(path,1); dir = opendir(path[0]?path:"."); if (dir) { struct dirent* entry; addendpath(path); while ((entry = readdir(dir)) != NULL) { if (entry->d_name[0]!='.' && match(entry->d_name,mask)) { char filepath[MAX_PATH]; strcpy(filepath,path); strcat(filepath,entry->d_name); remove(filepath); } } closedir(dir); } } } void remove_dir(const char* name) { DIR* dir = opendir(name); if (dir) { struct dirent* entry; while ((entry = readdir(dir)) != NULL) { if (entry->d_name[0]!='.') { char item[MAX_PATH]; sprintf(item,"%s/%s",name,entry->d_name); remove_dir(item); } } closedir(dir); remove_dir(".DS_Store"); remove_dir(".Trashes"); rmdir(name); } else remove(name); } item* reader_item(reader* file, int skip, build_pos* pos) { item* i = NULL; reader_name(file); if (!skip) { const char* token = file->token; build_pos* parent = pos; while (token[0]=='.' && token[1]=='.' && token[2]=='/') { if (parent) parent = parent->prev; token += 3; } if (parent) i = item_get(parent->p,token,1); } return i; } void create_missing_dirs(const char *path) { size_t strpos = 0, strpos_i; char new_dir[MAX_PATH]; char new_path[MAX_PATH]; int ret; struct stat dir_stats; assert(ispathabs(path)); // internally all pathes should be absolute strcpy(new_path,path); pathunix(new_path); simplifypath(new_path,1); for (;;) { strpos_i = strcspn(&new_path[strpos], "/"); if (strpos_i == strlen(&new_path[strpos])) break; strpos += strpos_i+1; strncpy(new_dir, new_path, strpos-1); new_dir[strpos-1] = '\0'; if (stat(new_dir, &dir_stats) == 0) { if ((dir_stats.st_mode & S_IFDIR) != S_IFDIR) { printf("%s is not a directory\r\n",new_dir); exit(1); } } else if (strpos>1 && new_dir[strpos-2] != ':') { ret = make_dir(new_dir); if (ret != 0 && ret != EEXIST) { printf("can't create directory %s\r\n",new_dir); exit(1); } } } } void getarg(char* s, const char** in) { int quote = 0; while (**in && isspace(**in)) ++(*in); for (;**in && (quote || !isspace(**in));++(*in)) { if (**in == '"') { quote = !quote; continue; } *(s++) = **in; } *s = 0; } void build_file(item* p,const char* filename, int reader_flags); int build_parse(item* p,reader* file,int sub,int skip,build_pos* pos0) { int bin; int result=0; item* i; build_pos pos; int is_sharped; char tmpstr[MAX_LINE]; if (pos0 && pos0->p == p) pos.prev = pos0->prev; else pos.prev = pos0; pos.p = p; while (!reader_eof(file)) { is_sharped =0; if (reader_istoken_n(file,"#",1)) { is_sharped = 1; reader_token_skip(file,1); } if (is_sharped && reader_istoken(file,"include")) { reader_token(file); reader_filename(file,FLAG_PATH_COREMAKE); if (!skip) build_file(p,file->token,FLAG_PATH_COREMAKE); } else if (is_sharped && reader_istoken(file,"undef")) { reader_name(file); if (!skip) { i=item_find(getconfig(p),file->token); if (i) i->flags &= ~FLAG_DEFINED; } } else if (is_sharped && reader_istoken(file,"define")) { reader_name(file); i = skip?NULL:item_get(getconfig(p),file->token,1); if (!skip && strnicmp(file->token,"CONFIG_CUSTOMER_",16)==0) { char *lower = file->token+16; i = item_get(getconfig(p),"CONFIG_CUSTOMER",1); lwr(lower); item_get(i,lower,1); } else if (reader_tokenline(file,0) && !skip) { char* s = file->token; size_t len = strlen(s); if (len>=2 && s[0]=='\'' && s[len-1]=='\'') { strdel(s+len-1,s+len); strdel(s,s+1); } if (len>=5 && s[0]=='T' && s[1]=='(' && s[2]=='"' && s[len-1]==')' && s[len-2]=='"') { strdel(s+len-2,s+len); strdel(s,s+3); } i = item_get(i,file->token,1); if (stricmp(i->parent->value,"CONFIG_ANDROID_NDK")==0) { pathunix(i->value); set_path_type(i,FLAG_PATH_SYSTEM); } } } else if (!is_sharped && reader_istoken(file,"config")) { if (!skip) { item* config = getroot(p,"config_file"); if (getvalue(config)) { set_path_type(config,FLAG_PATH_GENERATED); build_file(p,getvalue(config)->value, FLAG_PATH_GENERATED); } config = item_get(getconfig(p),"COREMAKE_CONFIG_HELPER",0); if (config && config->flags & FLAG_DEFINED) { strcpy(tmpstr,coremake_root); strcat(tmpstr,"config_helper.h"); build_file(p,tmpstr, FLAG_PATH_COREMAKE); } config = getroot(p,"config_cleaner"); if (getvalue(config)) { set_path_type(config,FLAG_PATH_SOURCE); build_file(p,getvalue(config)->value, FLAG_PATH_SOURCE); } preprocess(p); } } else if (!is_sharped && reader_istoken(file,"while")) { int v; reader whilepos; reader_save(file,&whilepos); do { reader_restore(file,&whilepos); reader_tokeneval(file,skip,0,&pos,0); v = eval(file->token,getconfig(p),file); build_parse(p,file,21,!v || skip,&pos); if (p->flags & FLAG_REMOVED) skip = 1; } while (v && !skip); reader_free(&whilepos); } else if (reader_istoken(file,"if")) { int done=0; int m; do { int v; reader_tokeneval(file,skip,0,&pos,0); v = eval(file->token,getconfig(p),file); m = build_parse(p,file,2,!v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; if (m==1) { build_parse(p,file,3,v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; } else if (v) done = 1; } while (m==2); } else if (reader_istoken(file,"ifdef")) { int done=0; int m; do { int v; reader_tokeneval(file,skip,0,&pos,0); i = item_find(getconfig(p),file->token); v = i && (i->flags & FLAG_DEFINED); m = build_parse(p,file,2,!v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; if (m==1) { build_parse(p,file,3,v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; } else if (v) done = 1; } while (m==2); } else if (reader_istoken(file,"ifndef")) { int done=0; int m; do { int v; reader_tokeneval(file,skip,0,&pos,0); i = item_find(getconfig(p),file->token); v = !i || !(i->flags & FLAG_DEFINED); m = build_parse(p,file,2,!v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; if (m==1) { build_parse(p,file,3,v || skip || done,&pos); if (p->flags & FLAG_REMOVED) skip = 1; } else if (v) done = 1; } while (m==2); } else if (!is_sharped && reader_istoken(file,"%%END")) { if (sub!=16) syntax(file); break; } else if (reader_istoken(file,"else")) { if (sub!=2) syntax(file); result = 1; break; } else if (reader_istoken(file,"elif")) { if (sub!=2) syntax(file); result = 2; break; } else if (reader_istoken(file,"endif")) { if (sub!=2 && sub!=3) syntax(file); break; } else if (!is_sharped && reader_istoken(file,"endadd")) { if (sub!=9) syntax(file); break; } else if (!is_sharped && reader_istoken(file,"endwhile")) { if (sub!=21) syntax(file); break; } else if (!is_sharped && reader_istoken(file,"print")) { reader_tokeneval(file,skip,1,&pos,0); if (!skip) { if (!build) { printf("not file opened!\r\n"); exit(1); } fprintf(build,"%s",file->token); } } else if (!is_sharped && reader_istoken(file,"echo")) { reader_tokeneval(file,skip,1,&pos,0); if (!skip) printf("%s\r\n",file->token); } else if (!is_sharped && reader_istoken(file,"printnl")) { reader_tokeneval(file,skip,1,&pos,0); if (!skip) { if (!build) { printf("no file opened!\r\n"); exit(1); } fprintf(build,"%s\n",file->token); } } else if (!is_sharped && reader_istoken(file,"printnldos")) { reader_tokeneval(file,skip,1,&pos,0); if (!skip) { if (!build) { printf("no file opened!\r\n"); exit(1); } #ifdef _WIN32 fprintf(build,"%s\n",file->token); #else fprintf(build,"%s\r\n",file->token); #endif } } else if (!is_sharped && reader_istoken(file,"compile")) { int flags = reader_tokeneval(file,skip,1,&pos,0); if (!skip) { reader r; const char* s = file->token; reader_init(&r); getarg(r.filename,&s); pathunix(r.filename); getabspath(r.filename,flags,"",FLAG_PATH_SOURCE); r.r.f = fopen(r.filename,"r"); r.r.flags = flags; r.pos = r.line; r.r.filename_kind = FLAG_PATH_SOURCE; // TODO: in verbose mode we should issue a warning if the file is not found if (r.r.f) { item *src; char backup[MAX_PATH]; FILE* backupfile = build; int backupflags = buildflags[curr_build]; strcpy(backup,buildpath[curr_build]); getarg(buildpath[curr_build],&s); getabspath(buildpath[curr_build],FLAG_PATH_GENERATED|(ispathabs(buildpath[curr_build])?FLAG_PATH_SET_ABSOLUTE:0),"",FLAG_PATH_GENERATED); simplifypath(buildpath[curr_build],0); buildflags[curr_build] = FLAG_PATH_GENERATED; // check that the src and dst files are different if (stricmp(r.filename,buildpath[curr_build])==0) { char *ext = strrchr(buildpath[curr_build],'.'); if (!ext) strcat(buildpath[curr_build],".compiled"); else strins(ext,ext,NULL); printf("*warning: COMPILE '%s' already exists, using '%s'\r\n",r.filename,buildpath[curr_build]); } create_missing_dirs(buildpath[curr_build]); build = fopen(buildpath[curr_build],"w+"); tmpstr[0]=0; strins(tmpstr,r.filename,getfilename(r.filename)); item_delete(item_find(pos.p,"base")); src = item_get(item_get(pos.p,"base",0),tmpstr,1); set_path_type(src,FLAG_PATH_SOURCE); if (build) { while (reader_line(&r)) { const char* eval = r.line; evalspace(&eval); if (stricmp(eval,"%%BEGIN")==0) { reader_line(&r); build_parse(p,&r,16,0,&pos); } else { reader_tokeneval(&r,0,-1,&pos,1); fputs(r.token,build); fputc(10,build); } } fclose(build); } fclose(r.r.f); build = backupfile; strcpy(buildpath[curr_build],backup); buildflags[curr_build] = backupflags; } reader_free(&r); } } else if (!is_sharped && reader_istoken(file,"inc")) { i = reader_item(file,skip,&pos); i = getvalue(i); if (!skip && i && i->value) { char v[16]; sprintf(v,"%d",atoi(i->value)+1); free(i->value); i->value = strdup(v); } } else if (!is_sharped && reader_istoken(file,"for")) { int reverse = reader_istoken(file,"reverse"); if (reader_istoken(file,"each")) { char* s; reader forpos; int first=1; reader_tokeneval(file,skip,0,&pos,0); reader_save(file,&forpos); s = forpos.token; for (;;) { build_pos* ipos = &pos; const char* iname = tmpstr; s = getname(s,tmpstr); while (iname[0]=='.' && iname[1]=='.' && iname[2]=='/') { if (ipos->prev) ipos = ipos->prev; iname += 3; } i = item_find(ipos->p,iname); if (i && !skip) { item** child; item** childend; if (reverse) { child = i->childend-1; childend = i->child-1; } else { child = i->child; childend = i->childend; } while (child!=childend) { item* w; if (!first) reader_restore(file,&forpos); w = findref2(*child); if (w) setvalue(item_get(w,"for_last",0),(child+(reverse?-1:1)==childend)?"1":"0"); build_parse(w,file,1,0,&pos); if (w->flags & FLAG_REMOVED) { item_delete(w); if (!reverse) { --child; childend = i->childend; } } if (reverse) --child; else ++child; first = 0; } } for (;*s && isspace(*s);++s); if (*s==0) break; if (*s!=',') syntax(&forpos); ++s; } reader_free(&forpos); if (first) build_parse(p,file,1,1,&pos); } else syntax(file); } else if (!is_sharped && reader_istoken(file,"endfor")) { if (sub!=1) syntax(file); break; } else if (!is_sharped && reader_istoken(file,"remove")) { reader_tokeneval(file,skip,0,&pos,0); if (!skip) remove_file(file->token); } else if (!is_sharped && reader_istoken(file,"delete")) { if (!skip) { p->flags |= FLAG_REMOVED; skip = 1; } } else if (!is_sharped && reader_istoken(file,"removedir")) { reader_tokeneval(file,skip,0,&pos,0); if (!skip) remove_dir(file->token); } else if (!is_sharped && reader_istoken(file,"script")) { chmod(buildpath[curr_build],S_IEXEC|S_IREAD|S_IWRITE); } else if (!is_sharped && reader_istoken(file,"fileabs")) { if (!skip) buildflags[curr_build] |= FLAG_PATH_SET_ABSOLUTE; } else if (!is_sharped && ((bin=reader_istoken(file,"filebin"))!=0 || reader_istoken(file,"file"))) { if (!skip) { if (build) { fclose(build); file_finalize(buildpath[curr_build]); } } buildflags[curr_build] = reader_tokeneval(file,skip,0,&pos,0); if (!skip) { strcat(file->token,".tmp"); strcpy(buildpath[curr_build],file->token); simplifypath(buildpath[curr_build],0); getabspath(buildpath[curr_build],buildflags[curr_build],"",buildflags[curr_build]); create_missing_dirs(buildpath[curr_build]); build = fopen(buildpath[curr_build],bin?"wb":"w"); if (!build) { printf("can't create %s\r\n",file->token); exit(1); } } } else if (!is_sharped && reader_istoken(file,"add")) { int flags; i = reader_item(file,skip,&pos); flags = reader_tokeneval(file,skip,0,&pos,0); if (i) { item *j = item_get(i,file->token,1); set_path_type(j,flags & FLAG_PATH_MASK); build_parse(j,file,9,skip,&pos); } else build_parse(p,file,9,1,&pos); } else if (!is_sharped && reader_istoken(file,"dirpush")) { int flags = reader_tokeneval(file,skip,0,&pos,0); if (!skip) { if (++curr_build > MAX_PUSHED_PATH) { printf("can't push directory %s, limit reached\r\n",file->token); exit(1); } getabspath(file->token,flags,buildpath[curr_build-1],buildflags[curr_build-1]); addendpath(file->token); strcpy(buildpath[curr_build],file->token); buildflags[curr_build] = flags; } } else if (!is_sharped && reader_istoken(file,"dirpop")) { if (!skip) { if (--curr_build < 0) { printf("can't pop directory limit reached\r\n"); exit(1); } } } else if (!is_sharped && reader_istoken(file,"mkdir")) { int flags = reader_tokeneval(file,skip,0,&pos,0); if (!skip) { getabspath(file->token,flags,"",FLAG_PATH_GENERATED); create_missing_dirs(file->token); } } else if (!is_sharped && reader_istoken(file,"copy")) { int flags = reader_tokeneval(file,skip,0,&pos,0); if (!skip) { FILE *src,*dst; const char* s = file->token; getarg(tmpstr,&s); pathunix(tmpstr); getabspath(tmpstr,flags,"",buildflags[curr_build]); src = fopen(tmpstr,"rb"); if (!src) printf("can't open file %s for copy reading\r\n",tmpstr); else { getarg(tmpstr,&s); pathunix(tmpstr); getabspath(tmpstr,flags,"",buildflags[curr_build]); dst = fopen(tmpstr,"wb"); if (!dst) printf("can't open file %s for copy writing\r\n",tmpstr); else { size_t read_size; read_size = fread(tmpstr,1,sizeof(tmpstr),src); while (read_size) { if (fwrite(tmpstr,1,read_size,dst)!=read_size) { printf("error copying !"); exit(1); } if (feof(src)) break; read_size = fread(tmpstr,1,sizeof(tmpstr),src); } fclose(dst); } fclose(src); } } } else if (!is_sharped) { i = reader_item(file,skip,&pos); if (reader_istoken(file,"=")) { int flags = reader_tokeneval(file,skip,0,&pos,0); while (i && i->child != i->childend) item_delete(i->child[0]); if (i) { item_get(i,file->token,1); set_path_type(i,flags & FLAG_PATH_MASK); } } else if (reader_istoken(file,"+=")) { int flags; flags = reader_tokeneval(file,skip,0,&pos,0); if (i) { item *j = item_get(i,file->token,1); set_path_type(j,flags & FLAG_PATH_MASK); } } else syntax(file); } else syntax(file); } return result; } void build_file(item* p,const char* filename, int reader_flags) { reader r; reader_init(&r); strcpy(r.filename,filename); pathunix(r.filename); r.r.f = fopen(filename,"r"); r.pos = r.line; if (!r.r.f) { printf("'%s' build file not found!\r\n",filename); exit(1); } r.r.flags = reader_flags; r.r.filename_kind = reader_flags; build_parse(p,&r,0,0,NULL); fclose(r.r.f); reader_free(&r); } item* default_workspace(item* workspace,item* i,item* p) { item** child; if (!p) return i; for (child=p->child;child!=p->childend;++child) { if (!i) { truncfilename(proj); i = item_get(workspace,proj,1); } item_get(item_get(i,"use",1),(*child)->value,1); } return i; } int main(int argc, char** argv) { int n; int dumppost = 0; int dump = 0; item* i; char path[MAX_PATH]; char root_forced = 0; item* root = item_get(NULL,"ROOT",0); getconfig(root); getcwd(proj_root,sizeof(proj_root)); pathunix(proj_root); addendpath(proj_root); proj_root_len = strlen(proj_root); for (n=1;n.proj strcpy(proj,src_root); delendpath(proj); truncfilename(proj); strcat(proj,".proj"); strins(proj,src_root,NULL); if (!load_file(root,proj,FLAG_PATH_SOURCE,NULL)) { // search for *.proj DIR* dir = opendir(src_root); if (dir) { int found = 0; struct dirent* entry; while ((entry = readdir(dir)) != NULL) if (entry->d_name[0]!='.' && strrchr(entry->d_name,'.') && stricmp(strrchr(entry->d_name,'.'),".proj")==0 && load_file(root,entry->d_name,FLAG_PATH_SOURCE,NULL)) { found = 1; strcpy(proj,entry->d_name); pathunix(proj); truncfilename(proj); break; } closedir(dir); if (!found) { printf("No root .proj file found !"); exit(1); } } } } if (!getvalue(item_find(root,"workspace"))) { // add default workspace item* w = item_get(root,"workspace",0); item* i = NULL; i=default_workspace(w,i,item_find(root,"exe")); i=default_workspace(w,i,item_find(root,"dll")); i=default_workspace(w,i,item_find(root,"con")); i=default_workspace(w,i,item_find(root,"exe_java")); } preprocess_project(item_find(root,"project")); if (dump) dumpitem(root,1); if (!platform[0]) { if (!dump) usage(); return 1; } item_get(item_get(root,"platformname",1),platform,1); i = item_get(root,"rootpath",1); i = item_get(i,src_root,1); set_path_type(i,FLAG_PATH_SOURCE); i = item_get(root,"builddir",1); i = item_get(i,proj_root,1); set_path_type(i,FLAG_PATH_GENERATED); sprintf(path,"%srelease/%s/",proj_root,platform); i = item_get(root,"outputpath",1); i = item_get(i,path,1); set_path_type(i,FLAG_PATH_GENERATED); sprintf(path,"%sbuild/%s/",proj_root,platform); i = item_get(root,"buildpath",1); i = item_get(i,path,1); set_path_type(i,FLAG_PATH_GENERATED); i = getvalue(getroot(root,"platform_files")); if (i) { if (ispathabs(i->value) || !ispathabs(src_root)) strcpy(coremake_root,i->value); else { strcpy(coremake_root,src_root); strcat(coremake_root,i->value); } simplifypath(coremake_root,1); } else { #ifdef _WIN32 HMODULE this = GetModuleHandleA("coremake.exe"); if (this) { GetModuleFileNameA(this,coremake_root,MAX_PATH); FreeLibrary(this); pathunix(coremake_root); getfilename(coremake_root)[0] = 0; strcat(coremake_root,"coremake"); } #else /// \todo this shouldn't work on UNIX platforms /// since the platform files should be in a dir like /usr/share /// and the argv most likely doesn't contain the path to the exe /// We probably need a --prefix during compilation to hardcode that /usr/share path strcpy(coremake_root,"/usr/local/share/coremake"); #endif i = item_get(root,"platform_files",1); i = item_get(i,coremake_root,1); set_path_type(i,FLAG_PATH_COREMAKE); strcpy(coremake_root,i->value); } addendpath(coremake_root); coremake_root_len = strlen(coremake_root); strcpy(path,coremake_root); strcat(path,platform); strcat(path,".build"); strcpy(buildpath[0],proj_root); //safety buildflags[0] = FLAG_PATH_GENERATED; build = NULL; build_file(root,path,FLAG_PATH_COREMAKE); if (build) { fclose(build); file_finalize(buildpath[curr_build]); } if (dumppost) dumpitem(root,1); item_delete(root); return 0; } bcmatroska2-5.3.101/corec/tools/coremake/coremake.proj000066400000000000000000000002151462133141200225670ustar00rootroot00000000000000PLATFORM_FILES . WORKSPACE coremake { USE coremake USE corerc } CON coremake { SOURCE coremake.c } CON corerc { SOURCE corerc.c } bcmatroska2-5.3.101/corec/tools/coremake/coremake.sln000066400000000000000000000024341462133141200224160ustar00rootroot00000000000000Microsoft Visual Studio Solution File, Format Version 9.00 # Visual C++ Express 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "coremake", ".\coremake.vcproj", "{2EC49E2B-AAFB-4B65-02F7-79964C1F3D25}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "corerc", ".\corerc.vcproj", "{FF7E82E1-7FFA-4C82-EAF5-CB79AAF74D68}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2EC49E2B-AAFB-4B65-02F7-79964C1F3D25}.Debug|Win32.ActiveCfg = Debug|Win32 {2EC49E2B-AAFB-4B65-02F7-79964C1F3D25}.Debug|Win32.Build.0 = Debug|Win32 {2EC49E2B-AAFB-4B65-02F7-79964C1F3D25}.Release|Win32.ActiveCfg = Release|Win32 {2EC49E2B-AAFB-4B65-02F7-79964C1F3D25}.Release|Win32.Build.0 = Release|Win32 {FF7E82E1-7FFA-4C82-EAF5-CB79AAF74D68}.Debug|Win32.ActiveCfg = Debug|Win32 {FF7E82E1-7FFA-4C82-EAF5-CB79AAF74D68}.Debug|Win32.Build.0 = Debug|Win32 {FF7E82E1-7FFA-4C82-EAF5-CB79AAF74D68}.Release|Win32.ActiveCfg = Release|Win32 {FF7E82E1-7FFA-4C82-EAF5-CB79AAF74D68}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal bcmatroska2-5.3.101/corec/tools/coremake/coremake.vcproj000066400000000000000000000124651462133141200231320ustar00rootroot00000000000000 bcmatroska2-5.3.101/corec/tools/coremake/corerc.c000066400000000000000000000105211462133141200215270ustar00rootroot00000000000000/* Copyright (c) 2006-2010, CoreCodec, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CoreCodec, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include void pathunix(char* path) { int i; for (i=0;path[i];++i) if (path[i]=='\\') path[i]='/'; } char* getfilename(const char* path) { char* i = strrchr(path,'/'); if (i) return i+1; return (char*)path; } void truncfilename(char* path) { char* i = getfilename(path); memmove(path,i,strlen(i)+1); i = strrchr(path,'.'); if (i) *i=0; } int main(int argc, char** argv) { FILE *f = NULL; FILE *e = stdout; char filename[256]; char varname[256]; char name[256]; char align[32]; int writeable=0; int corec=0; int n; if (argc<=1) { printf("usage: %s [-a ] [-w] [-corec] [-n ] []\n",argv[0]); return 1; } align[0]=0; varname[0]=0; for (n=1;n bcmatroska2-5.3.101/corec/tools/coremake/distclean.build000066400000000000000000000024261462133141200231020ustar00rootroot00000000000000#include "clean.build" FOR EACH WORKSPACE REMOVE %(¯PATH)%(NAME).ncb REMOVE %(¯PATH)%(NAME)_wins.ncb REMOVE %(¯PATH)%(NAME).suo REMOVE %(¯PATH)%(NAME).opt REMOVE %(¯PATH)%(NAME)_wins.opt REMOVE %(¯PATH)%(NAME).vcb REMOVE %(¯PATH)%(NAME).vco REMOVE %(¯PATH)%(NAME).kdevelop REMOVE %(¯PATH)%(NAME).kdevelop.pcs REMOVE %(¯PATH)%(NAME).kdevses FOR EACH USE FOR EACH COMPILE REMOVE %(NAME).%(>NAME) ENDFOR ENDFOR ENDFOR REMOVE %(¯)root.kdevelop.pcs REMOVE %(¯)root.kdevses REMOVE %(¯)configure REMOVE %(¯)configure.in FOR EACH LIB,DLL,EXE,CON,CAB,LIB_CSHARP,DLL_CSHARP,EXE_CSHARP,CON_CSHARP REMOVE %(¯PATH)%(NAME)_win32.aps REMOVE %(¯PATH)%(NAME).aps REMOVE %(¯PATH)%(NAME).vcproj.*.user REMOVE %(¯PATH)%(NAME).vcproj.user REMOVE %(!ROOTPATH)%(PATH)%(NAME).csproj.*.user REMOVE %(!ROOTPATH)%(PATH)%(NAME).csproj.user REMOVE %(¯PATH)%(NAME).vcl REMOVE %(¯PATH)*.pbxuser REMOVE %(¯PATH)*.mode1 REMOVE %(¯PATH)*.*~ REMOVEDIR %(BUILDPATH)../kdevelop REMOVEDIR %(BUILDPATH)../carbide REMOVEDIR %(BUILDPATH)../carbide_12 REMOVEDIR %(BUILDPATH)../carbide_20 REMOVE %(¯PATH)%(NAME).qrc REMOVEDIR %(PATH)Deb_WINSCW FOR EACH SOURCE IF %(>NAME)==rc REMOVE %(¯PATH)%( PRINTNLDOS PRINTNLDOS Package=<5> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS Package=<4> PRINTNLDOS {{{ FOR EACH USE IF ((%(TYPE)!=LIB) || (%(../TYPE)!=LIB)) && (%(TYPE)!=LIB_CSHARP) && (%(TYPE)!=DLL_CSHARP) && (%(TYPE)!=CON_CSHARP) && (%(TYPE)!=EXE_CSHARP) PRINTNLDOS Begin Project Dependency PRINTNLDOS Project_Dep_Name %(NAME) PRINTNLDOS End Project Dependency ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../ITEM_DEPS += "%(NAME)" ENDIF ENDFOR FOR EACH DEP IF (%(TYPE)!="LIB_CSHARP") && (%(TYPE)!="DLL_CSHARP") && (%(TYPE)!="CON_CSHARP") && (%(TYPE)!="EXE_CSHARP") PRINTNLDOS Begin Project Dependency PRINTNLDOS Project_Dep_Name %(NAME) PRINTNLDOS End Project Dependency ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../ITEM_DEPS += "%(NAME)" ENDIF ENDFOR PRINTNLDOS }}} PRINTNLDOS ENDIF ENDFOR PRINTNLDOS ############################################################################### PRINTNLDOS PRINTNLDOS Global: PRINTNLDOS PRINTNLDOS Package=<5> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS Package=<3> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS ############################################################################### PRINTNLDOS IF %(EVC)!="" FILE %(¯PATH)Makefile.evc FOR EACH USE IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../TO_BUILD += "%(NAME)" ENDIF ENDFOR PRINTNL all: %(TO_BUILD) PRINTNL FOR EACH USE PRINTNL "%(NAME)": %(ITEM_DEPS) PRINTNL @%(EVC) %(../NAME).vcw /make "%(NAME) - Win32 (%(TARGID)) Release" /CEConfig="%(EVC_SDK)" /out "%(../NAME).log.tmp" PRINTNL @grep -v "Could not find the file" <%(../NAME).log.tmp >>%(../NAME).log PRINTNL @del /q %(../NAME).log.tmp IF %(EXEPROTECT)!="" TARGET = %(¯~!OUTPUTPATH)release\%(OUTPUT) PRINTNL @-%(EXEPROTECT) FOR EACH USE IF %(TYPE)==DLL TARGET = %(¯~!OUTPUTPATH)release\%(OUTPUT) PRINTNL @-%(../EXEPROTECT) ENDIF ENDFOR ENDIF FOR EACH INSTALL, INSTALL_CAB PRINTNL @copy /Y %(~!NAME) %(¯~!OUTPUTPATH)release ENDFOR IF %(CAB)!="" && %(CABWIZ)!="" PRINTNL @%(CABWIZ) "%(¯~!PATH)%(NAME)_wince.inf" /dest "%(¯~|OUTPUTPATH)" PRINTNL @move "%(¯~!OUTPUTPATH)%(NAME)_wince.CAB" "%(¯~!OUTPUTPATH)%(PROJECT_NAME).%(CABNAME).cab" ENDIF IF %(NSI)!="" COMPILE %(NSI) %(PATH)%(NAME)_win32.nsi PRINTNL @makensis.exe /V2 %(¯!PATH)%(NAME)_win32.nsi /O%(NAME)_nsi.log ENDIF PRINTNL ENDFOR PRINTNL clean: PRINTNL @if exist %(¯~!§BUILDPATH) rmdir /s /q %(¯~!§BUILDPATH) PRINTNL @if exist %(¯~!§OUTPUTPATH) rmdir /s /q %(¯~!§OUTPUTPATH) ENDIF ENDFOR FOR EACH LIB,DLL,EXE FILE %(¯PATH)%(NAME).vcp PRJNAME = %(NAME) IFNDEF COREMAKE_UNICODE DEFINE += _MBCS ELSE DEFINE += UNICODE DEFINE += _UNICODE ENDIF IF "%(USE_MFC)"!="" USE_MFC = dll ENDIF IF "%(USE_MFC)"=="" && "%(USE_ATL)"!="" USE_MFC = . ENDIF USE_DLL_RUNTIME = IF %(USE_MFC)=="dll" DEFINE += _AFXDLL MFCFLAGS = USE_DLL_RUNTIME = 1 ELSE LIBS += coredll.lib MFCFLAGS = %(TARGLFLAGS_noMFC) ENDIF IF %(USE_ATL) && %(USE_ATL)!="dll" DEFINE += _ATL_STATIC_REGISTRY ENDIF IF (%(TYPE)==EXE) TARGTYPE = 01 TARGNAME = Application TARGLINK = /base:"0x00010000" /stack:0x20000,0x1000 %(SUBSYSTEM) IF "%(USE_MFC)" TARGLINK += /entry:"wWinMainCRTStartup" ELSE TARGLINK += /entry:"WinMainCRTStartup" ENDIF DEFINE += _WINDOWS ENDIF IF (%(TYPE)==DLL) TARGTYPE = 02 TARGNAME = Dynamic-Link Library TARGLINK = /base:"0x00100000" /stack:0x10000,0x1000 /entry:"_DllMainCRTStartup" /dll %(SUBSYSTEM) DEFINE += _USRDLL DEFINE += _WINDOWS DEFINE += %(<^NAME)_EXPORTS ENDIF IF (%(TYPE)==LIB) TARGTYPE = 04 TARGNAME = Static Library DEFINE += _LIB ENDIF IF "%(USELIB)" LIBS += %(USELIB:%=%_%(PLATFORMLIB).lib) ENDIF HAS_IDL = FOR EACH SOURCE IF (%(>NAME)==idl) ../HAS_IDL = 1 ENDIF ENDFOR IF %(HAS_IDL) INCLUDE += %(¯|BUILDPATH)%(~§PATH) INCLUDE_DEBUG += %(¯|OUTPUTPATH)debug\%(OUTPUT_DIR) INCLUDE_RELEASE += %(¯|OUTPUTPATH)release\%(OUTPUT_DIR) ENDIF AFLAGS = %(DEFINE:%=-D%) %(TARGDEFINE:%=-D%) -D_WIN32 RFLAGS = /d UNDER_CE /d _WIN32_WCE=$(CEVersion) /d "$(CePlatform)" %(DEFINE:%=/d "%") %(TARGDEFINE:%=/d "%") DFLAGS = /D UNDER_CE /D _WIN32_WCE=$(CEVersion) /D "$(CePlatform)" %(DEFINE:%=/D "%") %(TARGDEFINE:%=/D "%") CFLAGS = /D UNDER_CE /D _WIN32_WCE=$(CEVersion) /D "$(CePlatform)" %(DEFINE:%=/D "%") %(TARGDEFINE:%=/D "%") %(~@INCLUDE:%=/I "%") %(~@SYSINCLUDE:%=/I "%") %(TARGCFLAGS) GFLAGS = -D __GLIBC__ -D _WIN32 -D _WIN32_WCE=$(CEVersion) -D __cdecl= -O3 -fsigned-char -fomit-frame-pointer -mno-apcs-frame -march=armv4 -mtune=xscale -fno-leading-underscore %(DEFINE:%=-D %) %(TARGDEFINE:%=-D %) %(@INCLUDE:%=-I"%") -I. -I/usr/include -I/usr/include/w32api -IC:\MinGW\include SFLAGS = %(~@SYSINCLUDE:%=/I "%") PRINTNLDOS # Microsoft eMbedded Visual Tools Project File - Name="%(NAME)" - Package Owner=<4> PRINTNLDOS # Microsoft eMbedded Visual Tools Generated Build File, Format Version 6.02 PRINTNLDOS # ** DO NOT EDIT ** PRINTNLDOS PRINTNLDOS # TARGTYPE "Win32 (%(TARGID)) %(TARGNAME)" %(TARGCODE)%(TARGTYPE) PRINTNLDOS PRINTNLDOS CFG=%(NAME) - Win32 (%(TARGID)) Debug PRINTNLDOS !MESSAGE This is not a valid makefile. To build this project using NMAKE, PRINTNLDOS !MESSAGE use the Export Makefile command and run PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE NMAKE /f "%(NAME).vcn". PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE You can specify a configuration when running NMAKE PRINTNLDOS !MESSAGE by defining the macro CFG on the command line. For example: PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE NMAKE /f "%(NAME).vcn" CFG="%(NAME) - Win32 (%(TARGID)) Debug" PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE Possible choices for configuration are: PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE "%(NAME) - Win32 (%(TARGID)) Release" (based on "Win32 (%(TARGID)) %(TARGNAME)") PRINTNLDOS !MESSAGE "%(NAME) - Win32 (%(TARGID)) Debug" (based on "Win32 (%(TARGID)) %(TARGNAME)") PRINTNLDOS !MESSAGE PRINTNLDOS PRINTNLDOS # Begin Project PRINTNLDOS # PROP AllowPerConfigDependencies 0 PRINTNLDOS # PROP Scc_ProjName "" PRINTNLDOS # PROP Scc_LocalPath "" PRINTNLDOS # PROP ATL_Project 2 PRINTNLDOS CPP=%(TARGCC) PRINTNLDOS MTL=midl.exe PRINTNLDOS RSC=rc.exe PRINTNLDOS PRINTNLDOS !IF "$(CFG)" == "%(NAME) - Win32 (%(TARGID)) Release" PRINTNLDOS IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP BASE Use_MFC 2 ELSE PRINTNLDOS # PROP BASE Use_MFC 1 ENDIF LIBS += mfcs42.lib ELSE PRINTNLDOS # PROP BASE Use_MFC 0 ENDIF PRINTNLDOS # PROP BASE Use_Debug_Libraries 0 PRINTNLDOS # PROP BASE Output_Dir "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)" PRINTNLDOS # PROP BASE Intermediate_Dir "%(¯~!BUILDPATH)release\%(~PATH)" PRINTNLDOS # PROP BASE CPU_ID %(TARGCPU) PRINTNLDOS # PROP BASE Platform_ID "{8A9A2F80-6887-11D3-842E-005004848CBA}" PRINTNLDOS # PROP BASE Target_Dir "" IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP Use_MFC 2 ELSE PRINTNLDOS # PROP Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP Use_MFC 0 ENDIF PRINTNLDOS # PROP Use_Debug_Libraries 0 PRINTNLDOS # PROP Output_Dir "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)" PRINTNLDOS # PROP Intermediate_Dir "%(¯~!BUILDPATH)release\%(~PATH)" PRINTNLDOS # PROP CPU_ID %(TARGCPU) PRINTNLDOS # PROP Platform_ID "{8A9A2F80-6887-11D3-842E-005004848CBA}" // PRINTNLDOS # PROP Ignore_Export_Lib 0 IF %(TYPE)==LIB PRINTNLDOS # PROP Sec_AlwaysSign 0 ENDIF IF ("%(WIN_CERTIFICATE)"!="") PRINTNLDOS # PROP Sec_CertificateHash "%(WIN_CERTIFICATE)" ELSE PRINTNLDOS # PROP Sec_CertificateHash "8aeb6e720079eb0494ae9be32cb13a9e3687d913" ENDIF PRINTNLDOS # PROP Sec_ConfigureDevice 0 PRINTNLDOS # PROP Target_Dir "" PRINTNLDOS # ADD BASE RSC /l 0x409 %(RFLAGS) /d "NDEBUG" /r %(~!INCLUDERC:%=/i "%") IF %(PRECOMPILED_HEADER)!="" PRECOMP_OPTION = /Yu"%(PRECOMPILED_HEADER)" SET_PRECOMPILED_HEADER = 1 ELSE PRECOMP_OPTION = /YX ENDIF PRINTNLDOS # ADD RSC /l 0x409 %(~@INCLUDE_RELEASE:%=/i "%") %(RFLAGS) /d "NDEBUG" /r %(~!INCLUDERC:%=/i "%") %(CONFIG_INCLUDE:%=/i "%") PRINTNLDOS # ADD BASE CPP /nologo %(TARGCFLAGS_REL) /D "NDEBUG" %(CFLAGS) %(~@INCLUDE_RELEASE:%=/I "%") %(CONFIG_INCLUDE:%=/i "%") /FA %(PRECOMP_OPTION) /c PRINTNLDOS # ADD CPP /nologo %(TARGCFLAGS_REL) /D "NDEBUG" %(CFLAGS) %(~@INCLUDE_RELEASE:%=/I "%") %(CONFIG_INCLUDE:%=/i "%") /FA %(PRECOMP_OPTION) /c IF (%(TYPE)!=LIB && %(TYPE)!=CON) PRINTNLDOS # ADD BASE MTL /nologo /D "NDEBUG" %(DFLAGS) /mktyplib203 /o "NUL" /win32 PRINTNLDOS # ADD MTL /nologo /D "NDEBUG" %(DFLAGS) /mktyplib203 /o "NUL" /win32 ENDIF PRINTNLDOS BSC32=bscmake.exe PRINTNLDOS # ADD BASE BSC32 /nologo PRINTNLDOS # ADD BSC32 /nologo IF (%(TYPE)==LIB) PRINTNLDOS LIB32=link.exe -lib PRINTNLDOS # ADD BASE LIB32 /nologo PRINTNLDOS # ADD LIB32 /nologo ELSE PRINTNLDOS LINK32=link.exe PRINTNLDOS # ADD BASE LINK32 %(LIBS) %(LIBS_RELEASE) /nologo %(TARGLINK) /map /nodefaultlib:"$(CENoDefaultLib)" /out:"%(¯!OUTPUTPATH)release/%(OUTPUT)" %(TARGLFLAGS) %(MFCFLAGS) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_RELEASE:%=/libpath:%) PRINTNLDOS # ADD LINK32 %(LIBS) %(LIBS_RELEASE) /nologo %(TARGLINK) /map /nodefaultlib:"$(CENoDefaultLib)" /out:"%(¯!OUTPUTPATH)release/%(OUTPUT)" %(TARGLFLAGS) %(MFCFLAGS) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_RELEASE:%=/libpath:%) ENDIF PRINTNLDOS PRINTNLDOS !ELSEIF "$(CFG)" == "%(NAME) - Win32 (%(TARGID)) Debug" PRINTNLDOS IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP BASE Use_MFC 2 ELSE PRINTNLDOS # PROP BASE Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP BASE Use_MFC 0 ENDIF PRINTNLDOS # PROP BASE Use_Debug_Libraries 1 PRINTNLDOS # PROP BASE Output_Dir "%(¯~!OUTPUTPATH)debug\%(OUTPUT_DIR)" PRINTNLDOS # PROP BASE Intermediate_Dir "%(¯~!BUILDPATH)debug\%(~PATH)" PRINTNLDOS # PROP BASE CPU_ID %(TARGCPU) PRINTNLDOS # PROP BASE Platform_ID "{8A9A2F80-6887-11D3-842E-005004848CBA}" PRINTNLDOS # PROP BASE Target_Dir "" IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP Use_MFC 2 ELSE PRINTNLDOS # PROP Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP Use_MFC 0 ENDIF PRINTNLDOS # PROP Use_Debug_Libraries 1 PRINTNLDOS # PROP Output_Dir "%(¯~!OUTPUTPATH)debug\%(OUTPUT_DIR)" PRINTNLDOS # PROP Intermediate_Dir "%(¯~!BUILDPATH)debug\%(~PATH)" PRINTNLDOS # PROP CPU_ID %(TARGCPU) PRINTNLDOS # PROP Platform_ID "{8A9A2F80-6887-11D3-842E-005004848CBA}" // PRINTNLDOS # PROP Ignore_Export_Lib 0 IF %(TYPE)==LIB PRINTNLDOS # PROP Sec_AlwaysSign 0 ENDIF IF ("%(WIN_CERTIFICATE)"!="") PRINTNLDOS # PROP Sec_CertificateHash "%(WIN_CERTIFICATE)" ELSE PRINTNLDOS # PROP Sec_CertificateHash "8aeb6e720079eb0494ae9be32cb13a9e3687d913" ENDIF PRINTNLDOS # PROP Sec_ConfigureDevice 0 PRINTNLDOS # PROP Target_Dir "" PRINTNLDOS # ADD BASE RSC /l 0x409 %(RFLAGS) /d "DEBUG" /r %(~!INCLUDERC:%=/i "%") PRINTNLDOS # ADD RSC /l 0x409 %(~@INCLUDE_DEBUG:%=/i "%") %(RFLAGS) /d "DEBUG" /r %(~!INCLUDERC:%=/i "%") %(CONFIG_INCLUDE:%=/i "%") PRINTNLDOS # ADD BASE CPP /nologo %(TARGCFLAGS_DBG) /W3 /Zi /Od /D "DEBUG" %(CFLAGS) %(~@INCLUDE_DEBUG:%=/I "%") %(CONFIG_INCLUDE:%=/i "%") %(PRECOMP_OPTION) /c PRINTNLDOS # ADD CPP /nologo %(TARGCFLAGS_DBG) /W3 /Zi /Od /D "DEBUG" %(CFLAGS) %(~@INCLUDE_DEBUG:%=/I "%") %(CONFIG_INCLUDE:%=/i "%") %(PRECOMP_OPTION) /c IF (%(TYPE)!=LIB && %(TYPE)!=CON) PRINTNLDOS # ADD BASE MTL /nologo /D "_DEBUG" %(DFLAGS) /mktyplib203 /o "NUL" /win32 PRINTNLDOS # ADD MTL /nologo /D "_DEBUG" %(DFLAGS) /mktyplib203 /o "NUL" /win32 ENDIF PRINTNLDOS BSC32=bscmake.exe PRINTNLDOS # ADD BASE BSC32 /nologo PRINTNLDOS # ADD BSC32 /nologo IF (%(TYPE)==LIB) PRINTNLDOS LIB32=link.exe -lib PRINTNLDOS # ADD BASE LIB32 /nologo PRINTNLDOS # ADD LIB32 /nologo ELSE PRINTNLDOS LINK32=link.exe PRINTNLDOS # ADD BASE LINK32 %(LIBS) %(LIBS_DEBUG) /nologo %(TARGLINK) /debug /nodefaultlib:"$(CENoDefaultLib)" /out:"%(¯!OUTPUTPATH)debug/%(OUTPUT)" %(TARGLFLAGS) %(MFCFLAGS) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_DEBUG:%=/libpath:%) PRINTNLDOS # ADD LINK32 %(LIBS) %(LIBS_DEBUG) /nologo %(TARGLINK) /debug /nodefaultlib:"$(CENoDefaultLib)" /out:"%(¯!OUTPUTPATH)debug/%(OUTPUT)" %(TARGLFLAGS) %(MFCFLAGS) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_DEBUG:%=/libpath:%) ENDIF PRINTNLDOS PRINTNLDOS !ENDIF PRINTNLDOS PRINTNLDOS # Begin Target PRINTNLDOS PRINTNLDOS # Name "%(NAME) - Win32 (%(TARGID)) Release" PRINTNLDOS # Name "%(NAME) - Win32 (%(TARGID)) Debug" PRINTNLDOS # Begin Group "Source Files" PRINTNLDOS PRINTNLDOS # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" FOR EACH SOURCE, DEF PRINTNLDOS # Begin Source File PRINTNLDOS PRINTNLDOS SOURCE=%(~!NAME) IF (%(../SET_PRECOMPILED_HEADER)==1) && (%(>NAME)==c || %(>NAME)==cpp) PRINTNLDOS # ADD CPP /Yc"%(PRECOMPILED_HEADER)" ../SET_PRECOMPILED_HEADER = ELSE IF ((%(>NAME)==c || %(>NAME)==cpp) && %(w)) PRINTNLDOS # ADD CPP /w /W0 ENDIF ENDIF IF (%(>NAME)==idl) PRINTNLDOS !IF "$(CFG)" == "%(PRJNAME) - Win32 (%(TARGID)) Release" PRINTNLDOS # ADD MTL /tlb "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)%(PRJNAME).tlb" /h "%(¯~!BUILDPATH)%(~§PATH)\%(NAME)==asm) PRINTNLDOS !IF "$(CFG)" == "%(PRJNAME) - Win32 (%(TARGID)) Release" PRINTNLDOS PRINTNLDOS # PROP Ignore_Default_Tool 1 PRINTNLDOS # Begin Custom Build PRINTNLDOS IntDir=%(¯!BUILDPATH)release\%(PATH) PRINTNLDOS InputPath=%(!NAME) PRINTNLDOS InputName=%(NAME)==s) PRINTNLDOS !IF "$(CFG)" == "%(PRJNAME) - Win32 (%(TARGID)) Release" PRINTNLDOS PRINTNLDOS # PROP Ignore_Default_Tool 1 PRINTNLDOS # Begin Custom Build PRINTNLDOS IntDir=%(¯!BUILDPATH)release\%(PATH) PRINTNLDOS InputPath=%(!NAME) PRINTNLDOS InputName=%(NAME)==idl) && %(hmarshal)!="" PRINTNLDOS # Begin Source File PRINTNLDOS PRINTNLDOS SOURCE="%(nul PRINTNL echo DATA \"$3\" ID `expr 1000 + $n` \"$4.$n\" >>$4.rcp PRINTNL n=`expr $n + 1` PRINTNL done ENDIF ENDIF ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux.build000066400000000000000000000011461462133141200231050ustar00rootroot00000000000000#define TARGET_LINUX #define IX86 #define RESOURCE_COREC PLATFORMLIB = linux_x86 SVNDIR = linux_x86 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define ASM yasm #define STRIP strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -O3 -m32 -march=i486 -msse -mmmx -Wno-multichar -fvisibility=hidden -DRESOURCE_COREC #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_arm.build000066400000000000000000000014611462133141200237440ustar00rootroot00000000000000#define TARGET_LINUX #define ARM #define RESOURCE_COREC PLATFORMLIB = linux_arm SVNDIR = linux_arm #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a #define CC arm-none-linux-gnueabi-gcc #define CXX arm-none-linux-gnueabi-g++ #define AR arm-none-linux-gnueabi-ar #define STRIP arm-none-linux-gnueabi-strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -DARM -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -march=armv4t -mtune=xscale -fvisibility=hidden -DRESOURCE_COREC #define SFLAGS -DARM -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -mcpu=iwmmxt -mtune=xscale -D_HIDDEN #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_debug.build000066400000000000000000000012021462133141200242440ustar00rootroot00000000000000#define TARGET_LINUX #define IX86 #define DEBUG #define RESOURCE_COREC PLATFORMLIB = linux_x86 SVNDIR = linux_x86 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define ASM yasm //#define STRIP strip //#define STRIPFLAGS #define GLIBC #define CCFLAGS -DDEBUG -ggdb -m32 -march=i486 -msse -mmmx -Wno-multichar -DRESOURCE_COREC // -savetemps doesn't work with the corerc | pipe #define ASMFLAGS -f elf #define LFLAGS #define SHFLAGS -shared #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_mips.build000066400000000000000000000014301462133141200241310ustar00rootroot00000000000000#define TARGET_LINUX #define MIPS #define RESOURCE_COREC PLATFORMLIB = linux_mips SVNDIR = linux_mips #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a #define CC mipsel-linux-gcc #define CXX mipsel-linux-g++ #define AR mipsel-linux-ar #define STRIP mipsel-linux-strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -DMIPS -Wno-multichar -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 -fvisibility=hidden -DRESOURCE_COREC #define SFLAGS -DMIPS -Wno-multichar -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 -D_HIDDEN #define SHFLAGS -shared -Wl,--strip-all #define CXXFLAGS -fno-rtti #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_ppc.build000066400000000000000000000011411462133141200237420ustar00rootroot00000000000000#define TARGET_LINUX #define POWERPC #define PPC PLATFORMLIB = linux_ppc SVNDIR = linux_ppc #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define ASM as #define STRIP strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -O3 -Wno-multichar -fPIC -fno-strict-aliasing -maltivec -mabi=altivec -fvisibility=hidden #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_qt_x86.build000066400000000000000000000005271462133141200243200ustar00rootroot00000000000000#define IX86 #define ASM yasm #define STIP strip #define STRIPFLAGS -s -x #define CCFLAGS -O3 -DTARGET_QTOPIA -DTARGET_DESKTOP -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions -fvisibility=hidden #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_qt_x86_debug.build000066400000000000000000000005431462133141200254640ustar00rootroot00000000000000#define IX86 #define DEBUG #define ASM yasm //#define STIP strip //#define STRIPFLAGS -s -x #define CCFLAGS -DDEBUG -ggdb -DTARGET_QTOPIA -DTARGET_DESKTOP -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions -fvisibility=hidden #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_x64.build000066400000000000000000000011461462133141200236060ustar00rootroot00000000000000#define TARGET_LINUX #define IX64 #define IX86_64 #define RESOURCE_COREC PLATFORMLIB = linux_x64 SVNDIR = linux_x64 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define ASM yasm #define STRIP strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -O3 -m64 -Wno-multichar -fPIC -fvisibility=hidden -DRESOURCE_COREC #define ASMFLAGS -f elf64 -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_linux_x64_debug.build000066400000000000000000000011401462133141200247460ustar00rootroot00000000000000#define TARGET_LINUX #define IX64 #define IX86_64 #define RESOURCE_COREC #define DEBUG PLATFORMLIB = linux_x64 SVNDIR = linux_x64 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define ASM yasm //#define STRIP strip //#define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -DDEBUG -ggdb -m64 -Wno-multichar -fPIC -save-temps -DRESOURCE_COREC #define ASMFLAGS -f elf64 #define LFLAGS #define SHFLAGS -shared #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_mak.inc000066400000000000000000000702471462133141200222000ustar00rootroot00000000000000RESOURCEPATH=%(¯OUTPUTPATH) IFDEF TARGET_OSX IF %(TYPE)==EXE IFDEF TARGET_IPHONE PRINTNL OUTPUT = %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(PROJECT_NAME).app/%(PROJECT_NAME) IF %(PLIST_FILE)!="" PLIST_PATH = %(¯OUTPUTPATH)%(+OUTPUT_DIR)%(PROJECT_NAME).app PRINTNL PLIST = %(!PLIST_PATH)/Info.plist ENDIF OUTPUT_DIR=%(OUTPUT_DIR)%(PROJECT_NAME).app RESOURCEPATH=%(¯OUTPUTPATH)%(PROJECT_PATH).app/ ELSE PRINTNL OUTPUT = %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(PROJECT_NAME).app/Contents/MacOS/%(PROJECT_NAME) IF %(PLIST_FILE)!="" PLIST_PATH = %(¯OUTPUTPATH)%(+OUTPUT_DIR)%(PROJECT_NAME).app/Contents PRINTNL PLIST = %(!PLIST_PATH)/Info.plist ENDIF RESOURCEPATH=%(¯OUTPUTPATH)%(PROJECT_PATH).app/Contents/Resources/ OUTPUT_DIR=%(OUTPUT_DIR)%(PROJECT_NAME).app/Contents/MacOS FOR EACH ICON ../INSTALL += %(|NAME).icns ENDFOR ENDIF ELSE PRINTNL OUTPUT = %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT) ENDIF ELSE PRINTNL OUTPUT = %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT) ENDIF PRINTNL BUILD = %(!BUILDPATH) IFDEF TARGET_PALMOS PRINTNL BUILD_M68K = %(!BUILDPATH)m68k/%(PATH) ENDIF IF defined(TARGET_PS2SDK) && %(IOP) CC = %(iop_cc) CXX = %(iop_cxx) AR = %(iop_ar) STRIP = %(iop_strip) CCFLAGS = %(iop_ccflags) SHFLAGS = %(iop_shflags) LFLAGS = %(iop_lflags) ENDIF PRINTNL IF ("%(CC)"!="") PRINTNL CC = %(CC) ENDIF IF ("%(CXX)"!="") PRINTNL CXX = %(CXX) ENDIF IF ("%(CC_M68K)"!="") PRINTNL CC_M68K = %(CC_M68K) ENDIF IF ("%(CXX_HOST)"!="") PRINTNL CXX_HOST = %(CXX_HOST) ENDIF IF ("%(WINDRES)"!="") PRINTNL WINDRES = %(WINDRES) ENDIF IF (%(ASM)!="") PRINTNL ASM = %(ASM) ENDIF IF (%(NASM)!="") PRINTNL NASM = %(NASM) ENDIF IF (%(AR)!="") PRINTNL AR = %(AR) ENDIF IF ("%(CCENV)"!="") PRINTNL CCENV = %(CCENV) ENDIF IF ("%(STRIP)"!="") PRINTNL STRIP = %(STRIP) ENDIF PRINTNL IF (%(TYPE)==dll) DEFINE += %(<^NAME)_EXPORTS ENDIF // make sure we don't use the one from another configuration REMOVE %(PATH)%(PRECOMPILED_HEADER).gch REMOVE %(PATH)%(PRECOMPILED_HEADER).gch.%(NAME) IF "%(PRECOMPILED_HEADER)"!="" && "%(PRECOMPILED_HEADER_FORCED)"!=no PRINTNL CCFLAGS += -include %(PRECOMPILED_HEADER) ENDIF IF %(OS_INCLUDE)!="" PRINTNL CCFLAGS += %(|OS_INCLUDE:%=-isystem '%') ENDIF PRINTNL CCFLAGS += %(DEFINE:%=-D%) -I . %(@INCLUDE:%=-I '%') %(@SYSINCLUDE:%=-I '%') %(@CONFIG_INCLUDE:%=-I '%') IF %(CCFLAGS)!="" PRINTNL CCFLAGS += %(CCFLAGS) ENDIF IF %(CFLAGS)!="" PRINTNL CFLAGS += %(CFLAGS) ENDIF IF "%(UI_FORM_QT4)"!="" PRINTNL CCFLAGS += -I %(!BUILDPATH)%(PATH)GeneratedFiles ENDIF PRINTNL CXXFLAGS += %(CXXFLAGS) -fno-for-scope IF %(ASMFLAGS)!="" || %(DEFINE)!="" PRINTNL ASMFLAGS += %(ASMFLAGS) %(DEFINE:%=-D%) ENDIF PRINTNL NASMFLAGS += %(NASMFLAGS) %(DEFINE:%=-D%) %(@INCLUDE:%=-I%) %(@CONFIG_INCLUDE:%=-I '%') PRINTNL SFLAGS += %(SFLAGS) %(DEFINE:%=-D%) %(@INCLUDE:%=-I%) %(@CONFIG_INCLUDE:%=-I '%') IFDEF RESOURCE_COREC PRINTNL CORERCFLAGS += %(CORERCFLAGS) ENDIF IFDEF TARGET_PALMOS PRINTNL CFLAGS_M68K = %(CFLAGS_M68K) %(DEFINE:%=-D '%') %(@INCLUDE:%=-I '%') %(@SYSINCLUDE:%=-I '%') %(@CONFIG_INCLUDE:%=-I '%') -D "PROJECT_OUTPUT=%(NAME)==c || %(>NAME)==cpp || %(>NAME)==m || (%(ASM)!="" && %(>NAME)==asm) || (%(NASM)!="" && %(>NAME)==nas) ||%(>NAME)==S || %(>NAME)==rc || (%(DVP_AS)!="" && %(>NAME)==vsm)) IF "%(FUNC)"=="" PRINTNL SOURCE += %(!NAME) ELSE FOR EACH FUNC PRINTNL SOURCE += %(/../NAME)%(<../NAME).%(NAME).%(>../NAME) IF %(>../NAME)==c ../../FUNC_C += %(NAME) ELIF %(>../NAME)==S ../../FUNC_S += %(NAME) ENDIF ENDFOR ENDIF ENDIF IF defined(TARGET_PS2SDK) && (%(>NAME)==lst || %(>NAME)==tab) PRINTNL SOURCE += %(!NAME) ENDIF ENDFOR IFDEF TARGET_PS2SDK IF %(ICON) PRINTNL SOURCE += %(!ICON)_ps2.icn ENDIF ENDIF FOR EACH RESOURCE_QT4 PRINTNL SOURCE += %(!BUILDPATH)%(PATH)GeneratedFiles/qrc_%(~NAME)==c) PRINTNL SOURCE_M68K += %(!NAME) ENDIF IF (%(>NAME)==rcp) PRINTNL RESOURCE_M68K += %(!NAME) ENDIF ENDFOR PRINTNL OBJS_M68K=$(SOURCE_M68K:%.c=$(BUILD_M68K)%.%(NAME).o) PRINTNL RES_M68K=$(RESOURCE_M68K:%.rcp=$(BUILD_M68K)%.ro) ENDIF PRINTNL .PHONY: all prebuild postbuild install clean distclean cleandep $(LIBS) PRINTNL PRINTNL all: prebuild $(LIBS) $(GENERATED) $(OUTPUT) postbuild PRINTNL IF "%(PRECOMPILED_HEADER)"!="" PRINTNL prebuild: // PRINTNL $(hide)echo prebuild PRINTNL $(hide)-test ! -f %(PRECOMPILED_HEADER).gch.%(NAME) || mv %(PRECOMPILED_HEADER).gch.%(NAME) %(!PATH)%(PRECOMPILED_HEADER).gch PRINTNL ENDIF IF "%(PRECOMPILED_HEADER)"!="" PRINTNL postbuild: // PRINTNL $(hide)echo postbuild PRINTNL $(hide)-test ! -f %(!PATH)%(PRECOMPILED_HEADER).gch || mv %(!PATH)%(PRECOMPILED_HEADER).gch %(PRECOMPILED_HEADER).gch.%(NAME) PRINTNL ENDIF IF defined(TARGET_PALMOS) IF (%(TYPE)==lib) PRINTNL $(OUTPUT): $(OBJS) PRINTNL $(hide)echo linking $@ PRINTNL $(hide)mkdir -p %(¯!OUTPUTPATH)%(OUTPUT_DIR) PRINTNL $(hide)$(AR) rcs $@ $(OBJS) ELSE PRINTNL $(OUTPUT): %(!BUILDPATH)%(NAME)_arm.ro %(¯!PATH)%(NAME)_palmos.def %(OUTPUT_M68K) $(RES_M68K) $(PEAL) PRINTNL $(hide)mkdir -p %(¯!OUTPUTPATH) IF !%(NOLIB) PRINTNL $(hide)$(PEAL) -l %(NAME) -o %(¯!OUTPUTPATH)lib%(NAME).a %(!BUILDPATH)%(NAME).elf ENDIF PRINTNL $(hide)build-prc %(¯!PATH)%(NAME)_palmos.def -o $@ %(!BUILDPATH)%(NAME)_arm.ro %(OUTPUT_M68K) $(RES_M68K) IF ("%(OUTPUT)"=="%(NAME).prc") && ("%(PROJECT_NAME)"!="%(NAME)") PRINTNL $(hide)cp $(OUTPUT) "%(¯!OUTPUTPATH)%(PROJECT_NAME).prc" ENDIF IF %(TYPE)=exe FOR EACH USE IF %(TYPE)=dll ../INSTALL_ZIP += "%(¯!OUTPUTPATH)%(PROJECT_NAME).prc" ENDIF ENDFOR IF "%(INSTALL_ZIP)"!="" INSTALL_ZIP += "%(¯!OUTPUTPATH)%(PROJECT_NAME).prc" PRINTNL $(hide)zip -X -q -o "%(¯!OUTPUTPATH)%(PROJECT_NAME).zip" %(INSTALL_ZIP) ENDIF ENDIF PRINTNL PRINTNL %(!BUILDPATH)%(NAME)_arm.ro: %(!BUILDPATH)%(NAME).elf $(PEAL) PRINTNL $(hide)$(PEAL) $(PFLAGS) -o $@ %(!BUILDPATH)%(NAME).elf PRINTNL PRINTNL %(!BUILDPATH)%(NAME).m68k: $(OBJS_M68K) PRINTNL $(hide)echo linking m68k PRINTNL $(hide)mkdir -p %(!BUILDPATH) PRINTNL $(hide)$(CC_M68K) $(CFLAGS_M68K) -static $(OBJS_M68K) $(LFLAGS_M68K) -o $@ PRINTNL PRINTNL %(!BUILDPATH)%(NAME).elf: $(OBJS) $(LIBS) PRINTNL $(hide)echo linking arm PRINTNL $(hide)mkdir -p %(!BUILDPATH) PRINTNL $(hide)$(CCENV) $(CC) $(OBJS) -o %(!BUILDPATH)%(NAME).elf $(LFLAGS) -Wl,-Map=%(!BUILDPATH)%(NAME).map PRINTNL PRINTNL $(PEAL): $(PEALSRC) PRINTNL $(hide)echo compiling peal-postlink PRINTNL $(hide)$(CXX_HOST) $(PEALSRC) -o $(PEAL) PRINTNL $(hide)chmod u+x $(PEAL) ENDIF PRINTNL PRINTNL $(BUILD_M68K)%.%(NAME).o: %.c PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD_M68K)$(*D) PRINTNL $(hide)$(CC_M68K) -Wall $(CFLAGS_M68K) -c $< -o $@ PRINTNL PRINTNL $(BUILD_M68K)%.ro: %.rcp PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD_M68K)$(*D) PRINTNL $(hide)pilrc -I $(*D) -q -ro $< $@ PRINTNL FOR EACH INSTALL PRINTNL $(BUILD_M68K)%(¯!NAME).ro: %(!NAME) PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD_M68K)%(¯/NAME) PRINTNL $(hide)%(../NAME)_split.sh %(!NAME) 64512 %(,NAME) $(BUILD_M68K)%(¯!NAME) PRINTNL $(hide)pilrc -q -ro $(BUILD_M68K)%(¯!NAME).rcp $@ PRINTNL ENDFOR ELSE IFNDEF TARGET_QTOPIA IF !defined(RESOURCE_COREC) && !defined(TARGET_ANDROID) FOR EACH INSTALL PRINTNL INSTALL += %(!RESOURCEPATH)%(NAME) ENDFOR ENDIF IFDEF TARGET_IPHONE IF %(ICON) PRINTNL ICON = %(!RESOURCEPATH)icon.png ENDIF ENDIF PRINTNL ENDIF IF (%(TYPE)==lib) PRINTNL $(OUTPUT): $(OBJS) $(USEBUILT) $(ICON) $(INSTALL) $(PLIST) ELSE PRINTNL $(OUTPUT): $(OBJS) $(LIBS) $(USEBUILT) $(ICON) $(INSTALL) $(PLIST) ENDIF PRINTNL $(hide)echo linking $@ PRINTNL $(hide)mkdir -p %(¯!OUTPUTPATH)%(OUTPUT_DIR) IF (%(TYPE)==lib) PRINTNL $(hide)$(AR) rcs $@ $(OBJS) IF "%(EXPORT_SVN)" PRINTNL $(hide)echo exporting for SVN IF "%(HOST_WIN32)"!="" PRINTNL $(hide)if not exist "%(!EXPORT_SVN)export/lib/%(SVNDIR)/static/" mkdir -p "%(!EXPORT_SVN)export/lib/%(SVNDIR)/static/" ELSE PRINTNL $(hide)test -d "%(!EXPORT_SVN)export/lib/%(SVNDIR)/static/" || mkdir -p "%(!EXPORT_SVN)export/lib/%(SVNDIR)/static/" ENDIF PRINTNL $(hide)cp -f "$@" "%(!EXPORT_SVN)export/lib/%(SVNDIR)/static/" ENDIF ELSE IF %(TYPE)==dll && defined(TARGET_ANDROID) PRINTNL $(hide)$(CC) -nostdlib -Wl,-soname,%(OUTPUT_DLL) -Wl,-shared,-Bsymbolic $(OBJS) $(LFLAGS) -o $@ ELSE PRINTNL $(hide)$(CXX) $(CCFLAGS) $(OBJS) -o $@ $(LFLAGS) //-Wl,-Map=%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(NAME).map ENDIF IF "%(STRIP)" PRINTNL $(hide)$(STRIP) %(STRIPFLAGS) $@ ENDIF IF %(TYPE)==dll && defined(TARGET_ANDROID) PRINTNL $(hide)mkdir -p %(!BUILDDIR)libs/%(ANDROID_ABI) PRINTNL $(hide)install -p $@ %(!BUILDDIR)libs/%(ANDROID_ABI) ENDIF IF (%(TYPE)==dll) IF defined(TARGET_WIN32) && "%(EXPORT_MSVC_LIB)"!="" PRINTNL $(hide)lib -machine:i386 -def:"%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_DEF)" -out:"%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(NAME): %(!NAME) PRINTNL $(hide)echo copy $< PRINTNL $(hide)mkdir -p %(!RESOURCEPATH) PRINTNL $(hide)cp -f $< $@ ENDFOR ENDIF ENDIF ENDIF IF "%(USEBUILT)" || "%(USE)" PRINTNL FOR EACH USEBUILT PRINTNL %(NAME): PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak ENDFOR IF !defined(TARGET_PS2SDK) // otherwise it has too many references FOR EACH USE IF (%(TYPE)==dll) && !defined(TARGET_PALMOS) PRINTNL %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT): PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak ELSE PRINTNL %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_LIB): PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak ENDIF ENDFOR ENDIF ENDIF IF "%(PRECOMPILED_HEADER)"!="" PRINTNL PRINTNL $(OBJS): %(!PATH)%(PRECOMPILED_HEADER).gch ENDIF PRINTNL IF ("%(WINDRES)"!="") PRINTNL $(BUILD)%_res.%(NAME).o: %(!ROOTPATH)%.rc PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(WINDRES) -F pe-i386 -I$(*D) $< $@ PRINTNL PRINTNL $(BUILD)%_res.%(NAME).o: %.rc PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(WINDRES) -F pe-i386 -I$(*D) $< $@ PRINTNL ENDIF PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.c PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.c PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL FOR EACH FUNC_C PRINTNL $(BUILD)%.%(NAME).%(../NAME).o: %(!ROOTPATH)%.c PRINTNL $(hide)echo compiling $< %(NAME) PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -DF_%(NAME) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).%(../NAME).o: %.c PRINTNL $(hide)echo compiling $< %(NAME) PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -DF_%(NAME) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL ENDFOR PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.m PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.m PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.S PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(SFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.S PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(SFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL FOR EACH FUNC_S PRINTNL $(BUILD)%.%(NAME).%(../NAME).o: %(!ROOTPATH)%.S PRINTNL $(hide)echo compiling $< %(NAME) PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(SFLAGS) -DF_%(NAME) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).%(../NAME).o: %.S PRINTNL $(hide)echo compiling $< %(NAME) PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CC) -Wall $(SFLAGS) -DF_%(NAME) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL ENDFOR PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.cpp PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CXX) -Wall $(CXXFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.cpp PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) $(CXX) -Wall $(CXXFLAGS) $(CCFLAGS) -c $< -o $@ -MMD -MP -MF $@.d PRINTNL IF (%(ASM)!="") PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.asm PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(ASM) $(ASMFLAGS) -o $@ $< PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.asm PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(ASM) $(ASMFLAGS) -o $@ $< PRINTNL ENDIF IF (%(NASM)!="") PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.nas PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(NASM) $(NASMFLAGS) -o $@ $< PRINTNL PRINTNL $(BUILD)%.%(NAME).o: %.nas PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(NASM) $(NASMFLAGS) -o $@ $< PRINTNL ENDIF IF defined(TARGET_PS2SDK) PRINTNL $(BUILD)%.%(NAME).o: %(!ROOTPATH)%.vsm PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)$(*D) PRINTNL $(hide)$(CCENV) %(DVP_AS) --warn -I $(PRECOMPILED_HEADER).gch: %(!ROOTPATH)%.%(>PRECOMPILED_HEADER) PRINTNL $(hide)echo precompiling header $< PRINTNL $(hide)-rm -f $@ IF "%(>SOURCE)"=="c" PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ ELSE PRINTNL $(hide)$(CCENV) $(CXX) -Wall $(CXXFLAGS) $(CCFLAGS) -c $< -o $@ ENDIF PRINTNL PRINTNL %.%(>PRECOMPILED_HEADER).gch: %.%(>PRECOMPILED_HEADER) PRINTNL $(hide)echo precompiling header $< PRINTNL $(hide)-rm -f $@ IF "%(>SOURCE)"=="c" PRINTNL $(hide)$(CCENV) $(CC) -Wall $(CFLAGS) $(CCFLAGS) -c $< -o $@ ELSE PRINTNL $(hide)$(CCENV) $(CXX) -Wall $(CXXFLAGS) $(CCFLAGS) -c $< -o $@ ENDIF PRINTNL ENDIF FOR EACH SOURCE IF (%(w)!="") && (%(>NAME)==c) PRINTNL $(BUILD)%(¯NAME:%.c=%).%(../NAME).o: %(!NAME) PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)%(¯/NAME) PRINTNL $(hide)$(CCENV) $(CC) $(CFLAGS) $(CCFLAGS) -w -c $< -o $@ -MMD -MP -MF $@.d PRINTNL ENDIF IF (%(w)!="") && (%(>NAME)==cpp) PRINTNL $(BUILD)%(¯NAME:%.cpp=%).%(../NAME).o: %(!NAME) PRINTNL $(hide)echo compiling $< PRINTNL $(hide)mkdir -p $(BUILD)%(¯/NAME) PRINTNL $(hide)$(CCENV) $(CXX) $(CXXFLAGS) $(CCFLAGS) -w -c $< -o $@ -MMD -MP -MF $@.d PRINTNL ENDIF ENDFOR /* FOR EACH USE // PRINTNL %(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_LIB): PRINTNL %(NAME): PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak PRINTNL ENDFOR */ PRINTNL install: $(OUTPUT) IF (%(TYPE)==EXE || %(TYPE)==CON) PRINTNL $(hide)install -c $(OUTPUT) /usr/local/bin ENDIF IF %(TYPE)==DLL PRINTNL $(hide)install -c $(OUTPUT) /usr/local/lib ENDIF PRINTNL PRINTNL clean: PRINTNL $(hide)rm -f $(OBJS) PRINTNL $(hide)rm -f $(OUTPUT) IF "%(PRECOMPILED_HEADER)"!="" PRINTNL $(hide)rm -f %(!PATH)%(PRECOMPILED_HEADER).gch %(PRECOMPILED_HEADER).gch.%(NAME) ENDIF PRINTNL PRINTNL cleandep: PRINTNL $(hide)rm -f $(DEPS) IF !defined(TARGET_PS2SDK) // too noisy FOR EACH USE IF (!%(NOLIB)) && (%(NAME)!=%(../NAME)) PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak cleandep ENDIF ENDFOR ENDIF PRINTNL PRINTNL distclean: cleandep PRINTNL $(hide)rm -f $(OBJS) $(LIBS) PRINTNL $(hide)rm -f $(OUTPUT) FOR EACH USE IF (!%(NOLIB)) PRINTNL $(hide)$(MAKE) -C %(¯!§PATH) -f %(NAME).mak distclean ENDIF ENDFOR IF "%(PRECOMPILED_HEADER)"!="" PRINTNL $(hide)rm -f %(!PATH)%(PRECOMPILED_HEADER).gch %(PRECOMPILED_HEADER).gch.%(NAME) ENDIF PRINTNL IFDEF TARGET_QTOPIA IF %(TYPE)==EXE PRINTNL install: PRINTNL $(hide)echo Installing %(NAME)... PRINTNL $(hide)cp -f "%(!PATH)%(NAME).desktop" "$$QPEDIR/image/apps/Applications/" PRINTNL $(hide)cp -f "%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(NAME)" "$$QPEDIR/image/bin/%(NAME)" IF %(ICON) PRINTNL $(hide)$$QPEDIR/bin/installpic "en_US" 14 16 22 %(!PATH) $$QPEDIR/image/pics/%(NAME) %(!ICON)_32x32.png ENDIF PRINTNL ENDIF ENDIF PRINTNL -include $(DEPS) PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx.build000066400000000000000000000004561462133141200225620ustar00rootroot00000000000000################################# #### NOT READY - DO NOT USE #### ################################# #define TARGET_OSX #define IX86 #define PPC PLATFORMLIB = osx_u SVNDIR = osx_univers SDK = /Developer/SDKs/MacOSX10.4u.sdk CCFLAGS=%(CCFLAGS) -arch i386 -arch ppc -faltivec #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx.inc000066400000000000000000000021021462133141200222220ustar00rootroot00000000000000#define TARGET_OSX #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).dylib #define OUTPUT_DLL_LIB lib%(NAME).lo #define OUTPUT_LIB lib%(NAME).a #define ASM yasm IFNDEF STRIP #define STRIP %(CC_PREFIX)strip ENDIF #define STRIPFLAGS -x // TODO should come from config.h #ifndef TARGET_IPHONE #define CCENV MACOSX_DEPLOYMENT_TARGET_ppc=10.3 MACOSX_DEPLOYMENT_TARGET_i386=10.5 #endif #define GLIBC IF %(SDK) CCFLAGS = %(CCFLAGS) -isysroot %(SDK) ENDIF IF %(SYSLIB_ROOT) LFLAGS= -Wl,-syslibroot,%(SYSLIB_ROOT) ELIF %(SDK) LFLAGS= -isysroot %(SDK) -Wl,-syslibroot,%(SDK) ENDIF CCFLAGS = %(CCFLAGS) -pipe -O3 IF %(SDK_PATH) CCFLAGS = -I%(SDK_PATH)/include %(CCFLAGS) ENDIF //#define ASMFLAGS -f elf //#define LFLAGS //#define LDFLAGS -Wl,-dynamic,-search_paths_first //#define FFSLDFLAGS -Wl,-bind_at_load #ifdef PIC #define SHFLAGS -dynamiclib -Wl,-single_module -Wl,-install_name,\$(OUTPUT) #else #define SHFLAGS -dynamiclib -Wl,-read_only_relocs,suppress -Wl,-single_module -Wl,-install_name,\$(OUTPUT) #endif #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx_iphone_dev.build000066400000000000000000000012461462133141200247600ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_DEV #define ARM // pathes according to http://code.google.com/p/iphone-dev/wiki/Building #define CC /usr/local/bin/arm-apple-darwin-gcc #define CXX /usr/local/bin/arm-apple-darwin-gcc #define AR /usr/local/bin/arm-apple-darwin-ar #define LD /usr/local/bin/arm-apple-darwin-gcc #define STRIP /usr/local/bin/arm-apple-darwin-strip PLATFORMLIB = osx_arm SVNDIR = osx_iphone_dev SDK_PATH = /usr/local/arm-apple-darwin //SYSLIB_ROOT = /usr/local/arm-apple-darwin/heavenly //SYSLIB_ROOT = /usr/local/share/iphone-filesystem CCFLAGS=%(CCFLAGS) -DTARGET_IPHONE -DTARGET_IPHONE_DEV -DARM -arch arm -mdynamic-no-pic #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx_ppc.build000066400000000000000000000004051462133141200234160ustar00rootroot00000000000000#define TARGET_OSX #define POWERPC PLATFORMLIB = osx_ppc SVNDIR = osx_ppc //SDK = /Developer/SDKs/MacOSX10.3.9.sdk SDK = /Developer/SDKs/MacOSX10.4u.sdk CCFLAGS=%(CCFLAGS) -arch ppc -faltivec -mdynamic-no-pic -mmacosx-version-min=10.3 #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx_x64.build000066400000000000000000000004011462133141200232510ustar00rootroot00000000000000#define TARGET_OSX #define IX64 #define IX86_64 PLATFORMLIB = osx_x86 SVNDIR = osx_x86 SDK = /Developer/SDKs/MacOSX10.6.sdk CCFLAGS=%(CCFLAGS) -arch x86_64 -mdynamic-no-pic -mmacosx-version-min=10.6 ASMFLAGS = -f macho64 -D_MACHO #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx_x86.build000066400000000000000000000003551462133141200232650ustar00rootroot00000000000000#define TARGET_OSX #define IX86 PLATFORMLIB = osx_x86 SVNDIR = osx_x86 SDK = /Developer/SDKs/MacOSX10.6.sdk CCFLAGS=%(CCFLAGS) -arch i386 -mdynamic-no-pic -mmacosx-version-min=10.6 ASMFLAGS = -f macho -D_MACHO #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_osx_x86_pic.build000066400000000000000000000003661462133141200241220ustar00rootroot00000000000000#define TARGET_OSX #define IX86 #define PIC PLATFORMLIB = osx_x86 SVNDIR = osx_x86 SDK = /Developer/SDKs/MacOSX10.4u.sdk CCFLAGS=%(CCFLAGS) -arch i386 -fPIC -mmacosx-version-min=10.4 ASMFLAGS = -f macho -D_MACHO -D_PIC #include "gcc_osx.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_palmos.build000066400000000000000000000015251462133141200232420ustar00rootroot00000000000000#define TARGET_PALMOS #define ARM PLATFORMLIB = palm_arm SVNDIR = palm_arm #define OUTPUT_EXE %(NAME).prc #define OUTPUT_DLL %(NAME).prc #define OUTPUT_LIB lib%(NAME).a #define CC arm-tcpmp-palmos-gcc #define CXX arm-tcpmp-palmos-g++ #define AR arm-tcpmp-palmos-ar #define CXX_HOST g++ #define CC_M68K m68k-palmos-gcc #define CCFLAGS -DARM -D__GLIBC__ -pipe -Wno-multichar -fshort-enums -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -march=armv4 -mtune=xscale #define SFLAGS -DARM -D__GLIBC__ -pipe -Wno-multichar -fshort-enums -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -mcpu=iwmmxt -mtune=xscale #define LFLAGS -Wl,--split-by-file=63000 -Wl,--emit-relocs -nostartfiles #define CFLAGS_M68K -pipe -O3 -mnoshort #define LFLAGS_M68K -L/usr/local/share/palmdev/sdk/lib/m68k-palmos-coff -lPalmOSGlue -lc -lgcc #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_ps2sdk.build000066400000000000000000000014151462133141200231530ustar00rootroot00000000000000#define TARGET_PS2SDK #define MIPS #define RESOURCE_COREC PLATFORMLIB = ps2sdk SVNDIR = ps2sdk #define OUTPUT_EXE %(NAME).elf #define OUTPUT_CON %(NAME).elf #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a #define CC ee-gcc #define CXX ee-gcc #define AR ee-ar #define STRIP ee-strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -O2 -G0 -ffast-math -Wno-multichar #define LFLAGS -mno-crt0 #define SHFLAGS -shared -Wl,--strip-all #define CORERCFLAGS -w -a 16 #define IOP_CC iop-gcc #define IOP_CXX iop-gcc #define IOP_AR iop-ar #define IOP_STRIP #define IOP_CCFLAGS -O2 -G0 -fno-builtin -Wno-multichar #define IOP_SHFLAGS -s #define IOP_LFLAGS -nostdlib #define DVP_AS dvp-as #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtcore_arm.build000066400000000000000000000013071462133141200241010ustar00rootroot00000000000000#define ARM #define CC arm-none-linux-gnueabi-gcc #define CXX arm-none-linux-gnueabi-g++ #define AR arm-none-linux-gnueabi-ar #define STRIP arm-none-linux-gnueabi-strip #define STRIPFLAGS -s -x #define QTOPIA_CORE #define CCFLAGS -DARM -DTARGET_DESKTOP -DTARGET_QTOPIA -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -march=armv4t -mtune=xscale -fvisibility=hidden #define SFLAGS -DARM -DTARGET_DESKTOP -DTARGET_QTOPIA -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -mcpu=iwmmxt -mtune=xscale -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #define CXXFLAGS -fno-rtti #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtcore_mips.build000066400000000000000000000012531462133141200242720ustar00rootroot00000000000000#define MIPS #define CC mipsel-linux-gcc #define CXX mipsel-linux-g++ #define AR mipsel-linux-ar #define STRIP mipsel-linux-strip #define STRIPFLAGS -s -x #define QTOPIA_CORE #define CCFLAGS -DMIPS -DTARGET_DESKTOP -DTARGET_QTOPIA -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -msoft-float -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 -fvisibility=hidden #define SFLAGS -DMIPS -DTARGET_DESKTOP -DTARGET_QTOPIA -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -msoft-float -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #define CXXFLAGS -fno-rtti #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtcore_x86.build000066400000000000000000000005711462133141200237510ustar00rootroot00000000000000#define IX86 #define ASM yasm #define STIP strip #define STRIPFLAGS -s -x #define QTOPIA_CORE #define CCFLAGS -O3 -DTARGET_QTOPIA -DTARGET_DESKTOP -DQTOPIA_CORE -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions -fvisibility=hidden #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtopia.inc000066400000000000000000000004441462133141200227150ustar00rootroot00000000000000#define TARGET_LINUX #define TARGET_QTOPIA // GLIBC because of no iconv ? #define GLIBC #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtphone_arm.build000066400000000000000000000013311462133141200242570ustar00rootroot00000000000000#define ARM #define CC arm-none-linux-gnueabi-gcc #define CXX arm-none-linux-gnueabi-g++ #define AR arm-none-linux-gnueabi-ar #define STRIP arm-none-linux-gnueabi-strip #define STRIPFLAGS -s -x #define QTOPIA_PHONE #define QTOPIA_CORE #define CCFLAGS -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -march=armv4t -mtune=xscale -fvisibility=hidden #define SFLAGS -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -mcpu=iwmmxt -mtune=xscale -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #define CXXFLAGS -fno-rtti #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_qtphone_x86.build000066400000000000000000000006141462133141200241300ustar00rootroot00000000000000#define IX86 #define ASM yasm #define STIP strip #define STRIPFLAGS -s -x #define QTOPIA_PHONE #define QTOPIA_CORE #define CCFLAGS -O3 -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions -fvisibility=hidden #define ASMFLAGS -f elf -D_HIDDEN #define LFLAGS #define SHFLAGS -shared -Wl,--strip-all #include "gcc_qtopia.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_sparc32.build000066400000000000000000000006711462133141200232250ustar00rootroot00000000000000#define TARGET_LINUX #define SPARC32 PLATFORMLIB = linux_sparc SVNDIR = linux_sparc32 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define STRIP strip #define STRIPFLAGS -s #define CCFLAGS -O3 -mcpu=v9 -m32 -Wno-multichar #define LFLAGS -mcpu=v9 -m32 #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_sparc64.build000066400000000000000000000006711462133141200232320ustar00rootroot00000000000000#define TARGET_LINUX #define SPARC64 PLATFORMLIB = linux_sparc SVNDIR = linux_sparc64 #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a //#define CC gcc //#define CXX g++ //#define AR ar #define STRIP strip #define STRIPFLAGS -s #define CCFLAGS -O3 -mcpu=v9 -m64 -Wno-multichar #define LFLAGS -mcpu=v9 -m64 #define SHFLAGS -shared -Wl,--strip-all #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_win32.build000066400000000000000000000020471462133141200227110ustar00rootroot00000000000000#define TARGET_WIN32 #define TARGET_WIN #define IX86 #define HOST_WIN32 PLATFORMLIB = win32_x86 SVNDIR = mingw32 #define OUTPUT_EXE %(NAME).exe #define OUTPUT_CON %(NAME).exe #define OUTPUT_DLL %(NAME).dll #define OUTPUT_DLL_LIB %(NAME).dll.a #define OUTPUT_DLL_DEF %(NAME).def #define OUTPUT_LIB lib%(NAME).a #define CC gcc #define CXX g++ #define WINDRES windres #define ASM yasm #define NASM nasmw #define STRIP strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -mthreads -D__MINGW32__ -D_WIN32 -D_M_IX86 -O3 -fomit-frame-pointer -march=i686 -msse -mmmx -mno-cygwin #define CFLAGS -Wdeclaration-after-statement #define ASMFLAGS -f win32 -D_WIN32 #define NASMFLAGS -f win32 -D_WIN32 #define LFLAGS -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 #define SHFLAGS -shared -Wl,--strip-all -Wl,--enable-stdcall-fixup -Wl,--output-def,%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_DEF) -Wl,--out-implib,%(!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_LIB) #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_wince_arm.build000066400000000000000000000016741462133141200237200ustar00rootroot00000000000000#define TARGET_WINCE #define TARGET_WIN #define ARM #define HOST_WIN32 PLATFORMLIB = wince_arm SVNDIR = mingw32ce #define OUTPUT_EXE %(NAME).exe #define OUTPUT_CON %(NAME).exe #define OUTPUT_DLL %(NAME).dll #define OUTPUT_DLL_LIB %(NAME).dll.a #define OUTPUT_DLL_DEF %(NAME).def #define OUTPUT_LIB lib%(NAME).a #define CC arm-mingw32ce-gcc #define CXX arm-mingw32ce-g++ #define WINDRES arm-mingw32ce-windres #define STRIP arm-mingw32ce-strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -mthreads -O3 -fomit-frame-pointer -mno-cygwin #define CFLAGS -Wdeclaration-after-statement #define LFLAGS -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 #define SHFLAGS -shared -Wl,--strip-all -Wl,--enable-stdcall-fixup -Wl,--output-def,%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_DEF) -Wl,--out-implib,%(!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_LIB) #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/gcc_x_win32.build000066400000000000000000000021451462133141200232370ustar00rootroot00000000000000#define TARGET_WIN32 #define TARGET_WIN #define IX86 PLATFORMLIB = win32_x86 SVNDIR = mingw32 #define OUTPUT_EXE %(NAME).exe #define OUTPUT_CON %(NAME).exe #define OUTPUT_DLL %(NAME).dll #define OUTPUT_DLL_LIB %(NAME).dll.a #define OUTPUT_DLL_DEF %(NAME).def #define OUTPUT_LIB lib%(NAME).a #define CC i686-mingw32msvc-gcc #define CXX i686-mingw32msvc-g++ #define WINDRES i686-mingw32msvc-windres #define AR i686-mingw32msvc-ar #define ASM yasm #define NASM nasm #define STRIP strip #define STRIPFLAGS -s -x #define GLIBC #define CCFLAGS -mthreads -D__MINGW32__ -D__GLIBC__ -D_WIN32 -D_M_IX86 -O3 -fomit-frame-pointer -march=i686 -msse -mmmx #define CFLAGS -Wdeclaration-after-statement #define ASMFLAGS -f win32 -D_WIN32 #define NASMFLAGS -f win32 -D_WIN32 #define LFLAGS -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 #define SHFLAGS -shared -Wl,--strip-all -Wl,--enable-stdcall-fixup -Wl,--output-def,%(¯!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_DEF) -Wl,--out-implib,%(!OUTPUTPATH)%(+OUTPUT_DIR)%(OUTPUT_DLL_LIB) #include "gcc.inc" bcmatroska2-5.3.101/corec/tools/coremake/icl11_2005.build000066400000000000000000000014211462133141200225050ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_ICL11 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 ICC_COMPILERVERSION = 11.1 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\win32 VSPDB=vc80.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/icl_2005.build000066400000000000000000000013131462133141200223430ustar00rootroot00000000000000DEVENV = devenv.exe #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_ICL9 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 9.0 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\win32 VSPDB=vc80.pdb MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/kdevelop.build000066400000000000000000000163231462133141200227460ustar00rootroot00000000000000#define TARGET_LINUX #define IX86 #define GLIBC #define COMPILER_GCC #define RESOURCE_COREC #define ASM yasm #define ASMFLAGS -f elf #define OUTPUT_EXE %(NAME) #define OUTPUT_DLL lib%(NAME).la #define OUTPUT_LIB lib%(NAME).la #define OUTPUT_CON %(NAME) #include "automake.inc" FILE %(BUILDPATH)dummy PRINTNL directory created FILE %(¯)root.kdevelop PRINTNL PRINTNL PRINTNL PRINTNL $VERSION$ IFDEF TARGET_QTOPIA PRINTNL KDevTrollProject PRINTNL C++ ELSE PRINTNL KDevAutoProject PRINTNL C ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ada PRINTNL ada_bugs_gcc PRINTNL bash PRINTNL bash_bugs PRINTNL clanlib PRINTNL fortran_bugs_gcc PRINTNL gnome1 PRINTNL gnustep PRINTNL gtk PRINTNL gtk_bugs PRINTNL haskell PRINTNL haskell_bugs_ghc PRINTNL java_bugs_gcc PRINTNL java_bugs_sun PRINTNL kde2book PRINTNL libstdc++ PRINTNL opengl PRINTNL pascal_bugs_fp PRINTNL php PRINTNL php_bugs PRINTNL perl PRINTNL perl_bugs PRINTNL python PRINTNL python_bugs PRINTNL qt-kdev3 PRINTNL ruby PRINTNL ruby_bugs PRINTNL sdl PRINTNL stl PRINTNL sw PRINTNL w3c-dom-level2-html PRINTNL w3c-svg PRINTNL w3c-uaag10 PRINTNL wxwidgets_bugs PRINTNL PRINTNL PRINTNL Guide to the Qt Translation Tools PRINTNL Qt Assistant Manual PRINTNL Qt Designer Manual PRINTNL Qt Reference Documentation PRINTNL qmake User Guide PRINTNL PRINTNL PRINTNL KDE Libraries (Doxygen) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL libtool PRINTNL PRINTNL IFDEF TARGET_QTOPIA PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL // PRINTNL ./kdev2 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL executable PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL false PRINTNL 1 PRINTNL false PRINTNL PRINTNL 0 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELSE PRINTNL PRINTNL PRINTNL %(ACTIVETARGET) PRINTNL debug PRINTNL PRINTNL PRINTNL %(ACTIVETARGET) PRINTNL executable PRINTNL PRINTNL PRINTNL PRINTNL %(@BUILDPATH)/optimized PRINTNL GccOptions PRINTNL GppOptions PRINTNL G77Options PRINTNL -O2 -g0 PRINTNL -DNDEBUG PRINTNL PRINTNL PRINTNL --enable-debug=full PRINTNL %(@BUILDPATH)/debug PRINTNL GccOptions PRINTNL GppOptions PRINTNL G77Options PRINTNL -O0 -g3 PRINTNL -D_DEBUG PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IFDEF TARGET_QTOPIA PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL PRINTNL PRINTNL .h PRINTNL .cpp PRINTNL true PRINTNL PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL true PRINTNL true PRINTNL false PRINTNL true PRINTNL true PRINTNL true PRINTNL 250 PRINTNL 400 PRINTNL 250 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL *.o,*.lo,CVS PRINTNL false PRINTNL PRINTNL PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtcore_arm_debug.build000066400000000000000000000006571462133141200263330ustar00rootroot00000000000000#define DEBUG #define QTOPIA_CORE #define CCFLAGS -DDEBUG -DARM -DTARGET_QTOPIA -DTARGET_DESKTOP -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -ggdb -g -fsigned-char -march=armv4t -mtune=xscale #define SFLAGS -DDEBUG -DARM -DTARGET_QTOPIA -DTARGET_DESKTOP -DQTOPIA_CORE -DQT_SHARED -Wno-multichar -ggdb -g -fsigned-char -mcpu=iwmmxt -mtune=xscale #define SHFLAGS -shared #define CXXFLAGS -fno-rtti #include "kdevelop_qtopia_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtopia_arm.inc000066400000000000000000000205241462133141200246320ustar00rootroot00000000000000#define ARM #define CC arm-none-linux-gnueabi-gcc #define CXX arm-none-linux-gnueabi-g++ #define AR arm-none-linux-gnueabi-ar #define LFLAGS #define TARGET_LINUX #define TARGET_QTOPIA // at least to remove the dependency on iconv #define GLIBC #define COMPILER_GCC #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a CONFIG IF "%(QPEDIR)"!="" #define QTDIR %(QPEDIR)/qtopiacore/target ENDIF FOR EACH WORKSPACE FILE %(¯PATH)%(NAME).kdevelop PRINTNL PRINTNL PRINTNL PRINTNL $VERSION$ PRINTNL KDevTrollProject PRINTNL C++ PRINTNL PRINTNL Qt PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL false PRINTNL *.o,*.lo,CVS PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ada PRINTNL ada_bugs_gcc PRINTNL bash PRINTNL bash_bugs PRINTNL clanlib PRINTNL fortran_bugs_gcc PRINTNL gnome1 PRINTNL gnustep PRINTNL gtk PRINTNL gtk_bugs PRINTNL haskell PRINTNL haskell_bugs_ghc PRINTNL java_bugs_gcc PRINTNL java_bugs_sun PRINTNL kde2book PRINTNL libstdc++ PRINTNL opengl PRINTNL pascal_bugs_fp PRINTNL php PRINTNL php_bugs PRINTNL perl PRINTNL perl_bugs PRINTNL python PRINTNL python_bugs PRINTNL qt-kdev3 PRINTNL ruby PRINTNL ruby_bugs PRINTNL sdl PRINTNL stl PRINTNL sw PRINTNL w3c-dom-level2-html PRINTNL w3c-svg PRINTNL w3c-uaag10 PRINTNL wxwidgets_bugs PRINTNL PRINTNL PRINTNL Guide to the Qt Translation Tools PRINTNL Qt Assistant Manual PRINTNL Qt Designer Manual PRINTNL Qt Reference Documentation PRINTNL qmake User Guide PRINTNL PRINTNL PRINTNL KDE Libraries (Doxygen) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL /usr/bin/libtool PRINTNL IF "%(KDEVELOP_GDBPATH)"!="" PRINTNL %(KDEVELOP_GDBPATH) ELSE PRINTNL /usr/bin/ ENDIF PRINTNL true PRINTNL false PRINTNL false IF "%(KDEVELOP_GDBSCRIPT)"!="" PRINTNL %(|PATH)%(NAME).kdevelop_gdbscript ENDIF PRINTNL PRINTNL PRINTNL false PRINTNL true PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL // PRINTNL ./kdev2 PRINTNL PRINTNL PRINTNL IF %(QPEDIR) PRINTNL PRINTNL ELSE PRINTNL ENDIF PRINTNL PRINTNL custom PRINTNL / FOR EACH USE IF %(TYPE)==EXE PRINTNL %(¯|OUTPUTPATH)%(NAME) ENDIF ENDFOR PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL false PRINTNL 1 PRINTNL false PRINTNL make -f Makefile PRINTNL 0 PRINTNL IF %(QPEDIR) PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL PRINTNL PRINTNL .h PRINTNL .cpp PRINTNL true PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL true PRINTNL true PRINTNL false PRINTNL true PRINTNL true PRINTNL true PRINTNL 250 PRINTNL 400 PRINTNL 250 PRINTNL PRINTNL PRINTNL true PRINTNL 4 PRINTNL %(QTDIR) PRINTNL PRINTNL PRINTNL IF "%(KDEVELOP_GDBSCRIPT)"!="" FILE %(¯PATH)%(NAME).kdevelop_gdbscript PRINTNL %(KDEVELOP_GDBSCRIPT) ENDIF FILE %(¯PATH)Makefile IF %(QPEDIR) // needed to run some of the Qtopia/Greenphone (stupid) scripts like gph PRINTNL PREFIX?=%(QPEDIR)/image PRINTNL DPREFIX?=%(QPEDIR)/dimage/opt/Qtopia PRINTNL D="-d" ENDIF PRINTNL all: %(USE) PRINTNL FOR EACH USE PRINTNL %(NAME): %(USE) PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak ENDFOR PRINTNL PRINTNL clean: FOR EACH USE IF %(TYPE)==EXE PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak clean ENDIF ENDFOR PRINTNL PRINTNL install: FOR EACH USE IF %(TYPE)==EXE PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak install ENDIF ENDFOR PRINTNL PRINTNL .phony: all install %(USE) PRINTNL FOR EACH USE #include "qtopia_desktop.inc" #include "qtopia_resource.inc" FILE %(¯PATH)%(NAME).mak #include "gcc_mak.inc" ENDFOR ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtopia_x86.inc000066400000000000000000000204151462133141200244770ustar00rootroot00000000000000#define IX86 #define ASM yasm #define ASMFLAGS -f elf #define LFLAGS #define TARGET_LINUX #define TARGET_QTOPIA // at least to remove the dependency on iconv #define GLIBC #define COMPILER_GCC #define OUTPUT_EXE %(NAME) #define OUTPUT_CON %(NAME) #define OUTPUT_DLL lib%(NAME).so #define OUTPUT_DLL_LIB lib%(NAME).so #define OUTPUT_LIB lib%(NAME).a CONFIG IF "%(QPEDIR)"!="" #define QTDIR %(QPEDIR)/qtopiacore/target ENDIF FOR EACH WORKSPACE FILE %(¯PATH)%(NAME).kdevelop PRINTNL PRINTNL PRINTNL PRINTNL $VERSION$ PRINTNL KDevTrollProject PRINTNL C++ PRINTNL PRINTNL Qt PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL false PRINTNL *.o,*.lo,CVS PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ada PRINTNL ada_bugs_gcc PRINTNL bash PRINTNL bash_bugs PRINTNL clanlib PRINTNL fortran_bugs_gcc PRINTNL gnome1 PRINTNL gnustep PRINTNL gtk PRINTNL gtk_bugs PRINTNL haskell PRINTNL haskell_bugs_ghc PRINTNL java_bugs_gcc PRINTNL java_bugs_sun PRINTNL kde2book PRINTNL libstdc++ PRINTNL opengl PRINTNL pascal_bugs_fp PRINTNL php PRINTNL php_bugs PRINTNL perl PRINTNL perl_bugs PRINTNL python PRINTNL python_bugs PRINTNL qt-kdev3 PRINTNL ruby PRINTNL ruby_bugs PRINTNL sdl PRINTNL stl PRINTNL sw PRINTNL w3c-dom-level2-html PRINTNL w3c-svg PRINTNL w3c-uaag10 PRINTNL wxwidgets_bugs PRINTNL PRINTNL PRINTNL Guide to the Qt Translation Tools PRINTNL Qt Assistant Manual PRINTNL Qt Designer Manual PRINTNL Qt Reference Documentation PRINTNL qmake User Guide PRINTNL PRINTNL PRINTNL KDE Libraries (Doxygen) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL /usr/bin/libtool PRINTNL IF "%(KDEVELOP_GDBPATH)"!="" PRINTNL %(KDEVELOP_GDBPATH) ELSE PRINTNL /usr/bin/ ENDIF PRINTNL true PRINTNL false PRINTNL false IF "%(KDEVELOP_GDBSCRIPT)"!="" PRINTNL %(|PATH)%(NAME).kdevelop_gdbscript ENDIF PRINTNL PRINTNL PRINTNL false PRINTNL true PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL // PRINTNL ./kdev2 PRINTNL PRINTNL PRINTNL IF %(QPEDIR) PRINTNL PRINTNL ELSE PRINTNL ENDIF PRINTNL PRINTNL custom PRINTNL / FOR EACH USE IF %(TYPE)==EXE PRINTNL %(¯|OUTPUTPATH)%(NAME) ENDIF ENDFOR PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL false PRINTNL 1 PRINTNL false PRINTNL make -f Makefile PRINTNL 0 PRINTNL IF %(QPEDIR) PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL false PRINTNL PRINTNL PRINTNL PRINTNL false PRINTNL PRINTNL PRINTNL .h PRINTNL .cpp PRINTNL true PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL true PRINTNL true PRINTNL true PRINTNL false PRINTNL true PRINTNL true PRINTNL true PRINTNL 250 PRINTNL 400 PRINTNL 250 PRINTNL PRINTNL PRINTNL true PRINTNL 4 PRINTNL %(QTDIR) PRINTNL PRINTNL PRINTNL IF "%(KDEVELOP_GDBSCRIPT)"!="" FILE %(¯PATH)%(NAME).kdevelop_gdbscript PRINTNL %(KDEVELOP_GDBSCRIPT) ENDIF FILE %(¯PATH)Makefile IF %(QPEDIR) // needed to run some of the Qtopia/Greenphone (stupid) scripts like gph PRINTNL PREFIX?=%(QPEDIR)/image PRINTNL DPREFIX?=%(QPEDIR)/dimage/opt/Qtopia PRINTNL D="-d" ENDIF PRINTNL all: %(USE) PRINTNL FOR EACH USE PRINTNL %(NAME): %(USE) PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak ENDFOR PRINTNL PRINTNL clean: FOR EACH USE IF %(TYPE)==EXE PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak clean ENDIF ENDFOR PRINTNL PRINTNL install: FOR EACH USE IF %(TYPE)==EXE PRINTNL @cd %(!PATH) && $(MAKE) -f %(NAME).mak install ENDIF ENDFOR PRINTNL PRINTNL .phony: all install %(USE) PRINTNL FOR EACH USE #include "qtopia_desktop.inc" #include "qtopia_resource.inc" FILE %(¯PATH)%(NAME).mak #include "gcc_mak.inc" ENDFOR ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtphone_arm.build000066400000000000000000000011101462133141200253270ustar00rootroot00000000000000#define STRIP arm-none-linux-gnueabi-strip #define STRIPFLAGS -s -x #define QTOPIA_PHONE #define QTOPIA_CORE #define CCFLAGS -DNDEBUG -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -march=armv4t -mtune=xscale #define SFLAGS -DNDEBUG -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -O3 -mno-apcs-frame -fomit-frame-pointer -fsigned-char -mcpu=iwmmxt -mtune=xscale #define SHFLAGS -shared -Wl,--strip-all #define CXXFLAGS -fno-rtti #include "kdevelop_qtopia_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtphone_arm_debug.build000066400000000000000000000007001462133141200265010ustar00rootroot00000000000000#define DEBUG #define QTOPIA_PHONE #define QTOPIA_CORE #define CCFLAGS -DDEBUG -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -ggdb -g -fsigned-char -march=armv4t -mtune=xscale #define SFLAGS -DDEBUG -DARM -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -Wno-multichar -ggdb -g -fsigned-char -mcpu=iwmmxt -mtune=xscale #define SHFLAGS -shared #define CXXFLAGS -fno-rtti #include "kdevelop_qtopia_arm.inc" bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtphone_x86.build000066400000000000000000000004721462133141200252070ustar00rootroot00000000000000#define QTOPIA_PHONE #defien QTOPIA_CORE #define STIP strip #define STRIPFLAGS -s -x #define CCFLAGS -DNDEBUG -O3 -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions #define SHFLAGS -shared -Wl,--strip-all #include "kdevelop_qtopia_x86.inc" bcmatroska2-5.3.101/corec/tools/coremake/kdevelop_qtphone_x86_debug.build000066400000000000000000000004171462133141200263540ustar00rootroot00000000000000#define DEBUG #define QTOPIA_PHONE #define QTOPIA_CORE #define CCFLAGS -DDEBUG -ggdb -g -DTARGET_QTOPIA -DQTOPIA_CORE -DQTOPIA_PHONE -DQT_SHARED -pipe -m32 -march=i486 -msse -mmmx -Wno-multichar -fno-exceptions #define SHFLAGS -shared #include "kdevelop_qtopia_x86.inc" bcmatroska2-5.3.101/corec/tools/coremake/osx_plist.inc000066400000000000000000000121031462133141200226230ustar00rootroot00000000000000PRINTNL PRINTNL PRINTNL PRINTNL HAS_EXTENSIONS = HAS_PROTOCOLS = #IFNDEF TARGET_IPHONE FOR EACH SOURCE FOR EACH MIME_TYPE IF "%(EXTENSION)"!="" ../../HAS_EXTENSIONS = 1 ENDIF ENDFOR ENDFOR FOR EACH USE FOR EACH SOURCE FOR EACH MIME_TYPE IF "%(EXTENSION)"!="" ../../../HAS_EXTENSIONS = 1 ENDIF ENDFOR ENDFOR ENDFOR ENDIF // !TARGET_IPHONE IFDEF TARGET_IPHONE_SDK FOR EACH SOURCE FOR EACH PROTOCOL ../../HAS_PROTOCOLS = 1 ENDFOR ENDFOR FOR EACH USE FOR EACH SOURCE FOR EACH PROTOCOL ../../../HAS_PROTOCOLS = 1 ENDFOR ENDFOR ENDFOR ENDIF // TARGET_IPHONE_SDK IFDEF TARGET_IPHONE_SDK IFDEF CONFIG_BACKGROUND_AUDIO PRINTNL UIBackgroundModes PRINTNL PRINTNL audio PRINTNL ENDIF ENDIF PRINTNL CFBundleDevelopmentRegion PRINTNL English IF %(HAS_EXTENSIONS) PRINTNL CFBundleDocumentTypes PRINTNL FOR EACH SOURCE FOR EACH MIME_TYPE PRINTNL IF "%(EXTENSION)"!="" PRINTNL CFBundleTypeExtensions PRINTNL FOR EACH EXTENSION PRINTNL %(NAME) ENDFOR PRINTNL ENDIF PRINTNL CFBundleTypeMIMETypes PRINTNL PRINTNL %(NAME) PRINTNL PRINTNL CFBundleTypeRole PRINTNL Viewer PRINTNL ENDFOR ENDFOR FOR EACH USE FOR EACH SOURCE FOR EACH MIME_TYPE PRINTNL IF %(EXTENSION) PRINTNL CFBundleTypeExtensions PRINTNL FOR EACH EXTENSION PRINTNL %(NAME) ENDFOR PRINTNL ENDIF PRINTNL CFBundleTypeMIMETypes PRINTNL PRINTNL %(NAME) PRINTNL PRINTNL CFBundleTypeRole PRINTNL Viewer PRINTNL ENDFOR ENDFOR ENDFOR PRINTNL ENDIF IF %(HAS_PROTOCOLS) PRINTNL CFBundleURLTypes PRINTNL PRINTNL PRINTNL CFBundleURLName PRINTNL com.%(PROJECT_VENDOR).%(NAME) PRINTNL CFBundleURLSchemes PRINTNL FOR EACH SOURCE FOR EACH PROTOCOL PRINTNL %(NAME) ENDFOR ENDFOR FOR EACH USE FOR EACH SOURCE FOR EACH PROTOCOL PRINTNL %(NAME) ENDFOR ENDFOR ENDFOR PRINTNL PRINTNL PRINTNL ENDIF IF %(OSX_STRINGS) PRINTNL CFBundleDevelopmentRegion PRINTNL %(OSX_STRINGS) ENDIF PRINTNL CFBundleExecutable IF %(PROJECT_PATH) PRINTNL %(PROJECT_PATH) ELSE PRINTNL %(NAME) ENDIF IF %(PROJECT_NAME) PRINTNL CFBundleGetInfoString PRINTNL %(PROJECT_NAME) ENDIF IFNDEF TARGET_IPHONE IF %(OSX_ICON) PRINTNL CFBundleIconFile PRINTNL %(OSX_ICON) ELIF %(ICON) PRINTNL CFBundleIconFile PRINTNL %( ENDIF ELSE IF %(ICON) PRINTNL CFBundleIconFile PRINTNL %( ENDIF PRINTNL UIRequiresPersistentWiFi PRINTNL ENDIF IF %(PROJECT_VENDOR) PRINTNL CFBundleIdentifier PRINTNL com.%(PROJECT_VENDOR).%(NAME) ENDIF PRINTNL CFBundleInfoDictionaryVersion PRINTNL 6.0 PRINTNL CFBundlePackageType IF (%(TYPE)==DLL) PRINTNL BNDL ELSE PRINTNL APPL ENDIF IF %(PROJECT_BUILD) PRINTNL CFBundleVersion PRINTNL %(PROJECT_BUILD) ENDIF IF %(PROJECT_VERSION) PRINTNL CFBundleShortVersionString PRINTNL %(PROJECT_VERSION) ENDIF IF %(PROJECT_FOURCC) PRINTNL CFBundleSignature PRINTNL %('PROJECT_FOURCC) ENDIF MAIN_NIB_FILE = MAIN_NIB_CLASS = FOR EACH SOURCE IF ((%(>NAME)==nib) && (%(MAIN_NIB))) ../MAIN_NIB_FILE = %(NAME) ../MAIN_NIB_CLASS = %(MAIN_NIB) ENDIF ENDFOR FOR EACH USE FOR EACH SOURCE IF ((%(>NAME)==nib) && (%(MAIN_NIB))) ../../MAIN_NIB_FILE = %(NAME) ../../MAIN_NIB_CLASS = %(MAIN_NIB) ENDIF ENDFOR ENDFOR IF ((%(MAIN_NIB_FILE)) && (%(MAIN_NIB_CLASS))) PRINTNL NSMainNibFile PRINTNL %( PRINTNL NSPrincipalClass PRINTNL %(MAIN_NIB_CLASS) ENDIF FOR EACH PLIST_KEY PRINTNL %(NAME) PRINTNL %(STRING) ENDFOR PRINTNL PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/qmake.inc000066400000000000000000000010171462133141200216770ustar00rootroot00000000000000PRINTNL TARGET = %(¯NAME) //PRINTNL DEPENDPATH += . //PRINTNL CONFIG += static PRINTNL TRANSLATIONS += \ FOR EACH TRANSLATION_QT4 PRINTNL %(NAME) \ ENDFOR PRINTNL PRINTNL HEADERS += \ FOR EACH HEADER_QT4 PRINTNL %(!NAME) \ ENDFOR FOR EACH HEADER PRINTNL %(!NAME) \ ENDFOR PRINTNL PRINTNL SOURCES += \ FOR EACH SOURCE PRINTNL %(!NAME) \ ENDFOR PRINTNL PRINTNL FORMS += \ FOR EACH UI_FORM_QT4 PRINTNL %(!NAME) \ ENDFOR PRINTNL PRINTNL RESOURCES += \ FOR EACH RESOURCE_QT4 PRINTNL %(!NAME) \ ENDFOR PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/qtopia_desktop.inc000066400000000000000000000013031462133141200236250ustar00rootroot00000000000000IF %(TYPE)==EXE FILE %(¯PATH)%(NAME).desktop PRINTNL [Desktop Entry] PRINTNL Exec=%(NAME) PRINTNL Type=Application IF %(ICON)!="" PRINTNL Icon=%(NAME)/%( PRINTNL FOR EACH INSTALL PRINTNL %(!PATH)%(!NAME) ENDFOR PRINTNL PRINTNL ENDIF ENDIF bcmatroska2-5.3.101/corec/tools/coremake/readme.txt000066400000000000000000000156741462133141200221220ustar00rootroot00000000000000 CoreMake USAGE DOCUMENTATION $Id: readme.txt 143 2008-02-11 06:32:23Z robux4 $ *** INTRODUCTION *** CoreMake is a meta-makefile processor that turns .proj files into makefiles for various compilers/IDE, including Visual Studio 2005, MSVC6 , EVC4 , XCode 2 kdevelop, GNU make, nmake, Carbide. Unlike other meta-makefile processors, CoreMake doesn't need a scripting language to run. It's just a .c file that needs to be compiled and some scripts that it will interpret. The default values for each compiler are meant to produce valid and optimized code. *** LICENSE *** CoreMake is a tool developped by CoreCodec, Inc. under the BSD license. *** GETTING STARTED *** coremake.c needs to be compiled before using coremake. On Windows, with Visual Studio you can use the following command to get coremake.exe : cl.exe coremake.c On Linux/OS X/Mingw you can generate it using : gcc -o coremake coremake.c Once you have the CoreMake executable you need to run it from the root of your source code : coremake vs_2005 This command will generate the project files to compile your source in Visual Studio 2005 for Windows on x86. Each target is located in the coremake directory with a .build file extension. See Apendix A for a list of target names and their corresponding use. *** .PROJ FILES *** * Directories * CoreMake uses .proj files to define what workspace and projects to build. There should be only one .proj file per directory and the name of the .proj file should be the name of the directory. With the exception of root.proj which can be in the root of your source directory. /root.proj /directory/directory.proj /otherdir/otherdir.proj From within a .proj you have to declare what subdirectory CoreMake should scan. If this is not done, subdirectories are not used. For example root.proj could have this: #include "directory/directory.proj" Or more generally: #include "*/*.proj" As the coremake folder (and all it's .build files) are generally not where the source code is, it is possible to tell in root.proj where the coremake folder is located: PLATFORM_FILES tools/coremake When building a coremake'd project the object files (.o or .obj) are generated in the /build/ directory. And the result of the build is put in the /release/ directory. For example: /build/vs_2005/test.o /release/vs_2005/test.exe * Syntax * A .proj file is just a text file that describes the projects to create and the source/libraries to use. All folders should use the '/' character and never the DOS/Windows '\' character. There are different types of definitions in CoreMake: - WORKSPACE lists all the projects that the makefile/solution will contain - EXE, CON, DLL, LIB are actual projects that will result in file to compile and link, all written in C, C++ or Assembler - EXE_CSHARP, CON_CSHARP, DLL_CSHARP, LIB_CSHARP are actual projects but written in the C# language - GROUP can list the same things as a regular project but don't result in a project to build. It can be included in many other projects where the content of the GROUP will be added (like an include file or a template) * Use command * To add a project into a WORKSPACE you have to use the USE command: EXE test { SOURCE test.c } WORKSPACE TestWorkspace { USE test } That USE command is also used to include the content of a GROUP or add compilation and linking dependencies between projects (an EXE using a DLL for example). In this example "test" use the fileHandler.dll (or .so) that will be compiled before "test" when building the solution "TestWorkspace": DLL fileHandler { SOURCE file.c } EXE test { SOURCE test.c USE fileHandler } WORKSPACE TestWorkspace { USE test } The order in which the WORKSPACE, EXE, DLL, GROUP, etc are placed in the .proj files is not important. But each project should have a unique name in all the .proj files found. * Libraries & Headers * Any regular C program usually has to include some headers and use the corresponding libraries. The headers and libraries can be in some specific location. The syntax to add such directories is the following: DLL fileHandler { SOURCE file.c INCLUDE path/to/headers LIBINCLUDE path/to/library } To add a library for linking the syntax is as follows: DLL fileHandler { SOURCE file.c LIBS a_library.lib LIBINCLUDE path/to/library } *** Apendix A: list of targets *** clean : clean the files generated by coremake distclean : clean the files generated by coremake and built evc_arm : Windows CE ARM target built with MS EVC 4.0 evc_arm_pocketpc : Pocket PC ARM target built with MS EVC 4.0 evc_arm_smartphone : Smartphone ARM target built with MS EVC 4.0 evc_armv4 : Windows CE ARM target built with MS EVC 4.0 evc_armv4_pocketpc : Pocket PC ARMv4 target built with MS EVC 4.0 evc_armv4_smartphone : Pocket PC ARMv4 target built with MS EVC 4.0 evc_armv4i : Windows CE ARMv4i target built with MS EVC 4.0 evc_emulator : Windows CE emulator target built with MS EVC 4.0 evc_mips : Windows CE MIPS target built with MS EVC 4.0 evc_mipsii : Windows CE MIPSII target built with MS EVC 4.0 evc_sh3 : Windows CE SH3 target built with MS EVC 4.0 evc_sh4 : Windows CE SH4 target built with MS EVC 4.0 evc_x86 : Windows CE x86 target built with MS EVC 4.0 evc_x86em : Windows CE x86 Emulator target built with MS EVC 4.0 gcc_linux gcc_linux_arm gcc_linux_debug gcc_linux_ppc gcc_linux_qt_x86 gcc_linux_x64 gcc_linux_x64_debug gcc_osx gcc_osx_iphone_dev gcc_osx_ppc gcc_osx_x86 gcc_osx_x86_pic gcc_palmos gcc_ps2sdk gcc_qtcore_arm gcc_qtcore_x86 gcc_qtphone_arm gcc_qtphone_x86 gcc_sparc32 gcc_sparc64 gcc_win32 : Windows 32bits on x86 built with MinGW+MSys gcc_x_win32 : Windows 32bits on x86 built with MinGW+MSys as a cross compiler icl_2005 kdevelop kdevelop_qtcore_arm_debug kdevelop_qtphone_arm kdevelop_qtphone_arm_debug kdevelop_qtphone_x86 kdevelop_qtphone_x86_debug s60_1st s60_1st_wins s60_2nd_fp3 s60_2nd_fp3_debug s60_2nd_fp3_winscw s60_3rd_fp1 s60_3rd_fp1_debug s60_3rd_fp1_winscw s60_3rd_mr s60_3rd_mr_debug s60_3rd_mr_winscw s80_dp2 s80_dp2_wins s90_7710 s90_7710_wins uiq_21 uiq_21_wins uiq_30 uiq_30_debug uiq_30_winscw uiq_31 uiq_31_winscw vc6 : Windows 32bits on x86 built with MS Visual C++ 6 vc6_palmos vs_2003 : Windows 32bits on x86 built with MS Visual Studio 2003 vs_2005 : Windows 32bits on x86 built with MS Visual Studio 2005 vs_2008 : Windows 32bits on x86 built with MS Visual Studio 2008 vs_ce5_armv4i vs_ce5_mipsii vs_express : Windows 32bits on x86 built with MS Visual C++ Express vs_ppc2003_armv4 vs_smart2003_armv4 vs_wm5_armv4i vs_wm5s_armv4i vs_wm6p_armv4i vs_wm6s_armv4i vs_x64 : Windows 64bits on x64 built with MS Visual Studio 2005 xcode xcode_iphone_dev : XCode project to build iPhone binaries using the iPhone SDK from the iPhoneDevTeam xcode_uni : XCode project to produce a Universal binary (debug is either i386 or ppc) bcmatroska2-5.3.101/corec/tools/coremake/s60_1st.build000066400000000000000000000005551462133141200223340ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SERIES60_1ST #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_1st TARGDEFINE = SERIES60 TARGDEFINE2 = __SERIES60_10__ TARGPLATFORM = ARMI TARGMODE = UREL TARGCPU = armi DEVICES_ID = S60_1st:com.nokia.series60 TARGSIS = (0x101F6F88),0,0,0,{"Series60ProductID"} TARGSIS_S60_1st = 1 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_1st_wins.build000066400000000000000000000004261462133141200233710ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SERIES60_1ST #define IX86 PLATFORMLIB = symbian_s60_1st_wins TARGDEFINE = SERIES60 TARGDEFINE2 = __SERIES60_10__ TARGPLATFORM = WINS TARGMODE = UDEB TARGCPU = wins DEVICES_ID = S60_1st:com.nokia.series60 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_2nd_fp3.build000066400000000000000000000005471462133141200230610ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_2nd_fp3 TARGDEFINE = SERIES60 TARGDEFINE2 = __SERIES60_20__ TARGPLATFORM = ARMI TARGMODE = UREL TARGCPU = armi DEVICES_ID = S60_2nd_FP3:com.nokia.series60 TARGSIS = (0x101f7960),0,0,0,{"Series60ProductID"} CARBIDE_SDK = S60_2nd_FP3 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_2nd_fp3_debug.build000066400000000000000000000005471462133141200242270ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_2nd_fp3 TARGDEFINE = SERIES60 TARGDEFINE2 = __SERIES60_20__ TARGPLATFORM = ARMI TARGMODE = UDEB TARGCPU = armi DEVICES_ID = S60_2nd_FP3:com.nokia.series60 TARGSIS = (0x101f7960),0,0,0,{"Series60ProductID"} CARBIDE_SDK = S60_2nd_FP3 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_2nd_fp3_winscw.build000066400000000000000000000005071462133141200244470ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define IX86 PLATFORMLIB = symbian_s60_2nd_fp3_winscw TARGDEFINE = SERIES60 TARGDEFINE2 = __SERIES60_20__ TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = S60_2nd_FP3:com.nokia.series60 CARBIDE_SDK = S60_2nd_FP3 CARBIDE_TOOLCHAIN = winscw #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_fp1.build000066400000000000000000000015231462133141200230570ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_3rd_fp1 TARGDEFINE = SERIES60 TARGPLATFORM = GCCE TARGMODE = UREL TARGCPU = armv5 DEVICES_ID = S60_3rd_FP1:com.nokia.s60 TARGSIS = [0x101F7961],0,0,0,{"Series60ProductID"} CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_FP1 CARBIDE_SDK_NAME = S60 3.0 Phone (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = toolChain. CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_31__ CARBIDE_DEFINE += __SERIES60_3X__ MIFCONV = /v1 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_fp1_debug.build000066400000000000000000000015231462133141200242250ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_3rd_fp1 TARGDEFINE = SERIES60 TARGPLATFORM = GCCE TARGMODE = UDEB TARGCPU = armv5 DEVICES_ID = S60_3rd_FP1:com.nokia.s60 TARGSIS = [0x101F7961],0,0,0,{"Series60ProductID"} CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_FP1 CARBIDE_SDK_NAME = S60 3.0 Phone (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = toolChain. CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_31__ CARBIDE_DEFINE += __SERIES60_3X__ MIFCONV = /v1 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_fp1_winscw.build000066400000000000000000000016221462133141200244510ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define IX86 PLATFORMLIB = symbian_s60_3rd_fp1_winscw TARGDEFINE = SERIES60 TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = S60_3rd_FP1:com.nokia.s60 CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_FP1 CARBIDE_SDK_NAME = S60 3.0 Emulator CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = winscw CARBIDE_ERRORPARSERS = errorParsers="com.symbian.cdt.build.WinscwErrorParser;org.eclipse.cdt.core.MakeErrorParser;;com.symbian.cdt.build.RCOMPErrorParser;;com.symbian.cdt.build.MakeDefErrorParser" CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __CW32__ CARBIDE_DEFINE += __WINS__ CARBIDE_DEFINE += __WINSCW__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_31__ CARBIDE_DEFINE += __SERIES60_3X__ MIFCONV = /v1 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_mr.build000066400000000000000000000015011462133141200230030ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_3rd_mr TARGDEFINE = SERIES60 TARGPLATFORM = GCCE TARGMODE = UREL TARGCPU = armv5 DEVICES_ID = S60_3rd_MR:com.nokia.s60 TARGSIS = [0x101F7961],0,0,0,{"Series60ProductID"} CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_MR CARBIDE_SDK_NAME = S60 3.0 Phone (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = toolChain. CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_30__ CARBIDE_DEFINE += __SERIES60_3X__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_mr_debug.build000066400000000000000000000015071462133141200241570ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_3rd_mr_debug TARGDEFINE = SERIES60 TARGPLATFORM = GCCE TARGMODE = UDEB TARGCPU = armv5 DEVICES_ID = S60_3rd_MR:com.nokia.s60 TARGSIS = [0x101F7961],0,0,0,{"Series60ProductID"} CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_MR CARBIDE_SDK_NAME = S60 3.0 Phone (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = toolChain. CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_30__ CARBIDE_DEFINE += __SERIES60_3X__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_3rd_mr_winscw.build000066400000000000000000000016001462133141200243750ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define IX86 PLATFORMLIB = symbian_s60_3rd_mr_winscw TARGDEFINE = SERIES60 TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = S60_3rd_MR:com.nokia.s60 CARBIDE_BASE = S60_3rd_com CARBIDE_SDK = S60_3rd_MR CARBIDE_SDK_NAME = S60 3.0 Emulator CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = winscw CARBIDE_ERRORPARSERS = errorParsers="com.symbian.cdt.build.WinscwErrorParser;org.eclipse.cdt.core.MakeErrorParser;;com.symbian.cdt.build.RCOMPErrorParser;;com.symbian.cdt.build.MakeDefErrorParser" CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __CW32__ CARBIDE_DEFINE += __WINS__ CARBIDE_DEFINE += __WINSCW__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_30__ CARBIDE_DEFINE += __SERIES60_3X__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_5th.build000066400000000000000000000015511462133141200223220ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s60_5th TARGDEFINE = SERIES60 TARGPLATFORM = GCCE TARGMODE = UREL TARGCPU = armv5 DEVICES_ID = S60_5th_Edition_SDK_v1.0:com.nokia.s60 TARGSIS = [0x101F7961],0,0,0,{"Series60ProductID"} CARBIDE_BASE = S60_5th_com CARBIDE_SDK = S60_5th_Edition_SDK_v1.0 CARBIDE_SDK_NAME = S60 5.0 Phone (GCCE) CARBIDE_CDT_SDK = 94 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = toolChain. CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_31__ CARBIDE_DEFINE += __SERIES60_3X__ MIFCONV = /v1 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s60_5th_winscw.build000066400000000000000000000016311462133141200237130ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES60 #define SYMBIAN90 #define IX86 PLATFORMLIB = symbian_s60_5th_winscw TARGDEFINE = SERIES60 TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = S60_5th_Edition_SDK_v1.0:com.nokia.s60 CARBIDE_BASE = S60_5th_com CARBIDE_SDK = S60_5th_Edition_SDK_v1.0 CARBIDE_SDK_NAME = S60 5.0 Emulator CARBIDE_CDT_SDK = 94 CARBIDE_NOKIA_SDK = S60_30 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = winscw CARBIDE_ERRORPARSERS = errorParsers="com.symbian.cdt.build.WinscwErrorParser;org.eclipse.cdt.core.MakeErrorParser;;com.symbian.cdt.build.RCOMPErrorParser;;com.symbian.cdt.build.MakeDefErrorParser" CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __CW32__ CARBIDE_DEFINE += __WINS__ CARBIDE_DEFINE += __WINSCW__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ CARBIDE_DEFINE += __SERIES60_30__ CARBIDE_DEFINE += __SERIES60_3X__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s80_dp2.build000066400000000000000000000005141462133141200223070ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES80 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s80_dp2 TARGDEFINE = SERIES80 TARGDEFINE2 = __SERIES80__ TARGPLATFORM = ARMI TARGMODE = UREL TARGCPU = armi DEVICES_ID = Series80_DP2_0_SDK:com.nokia.Series80 TARGSIS = (0x101F8ED2),0,0,0,{"Series80ProductID"} #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s80_dp2_wins.build000066400000000000000000000004111462133141200233430ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES80 #define IX86 PLATFORMLIB = symbian_s80_dp2_wins TARGDEFINE = SERIES80 TARGDEFINE2 = __SERIES80__ TARGPLATFORM = WINS TARGMODE = UDEB TARGCPU = wins DEVICES_ID = Series80_DP2_0_SDK:com.nokia.Series80 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s90_7710.build000066400000000000000000000005061462133141200222220ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_s90_7710 TARGDEFINE = SERIES90 TARGDEFINE2 = __SERIES90__ TARGPLATFORM = ARMI TARGMODE = UREL TARGCPU = armi DEVICES_ID = NOKIA_7710:com.nokia.Nokia7710 TARGSIS = (0x101FBE05),0,0,0,{"Series90ProductID"} #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/s90_7710_wins.build000066400000000000000000000004031462133141200232560ustar00rootroot00000000000000#define TARGET_SYMBIAN #define SERIES90 #define IX86 PLATFORMLIB = symbian_s90_7710_wins TARGDEFINE = SERIES90 TARGDEFINE2 = __SERIES90__ TARGPLATFORM = WINS TARGMODE = UDEB TARGCPU = wins DEVICES_ID = NOKIA_7710:com.nokia.Nokia7710 #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/script.build000066400000000000000000000015721462133141200224410ustar00rootroot00000000000000#define TARGET_SCRIPT #define NO_STDAFX #define NO_PROJECT #define OUTPUT_EXE %(NAME).dll #define OUTPUT_EXE %(NAME).exe #define OUTPUT_DLL %(NAME).dll #define OUTPUT_LIB %(NAME).lib #define OUTPUT_CON %(NAME).exe CONFIG FOR EACH WORKSPACE FOR EACH USE FOR EACH COMPILE BUILDSTR = IF %(CONFIG_CUSTOMER) BUILDSTR = %(CONFIG_CUSTOMER) ENDIF IF %(CONFIG_TEST_EXPIRE) IF %(BUILDSTR) BUILDSTR = %(BUILDSTR)_%(CONFIG_TEST_EXPIRE) ELSE BUILDSTR = %(CONFIG_TEST_EXPIRE) ENDIF ENDIF IF %(PROJECT_BUILD) IF %(BUILDSTR) BUILDSTR = %(BUILDSTR)_r%(PROJECT_BUILD) ELSE BUILDSTR = r%(PROJECT_BUILD) ENDIF ENDIF COMPILE %(NAME) %(¯NAME) ENDFOR IF %(DOXYGEN) COMPILE %(DOXYGEN) "%(PATH)%(`PROJECT_NAME).doxyfile" ENDIF ENDFOR ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/symbian.inc000066400000000000000000000537601462133141200222570ustar00rootroot00000000000000IF !DEFINED(CARBIDE_VS) #define CARBIDE_12 ENDIF #define OUTPUT_EXE %(PROJECT_PATH).app #define OUTPUT_CON %(PROJECT_PATH).app #define OUTPUT_DLL %(NAME).dll #define OUTPUT_LIB %(NAME).lib IF DEFINED(CARBIDE_20) CARBIDE_SUBDIR=carbide_20 ELIF DEFINED(CARBIDE_12) CARBIDE_SUBDIR=carbide_12 ELSE CARBIDE_SUBDIR=carbide ENDIF CONFIG FOR EACH LIB,DLL,EXE,CON IF DEFINED(CARBIDE_12) || DEFINED(CARBIDE_20) MAKEPATH=build/%(CARBIDE_SUBDIR)/%(PATH)%(NAME)/ ELSE MAKEPATH=%(PATH) ENDIF ENDFOR MKDIR %(OUTPUTPATH) FOR EACH WORKSPACE FILE %(¯PATH)make.bat PRINTNLDOS @if not "%ProgramFiles(x86)%"=="" cmd /c "path=%ProgramFiles(x86)%\common files\symbian\tools;%PATH% && make.exe @%(DEVICES_ID) %1 %2 %3 %4" PRINTNLDOS @if "%ProgramFiles(x86)%"=="" cmd /c "path=%ProgramFiles%\common files\symbian\tools;%PATH% && make.exe @%(DEVICES_ID) %1 %2 %3 %4" FILE %(¯PATH)bld.inf PRINTNL PRJ_PLATFORMS PRINTNL %(TARGPLATFORM) PRINTNL PRINTNL PRJ_MMPFILES FOR EACH USE IF %(TYPE)==exe IF defined(SYMBIAN90) && defined(SERIES60) && %(ICON)!="" PRINTNL gnumakefile %(¯~!PATH)%(PROJECT_PATH)_icon.mak ENDIF ENDIF PRINTNL %(¯~!MAKEPATH)%(NAME).mmp ENDFOR IF !DEFINED(CARBIDE_VS) FILE %(¯PATH)Makefile IF (%(TARGPLATFORM)==wins) || (%(TARGPLATFORM)==winscw) PRINTNL .PHONY: all install %(USE) PRINTNL PRINTNL all: install FOR EACH USE FOR EACH USELIB IF "%(~!+÷../LIBINCLUDE:%=%%(%(DSWPATH) PRINTNL @echo # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!>>%(DSWPATH) PRINTNL @perl -e "print chr(10);" >>%(DSWPATH) FOR EACH USE IF (%(TYPE)!=LIB_CSHARP) && (%(TYPE)!=DLL_CSHARP) && (%(TYPE)!=CON_CSHARP) && (%(TYPE)!=EXE_CSHARP) PRINTNL @echo ###############################################################################>>%(../DSWPATH) PRINTNL @perl -e "print chr(10);" >>%(../DSWPATH) DSPPATH = %EPOCROOT%/epoc32/BUILD%(:^|MAKEPATH)%(^NAME)/WINS/%(^NAME).DSP IF (%(TYPE)==EXE) PRINTNL @perl -e "print 'Project: '.chr(34).'%(^PROJECT_PATH)'.chr(34).'=%(~DSPPATH) - Package Owner=<4>'.chr(10);" >>%(../DSWPATH) ELSE PRINTNL @perl -e "print 'Project: '.chr(34).'%(^NAME)'.chr(34).'=%(~DSPPATH) - Package Owner=<4>'.chr(10);" >>%(../DSWPATH) ENDIF PRINTNL @perl -e "print chr(10);" >>%(../DSWPATH) PRINTNL @perl -e "print 'Package=<5>'.chr(10).'{{{'.chr(10).'}}}'.chr(10).chr(10);" >>%(../DSWPATH) PRINTNL @perl -e "print 'Package=<4>'.chr(10).'{{{'.chr(10);" >>%(../DSWPATH) FOR EACH USE IF ((%(TYPE)!=LIB) || (%(../TYPE)!=LIB)) && (%(TYPE)!=LIB_CSHARP) && (%(TYPE)!=DLL_CSHARP) && (%(TYPE)!=CON_CSHARP) && (%(TYPE)!=EXE_CSHARP) PRINTNL @echo Begin Project Dependency>>%(../../DSWPATH) PRINTNL @echo Project_Dep_Name %(^NAME)>>%(../../DSWPATH) PRINTNL @echo End Project Dependency>>%(../../DSWPATH) ENDIF ENDFOR FOR EACH DEP IF (%(TYPE)!="LIB_CSHARP") && (%(TYPE)!="DLL_CSHARP") && (%(TYPE)!="CON_CSHARP") && (%(TYPE)!="EXE_CSHARP") PRINTNL @echo Begin Project Dependency>>%(../../DSWPATH) PRINTNL @echo Project_Dep_Name %(NAME)>>%(../../DSWPATH) PRINTNL @echo End Project Dependency>>%(../../DSWPATH) ENDIF ENDFOR PRINTNL @perl -e "print '}}}'.chr(10).chr(10);" >>%(../DSWPATH) ENDIF ENDFOR PRINTNL @echo ###############################################################################>>%(DSWPATH) PRINTNL @perl -e "print chr(10).'Global:'.chr(10).chr(10).'Package=<5>'.chr(10).'{{{'.chr(10).'}}}'.chr(10);" >>%(DSWPATH) PRINTNL @perl -e "print chr(10).'Package=<3>'.chr(10).'{{{'.chr(10).'}}}'.chr(10).chr(10);" >>%(DSWPATH) PRINTNL @echo ###############################################################################>>%(DSWPATH) PRINTNL @perl -e "print chr(10);" >>%(DSWPATH) PRINTNL install: FOR EACH USE IF (%(TYPE)==EXE) IF %(INSTALL) IF DEFINED(SYMBIAN90) INSTALLDIR = private\%(#PROJECT_UID_3rd) ELSE INSTALLDIR = system\apps\%(PROJECT_PATH) ENDIF PRINTNL @if not exist %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\%(INSTALLDIR) mkdir %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\%(INSTALLDIR) FOR EACH INSTALL PRINTNL @copy /b /y %(~NAME) %EPOCROOT%Epoc32\release\%(TARGPLATFORM)\%(TARGMODE)\z\%(INSTALLDIR) ENDFOR ENDIF ENDIF ENDFOR ELSE PRINTNL .PHONY: all build %(USE) PRINTNL PRINTNL all: build FOR EACH USE, DEP IF (%(TYPE)==EXE) PRINTNL @cd %(¯~@PATH) && makesis -d$(EPOCROOT) %(PROJECT_PATH).pkg PRINTNL @if not exist %(~@OUTPUTPATH) md %(~@OUTPUTPATH) IF DEFINED(SYMBIAN90) && %(SYMBIAN_CERT) && %(SYMBIAN_KEY) PRINTNL @signsis "%(¯~!PATH)%(PROJECT_PATH).sis" "%(~!OUTPUTPATH)%(PROJECT_PATH).sis" "%(~!SYMBIAN_CERT)" "%(~!SYMBIAN_KEY)" %(SYMBIAN_PASS) && del /q "%(¯~!PATH)%(PROJECT_PATH).sis" ELSE PRINTNL @cmd /c move /y "%(¯~!PATH)%(PROJECT_PATH).sis" "%(~!OUTPUTPATH)%(PROJECT_PATH).sis" ENDIF ENDIF ENDFOR PRINTNL build: FOR EACH USE FOR EACH USELIB IF "%(~!+÷../LIBINCLUDE:%=%%(NAME)==c)||(%(>NAME)==cpp)||(%(>NAME)==S && defined(ARM))) PRINTNL SOURCE %(~!NAME) ENDIF ENDFOR DIRPOP PRINTNL PRINTNL SOURCEPATH . IF (%(TYPE)==EXE) IF defined(SYMBIAN90) IF defined(UIQ) && "%(ICON)"!="" PRINTNL START BITMAP %(PROJECT_PATH)Icon.mbm PRINTNL HEADER PRINTNL TARGETPATH \resource\apps PRINTNL SOURCE c24 %(~!ICON)_uiq3_18x18.bmp PRINTNL SOURCE 8 %(~!ICON)_uiq3_18x18_mask.bmp PRINTNL SOURCE c24 %(~!ICON)_uiq3_40x40.bmp PRINTNL SOURCE 8 %(~!ICON)_uiq3_40x40_mask.bmp PRINTNL SOURCE c24 %(~!ICON)_uiq3_64x64.bmp PRINTNL SOURCE 8 %(~!ICON)_uiq3_64x64_mask.bmp PRINTNL END PRINTNL ENDIF PRINTNL START RESOURCE %(PROJECT_PATH).rss PRINTNL HEADER PRINTNL TARGETPATH \resource\apps PRINTNL LANG SC PRINTNL END PRINTNL PRINTNL START RESOURCE %(PROJECT_PATH)_reg.rss IF %(TARGPLATFORM)==winscw PRINTNL TARGETPATH \private\10003a3f\apps ELSE PRINTNL TARGETPATH \private\10003a3f\import\apps ENDIF PRINTNL LANG SC PRINTNL END PRINTNL ELSE PRINTNL RESOURCE %(PROJECT_PATH).rss IF defined(SERIES60) PRINTNL RESOURCE %(PROJECT_PATH)_caption.rss ENDIF PRINTNL IF "%(ICON)"!="" IF defined(SERIES60) || defined(SERIES80) PRINTNL AIF %(PROJECT_PATH).aif . %(PROJECT_PATH)_aif.rss c16 %(~!ICON)_s60_44x44.bmp %(~!ICON)_s60_44x44_mask.bmp %(~!ICON)_s60_42x29.bmp %(~!ICON)_s60_42x29_mask.bmp ELIF defined(SERIES90) PRINTNL AIF %(PROJECT_PATH).aif . %(PROJECT_PATH)_aif.rss c16 %(~!ICON)_s90_25x20.bmp %(~!ICON)_s90_25x20_mask.bmp %(~!ICON)_s90_64x50.bmp %(~!ICON)_s90_64x50_mask.bmp ELIF defined(UIQ) PRINTNL AIF %(PROJECT_PATH).aif . %(PROJECT_PATH)_aif.rss c16 %(~!ICON)_uiq_20x16.bmp %(~!ICON)_uiq_20x16_mask.bmp %(~!ICON)_uiq_32x32.bmp %(~!ICON)_uiq_32x32_mask.bmp ENDIF ELSE PRINTNL AIF %(PROJECT_PATH).aif . %(PROJECT_PATH)_aif.rss ENDIF PRINTNL ENDIF ENDIF IF (%(TYPE)==DLL) && (%(DLL_TYPE)=="MDL") IF defined(SYMBIAN90) PRINTNL START RESOURCE %(PROJECT_PATH).rss PRINTNL TARGET %(PROJECT_PATH).rsc PRINTNL END ENDIF ENDIF FOR EACH INCLUDE ../USERINCLUDE += %(|NAME) ENDFOR FOR EACH EXPINCLUDE ../USERINCLUDE += %(|NAME) ENDFOR FOR EACH SUBINCLUDE ../USERINCLUDE += %(|NAME) ENDFOR IF %(CONFIG_FILE) USERINCLUDE += %(/|CONFIG_FILE) ENDIF FOR EACH USERINCLUDE PRINTNL USERINCLUDE %(~!§NAME) ENDFOR PRINTNL PRINTNL SYSTEMINCLUDE \epoc32\include PRINTNL SYSTEMINCLUDE \epoc32\include\libc IF defined(SYMBIAN90) IF %(DLL_TYPE)=="MDL" PRINTNL SYSTEMINCLUDE \epoc32\include\ecom ENDIF ENDIF IF defined(SERIES60) IF defined(SYMBIAN90) PRINTNL SYSTEMINCLUDE \epoc32\include\mmf\plugin ENDIF ENDIF FOR EACH SYSINCLUDE PRINTNL SYSTEMINCLUDE %(~!§NAME) ENDFOR PRINTNL // libraries IF (%(TYPE)!=LIB) FOR EACH USE IF (!%(NOLIB)) IF (%(TYPE)==DLL) PRINTNL LIBRARY %(NAME).lib ELSE PRINTNL STATICLIBRARY %(NAME).lib ENDIF ENDIF ENDFOR FOR EACH USELIB PRINTNL STATICLIBRARY %( PRINTNL ENDIF PRINTNL #define %(TARGDEFINE) PRINTNL FOR EACH SOURCE IF (%(>NAME)==rss) PRINTNL #include "%(~!NAME)" ENDIF ENDFOR IF defined(SYMBIAN90) PRINTNL PRINTNL rls_string STRING_%(NAME)_caption_string "%(PROJECT_NAME)" PRINTNL PRINTNL RESOURCE LOCALISABLE_APP_INFO r_%(NAME)_localisable_app_info PRINTNL { PRINTNL short_caption = STRING_%(NAME)_caption_string; PRINTNL caption_and_icon = PRINTNL CAPTION_AND_ICON_INFO PRINTNL { PRINTNL caption = STRING_%(NAME)_caption_string; IF %(ICON)!="" IF defined(SERIES60) PRINTNL number_of_icons = 1; PRINTNL icon_file = "\\resource\\apps\\%(PROJECT_PATH).mif"; ELSE PRINTNL number_of_icons = 3; PRINTNL icon_file = "\\resource\\apps\\%(PROJECT_PATH)Icon.mbm"; ENDIF ENDIF PRINTNL }; IF %(QIKVIEW)!="" PRINTNL view_list = PRINTNL { FOR EACH QIKVIEW PRINTNL VIEW_DATA PRINTNL { PRINTNL uid = %(UID); PRINTNL screen_mode = %(SCREEN_MODE); PRINTNL caption_and_icon = PRINTNL { PRINTNL CAPTION_AND_ICON_INFO PRINTNL { PRINTNL } PRINTNL }; IF %(FOR_LAST) PRINTNL } ELSE PRINTNL }, ENDIF ENDFOR PRINTNL }; ENDIF PRINTNL } ENDIF IF defined(SYMBIAN90) && defined(SERIES60) IF %(ICON)!="" FILE %(¯PATH)%(PROJECT_PATH)_icon.mak PRINTNL ifeq (WINS,$(findstring WINS, $(PLATFORM))) PRINTNL ZDIR=$(EPOCROOT)epoc32\release\$(PLATFORM)\$(CFG)\Z PRINTNL else PRINTNL ZDIR=$(EPOCROOT)epoc32\data\z PRINTNL endif PRINTNL PRINTNL TARGETDIR=$(ZDIR)\resource\apps PRINTNL ICONTARGETFILENAME=$(TARGETDIR)\%(PROJECT_PATH).mif PRINTNL PRINTNL do_nothing : PRINTNL @rem do_nothing PRINTNL PRINTNL MAKMAKE : do_nothing PRINTNL PRINTNL BLD : do_nothing PRINTNL PRINTNL CLEAN : PRINTNL del /q $(ICONTARGETFILENAME) PRINTNL PRINTNL LIB : do_nothing PRINTNL PRINTNL CLEANLIB : do_nothing PRINTNL PRINTNL RESOURCE : %(~!ICON)_s60.svg PRINTNL mifconv $(ICONTARGETFILENAME) %(MIFCONV) /c32 %(~!ICON)_s60.svg PRINTNL PRINTNL FREEZE : do_nothing PRINTNL PRINTNL SAVESPACE : do_nothing PRINTNL PRINTNL RELEASABLES : PRINTNL @echo $(ICONTARGETFILENAME) PRINTNL PRINTNL FINAL : do_nothing PRINTNL ENDIF ENDIF IFDEF SYMBIAN90 FILE %(¯PATH)%(PROJECT_PATH)_dll.txt FOR EACH USE IF %(TYPE)==DLL && "%(OUTPUT)" != "%(OUTPUT_DLL)" PRINTNL %(OUTPUT) HAVE_DLL_TXT = 1 ENDIF ENDFOR ENDIF FILE %(¯PATH)%(NAME)_rsg.h PRINTNL #include <%(PROJECT_PATH).rsg> IF "%(TARGSIS)"!="" TARGEPOC = \ TARGETMODE = %(TARGMODE) FILE %(¯PATH)%(PROJECT_PATH).pkg #include "symbian_pkg.inc" ENDIF IF %(PROJECT_MIME)!="" MIME_TYPES += %(PROJECT_MIME) ENDIF FOR EACH SOURCE FOR EACH MIME_TYPE ../../MIME_TYPES += %(NAME) ENDFOR ENDFOR FOR EACH USE FOR EACH SOURCE FOR EACH MIME_TYPE ../../../MIME_TYPES += %(NAME) ENDFOR ENDFOR ENDFOR IFNDEF SYMBIAN90 FILE %(¯MAKEPATH)%(PROJECT_PATH)_aif.rss PRINTNL #include PRINTNL PRINTNL RESOURCE AIF_DATA PRINTNL { PRINTNL app_uid=%(PROJECT_UID); PRINTNL caption_list= PRINTNL { PRINTNL CAPTION { code=ELangEnglish; caption="%(PROJECT_NAME)"; } PRINTNL }; PRINTNL num_icons=2; PRINTNL embeddability=KAppNotEmbeddable; PRINTNL newfile=KAppDoesNotSupportNewFile; IF %(MIME_TYPES)!="" PRINTNL datatype_list= PRINTNL { FOR EACH MIME_TYPES IF %(FOR_LAST) PRINTNL DATATYPE { priority=EDataTypePriorityLow; type="%(NAME)"; } ELSE PRINTNL DATATYPE { priority=EDataTypePriorityLow; type="%(NAME)"; }, ENDIF ENDFOR PRINTNL }; ENDIF PRINTNL } FILE %(¯MAKEPATH)%(PROJECT_PATH)_caption.rss PRINTNL #include PRINTNL PRINTNL RESOURCE CAPTION_DATA PRINTNL { PRINTNL caption="%(PROJECT_NAME)"; PRINTNL shortcaption="%(PROJECT_NAME)"; PRINTNL } ELSE FILE %(¯MAKEPATH)%(PROJECT_PATH)_backup.xml PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF %(SYMBIAN_BACKUP)!="" PRINTNL FOR EACH SYMBIAN_BACKUP PRINTNL ENDFOR PRINTNL ENDIF PRINTNL FILE %(¯MAKEPATH)%(PROJECT_PATH)_reg.rss PRINTNL #include PRINTNL #include <%(PROJECT_PATH).rsg> PRINTNL PRINTNL UID2 KUidAppRegistrationResourceFile IF %(PROJECT_UID_3rd) PRINTNL UID3 %(PROJECT_UID_3rd) ENDIF PRINTNL PRINTNL rls_string STRING_%(NAME)_resource_file "\\resource\\apps\\%(PROJECT_PATH)" PRINTNL PRINTNL RESOURCE APP_REGISTRATION_INFO PRINTNL { PRINTNL app_file="%(PROJECT_PATH)"; PRINTNL hidden = KAppNotHidden; PRINTNL embeddability = KAppNotEmbeddable; PRINTNL //embeddability = KAppEmbeddable; PRINTNL newfile = KAppDoesNotSupportNewFile; PRINTNL launch = KAppLaunchInForeground; PRINTNL localisable_resource_file = STRING_%(NAME)_resource_file; PRINTNL localisable_resource_id = R_%(^NAME)_LOCALISABLE_APP_INFO; IF %(MIME_TYPES)!="" PRINTNL datatype_list= PRINTNL { FOR EACH MIME_TYPES IF %(FOR_LAST) PRINTNL DATATYPE { priority=EDataTypePriorityLow; type="%(NAME)"; } ELSE PRINTNL DATATYPE { priority=EDataTypePriorityLow; type="%(NAME)"; }, ENDIF ENDFOR PRINTNL }; ENDIF PRINTNL } ENDIF ENDIF IF (%(TYPE)==DLL) && (%(DLL_TYPE)=="MDL") IF defined(SYMBIAN90) FILE %(¯MAKEPATH)%(PROJECT_PATH).rss PRINTNL #include PRINTNL PRINTNL RESOURCE REGISTRY_INFO r_registry PRINTNL { PRINTNL dll_uid = %(PROJECT_UID); // should match name of this file PRINTNL interfaces = PRINTNL { PRINTNL INTERFACE_INFO PRINTNL { PRINTNL interface_uid = 0x101F7D87; // const for all Data Recognizers PRINTNL implementations = PRINTNL { PRINTNL IMPLEMENTATION_INFO PRINTNL { PRINTNL implementation_uid = %(HOST_SYMBIAN_UID); // unique implementation uid PRINTNL version_no = 1; PRINTNL display_name = "%(HOST_SYMBIAN_NAME)"; PRINTNL default_data = ""; PRINTNL opaque_data = ""; PRINTNL } PRINTNL }; PRINTNL } PRINTNL }; PRINTNL } ELSE ENDIF ENDIF ENDFOR IF !DEFINED(CARBIDE_VS) #include "carbide.inc" ENDIF bcmatroska2-5.3.101/corec/tools/coremake/symbian_pkg.inc000066400000000000000000000101471462133141200231100ustar00rootroot00000000000000 PRINTNL &EN IF "%(PROJECT_BUILD)"=="" PROJECT_BUILD = 0 ENDIF IFDEF SYMBIAN90 IF %(PROJECT_UID_3rd) PRINTNL #{"%(PROJECT_NAME)"},(%(PROJECT_UID_3rd)),%(PROJECT_VERSION_MAJOR),%(PROJECT_VERSION_MINOR)%(PROJECT_VERSION_REVISION),%(PROJECT_BUILD) ENDIF IF "%(PROJECT_VENDOR)"=="" PROJECT_VENDOR = Vendor ENDIF IF "%(SYMBIAN_VENDOR)"=="" SYMBIAN_VENDOR = %(PROJECT_VENDOR) ENDIF PRINTNL %{"%(PROJECT_VENDOR)-EN"} PRINTNL :"%(SYMBIAN_VENDOR)" PRINTNL %(TARGSIS) PRINTNL "%(TARGEPOC)Epoc32\release\%(TARGPLATFORM)\%(TARGETMODE)\%(PROJECT_PATH).exe"-"!:\sys\bin\%(PROJECT_PATH).exe" FOR EACH USE, DEP IF %(NAME)==coreprotect_sdk PRINTNL "%(../TARGEPOC)Epoc32\release\%(TARGPLATFORM)\%(../TARGETMODE)\%(../PROJECT_PATH).cpb"-"!:\private\%(#../PROJECT_UID_3rd)\%(../PROJECT_PATH).cpb" ENDIF IF %(TYPE)==DLL IF %(DLL_TYPE)=="MDL" PRINTNL "%(../TARGEPOC)Epoc32\release\%(../TARGPLATFORM)\%(../TARGETMODE)\%(OUTPUT)"-"!:\sys\bin\%(#PROJECT_UID).dll" PRINTNL "%(../TARGEPOC)Epoc32\data\z\resource\plugins\%(NAME).rsc"-"!:\resource\plugins\%(#PROJECT_UID).rsc" ELSE PRINTNL "%(../TARGEPOC)Epoc32\release\%(../TARGPLATFORM)\%(../TARGETMODE)\%(OUTPUT)"-"!:\sys\bin\%(OUTPUT)" ENDIF ENDIF ENDFOR PRINTNL "%(TARGEPOC)Epoc32\data\z\resource\apps\%(PROJECT_PATH).rsc"-"!:\resource\apps\%(PROJECT_PATH).rsc" IF %(ICON)!="" IF defined(SERIES60) PRINTNL "%(TARGEPOC)Epoc32\data\z\resource\apps\%(PROJECT_PATH).mif"-"!:\resource\apps\%(PROJECT_PATH).mif" ELSE PRINTNL "%(TARGEPOC)Epoc32\data\z\resource\apps\%(PROJECT_PATH)Icon.mbm"-"!:\resource\apps\%(PROJECT_PATH)Icon.mbm" ENDIF ENDIF PRINTNL "%(TARGEPOC)Epoc32\data\z\private\10003a3f\import\apps\%(PROJECT_PATH)_reg.rsc"-"!:\private\10003a3f\import\apps\%(PROJECT_PATH)_reg.rsc" IF HAVE_DLL_TXT PRINTNL "%(¯~!PATH)%(PROJECT_PATH)_dll.txt"-"!:\private\%(#PROJECT_UID_3rd)\dll.txt" ENDIF FOR EACH INSTALL PRINTNL "%(~!NAME)"-"!:\private\%(#PROJECT_UID_3rd)\%(NAME)" ENDFOR FOR EACH UNINSTALL PRINTNL ""-"!:\private\%(#PROJECT_UID_3rd)\%(NAME)",FN ENDFOR PRINTNL "%(¯~!MAKEPATH)%(PROJECT_PATH)_backup.xml"-"!:\private\%(#PROJECT_UID_3rd)\backup_registration.xml" ELSE PRINTNL #{"%(PROJECT_NAME)"},(%(PROJECT_UID)),%(PROJECT_VERSION_MAJOR),%(PROJECT_VERSION_MINOR)%(PROJECT_VERSION_REVISION),%(PROJECT_BUILD) PRINTNL %(TARGSIS) PRINTNL "%(TARGEPOC)Epoc32\release\%(TARGPLATFORM)\%(TARGETMODE)\%(OUTPUT)"-"!:\system\apps\%(PROJECT_PATH)\%(OUTPUT)" FOR EACH USE, DEP IF %(NAME)==coreprotect_sdk // requires to patch the SDK toolchain(s) with coreprotect (see build.bat in coreprotect) PRINTNL "%(../TARGEPOC)Epoc32\release\%(../TARGPLATFORM)\%(../TARGETMODE)\%(../PROJECT_PATH).cpb"-"!:\system\apps\%(../PROJECT_PATH)\%(../PROJECT_PATH).cpb" ENDIF IF %(TYPE)==DLL IF %(DLL_TYPE)=="MDL" PRINTNL "%(../TARGEPOC)Epoc32\release\%(../TARGPLATFORM)\%(../TARGETMODE)\%(NAME).mdl"-"!:\system\recogs\%(#PROJECT_UID).mdl" ELSE PRINTNL "%(../TARGEPOC)Epoc32\release\%(../TARGPLATFORM)\%(../TARGETMODE)\%(OUTPUT)"-"!:\system\apps\%(../PROJECT_PATH)\%(OUTPUT)" ENDIF ENDIF ENDFOR IF %(TARGSIS_S60_1st) PRINTNL "%(TARGEPOC)Epoc32\release\%(TARGPLATFORM)\%(TARGETMODE)\%(PROJECT_PATH).rsc"-"!:\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).rsc" PRINTNL "%(TARGEPOC)Epoc32\release\%(TARGPLATFORM)\%(TARGETMODE)\%(PROJECT_PATH).aif"-"!:\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).aif" ELSE PRINTNL "%(TARGEPOC)Epoc32\data\z\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).rsc"-"!:\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).rsc" PRINTNL "%(TARGEPOC)Epoc32\data\z\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).aif"-"!:\system\apps\%(PROJECT_PATH)\%(PROJECT_PATH).aif" ENDIF FOR EACH INSTALL PRINTNL "%(~!NAME)"-"!:\system\apps\%(PROJECT_PATH)\%(NAME)" ENDFOR FOR EACH UNINSTALL PRINTNL ""-"!:\system\apps\%(PROJECT_PATH)\%(NAME)",FN ENDFOR ENDIF bcmatroska2-5.3.101/corec/tools/coremake/system_output.sh000066400000000000000000000025371462133141200234160ustar00rootroot00000000000000#!/bin/sh # output the right configuration (.build file) to use for the current OS cpu_name=`uname -m | sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/` os_name=`uname -s | sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/` cpu_type=`echo $HOSTTYPE` coremake_param="gcc_linux" #echo "CPU" $cpu_name #echo "OS" $os_name case $os_name in cygwin*) coremake_param="gcc_linux" ;; mingw* | pw32*) coremake_param="gcc_win32" ;; darwin* | rhapsody*) case $cpu_type in i*86) coremake_param="gcc_osx_x86" ;; powerpc*) coremake_param="gcc_osx_ppc" ;; x86_64) coremake_param="gcc_osx_x64" ;; esac ;; linux* | freebsd* | kfreebsd*-gnu | dragonfly*) case $cpu_name in i*86) coremake_param="gcc_linux" ;; x86_64 | amd64) coremake_param="gcc_linux_x64" ;; powerpc*) coremake_param="gcc_linux_ppc" ;; arm*) coremake_param="gcc_linux_arm" ;; mips*) coremake_param="gcc_linux_mips" ;; sparc64) coremake_param="gcc_linux_sparc64" ;; sparc*) coremake_param="gcc_linux_sparc32" ;; esac ;; esac echo $coremake_param exit bcmatroska2-5.3.101/corec/tools/coremake/uiq_21.build000066400000000000000000000004521462133141200222310ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_uiq_21 TARGDEFINE = UIQ TARGDEFINE2 = __UIQ__ TARGPLATFORM = ARMI TARGMODE = UREL TARGCPU = armi DEVICES_ID = UIQ_21:com.symbian.UIQ TARGSIS = (0x101F617B),2,0,0,{"UIQ20ProductID"} #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_21_wins.build000066400000000000000000000003521462133141200232700ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define IX86 PLATFORMLIB = symbian_uiq_21_wins TARGDEFINE = UIQ TARGDEFINE2 = __UIQ__ TARGPLATFORM = WINS TARGMODE = UDEB TARGCPU = wins DEVICES_ID = UIQ_21:com.symbian.UIQ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_30.build000066400000000000000000000013521462133141200222310ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_uiq_30 TARGDEFINE = UIQ TARGDEFINE2 = __UIQ3__ TARGPLATFORM = GCCE TARGMODE = UREL TARGCPU = armv5 DEVICES_ID = UIQ3:com.symbian.UIQ TARGSIS = (0x101F6300),3,0,0,{"UIQ30ProductID"} CARBIDE_BASE = UIQ3_com CARBIDE_SDK = UIQ3 CARBIDE_SDK_NAME = Phone Release (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = UIQ3 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_30_debug.build000066400000000000000000000013501462133141200233750ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_uiq_30 TARGDEFINE = UIQ TARGDEFINE2 = __UIQ3__ TARGPLATFORM = GCCE TARGMODE = UDEB TARGCPU = armv5 DEVICES_ID = UIQ3:com.symbian.UIQ TARGSIS = (0x101F6300),3,0,0,{"UIQ30ProductID"} CARBIDE_BASE = UIQ3_com CARBIDE_SDK = UIQ3 CARBIDE_SDK_NAME = Phone Debug (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = UIQ3 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_30_winscw.build000066400000000000000000000012251462133141200236220ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define SYMBIAN90 #define IX86 PLATFORMLIB = symbian_uiq_30_winscw TARGDEFINE = UIQ TARGDEFINE2 = __UIQ3__ TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = UIQ3:com.symbian.UIQ CARBIDE_BASE = UIQ3_com CARBIDE_SDK = UIQ3 CARBIDE_SDK_NAME = Emulator Debug (WINSCW) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = UIQ3 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = winscw CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __CW32__ CARBIDE_DEFINE += __WINS__ CARBIDE_DEFINE += __WINSCW__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_31.build000066400000000000000000000013571462133141200222370ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define SYMBIAN90 #define ARM #define COMPILER_GCC PLATFORMLIB = symbian_uiq_31 TARGDEFINE = UIQ TARGDEFINE2 = __UIQ3__ TARGPLATFORM = GCCE TARGMODE = UREL TARGCPU = armv5 DEVICES_ID = UIQ3.1:com.symbian.UIQ TARGSIS = (0x101F6300),3,0,0,{"UIQ30ProductID"} CARBIDE_BASE = UIQ31_com CARBIDE_SDK = UIQ3.1 CARBIDE_SDK_NAME = Phone Release (GCCE) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = UIQ3 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = gcce CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __GCCE__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __MARM__ CARBIDE_DEFINE += __EABI__ CARBIDE_DEFINE += __MARM_ARMV5__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/uiq_31_winscw.build000066400000000000000000000012321462133141200236210ustar00rootroot00000000000000#define TARGET_SYMBIAN #define UIQ #define SYMBIAN90 #define IX86 PLATFORMLIB = symbian_uiq_31_winscw TARGDEFINE = UIQ TARGDEFINE2 = __UIQ3__ TARGPLATFORM = WINSCW TARGMODE = UDEB TARGCPU = winscw DEVICES_ID = UIQ3.1:com.symbian.UIQ CARBIDE_BASE = UIQ31_com CARBIDE_SDK = UIQ3.1 CARBIDE_SDK_NAME = Emulator Debug (WINSCW) CARBIDE_CDT_SDK = 91 CARBIDE_NOKIA_SDK = UIQ3 CARBIDE_TOOLCHAIN_PREFIX = CARBIDE_TOOLCHAIN = winscw CARBIDE_DEFINE += _UNICODE CARBIDE_DEFINE += __SYMBIAN32__ CARBIDE_DEFINE += __CW32__ CARBIDE_DEFINE += __WINS__ CARBIDE_DEFINE += __WINSCW__ CARBIDE_DEFINE += __EPOC32__ CARBIDE_DEFINE += __SUPPORT_CPP_EXCEPTIONS__ #include "symbian.inc" bcmatroska2-5.3.101/corec/tools/coremake/vc6.build000066400000000000000000000004111462133141200216220ustar00rootroot00000000000000MSDEV = MSDEV.EXE #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_MSVC6 PLATFORMLIB = win32_x86 #define OUTPUT_EXE %(NAME).exe #define OUTPUT_DLL %(NAME).dll #define OUTPUT_LIB %(NAME).lib #define OUTPUT_CON %(NAME).exe #include "vc6.inc" bcmatroska2-5.3.101/corec/tools/coremake/vc6.inc000066400000000000000000000435411462133141200213070ustar00rootroot00000000000000#define COMPILER_MSVC CONFIG #include "winrc.inc" TARG_DEBUG = Debug TARG_RELEASE = Release IFDEF COREMAKE_UNICODE TARG_DEBUG = %(TARG_DEBUG) Unicode TARG_RELEASE = %(TARG_RELEASE) Unicode ENDIF IFDEF COREMAKE_STATIC TARG_DEBUG = %(TARG_DEBUG) Static TARG_RELEASE = %(TARG_RELEASE) Static ENDIF IFDEF COREMAKE_MSVCRT TARGRUNTIME = /MD ELSE TARGRUNTIME = /MT ENDIF FOR EACH WORKSPACE FILE %(¯PATH)%(NAME).dsw PRINTNLDOS Microsoft Developer Studio Workspace File, Format Version 6.00 PRINTNLDOS # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! PRINTNLDOS FOR EACH USE IF (%(TYPE)!=LIB_CSHARP) && (%(TYPE)!=DLL_CSHARP) && (%(TYPE)!=CON_CSHARP) && (%(TYPE)!=EXE_CSHARP) PRINTNLDOS ############################################################################### PRINTNLDOS PRINTNLDOS Project: "%(NAME)"=%(¯!PATH)%(NAME).dsp - Package Owner=<4> PRINTNLDOS PRINTNLDOS Package=<5> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS Package=<4> PRINTNLDOS {{{ FOR EACH USE IF ((%(TYPE)!=LIB) || (%(../TYPE)!=LIB)) && (%(TYPE)!=LIB_CSHARP) && (%(TYPE)!=DLL_CSHARP) && (%(TYPE)!=CON_CSHARP) && (%(TYPE)!=EXE_CSHARP) PRINTNLDOS Begin Project Dependency PRINTNLDOS Project_Dep_Name %(NAME) PRINTNLDOS End Project Dependency ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../ITEM_DEPS += "%(NAME)" ENDIF ENDFOR FOR EACH DEP IF (%(TYPE)!="LIB_CSHARP") && (%(TYPE)!="DLL_CSHARP") && (%(TYPE)!="CON_CSHARP") && (%(TYPE)!="EXE_CSHARP") PRINTNLDOS Begin Project Dependency PRINTNLDOS Project_Dep_Name %(NAME) PRINTNLDOS End Project Dependency ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../ITEM_DEPS += "%(NAME)" ENDIF ENDFOR PRINTNLDOS }}} PRINTNLDOS ENDIF ENDFOR PRINTNLDOS ############################################################################### PRINTNLDOS PRINTNLDOS Global: PRINTNLDOS PRINTNLDOS Package=<5> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS Package=<3> PRINTNLDOS {{{ PRINTNLDOS }}} PRINTNLDOS PRINTNLDOS ############################################################################### PRINTNLDOS IF %(MSDEV)!="" EXE = FOR EACH USE IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) ../EXE += "%(NAME)" ENDIF ENDFOR FILE %(¯PATH)Makefile.vc6 PRINTNL all: %(EXE) PRINTNL FOR EACH USE PRINTNL "%(NAME)": %(ITEM_DEPS) PRINTNL @%(MSDEV) %(../NAME).dsw /make "%(NAME) - Win32 %(TARG_RELEASE)" /out "%(../NAME).log.tmp" PRINTNL @grep -v "Could not find the file" <%(../NAME).log.tmp >>%(../NAME).log PRINTNL @del /q %(../NAME).log.tmp IF %(NSI)!="" IF %(EXEPROTECT)!="" TARGET = %(¯~!OUTPUTPATH)release\%(OUTPUT) PRINTNL @%(EXEPROTECT) FOR EACH USE IF %(TYPE)==DLL TARGET = %(¯~!OUTPUTPATH)release\%(OUTPUT) PRINTNL @%(../EXEPROTECT) ENDIF ENDFOR ENDIF COMPILE %(NSI) %(PATH)%(NAME)_win32.nsi PRINTNL @makensis.exe /V2 %(¯!PATH)%(NAME)_win32.nsi /O%(NAME)_nsi.log ENDIF PRINTNL ENDFOR PRINTNL clean: PRINTNL @if exist %(¯~!§BUILDPATH) rmdir /s /q %(¯~!§BUILDPATH) PRINTNL @if exist %(¯~!§OUTPUTPATH) rmdir /s /q %(¯~!§OUTPUTPATH) ENDIF ENDFOR FOR EACH LIB,DLL,EXE,CON PRJNAME = %(NAME) IFNDEF TARGET_PALMOS DEFINE += WIN32 ELSE DEFINE += __palmos__ ENDIF IFNDEF COREMAKE_UNICODE DEFINE += _MBCS ELSE DEFINE += UNICODE DEFINE += _UNICODE ENDIF IF "%(USE_MFC)"=="" && "%(USE_ATL)"!="" USE_MFC = . ENDIF IF %(USE_MFC)!="" && %(USE_MFC)!="dll" LIBS_RELEASE += uafxcw.lib LIBS_DEBUG += uafxcwd.lib ENDIF USE_DLL_RUNTIME = IF %(USE_MFC)=="dll" DEFINE += _AFXDLL MFCFLAGS = USE_DLL_RUNTIME = 1 ELSE MFCFLAGS = %(TARGLFLAGS_noMFC) ENDIF IF %(USE_ATL) && %(USE_ATL)!="dll" DEFINE += _ATL_STATIC_REGISTRY ENDIF IF (%(TYPE)==EXE) && !defined(TARGET_PALMOS) TARGTYPE = 0x0101 TARGNAME = Application TARGLINK = /subsystem:windows DEFINE += _WINDOWS ENDIF IF (%(TYPE)==CON) TARGTYPE = 0x0103 TARGNAME = Console Application TARGLINK = /subsystem:console DEFINE += _CONSOLE ENDIF IF (%(TYPE)==DLL) || ((%(TYPE)==EXE) && defined(TARGET_PALMOS)) TARGTYPE = 0x0102 TARGNAME = Dynamic-Link Library TARGLINK = /dll DEFINE += _USRDLL IFNDEF TARGET_PALMOS DEFINE += _WINDOWS ENDIF DEFINE += %(<^NAME)_EXPORTS ENDIF IF (%(TYPE)==LIB) TARGTYPE = 0x0104 TARGNAME = Static Library DEFINE += _LIB ENDIF IF %(DEF) SOURCE += %(DEF) ENDIF FILE %(¯PATH)%(NAME).dsp IF "%(USELIB)" LIBS += %(USELIB:%=%_%(PLATFORMLIB).lib) ENDIF HAS_IDL = FOR EACH SOURCE IF (%(>NAME)==idl) ../HAS_IDL = 1 ENDIF ENDFOR IF %(HAS_IDL) INCLUDE += %(¯|BUILDPATH)%(~§PATH) INCLUDE_DEBUG += %(¯|OUTPUTPATH)debug\%(OUTPUT_DIR) INCLUDE_RELEASE += %(¯|OUTPUTPATH)release\%(OUTPUT_DIR) ENDIF IF %(PRECOMPILED_HEADER)!="" PRECOMP_OPTION = /YX"%(PRECOMPILED_HEADER)" SET_PRECOMPILED_HEADER = 1 ELIF %(NO_PRECOMPILED_HEADER)=="" PRECOMP_OPTION = /YX ENDIF CFLAGS = %(DEFINE:%=/D "%") %(@INCLUDE:%=/I "%") %(@SYSINCLUDE:%=/I "%") IF defined(TARGET_PALMOS) IF %(PALMSDK5R4)=="" PALMSDK5R4 = C:\Program Files\ACCESS\Garnet OS Development Suite\sdk-5r4 ENDIF CFLAGS += /I "%(~PALMSDK5R4)\include" CFLAGS += /I "%(~PALMSDK5R4)\include\Core" CFLAGS += /I "%(~PALMSDK5R4)\include\Core\Hardware" CFLAGS += /I "%(~PALMSDK5R4)\include\Core\System" CFLAGS += /I "%(~PALMSDK5R4)\include\Core\UI" CFLAGS += /I "%(~PALMSDK5R4)\include\Dynamic" CFLAGS += /I "%(~PALMSDK5R4)\include\Libraries" ENDIF PRINTNLDOS # Microsoft Developer Studio Project File - Name="%(NAME)" - Package Owner=<4> PRINTNLDOS # Microsoft Developer Studio Generated Build File, Format Version 6.00 PRINTNLDOS # ** DO NOT EDIT ** PRINTNLDOS PRINTNLDOS # TARGTYPE "Win32 (x86) %(TARGNAME)" %(TARGTYPE) PRINTNLDOS PRINTNLDOS CFG=%(NAME) - Win32 %(TARG_DEBUG) PRINTNLDOS !MESSAGE This is not a valid makefile. To build this project using NMAKE, PRINTNLDOS !MESSAGE use the Export Makefile command and run PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE NMAKE /f "%(NAME).mak". PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE You can specify a configuration when running NMAKE PRINTNLDOS !MESSAGE by defining the macro CFG on the command line. For example: PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE NMAKE /f "%(NAME).mak" CFG="%(NAME) - Win32 %(TARG_DEBUG)" PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE Possible choices for configuration are: PRINTNLDOS !MESSAGE PRINTNLDOS !MESSAGE "%(NAME) - Win32 %(TARG_RELEASE)" (based on "Win32 (x86) %(TARGNAME)") PRINTNLDOS !MESSAGE "%(NAME) - Win32 %(TARG_DEBUG)" (based on "Win32 (x86) %(TARGNAME)") PRINTNLDOS !MESSAGE PRINTNLDOS PRINTNLDOS # Begin Project PRINTNLDOS # PROP AllowPerConfigDependencies 0 PRINTNLDOS # PROP Scc_ProjName "" PRINTNLDOS # PROP Scc_LocalPath "" PRINTNLDOS CPP=cl.exe IF (%(TYPE)!=LIB && %(TYPE)!=CON) PRINTNLDOS MTL=midl.exe ENDIF PRINTNLDOS RSC=rc.exe PRINTNLDOS PRINTNLDOS !IF "$(CFG)" == "%(NAME) - Win32 %(TARG_RELEASE)" PRINTNLDOS IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP BASE Use_MFC 2 ELSE PRINTNLDOS # PROP BASE Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP BASE Use_MFC 0 ENDIF PRINTNLDOS # PROP BASE Use_Debug_Libraries 0 PRINTNLDOS # PROP BASE Output_Dir "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)" PRINTNLDOS # PROP BASE Intermediate_Dir "%(¯~!BUILDPATH)release\%(~PATH)" PRINTNLDOS # PROP BASE Target_Dir "" IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP Use_MFC 2 ELSE PRINTNLDOS # PROP Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP Use_MFC 0 ENDIF PRINTNLDOS # PROP Use_Debug_Libraries 0 PRINTNLDOS # PROP Output_Dir "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)" PRINTNLDOS # PROP Intermediate_Dir "%(¯~!BUILDPATH)release\%(~PATH)" PRINTNLDOS # PROP Ignore_Export_Lib 0 PRINTNLDOS # PROP Target_Dir "" PRINTNLDOS # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "NDEBUG" %(CFLAGS) %(@INCLUDE_RELEASE:%=/I "%") %(CONFIG_INCLUDE:%=/I "%") %(PRECOMP_OPTION) /FD /c PRINTNLDOS # ADD CPP /nologo %(TARGRUNTIME) /GX /O2 /D "NDEBUG" %(CFLAGS) %(@INCLUDE_RELEASE:%=/I "%") %(CONFIG_INCLUDE:%=/I "%") %(PRECOMP_OPTION) /FD /c IF (%(TYPE)!=LIB && %(TYPE)!=CON) PRINTNLDOS # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 PRINTNLDOS # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 ENDIF PRINTNLDOS # ADD BASE RSC /l 0x40e /d "NDEBUG" %(CFLAGS) %(INCLUDERC:%=/i "%") %(INCLUDE_RELEASE:%=/i "%") %(CONFIG_INCLUDE:%=/I "%") PRINTNLDOS # ADD RSC /l 0x40e /d "NDEBUG" %(CFLAGS) %(INCLUDERC:%=/i "%") %(INCLUDE_RELEASE:%=/i "%") %(CONFIG_INCLUDE:%=/I "%") PRINTNLDOS BSC32=bscmake.exe PRINTNLDOS # ADD BASE BSC32 /nologo PRINTNLDOS # ADD BSC32 /nologo IF (%(TYPE)==LIB) PRINTNLDOS LIB32=link.exe -lib PRINTNLDOS # ADD BASE LIB32 /nologo PRINTNLDOS # ADD LIB32 /nologo ELSE PRINTNLDOS LINK32=link.exe PRINTNLDOS # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib %(LIBS) %(LIBS_RELEASE) %(MFCFLAGS) /nologo %(TARGLINK) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_RELEASE:%=/libpath:%) /machine:I386 PRINTNLDOS # ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib %(LIBS) %(LIBS_RELEASE) %(MFCFLAGS) /nologo %(TARGLINK) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_RELEASE:%=/libpath:%) /map /machine:I386 /out:"%(¯~!OUTPUTPATH)release/%(OUTPUT)" ENDIF IF (%(TYPE)==EXE) && defined(TARGET_PALMOS) PRINTNLDOS # Begin Special Build Tool PRINTNLDOS SOURCE="$(InputPath)" PRINTNLDOS PostBuild_Cmds=copy $(TargetPath) "%(PALMSDK5R4)\tools\Palm_OS_54_Simulator\release\AutoLoad" PRINTNLDOS # End Special Build Tool ENDIF PRINTNLDOS PRINTNLDOS !ELSEIF "$(CFG)" == "%(NAME) - Win32 %(TARG_DEBUG)" PRINTNLDOS IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP BASE Use_MFC 2 ELSE PRINTNLDOS # PROP BASE Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP BASE Use_MFC 0 ENDIF PRINTNLDOS # PROP BASE Use_Debug_Libraries 1 PRINTNLDOS # PROP BASE Output_Dir "%(¯~!OUTPUTPATH)debug\%(OUTPUT_DIR)" PRINTNLDOS # PROP BASE Intermediate_Dir "%(¯~!BUILDPATH)debug\%(~PATH)" PRINTNLDOS # PROP BASE Target_Dir "" IF "%(USE_MFC)" IF %(USE_MFC)=="dll" PRINTNLDOS # PROP Use_MFC 2 ELSE PRINTNLDOS # PROP Use_MFC 1 ENDIF ELSE PRINTNLDOS # PROP Use_MFC 0 ENDIF PRINTNLDOS # PROP Use_Debug_Libraries 1 PRINTNLDOS # PROP Output_Dir "%(¯~!OUTPUTPATH)debug\%(OUTPUT_DIR)" PRINTNLDOS # PROP Intermediate_Dir "%(¯~!BUILDPATH)debug\%(~PATH)" PRINTNLDOS # PROP Ignore_Export_Lib 0 PRINTNLDOS # PROP Target_Dir "" PRINTNLDOS # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "_DEBUG" %(CFLAGS) %(@INCLUDE_DEBUG:%=/I "%") %(CONFIG_INCLUDE:%=/I "%") %(PRECOMP_OPTION) /FD /GZ /c PRINTNLDOS # ADD CPP /nologo %(TARGRUNTIME)d /Gm /GX /ZI /Od /D "_DEBUG" %(CFLAGS) %(@INCLUDE_DEBUG:%=/I "%") %(CONFIG_INCLUDE:%=/I "%") %(PRECOMP_OPTION) /FD /GZ /c IF (%(TYPE)!=LIB && %(TYPE)!=CON) PRINTNLDOS # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 PRINTNLDOS # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 ENDIF PRINTNLDOS # ADD BASE RSC /l 0x40e /d "_DEBUG" %(CFLAGS) %(INCLUDERC:%=/i "%") %(INCLUDE_DEBUG:%=/i "%") %(CONFIG_INCLUDE:%=/I "%") PRINTNLDOS # ADD RSC /l 0x40e /d "_DEBUG" %(CFLAGS) %(INCLUDERC:%=/i "%") %(INCLUDE_DEBUG:%=/i "%") %(CONFIG_INCLUDE:%=/I "%") PRINTNLDOS BSC32=bscmake.exe PRINTNLDOS # ADD BASE BSC32 /nologo PRINTNLDOS # ADD BSC32 /nologo IF (%(TYPE)==LIB) PRINTNLDOS LIB32=link.exe -lib PRINTNLDOS # ADD BASE LIB32 /nologo PRINTNLDOS # ADD LIB32 /nologo ELSE PRINTNLDOS LINK32=link.exe PRINTNLDOS # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib %(LIBS) %(LIBS_DEBUG) %(MFCFLAGS) /nologo %(TARGLINK) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_DEBUG:%=/libpath:%) /debug /machine:I386 /pdbtype:sept PRINTNLDOS # ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib %(LIBS) %(LIBS_DEBUG) %(MFCFLAGS) /nologo %(TARGLINK) %(@LIBINCLUDE:%=/libpath:%) %(@LIBINCLUDE_DEBUG:%=/libpath:%) /debug /machine:I386 /out:"%(¯~!OUTPUTPATH)debug/%(OUTPUT)" /pdbtype:sept ENDIF IF (%(TYPE)==EXE) && defined(TARGET_PALMOS) PRINTNLDOS # Begin Special Build Tool PRINTNLDOS SOURCE="$(InputPath)" PRINTNLDOS PostBuild_Cmds=copy $(TargetPath) "%(PALMSDK5R4)\tools\Palm_OS_54_Simulator\debug\AutoLoad" PRINTNLDOS # End Special Build Tool ENDIF PRINTNLDOS PRINTNLDOS !ENDIF PRINTNLDOS PRINTNLDOS # Begin Target PRINTNLDOS PRINTNLDOS # Name "%(NAME) - Win32 %(TARG_RELEASE)" PRINTNLDOS # Name "%(NAME) - Win32 %(TARG_DEBUG)" PRINTNLDOS # Begin Group "Source Files" PRINTNLDOS PRINTNLDOS # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" FOR EACH SOURCE PRINTNLDOS # Begin Source File PRINTNLDOS PRINTNLDOS SOURCE=%(~!NAME) IF (%(../SET_PRECOMPILED_HEADER)==1) && (%(>NAME)==c || %(>NAME)==cpp) PRINTNLDOS # ADD CPP /Yc"%(PRECOMPILED_HEADER)" ../SET_PRECOMPILED_HEADER = ELSE IF ((%(>NAME)==c || %(>NAME)==cpp) && %(w)) PRINTNLDOS # ADD CPP /w /W0 ENDIF ENDIF IF (%(>NAME)==asm) PRINTNLDOS !IF "$(CFG)" == "%(PRJNAME) - Win32 %(TARG_RELEASE)" PRINTNLDOS PRINTNLDOS # PROP Ignore_Default_Tool 1 PRINTNLDOS # Begin Custom Build PRINTNLDOS IntDir=%(¯~!BUILDPATH)release\%(~PATH) PRINTNLDOS InputPath=%(~!NAME) PRINTNLDOS InputName=%(NAME)==idl) PRINTNLDOS !IF "$(CFG)" == "%(PRJNAME) - Win32 %(TARG_RELEASE)" PRINTNLDOS # ADD MTL /tlb "%(¯~!OUTPUTPATH)release\%(OUTPUT_DIR)%(PRJNAME).tlb" /h "%(¯~!BUILDPATH)%(~§PATH)\%(NAME)" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" PRINTNLDOS copy "$(InputPath)" "$(TargetDir)" >nul PRINTNLDOS PRINTNLDOS # End Custom Build PRINTNLDOS PRINTNLDOS !ELSEIF "$(CFG)" == "%(PRJNAME) - Win32 %(TARG_DEBUG)" PRINTNLDOS PRINTNLDOS # PROP Ignore_Default_Tool 1 PRINTNLDOS # Begin Custom Build PRINTNLDOS TargetDir=%(¯~!OUTPUTPATH)debug PRINTNLDOS InputPath=%(~!NAME) PRINTNLDOS InputName=%(NAME)" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" PRINTNLDOS copy "$(InputPath)" "$(TargetDir)" >nul PRINTNLDOS PRINTNLDOS # End Custom Build PRINTNLDOS PRINTNLDOS !ENDIF PRINTNLDOS ENDIF ENDIF ENDIF PRINTNLDOS # End Source File ENDFOR PRINTNLDOS # End Group PRINTNLDOS # Begin Group "Header Files" PRINTNLDOS PRINTNLDOS # PROP Default_Filter "h;hpp;hxx;hm;inl" FOR EACH HEADER PRINTNLDOS # Begin Source File PRINTNLDOS PRINTNLDOS SOURCE=%(~!NAME) PRINTNLDOS # End Source File ENDFOR IF %(HAS_IDL) FOR EACH SOURCE IF (%(>NAME)==idl) && %(hmarshal)!="" PRINTNLDOS # Begin Source File PRINTNLDOS PRINTNLDOS SOURCE="%( PRINTNL ENDIF PRINTNL PRINTNL PRINTNL ELIF DEFINED(COMPILER_ICL9) VS_PROJECT_TYPE=Intel C++ Project PREBUILTOOL=PreBuildEventTool POSTBUILTOOL=PostBuildEventTool PRELINKTOOL=PreLinkEventTool CUSTOM_TOOL=CustomTool IDL_TOOL=MidlCmplrTool CPP_TOOL=CppCmplrTool RES_TOOL=ResCmplrTool LIB_TOOL=LibrarianTool BSC_TOOL=BscMakeTool LINKER_TOOL=LinkerTool CMD_NEWLINE=#xA; VSNESTED=%(NAME).vcproj PROJ_IS_ICL=yes PRECOMPILED_HEADER= FILE %(¯PATH)%(NAME).icproj #include "vsproj.inc" IFDEF TARGET_WINCE // FILE %(¯PATH)%(NAME).icproj.%(MACHINE).%(USER).user // FILE %(¯PATH)%(NAME).icproj.user // IF defined(COREMAKE_STATIC) // EXECUTABLE_RELEASE = "%CSIDL_PROGRAM_FILES%\%(PROJECT_PATH)\$(TargetFileName)" // ELSE // EXECUTABLE_RELEASE = "%CSIDL_PROGRAM_FILES%\%(PLATFORMNAME)\$(TargetFileName)" // ENDIF // EXECUTABLE_DEBUG = %(RemoteExecutable) // #include "vsproj-user.inc" ENDIF IFDEF TARGET_PALMOS FILE %(¯PATH)%(NAME).icproj.user EXECUTABLE_RELEASE = %(~PALMSDK5R4)\tools\Palm_OS_54_Simulator\release\PalmSim_54_rel.exe EXECUTABLE_DEBUG = %(~PALMSDK5R4)\tools\Palm_OS_54_Simulator\debug\PalmSim_54_dbg.exe #include "vsproj-user.inc" ENDIF // clean for the next project COMPILERVERSION=8.00 VSPROJ_GUID=%(GUIDBIS) VSNESTED= PROJ_IS_ICL= ENDIF VS_PROJECT_TYPE=Visual C++ PREBUILTOOL=VCPreBuildEventTool POSTBUILTOOL=VCPostBuildEventTool PRELINKTOOL=VCPreLinkEventTool CUSTOM_TOOL=VCCustomBuildTool IDL_TOOL=VCMIDLTool CPP_TOOL=VCCLCompilerTool RES_TOOL=VCResourceCompilerTool LIB_TOOL=VCLibrarianTool BSC_TOOL=VCBscMakeTool LINKER_TOOL=VCLinkerTool CMD_NEWLINE=#x0D; FILE %(¯PATH)%(NAME).vcproj #include "vsproj.inc" IFDEF TARGET_WINCE // FILE %(¯PATH)%(NAME).vcproj.%(MACHINE).%(USER).user // FILE %(¯PATH)%(NAME).vcproj.user // IF defined(COREMAKE_STATIC) // EXECUTABLE_RELEASE = "%CSIDL_PROGRAM_FILES%\%(PROJECT_PATH)\$(TargetFileName)" // ELSE // EXECUTABLE_RELEASE = "%CSIDL_PROGRAM_FILES%\%(PLATFORMNAME)\$(TargetFileName)" // ENDIF // EXECUTABLE_DEBUG = %(RemoteExecutable) // #include "vsproj-user.inc" ENDIF IFDEF TARGET_PALMOS FILE %(¯PATH)%(NAME).vcproj.user EXECUTABLE_RELEASE = %(~PALMSDK5R4)\tools\Palm_OS_54_Simulator\release\PalmSim_54_rel.exe EXECUTABLE_DEBUG = %(~PALMSDK5R4)\tools\Palm_OS_54_Simulator\debug\PalmSim_54_dbg.exe WORKINGDIR_DEBUG = %(~`|OUTPUTPATH) #include "vsproj-user.inc" ENDIF ENDFOR IFNDEF TARGET_NO_DOT_NET FOR EACH LIB_CSHARP,DLL_CSHARP,EXE_CSHARP,CON_CSHARP FILE %(PATH)%(NAME).csproj PRINTNL PRINTNL PRINTNL %(TARG_DEBUG) PRINTNL AnyCPU PRINTNL %(CSPROJVERSION) PRINTNL 2.0 PRINTNL %(GUID) IF %(TYPE)==LIB_CSHARP || %(TYPE)==DLL_CSHARP PRINTNL Library ELIF %(TYPE)==EXE_CSHARP PRINTNL WinExe ENDIF PRINTNL Properties PRINTNL %(NAME) PRINTNL %(NAME) IFDEF TARGET_WINCE PRINTNL {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} IFDEF TARGET_SMARTPHONE PRINTNL Smartphone ELSE IFDEF TARGET_NO_WINMO PRINTNL WindowsCE ELSE PRINTNL PocketPC ENDIF ENDIF PRINTNL %(WINCE_CS_UUID) PRINTNL %(WINCE_VERSION) PRINTNL %(PLATFORMNAME) PRINTNL PRINTNL ENDIF IFDEF COREMAKE_NET_FRAMEWORK_35 PRINTNL v3.5 ELSE PRINTNL v2.0 ENDIF PRINTNL PRINTNL PRINTNL true PRINTNL full PRINTNL false PRINTNL %(~!OUTPUTPATH)debug%(OUTPUTDIR) PRINTNL TRACE%(TARGDEF:%=;%)%(DEFINE:%=;%)%(DEFINE_DEBUG:%=;%) IFDEF TARGET_WINCE PRINTNL true PRINTNL true PRINTNL 512 ENDIF PRINTNL prompt PRINTNL 4 IFDEF TARGET_WINCE PRINTNL Off PRINTNL true ENDIF PRINTNL PRINTNL PRINTNL false PRINTNL pdbonly PRINTNL true PRINTNL %(~!OUTPUTPATH)release%(OUTPUTDIR) PRINTNL TRACE%(TARGDEF:%=;%)%(DEFINE:%=;%)%(DEFINE_RELEASE:%=;%) IFDEF TARGET_WINCE PRINTNL true PRINTNL true PRINTNL 512 ENDIF PRINTNL prompt PRINTNL 4 IFDEF TARGET_WINCE PRINTNL Off PRINTNL true ENDIF PRINTNL PRINTNL IFDEF TARGET_WINCE PRINTNL ENDIF IFDEF COREMAKE_NET_FRAMEWORK_35 PRINTNL PRINTNL 3.5 PRINTNL ENDIF FOR EACH REFERENCES PRINTNL ENDFOR PRINTNL PRINTNL FOR EACH SOURCE PRINTNL IF %(control)!="" PRINTNL UserControl ELIF %(form)!="" PRINTNL Form ELSE PRINTNL Code ENDIF PRINTNL IF %(designer)!="" PRINTNL PRINTNL %(~!NAME) PRINTNL ENDIF IF %(resx)!="" PRINTNL PRINTNL Designer PRINTNL %(~!NAME) PRINTNL ENDIF ENDFOR FOR EACH CS_RESOURCES PRINTNL PRINTNL ResXFileCodeGenerator PRINTNL %(~!PATH)%(NAME).Designer.cs PRINTNL Designer PRINTNL PRINTNL PRINTNL True PRINTNL %(~!PATH)%( PRINTNL ENDFOR FOR EACH CS_SETTINGS PRINTNL PRINTNL SettingsSingleFileGenerator PRINTNL %(~!PATH)%(NAME).Designer.cs PRINTNL PRINTNL PRINTNL True PRINTNL %(~!PATH)%( PRINTNL True PRINTNL ENDFOR PRINTNL PRINTNL PRINTNL FOR EACH USE, DEP IF %(TYPE)==LIB_CSHARP || %(TYPE)==DLL_CSHARP || %(TYPE)==EXE_CSHARP || %(TYPE)==CON_CSHARP PRINTNL ELSE PRINTNL ENDIF PRINTNL %(GUID) PRINTNL %(NAME) PRINTNL False PRINTNL ENDFOR PRINTNL PRINTNL FOR EACH REFERENCES_COM PRINTNL IF %(com_guid)!="" PRINTNL {%(com_guid)} ENDIF PRINTNL 1 PRINTNL 0 PRINTNL 0 PRINTNL tlbimp PRINTNL False PRINTNL ENDFOR PRINTNL IFDEF TARGET_WINCE PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELSE PRINTNL ENDIF PRINTNL PRINTNL ENDFOR ENDIFbcmatroska2-5.3.101/corec/tools/coremake/vs9_ce5_armv4i.build000066400000000000000000000015631462133141200236740ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZCLI = /compress CABNAME = WindowsCE.ARM VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = STANDARDSDK_500 (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc9\armv4i VSPDB=vc90.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ce5_mips32_gcc.build000066400000000000000000000020041462133141200244120ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define MIPS #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_mips CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Mips CABCPU = 4000 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = STANDARDSDK_500 (MIPSII) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 7 TARGCOMPILEARCH = 1 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\mipsii VSPDB=vc90.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 TARGGCC = mipsel-linux-gnu-gcc -D_WIN32_WCE=500 -DMIPS -msoft-float -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ce5_mipsii.build000066400000000000000000000015651462133141200237660ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define MIPS #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_mips CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Mips CABCPU = 4000 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = STANDARDSDK_500 (MIPSII) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 7 TARGCOMPILEARCH = 1 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\mipsii VSPDB=vc90.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ce5_x86.build000066400000000000000000000016001462133141200231070ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define IX86 #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_x86 CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = WindowsCE CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = STANDARDSDK_500 (x86) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 1 TARGEXESUBSYSTEM = 9 SVNDIR=msvc9\armv4i VSPDB=vc90.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=C0159835-AD47-41c9-A473-7AA85EF01D8D #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_express.build000066400000000000000000000014701462133141200234240ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_MSVC_EXPRESS PLATFORMLIB = win32_x86 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGDEF += COMPILER_MSVC_EXPRESS TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc9\win32 VSPDB=vc90.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ic_x64.build000066400000000000000000000006541462133141200230320ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN64 #define TARGET_WIN #define IX86_64 #define COMPILER_ICL11 PLATFORMLIB = win32_x64 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9,00 ICC_COMPILERVERSION = 11.1 CSPROJVERSION = 9.0.30729 TARGNAME = x64 TARGDEPLOY = 0 TARGDEF = WIN64 TARGMACHINE = 17 TARG64 = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc9\x64 VSPDB=vc90.pdb TARGARCH=amd64 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ic_x86.build000066400000000000000000000014531462133141200230340ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_ICL11 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9,00 ICC_COMPILERVERSION = 11.1 CSPROJVERSION = 9.0.30729 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc9\win32 VSPDB=vc90.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_ppc2003_armv4.build000066400000000000000000000020041462133141200241250ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WINCE_2003 #define TARGET_WIN #define ARM #define NO_RUNTIME_CHECK #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4 //CABWIZ = "$(VSInstallDir)\Windows CE Tools\wce420\POCKET PC 2003\Tools\Cabwiz.exe" CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZCLI = /compress CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Pocket PC 2003 (ARMV4) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) TARGLFLAGS = /subsystem:windowsce,4.20 //TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 3 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\armv4 VSPDB=vc90.pdb WINCE_VERSION=4.20 WINCE_CS_UUID=3C41C503-53EF-4c2a-8DD4-A8217CAD115E #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_smart2003_armv4.build000066400000000000000000000020241462133141200244730ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WINCE_2003 #define TARGET_WIN #define TARGET_SMARTPHONE #define ARM #define NO_RUNTIME_CHECK #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4 //CABWIZ = "$(VSInstallDir)\Windows CE Tools\wce420\SMARTPHONE 2003\Tools\CabwizSP.exe" CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZCLI = /compress CABNAME = Smartphone CABCPU = 2577 CABUNSUPPORTED = "Jupiter","HPC","HPC Pro","Pocket PC","Palm PC2","Palm PC" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Smartphone 2003 (ARMV4) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += SMARTPHONE2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) TARGLFLAGS = /subsystem:windowsce,4.20 //TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 3 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\smart_armv4 VSPDB=vc90.pdb #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_win32.build000066400000000000000000000013711462133141200226750ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc9\win32 VSPDB=vc90.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_wm5_armv4i.build000066400000000000000000000016171462133141200237300ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Windows Mobile 5.0 Pocket PC SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\armv4i VSPDB=vc90.pdb WINCE_VERSION=5.01 WINCE_CS_UUID=4118C335-430C-497f-BE48-11C3316B135E #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_wm5s_armv4i.build000066400000000000000000000017411462133141200241110ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_SMARTPHONE #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4 CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Smartphone CABCPU = 2577 CABUNSUPPORTED = "Jupiter","HPC","HPC Pro","Pocket PC","Palm PC2","Palm PC" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Windows Mobile 5.0 Smartphone SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += SMARTPHONE2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\smart_armv4i VSPDB=vc90.pdb WINCE_VERSION=5.01 WINCE_CS_UUID=4118C335-430C-497f-BE48-11C3316B135E #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_wm6p_armv4i.build000066400000000000000000000016201462133141200241030ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = Windows Mobile 6 Professional SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) TARGLFLAGS = /subsystem:windowsce,4.20 //TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 8 SVNDIR=msvc9\armv4i VSPDB=vc90.pdb WINCE_VERSION=5.02 WINCE_CS_UUID=b2c48bd2-963d-4549-9169-1fa021dce484 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs9_x64.build000066400000000000000000000005721462133141200223560ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN64 #define TARGET_WIN #define IX86_64 PLATFORMLIB = win32_x64 VSBUILDER = Studio 2008 VSVERSION = 9.00 COMPILERVERSION = 9.00 CSPROJVERSION = 9.0.30729 TARGNAME = x64 TARGDEPLOY = 0 TARGDEF = WIN64 TARGMACHINE = 17 TARG64 = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc9\x64 VSPDB=vc90.pdb TARGARCH=amd64 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_2003.build000066400000000000000000000005261462133141200222270ustar00rootroot00000000000000DEVENV = "%VS71COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2003 VSVERSION = 7.10 COMPILERVERSION = 7.10 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 TARGNONAME = 1 SVNDIR=msvc71\win32 VSPDB=vc71.pdb #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_2005.build000066400000000000000000000013711462133141200222300ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN32 #define TARGET_WIN #define IX86 PLATFORMLIB = win32_x86 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\win32 VSPDB=vc80.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce5_armv4i.build000066400000000000000000000015631462133141200236030ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZCLI = /compress CABNAME = WindowsCE.ARM VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = STANDARDSDK_500 (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\armv4i VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce5_mips32.build000066400000000000000000000015651462133141200235200ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define MIPS #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_mips CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Mips CABCPU = 4000 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = STANDARDSDK_500 (MIPSII) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 7 TARGCOMPILEARCH = 6 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\mipsii VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce5_mips32_gcc.build000066400000000000000000000020041462133141200243210ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define MIPS #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_mips CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Mips CABCPU = 4000 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = STANDARDSDK_500 (MIPSII) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 7 TARGCOMPILEARCH = 6 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\mipsii VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 TARGGCC = mipsel-linux-gnu-gcc -D_WIN32_WCE=500 -DMIPS -msoft-float -mno-explicit-relocs -fomit-frame-pointer -fsigned-char -march=mips32 -O2 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce5_mipsii.build000066400000000000000000000015651462133141200236750ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define MIPS #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_mips CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Mips CABCPU = 4000 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = STANDARDSDK_500 (MIPSII) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 7 TARGCOMPILEARCH = 1 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\mipsii VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce5_x86.build000066400000000000000000000015751462133141200230310ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define IX86 #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_x86 CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = WindowsCE CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = STANDARDSDK_500 (x86) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 1 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\x86 VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=C0159835-AD47-41c9-A473-7AA85EF01D8D #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ce6_krs_armv4i.build000066400000000000000000000016271462133141200244640ustar00rootroot00000000000000DEVENV = "%VS90COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_NO_WINMO #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = WindowsCE CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = KRS_6400_RC5 (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += STANDARDSHELL_UI_MODEL //TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\armv4i VSPDB=vc80.pdb WINCE_VERSION=5.00 WINCE_CS_UUID=E2BECB1F-8C8C-41ba-B736-9BE7D946A398 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_express.build000066400000000000000000000014501462133141200233310ustar00rootroot00000000000000DEVENV = VCExpress.exe #define TARGET_WIN32 #define TARGET_WIN #define IX86 #define COMPILER_MSVC_EXPRESS PLATFORMLIB = win32_x86 VSBUILDER = C++ Express 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = WIN32 TARGDEF += COMPILER_MSVC_EXPRESS TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\win32 VSPDB=vc80.pdb TARGARCH=x86 //MANIFEST_DEBUG_DEP=type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_palmos.build000066400000000000000000000005411462133141200231330ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_PALMOS #define IX86 PLATFORMLIB = palm_x86 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Win32 TARGDEPLOY = 0 TARGDEF = __palmos__ TARGMACHINE = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\palmemu VSPDB=vc80.pdb TARGARCH=x86 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_ppc2003_armv4.build000066400000000000000000000017731462133141200240500ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WINCE_2003 #define TARGET_WIN #define ARM #define NO_RUNTIME_CHECK #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4 CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZ = "$(VSInstallDir)\..\Windows CE Tools\wce420\POCKET PC 2003\Tools\Cabwiz.exe" CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Pocket PC 2003 (ARMV4) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,4.20 /ARMPADCODE TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 3 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\armv4 VSPDB=vc80.pdb WINCE_VERSION=4.20 WINCE_CS_UUID=3C41C503-53EF-4c2a-8DD4-A8217CAD115E #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_s60_3rd_mr.build000066400000000000000000000004161462133141200235170ustar00rootroot00000000000000#define SERIES60 #define SYMBIAN90 TARGPLATFORM = WINSCW ARMV5 GCCE TARGDEFINE = SERIES60 PLATFORMLIB = symbian_s60_3rd_mr PLATFORM_KEYWORD = SymbianOS_3.Symbian9.S60 SDKNAME = S60_30M TARGDEF += __SERIES60_30__ TARGDEF += __SERIES60_3X__ #include "carbide_vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_smart2003_armv4.build000066400000000000000000000020131462133141200244000ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WINCE_2003 #define TARGET_WIN #define TARGET_SMARTPHONE #define ARM #define NO_RUNTIME_CHECK #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4 CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" //CABWIZ = "$(VSInstallDir)\..\Windows CE Tools\wce420\SMARTPHONE 2003\Tools\CabwizSP.exe" CABNAME = Smartphone CABCPU = 2577 CABUNSUPPORTED = "Jupiter","HPC","HPC Pro","Pocket PC","Palm PC2","Palm PC" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Smartphone 2003 (ARMV4) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += SMARTPHONE2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,4.20 /ARMPADCODE TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 3 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\smart_armv4 VSPDB=vc80.pdb #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_wm5_armv4i.build000066400000000000000000000016171462133141200236370ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Windows Mobile 5.0 Pocket PC SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\armv4i VSPDB=vc80.pdb WINCE_VERSION=5.01 WINCE_CS_UUID=4118C335-430C-497f-BE48-11C3316B135E #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_wm5s_armv4i.build000066400000000000000000000017421462133141200240210ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_SMARTPHONE #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Smartphone CABCPU = 2577 CABUNSUPPORTED = "Jupiter","HPC","HPC Pro","Pocket PC","Palm PC2","Palm PC" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Windows Mobile 5.0 Smartphone SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += SMARTPHONE2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.01 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\smart_armv4i VSPDB=vc80.pdb WINCE_VERSION=5.01 WINCE_CS_UUID=BD0CC567-F6FD-4ca3-99D2-063EFDFC0A39 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_wm6p_armv4i.build000066400000000000000000000016201462133141200240120ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = PocketPC CABCPU = 2577 CABUNSUPPORTED = "Smartphone" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Windows Mobile 6 Professional SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += POCKETPC2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.02 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\armv4i VSPDB=vc80.pdb WINCE_VERSION=5.02 WINCE_CS_UUID=b2c48bd2-963d-4549-9169-1fa021dce484 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_wm6s_armv4i.build000066400000000000000000000017361462133141200240250ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WINCE #define TARGET_WIN #define TARGET_SMARTPHONE #define ARM #define MSVC_SEE_DEPRECATE PLATFORMLIB = wince_armv4i CABWIZ = "$(VSInstallDir)\SmartDevices\SDK\SDKTools\cabwiz.exe" CABWIZCLI = /compress CABNAME = Smartphone CABCPU = 2577 CABUNSUPPORTED = "Jupiter","HPC","HPC Pro","Pocket PC","Palm PC2","Palm PC" VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = Windows Mobile 6 Standard SDK (ARMV4I) TARGDEPLOY = 1 TARGDEF = $(ARCHFAM) TARGDEF += $(_ARCHFAM_) TARGDEF += _WIN32_WCE=$(CEVER) TARGDEF += UNDER_CE=$(CEVER) TARGDEF += WINCE TARGDEF += SMARTPHONE2003_UI_MODEL TARGDEF += $(PLATFORMDEFINES) //TARGLFLAGS = /subsystem:windowsce,5.02 TARGLFLAGS = /subsystem:windowsce,3.00 TARGMACHINE = 16 TARGCOMPILEARCH = 0 TARGEXESUBSYSTEM = 9 SVNDIR=msvc8\smart_armv4i VSPDB=vc80.pdb WINCE_VERSION=5.02 WINCE_CS_UUID=f27da329-3269-4191-98e0-c87d3d7f1db9 #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vs_x64.build000066400000000000000000000014121462133141200222570ustar00rootroot00000000000000DEVENV = "%VS80COMNTOOLS%..\IDE\devenv.exe" #define TARGET_WIN64 #define TARGET_WIN #define IX86_64 PLATFORMLIB = win32_x64 VSBUILDER = Studio 2005 VSVERSION = 8.00 COMPILERVERSION = 8.00 CSPROJVERSION = 8.0.50727 TARGNAME = x64 TARGDEPLOY = 0 TARGDEF = WIN64 TARGMACHINE = 17 TARG64 = 1 TARGEXESUBSYSTEM = 2 SVNDIR=msvc8\x64 VSPDB=vc80.pdb TARGARCH=amd64 //MANIFEST_DEBUG_DEP=type='win64' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='amd64' publicKeyToken='1fc8b3b9a1e18e3b' //MANIFEST_RELEASE_DEP=type='win64' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='amd64' publicKeyToken='1fc8b3b9a1e18e3b' #include "vs.inc" bcmatroska2-5.3.101/corec/tools/coremake/vsproj-user.inc000066400000000000000000000021731462133141200231040ustar00rootroot00000000000000IF DEFINED(TARGET_WINCE) DEBUGCLASS = DebuggerTool EXECLASS = RemoteExecutable ARGCLASS = Arguments ELSE DEBUGCLASS = DebugSettings EXECLASS = Command ARGCLASS = CommandArguments WORKINGDIR = %(~|OUTPUTPATH) ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL <%(DEBUGCLASS) PRINTNL %(EXECLASS)="%(EXECUTABLE_DEBUG)" IF %(WORKINGDIR) PRINTNL WorkingDirectory="%(WORKINGDIR)debug%(OUTPUTDIR)" ENDIF PRINTNL %(ARGCLASS)="%(ARGUMENTS_DEBUG)" PRINTNL /> PRINTNL PRINTNL PRINTNL <%(DEBUGCLASS) PRINTNL %(EXECLASS)="%(EXECUTABLE_RELEASE)" IF %(WORKINGDIR) PRINTNL WorkingDirectory="%(WORKINGDIR)release%(OUTPUTDIR)" ENDIF PRINTNL %(ARGCLASS)="" PRINTNL /> PRINTNL PRINTNL PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/vsproj.inc000066400000000000000000001467701462133141200221440ustar00rootroot00000000000000IFNDEF COREMAKE_UNICODE TARGUNICODETYPE = 2 ELSE TARGUNICODETYPE = 1 ENDIF IF DEFINED(COREMAKE_MSVCRT) || "%(USE_MFC)"=="dll" USE_DLL_RUNTIME=1 ENDIF IF %(TYPE)==DLL DEFINE += _USRDLL ENDIF IF "%(USE_DLL_RUNTIME)"!="" && "%(USE_MFC)"=="dll" DEFINE += _AFXDLL ENDIF IF %(USE_MFC)!="" && %(USE_MFC)!="dll" LIBS_RELEASE += uafxcw.lib LIBS_DEBUG += uafxcwd.lib ENDIF IF %(USE_ATL) && %(USE_ATL)!="dll" DEFINE += _ATL_STATIC_REGISTRY ENDIF IFDEF TARGET_PALMOS IF %(PALMSDK5R4)=="" PALMSDK5R4 = C:\Program Files\ACCESS\Garnet OS Development Suite\sdk-5r4 ENDIF TARGINC += ;"%(~PALMSDK5R4)\include" TARGINC += ;"%(~PALMSDK5R4)\include\Core" TARGINC += ;"%(~PALMSDK5R4)\include\Core\Hardware" TARGINC += ;"%(~PALMSDK5R4)\include\Core\System" TARGINC += ;"%(~PALMSDK5R4)\include\Core\UI" TARGINC += ;"%(~PALMSDK5R4)\include\Dynamic" TARGINC += ;"%(~PALMSDK5R4)\include\Libraries" ENDIF DEFINE += STRICT IF "%(VSVERSION)"=="8.00" || "%(VSVERSION)"=="9.00" IFNDEF MSVC_SEE_DEPRECATE DEFINE += _CRT_SECURE_NO_DEPRECATE DEFINE += _CRT_NONSTDC_NO_DEPRECATE DEFINE += _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES ENDIF ENDIF HAS_IDL = FOR EACH SOURCE IF (%(>NAME)==idl) ../HAS_IDL = 1 ENDIF ENDFOR IF %(DOXYGEN) COMPILE %(DOXYGEN) "%(PATH)%(`PROJECT_NAME).doxyfile" ENDIF IF "%(PRECOMPILED_HEADER)" // IF "%(PRECOMPILED_HEADER_FORCED)"=="no" // PCH_FILE = %(PRECOMPILED_HEADER) // ELSE PCH_FILE = %(PRECOMPILED_HEADER) // ENDIF PCH_SOURCE=%(PRECOMPILED_HEADER) ENDIF IF "%(OUTPUT_DIR)"!="" OUTPUTDIR = \%(~§OUTPUT_DIR) ENDIF // trick because it's not possible to do the basic assignment with & CMD_NEWLINE= &%(CMD_NEWLINE) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF DEFINED(CARBIDE_VS) PRINTNL ENDIF PRINTNL PRINTNL IF "%(PROJ_IS_ICL)" PRINTNL PRINTNL ELSE PRINTNL > ENDIF PRINTNL PRINTNL IF DEFINED(CARBIDE_VS) PRINTNL ENDIF PRINTNL PRINTNL ADDOPTIONS = %(TARGLFLAGS) FOR EACH SOURCE_OBJ ../ADDOPTIONS += %(NAME) ENDFOR PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF (%(TYPE)!=LIB) && %(SKIP_MANIFEST)=="" PRINTNL ENDIF PRINTNL PRINTNL IF ("%(TARGSIGN)"!="") && (%(TYPE)!=LIB) PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL NAME)==r) ../POSTCOMMAND += cmd /c move /y "$(TargetPath)" "$(TargetPath).tmp"%(CMD_NEWLINE) ../POSTCOMMAND += "%(CONFIG_QUICKTIME_SDK)\Tools\RezWack.exe" -f -d "$(TargetPath).tmp" -r "$(IntDir)\%( IF %(TARGDEPLOY) PRINTNL ENDIF IFDEF TARGET_WINCE PRINTNL ENDIF PRINTNL IF "%(PROJ_IS_ICL)" PRINTNL PRINTNL ELSE PRINTNL > ENDIF IF DEFINED(CARBIDE_VS) PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF "%(PROJ_IS_ICL)" PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL IF (%(TYPE)!=LIB) && %(SKIP_MANIFEST)=="" PRINTNL ENDIF PRINTNL PRINTNL IF ("%(TARGSIGN)"!="") && (%(TYPE)!=LIB) PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL NAME)==r) ../POSTCOMMAND += cmd /c move /y "$(TargetPath)" "$(TargetPath).tmp"%(CMD_NEWLINE) ../POSTCOMMAND += "%(CONFIG_QUICKTIME_SDK)\Tools\RezWack.exe" -f -d "$(TargetPath).tmp" -r "$(IntDir)\%( IF %(TARGDEPLOY) PRINTNL ENDIF IFDEF TARGET_WINCE PRINTNL ENDIF PRINTNL PRINTNL PRINTNL FOR EACH USE IF (!%(NOLIB)) PRINTNL ENDIF ENDFOR FOR EACH DEP PRINTNL ENDFOR IF %(MANAGED_CLR)!="" PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL PRINTNL PRINTNL FOR EACH SOURCE PRINTNL IF DEFINED(CARBIDE_VS) PRINTNL PRINTNL ELIF ((%(>NAME)==c || %(>NAME)==cpp) && %(../PCH_SOURCE) && %(NO_PCH)=="") PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ../PCH_SOURCE = ELIF ((%(>NAME)==c || %(>NAME)==cpp) && (%(w) || (%(NO_PCH)!="" && %(PRECOMPILED_HEADER)))) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(>NAME)==asm) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(>NAME)==nas) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(>NAME)==c) && defined(MIPS) && ("%(TARGGCC)"!="") && %(gcc) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(>NAME)==s) && defined(MIPS) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(_copy_item)) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ELIF (%(>NAME)==r) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL ENDFOR FOR EACH DEF PRINTNL PRINTNL ENDFOR PRINTNL IF DEFINED(CARBIDE_VS) PRINTNL IF (%(TYPE)==EXE) PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF IF %(HEADER_QT4) || %(HEADER) PRINTNL FOR EACH HEADER_QT4 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR FOR EACH HEADER PRINTNL IF DEFINED(CARBIDE_VS) PRINTNL PRINTNL ELIF (%(>NAME)==cpp) || (%(>NAME)==c) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF IF %(resx)!="" PRINTNL PRINTNL ENDIF PRINTNL ENDFOR FOR EACH HEADER_QT4 PRINTNL PRINTNL ENDFOR PRINTNL ENDIF IF "%(XRC_SOURCE)"!="" PRINTNL FOR EACH XRC_SOURCE PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR PRINTNL ENDIF IF "%(UI_FORM_QT4)"!="" PRINTNL FOR EACH UI_FORM_QT4 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR PRINTNL ENDIF IF "%(HEADER_QT4)"!=""||"%(RESOURCE_QT4)"!=""||"%(XRC_SOURCE)"!=""||"%(HAS_IDL)"!="" PRINTNL FOR EACH SOURCE IF (%(>NAME)==idl) && %(hmarshal)!="" PRINTNL PRINTNL ENDIF IF (%(>NAME)==idl) && %(cmarshal)!="" PRINTNL IF "%(PRECOMPILED_HEADER)" PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL ENDIF ENDFOR FOR EACH XRC_SOURCE PRINTNL PRINTNL ENDFOR FOR EACH HEADER_QT4 IF (%(>NAME)!=cpp) PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF ENDFOR FOR EACH RESOURCE_QT4 PRINTNL IF "%(PRECOMPILED_HEADER)"!="" && "%(PRECOMPILED_HEADER_FORCED)"=="no" PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDIF PRINTNL ENDFOR PRINTNL ENDIF IF "%(RESOURCE_QT4)"!="" PRINTNL FOR EACH RESOURCE_QT4 PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR PRINTNL ENDIF IF "%(I18N)" PRINTNL PRINTNL I18NCOMMAND =if not exist "%(I18N)" mkdir "%(I18N)"%(CMD_NEWLINE) I18NCOMMAND +=xgettext -p %(I18N) -o %(NAME).pot --no-location --from-code=UTF-8 IF %(I18N_KEYWORD) I18NCOMMAND += --keyword="%(I18N_KEYWORD)" ELSE I18NCOMMAND += -a ENDIF FOR EACH SOURCE IF (%(>NAME)!=rc) ../I18NSOURCES += %(~!NAME) ENDIF ENDFOR I18NCOMMAND +=%(I18NSOURCES)%(CMD_NEWLINE) OUTDIR_LOCALE = %(~I18N)\%(../NAME) FOR EACH I18N_LANG ../I18NCOMMAND +=if not exist "%(OUTDIR_LOCALE)" mkdir "%(OUTDIR_LOCALE)"%(CMD_NEWLINE) ../I18NCOMMAND +=if not exist "%(OUTDIR_LOCALE)\%(NAME).po" copy "%(~I18N)\%(../NAME).pot" "%(OUTDIR_LOCALE)\%(NAME).po"%(CMD_NEWLINE) ../I18NCOMMAND +=msgmerge -U --backup=none %(OUTDIR_LOCALE)\%(NAME).po %(~I18N)\%(../NAME).pot%(CMD_NEWLINE) ENDFOR PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL FOR EACH I18N_LANG PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL PRINTNL ENDFOR PRINTNL ENDIF PRINTNL PRINTNL // PRINTNL PRINTNL bcmatroska2-5.3.101/corec/tools/coremake/wincab.inc000066400000000000000000000064751462133141200220610ustar00rootroot00000000000000IF %(CAB)!="" && %(CABWIZ)!="" SOURCE += %(¯PATH)%(NAME)_wince.inf FILE %(¯PATH)%(NAME)_wince.inf PRINTNLDOS [Version] PRINTNLDOS Signature="$Windows NT$" PRINTNLDOS Provider="%(PROJECT_VENDOR)" PRINTNLDOS CESignature="$Windows CE$" PRINTNLDOS PRINTNLDOS [CEStrings] IF "%(APPNAME_CAB)"!="" PRINTNLDOS AppName="%(APPNAME_CAB)" ELSE PRINTNLDOS AppName="%(PROJECT_NAME)" ENDIF PRINTNLDOS InstallDir=%CE1%\%(PROJECT_PATH) PRINTNLDOS PRINTNLDOS [CEDevice] IF %(CABCPU) PRINTNLDOS ProcessorType = %(CABCPU) ENDIF IFDEF CONFIG_WINCE2 PRINTNLDOS VersionMin = 2.0 PRINTNLDOS VersionMax = 2.999 ELSE PRINTNLDOS VersionMin = 3.0 PRINTNLDOS VersionMax = 100.0 IFDEF ARM PRINTNLDOS BuildMax = 0xE0000000 IF %(CABUNSUPPORTED) PRINTNLDOS UnsupportedPlatforms = %(CABUNSUPPORTED) ENDIF ENDIF ENDIF PRINTNLDOS PRINTNLDOS [DefaultInstall] PRINTNLDOS CEShortcuts=Shortcuts IF %(REGISTER_CAB) || %(EXTRA_REGISTER_CAB) PRINTNLDOS AddReg=RegKeys ENDIF PRINTNLDOS CopyFiles=Files IF %(TYPE)==DLL COM_INSTALL = "%(OUTPUT)" ENDIF FOR EACH USE, DEP IF %(TYPE)==DLL IF %(SETUP)!="" PRINTNLDOS CESetupDLL="%(OUTPUT)" ELIF %(COM_COMPONENT)!="" IF %(../COM_INSTALL)!="" ../COM_INSTALL += , ENDIF ../COM_INSTALL += "%(OUTPUT)" ENDIF ENDIF ENDFOR IF %(COM_INSTALL)!="" PRINTNLDOS CESelfRegister=%(COM_INSTALL) ENDIF PRINTNLDOS PRINTNLDOS [SourceDisksNames] PRINTNLDOS 1 = ,"",,"%(~|OUTPUTPATH)\release" DISK = 1 FOR EACH INSTALL_CAB INC ../DISK DISK = %(../DISK) PRINTNLDOS %(DISK) = ,"",,"%(~/|NAME)" ENDFOR PRINTNLDOS PRINTNLDOS [SourceDisksFiles] PRINTNLDOS "%(OUTPUT)"=1 FOR EACH USE, DEP IF %(TYPE)==DLL PRINTNLDOS "%(OUTPUT)"=1 ENDIF ENDFOR FOR EACH INSTALL_CAB PRINTNLDOS "%(NAME)"=%(DISK) ENDFOR PRINTNLDOS PRINTNLDOS [DestinationDirs] PRINTNLDOS Shortcuts=0,"%CE11%" PRINTNLDOS Files=0,"%InstallDir%" PRINTNLDOS DefaultDestDir = 0, %InstallDir% PRINTNLDOS PRINTNLDOS [Files] PRINTNLDOS "%(OUTPUT)",,,0 FOR EACH USE, DEP IF %(TYPE)==DLL PRINTNLDOS "%(OUTPUT)",,,0 ENDIF ENDFOR FOR EACH INSTALL_CAB PRINTNLDOS "%(NAME)",,,0 ENDFOR PRINTNLDOS PRINTNLDOS [Shortcuts] PRINTNLDOS "%(PROJECT_NAME).lnk",0,"%(OUTPUT)" IF %(REGISTER_CAB) || %(EXTRA_REGISTER_CAB) PRINTNLDOS PRINTNLDOS [RegKeys] REGEXE=%(OUTPUT) FOR EACH REGISTER_CAB PRINTNLDOS HKCR,.%(NAME),Default,0x0,"%(NAME)file" PRINTNLDOS HKCR,%(NAME)file\shell\open\command,Default,0x0,"""%InstallDir%\\%(REGEXE)""" """%%1""" PRINTNLDOS HKCR,%(NAME)file\DefaultIcon,Default,0x0,"%InstallDir%\\%(REGEXE),0" IF %(DESCRIPTION) PRINTNLDOS HKCR,%(NAME)file,Default,0x0,"%(DESCRIPTION)" ENDIF PRINTNLDOS ENDFOR FOR EACH EXTRA_REGISTER_CAB PRINTNLDOS %(NAME) ENDFOR ENDIF SOURCE += %(¯PATH)%(NAME)_wince.ini FILE %(¯PATH)%(NAME)_wince.ini PRINTNLDOS [CEAppManager] PRINTNLDOS Version = 1.0 PRINTNLDOS Component = %(PROJECT_PATH) PRINTNLDOS PRINTNLDOS [%(PROJECT_PATH)] PRINTNLDOS Description = %(PROJECT_NAME) PRINTNLDOS Uninstall = %(PROJECT_PATH) PRINTNLDOS CabFiles = %(PROJECT_NAME).%(CABNAME).cab ENDIF bcmatroska2-5.3.101/corec/tools/coremake/winrc.inc000066400000000000000000000021711462133141200217250ustar00rootroot00000000000000FOR EACH DLL,EXE,CON IFNDEF COREMAKE_STATIC FOR EACH INSTALL ../INSTALL_CAB += %(|NAME) ADD ../SOURCE %(|NAME) _COPY_ITEM = 1 ENDADD DELETE ENDFOR ENDIF FOR EACH SOURCE IF %(>NAME)==rc ../SOURCERC += %(|NAME) DELETE ENDIF ENDFOR FOR EACH USE IF %(TYPE)==lib FOR EACH SOURCE IF %(>NAME)==rc ../../SOURCERC += %(|NAME) ENDIF ENDFOR ENDIF ENDFOR IF "%(=SOURCERC)"!="0" || "%(ICON)"!="" || "%(INSTALL)"!="" IF "%(=SOURCERC)"=="1" && "%(ICON)"=="" && "%(INSTALL)"=="" SOURCE += %(|SOURCERC) ELSE SOURCE += %(¯PATH)%(NAME)_win32.rc FILE %(¯PATH)%(NAME)_win32.rc FOR EACH SOURCERC ../INCLUDERC += %(|PATH) PRINTNL #include "%(!NAME)" ENDFOR IF "%(ICON)"!="" IFDEF TARGET_WINCE PRINTNL 1000 ICON DISCARDABLE "%(!ICON)_wince.ico" ELSE PRINTNL 1000 ICON DISCARDABLE "%(!ICON)_win32.ico" ENDIF ENDIF FOR EACH INSTALL PRINTNL 1000 %(NAME) DISCARDABLE "%(!NAME)" ENDFOR ENDIF ENDIF ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/xcode.build000066400000000000000000000002141462133141200222270ustar00rootroot00000000000000#define POWERPC SDK = /Developer/SDKs/MacOSX10.3.9.sdk FRAMEWORK_PATH = / GCC_VERSION = 4.0 XCODECOMPATVERSION = 2.4 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode.inc000066400000000000000000001255631462133141200217200ustar00rootroot00000000000000#define TARGET_OSX ASMFLAGS = -f macho -D_MACHO PLATFORMLIB = osx_ppc #define OUTPUT_EXE %(NAME) #define OUTPUT_DLL %(NAME).so #define OUTPUT_LIB lib%(NAME).a #define OUTPUT_CON %(NAME) #define COMPILER_XCODE #define COMPILER_GCC IFDEF USE_MAKEFILE #include "gcc_osx.inc" ELSE CONFIG ENDIF IFDEF TARGET_IPHONE ICONSUFFIX = _iphone2.png ELSE ICONSUFFIX = .icns ENDIF FOR EACH WORKSPACE FOR EACH USE IF %(TYPE)==EXE || %(TYPE)==DLL IF (%(TYPE)==DLL) DEFINE += %(<^NAME)_EXPORTS ENDIF FILE %(¯../PATH)%(NAME).plist #include "osx_plist.inc" ENDIF IF %(PMDOC)!="" COMPILE %(PMDOC).pmdoc/index.xml %(PATH)%(NAME).pmdoc/index.xml COMPILE %(PMDOC).pmdoc/01%(PROJECT_NAME).xml %(PATH)%(NAME).pmdoc/01%(PROJECT_NAME).xml COMPILE %(PMDOC).pmdoc/01%(PROJECT_NAME)-contents.xml %(PATH)%(NAME).pmdoc/01%(PROJECT_NAME)-contents.xml ENDIF ENDFOR HAS_PRIVATE_FRAMEWORK = FILE %(¯PATH)%(NAME).xcodeproj/project.pbxproj PRINTNL // !$*UTF8*$! PRINTNL { PRINTNL archiveVersion = 1; PRINTNL classes = { PRINTNL }; IF "%(XCODECOMPATVERSION)"=="2.4" PRINTNL objectVersion = 42; ELSE PRINTNL objectVersion = 45; ENDIF PRINTNL objects = { PRINTNL PRINTNL /* Begin PBXBuildFile section */ FOR EACH USE HAS_RESOURCE = HAS_REZ = FOR EACH SOURCE IF (%(>NAME)==r) PRINTNL %(_XCODEUID) /* %(!;NAME) in Rez */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME) */; }; ../HAS_REZ = 1 ELIF (%(>NAME)==nib) PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME) */; }; ../HAS_RESOURCE = 1 ELSE PRINTNL %(_XCODEUID) /* %(!;NAME) in Sources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME) */; }; ENDIF ENDFOR IF (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(_XCODEGRPUID10) /* %(!;NAME).plist in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEGRPUID9) /* %(!;NAME).plist */; }; ENDIF FOR EACH OSX_ICON PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME) */; }; ENDFOR FOR EACH ICON PRINTNL %(_XCODEUID) /* %(!;NAME)%(ICONSUFFIX) in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME)%(ICONSUFFIX) */; }; ENDFOR FOR EACH INSTALL PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* %(!;NAME) */; }; ../HAS_RESOURCE = 1 ENDFOR FOR EACH OSX_STRINGS PRINTNL %(_XCODEUID) /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = %(XCODEUID) /* InfoPlist.strings */; }; ENDFOR // IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) FOR EACH FRAMEWORK PRINTNL %(XCODEFRWFILE) /* %(NAME).framework in %(../NAME) Frameworks */ = {isa = PBXBuildFile; fileRef = %(_XCODEFRWFILE) /* %(NAME).framework */; }; ENDFOR FOR EACH FRAMEWORK_LIB PRINTNL %(XCODEFRWFILE) /* %(NAME) in Frameworks */ = {isa = PBXBuildFile; fileRef = %(_XCODEFRWFILE) /* %(NAME) */; }; ENDFOR FOR EACH PRIVATEFRAMEWORK PRINTNL %(XCODEFRWFILE) /* %(NAME).framework in %(../NAME) Frameworks */ = {isa = PBXBuildFile; fileRef = %(_XCODEFRWFILE) /* %(NAME).framework */; }; ../../HAS_PRIVATE_FRAMEWORK = 1 ENDFOR FOR EACH USE IF (%(TYPE)==LIB) PRINTNL %(*XCODEFRWFILE) /* lib%(NAME).a in %(../NAME) Frameworks */ = {isa = PBXBuildFile; fileRef = %(XCODEGRPUID3) /* lib%(NAME).a */; }; ENDIF IF (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL %(*XCODEFRWFILE) /* %(NAME).component in %(../NAME) Frameworks */ = {isa = PBXBuildFile; fileRef = %(XCODEGRPUID3) /* %(NAME).component */; }; ELSE PRINTNL %(*XCODEFRWFILE) /* %(NAME).dylib in %(../NAME) Frameworks */ = {isa = PBXBuildFile; fileRef = %(XCODEGRPUID3) /* %(NAME).dylib */; }; ENDIF ENDIF ENDFOR // ENDIF ENDFOR PRINTNL /* End PBXBuildFile section */ PRINTNL PRINTNL /* Begin PBXContainerItemProxy section */ FOR EACH USE IF (%(TYPE)==LIB) PRINTNL %(_XCODEGRPUID5) /* PBXContainerItemProxy */ = { PRINTNL isa = PBXContainerItemProxy; PRINTNL containerPortal = 91B15E841AA80083484172DE /* Project object */; PRINTNL proxyType = 1; PRINTNL remoteGlobalIDString = %(_XCODEGRPUID3); PRINTNL remoteInfo = lib%(NAME).a; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXContainerItemProxy section */ PRINTNL PRINTNL /* Begin PBXFileReference section */ FOR EACH USE IF (%(TYPE)==CON) PRINTNL %(XCODEGRPUID3) /* %(NAME) */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; sourceTree = BUILT_PRODUCTS_DIR; }; ENDIF IF (%(TYPE)==LIB) PRINTNL %(XCODEGRPUID3) /* lib%(NAME).a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; name = lib%(NAME).a; path = lib%(NAME).a; sourceTree = BUILT_PRODUCTS_DIR; }; ENDIF IF (%(TYPE)==EXE) IF %(PROJECT_PATH) PRINTNL %(XCODEGRPUID3) /* %(NAME).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = %(PROJECT_PATH).app; sourceTree = BUILT_PRODUCTS_DIR; }; ELSE PRINTNL %(XCODEGRPUID3) /* %(NAME).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; sourceTree = BUILT_PRODUCTS_DIR; }; ENDIF ENDIF IF (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL %(XCODEGRPUID3) /* %(NAME).component */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = %(NAME).component; sourceTree = BUILT_PRODUCTS_DIR; }; ELSE PRINTNL %(XCODEGRPUID3) /* %(NAME).dylib */ = {isa = PBXFileReference; explicitFileType = compiled.mach-o.dylib; includeInIndex = 0; path = lib%(NAME).dylib; sourceTree = BUILT_PRODUCTS_DIR; }; ENDIF ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(XCODEGRPUID9) /* %(NAME).plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = %(NAME).plist; sourceTree = ""; }; ENDIF FOR EACH OSX_ICON PRINTNL %(XCODEUID) /* %(NAME) */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = %(NAME); path = %(!;NAME); sourceTree = ""; }; ENDFOR FOR EACH ICON PRINTNL %(XCODEUID) /* %(NAME)%(ICONSUFFIX) */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = %(NAME)%(ICONSUFFIX); path = %(!;NAME)%(ICONSUFFIX); sourceTree = ""; }; ENDFOR FOR EACH INSTALL PRINTNL %(XCODEUID) /* %(NAME) */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = %(NAME); path = %(!;NAME); sourceTree = ""; }; ENDFOR FOR EACH OSX_STRINGS PRINTNL %(_XCODEUID) /* %(NAME) */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = %(NAME); path = %(!;NAME).lproj/InfoPlist.strings; sourceTree = ""; }; ENDFOR FOR EACH HEADER PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 12; lastKnownFileType = sourcecode.c.h; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ENDFOR FOR EACH SOURCE IF (%(>NAME)==cpp) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 12; lastKnownFileType = sourcecode.cpp.cpp; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==c) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 12; lastKnownFileType = sourcecode.c.c; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==r) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.rez; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF ((%(>NAME)==m) || (%(>NAME)==rl)) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==mm) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objcpp; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==asm) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.yasm; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==S) SOURCEASM = sourcecode.asm.asm IFDEF TARGET_IPHONE SOURCEASM = sourcecode.asm.arm IF DEFINED(CONFIG_NEON) && %(cpu)==neon SOURCEASM = sourcecode.asm.gaspp ENDIF ENDIF PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = %(SOURCEASM); name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==s) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ELIF (%(>NAME)==nib) PRINTNL %(XCODEUID) /* %(!;NAME) */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = %(!;NAME); path = %(!;NAME); sourceTree = ""; }; ENDIF ENDFOR FOR EACH FRAMEWORK_LIB PRINTNL %(_XCODEFRWFILE) /* %(NAME) */ = {isa = PBXFileReference; explicitFileType = compiled.mach-o.dylib; includeInIndex = 0; name = %(NAME); path = System/Library/Frameworks/%(NAME).framework/Versions/A/%(NAME); sourceTree = SDKROOT; }; ENDFOR // IF (%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL) FOR EACH FRAMEWORK IFDEF TARGET_IPHONE PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = %(NAME).framework; path = %(FRAMEWORK_PATH)System/Library/Frameworks/%(NAME).framework; sourceTree = SDKROOT; }; ELSE PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = %(NAME).framework; path = %(FRAMEWORK_PATH)System/Library/Frameworks/%(NAME).framework; sourceTree = ""; }; ENDIF ENDFOR FOR EACH PRIVATEFRAMEWORK IFDEF TARGET_IPHONE PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = %(NAME).framework; path = %(FRAMEWORK_PATH)System/Library/PrivateFrameworks/%(NAME).framework; sourceTree = SDKROOT; }; ELSE PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = %(NAME).framework; path = %(FRAMEWORK_PATH)System/Library/PrivateFrameworks/%(NAME).framework; sourceTree = ""; }; ENDIF ENDFOR // ENDIF ENDFOR PRINTNL /* End PBXFileReference section */ PRINTNL PRINTNL /* Begin PBXFrameworksBuildPhase section */ FOR EACH USE // IF ((%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL)) && ("%(FRAMEWORK)" || "%(PRIVATEFRAMEWORK)" || "%(USE)") IF ("%(FRAMEWORK)" || "%(PRIVATEFRAMEWORK)" || "%(USE)" || "%(FRAMEWORK_LIB)") PRINTNL %(_XCODEGRPUID7) /* %(NAME) Frameworks */ = { PRINTNL isa = PBXFrameworksBuildPhase; PRINTNL buildActionMask = 2147483647; PRINTNL files = ( FOR EACH FRAMEWORK PRINTNL %(XCODEFRWFILE) /* %(NAME).framework in Frameworks */, ENDFOR FOR EACH PRIVATEFRAMEWORK PRINTNL %(XCODEFRWFILE) /* %(NAME).framework in Frameworks */, ENDFOR FOR EACH USE IF (%(TYPE)==LIB) PRINTNL %(*XCODEFRWFILE) /* lib%(NAME).a in Frameworks */, ENDIF IF (%(TYPE)==DLL) PRINTNL %(*XCODEFRWFILE) /* %(NAME).dylib in Frameworks */, ENDIF ENDFOR FOR EACH FRAMEWORK_LIB PRINTNL %(XCODEFRWFILE) /* %(NAME) in Frameworks */, ENDFOR PRINTNL ); PRINTNL runOnlyForDeploymentPostprocessing = 0; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXFrameworksBuildPhase section */ PRINTNL PRINTNL /* Begin PBXGroup section */ PRINTNL 001B7795FE84155DC02AAC07 /* %(NAME) */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH USE PRINTNL %(XCODEGRPUID) /* %(NAME) */, ENDFOR PRINTNL 00249F820B5EBE71005A4BD4 /* Products */, PRINTNL ); PRINTNL name = %(NAME); PRINTNL sourceTree = ""; PRINTNL }; PRINTNL 00249F820B5EBE71005A4BD4 /* Products */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH USE IF (%(TYPE)==CON) || (%(TYPE)==EXE) PRINTNL %(XCODEGRPUID3) /* %(NAME) */, ENDIF IF (%(TYPE)==LIB) PRINTNL %(XCODEGRPUID3) /* lib%(NAME).a */, ENDIF IF (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL %(XCODEGRPUID3) /* %(NAME).component */, ELSE PRINTNL %(XCODEGRPUID3) /* %(NAME).dylib */, ENDIF ENDIF FOR EACH FRAMEWORK_LIB PRINTNL %(_XCODEFRWFILE) /* %(NAME) */, ENDFOR ENDFOR PRINTNL ); PRINTNL name = Products; PRINTNL sourceTree = ""; PRINTNL }; FOR EACH USE PRINTNL %(XCODEGRPUID) /* %(NAME) */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( IF %(SOURCE) PRINTNL %(_XCODEGRPUID) /* Sources */, ENDIF IF %(HEADER) PRINTNL %(XCODEGRPUID2) /* Headers */, ENDIF IF %(HAS_REZ) || %(HAS_RESOURCE) || %(OSX_STRINGS) || (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(_XCODEGRPUID9) /* Resources */, ENDIF IF ((%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL)) && ("%(FRAMEWORK)"!="" || "%(PRIVATEFRAMEWORK)"!="") PRINTNL %(XCODEGRPUID8) /* External Frameworks and Libraries */, ENDIF PRINTNL ); PRINTNL name = %(NAME); PRINTNL sourceTree = ""; PRINTNL }; IF %(HEADER) PRINTNL %(XCODEGRPUID2) /* Headers */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH HEADER PRINTNL %(XCODEUID) /* %(!;NAME) */, ENDFOR PRINTNL ); PRINTNL name = Headers; PRINTNL sourceTree = ""; PRINTNL }; ENDIF IF %(SOURCE) PRINTNL %(_XCODEGRPUID) /* Sources */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH SOURCE IF ((%(>NAME)!=r) && (%(>NAME)!=nib)) PRINTNL %(XCODEUID) /* %(!;NAME) */, ENDIF ENDFOR PRINTNL ); PRINTNL name = Sources; PRINTNL sourceTree = ""; PRINTNL }; ENDIF // IF ((%(TYPE)==EXE) || (%(TYPE)==CON) || (%(TYPE)==DLL)) && %(FRAMEWORK) IF %(FRAMEWORK) || %(PRIVATEFRAMEWORK) PRINTNL %(XCODEGRPUID8) /* External Frameworks and Libraries */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH FRAMEWORK PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */, ENDFOR FOR EACH PRIVATEFRAMEWORK PRINTNL %(_XCODEFRWFILE) /* %(NAME).framework */, ENDFOR PRINTNL ); PRINTNL name = "External Frameworks and Libraries"; PRINTNL sourceTree = ""; PRINTNL }; ENDIF IF %(HAS_REZ) || %(HAS_RESOURCE) || %(OSX_STRINGS) || (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(_XCODEGRPUID9) /* Resources */ = { PRINTNL isa = PBXGroup; PRINTNL children = ( FOR EACH SOURCE IF ((%(>NAME)==r) || (%(>NAME)==nib)) PRINTNL %(XCODEUID) /* %(!;NAME) */, ENDIF ENDFOR IF (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(XCODEGRPUID9) /* %(NAME).plist */, ENDIF FOR EACH OSX_ICON PRINTNL %(XCODEUID) /* %(!;NAME) */, ENDFOR FOR EACH ICON PRINTNL %(XCODEUID) /* %(!;NAME)%(ICONSUFFIX)*/, ENDFOR FOR EACH INSTALL PRINTNL %(XCODEUID) /* %(!;NAME) */, ENDFOR FOR EACH OSX_STRINGS PRINTNL %(XCODEUID) /* InfoPlist.strings */, ENDFOR PRINTNL ); PRINTNL name = Resources; PRINTNL sourceTree = ""; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXGroup section */ PRINTNL IFNDEF USE_MAKEFILE PRINTNL /* Begin PBXNativeTarget section */ FOR EACH USE PRINTNL %(_XCODEGRPUID3) /* %(NAME) */ = { PRINTNL isa = PBXNativeTarget; PRINTNL buildConfigurationList = %(XCODEGRPUID5) /* Build configuration list for PBXNativeTarget "%(NAME)" */; PRINTNL buildPhases = ( IF %(HAS_RESOURCE) || (((%(TYPE)==EXE) || (%(TYPE)==DLL)) && %(OSX_STRINGS)) PRINTNL %(XCODEGRPUID7) /* Resources */, ENDIF PRINTNL %(_XCODEGRPUID2) /* %(NAME) Sources */, IF ((%(TYPE)==EXE) || (%(TYPE)==DLL) || (%(TYPE)==CON)) && ("%(FRAMEWORK)"!="" || "%(PRIVATEFRAMEWORK)"!=""|| "%(USE)"!="") PRINTNL %(_XCODEGRPUID7) /* Frameworks */, ENDIF IF %(HAS_REZ) PRINTNL %(XCODEGRPUID10) /* Rez */, ENDIF IF %(I18N) || %(EXPORT_SVN) PRINTNL %(_XCODEGRPUID6) /* Post Build */, ENDIF PRINTNL ); PRINTNL buildRules = ( PRINTNL ); PRINTNL dependencies = ( FOR EACH USE PRINTNL %(XCODEGRPUID6) /* PBXTargetDependency */, ENDFOR PRINTNL ); IF (%(TYPE)==LIB) PRINTNL name = lib%(NAME).a; PRINTNL productName = lib%(NAME).a; PRINTNL productReference = %(XCODEGRPUID3) /* lib%(NAME).a */; PRINTNL productType = "com.apple.product-type.library.static"; ELSE PRINTNL name = %(NAME); // IF %(PROJECT_PATH) // PRINTNL productName = %(PROJECT_PATH); // ELSE PRINTNL productName = %(NAME); // ENDIF IF (%(TYPE)==CON) PRINTNL productReference = %(XCODEGRPUID3) /* %(NAME) */; PRINTNL productType = "com.apple.product-type.tool"; ENDIF IF (%(TYPE)==EXE) IF %(PROJECT_PATH) PRINTNL productReference = %(XCODEGRPUID3) /* %(PROJECT_PATH).app */; ELSE PRINTNL productReference = %(XCODEGRPUID3) /* %(NAME).app */; ENDIF PRINTNL productType = "com.apple.product-type.application"; ENDIF IF (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL productInstallPath = "$(HOME)/Library/Bundles"; PRINTNL productReference = %(XCODEGRPUID3) /* %(NAME).component */; PRINTNL productType = "com.apple.product-type.bundle"; ELSE PRINTNL productReference = %(XCODEGRPUID3) /* lib%(NAME).dylib */; PRINTNL productType = "com.apple.product-type.library.dynamic"; ENDIF ENDIF ENDIF PRINTNL }; ENDFOR PRINTNL /* End PBXNativeTarget section */ ELSE PRINTNL /* Begin PBXLegacyTarget section */ FOR EACH USE PRINTNL %(_XCODEGRPUID3) /* %(NAME) */ = { PRINTNL isa = PBXLegacyTarget; PRINTNL buildArgumentsString = "$(ACTION)"; PRINTNL buildConfigurationList = D92591D40C6B42CE00BBDBBC /* Build configuration list for PBXLegacyTarget "%(NAME)" */; PRINTNL buildPhases = ( PRINTNL ); PRINTNL buildToolPath = /usr/bin/make; PRINTNL dependencies = ( PRINTNL ); PRINTNL name = "%(NAME)"; PRINTNL passBuildSettingsInEnvironment = 1; PRINTNL productName = "%(NAME)"; PRINTNL }; ENDFOR PRINTNL /* End PBXLegacyTarget section */ ENDIF PRINTNL PRINTNL /* Begin PBXProject section */ PRINTNL 91B15E841AA80083484172DE /* Project object */ = { PRINTNL isa = PBXProject; PRINTNL attributes = { PRINTNL BuildIndependentTargetsInParallel = YES; PRINTNL }; PRINTNL buildConfigurationList = AA277BB30B5E830800EA36F7 /* Build configuration list for PBXProject "%(NAME)" */; PRINTNL compatibilityVersion = "Xcode %(XCODECOMPATVERSION)"; PRINTNL hasScannedForEncodings = 0; PRINTNL mainGroup = 001B7795FE84155DC02AAC07 /* %(NAME) */; PRINTNL projectDirPath = ""; PRINTNL projectRoot = ""; PRINTNL targets = ( FOR EACH USE PRINTNL %(_XCODEGRPUID3) /* %(NAME) */, ENDFOR PRINTNL ); PRINTNL }; PRINTNL /* End PBXProject section */ PRINTNL PRINTNL /* Begin PBXResourcesBuildPhase section */ FOR EACH USE IF (%(TYPE)==EXE) || (%(TYPE)==DLL) PRINTNL %(XCODEGRPUID7) /* Resources */ = { PRINTNL isa = PBXResourcesBuildPhase; PRINTNL buildActionMask = 2147483647; PRINTNL files = ( FOR EACH OSX_STRINGS PRINTNL %(_XCODEUID) /* InfoPlist.strings in Resources */, ENDFOR // PRINTNL %(_XCODEGRPUID10) /* %(NAME).plist */, FOR EACH SOURCE IF (%(>NAME)==nib) PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */, ENDIF ENDFOR FOR EACH OSX_ICON PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */, ENDFOR FOR EACH ICON PRINTNL %(_XCODEUID) /* %(!;NAME)%(ICONSUFFIX) in Resources */, ENDFOR FOR EACH INSTALL PRINTNL %(_XCODEUID) /* %(!;NAME) in Resources */, ENDFOR PRINTNL ); PRINTNL runOnlyForDeploymentPostprocessing = 0; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXResourcesBuildPhase section */ PRINTNL PRINTNL /* Begin PBXShellScriptBuildPhase section */ FOR EACH USE IF %(I18N) || %(EXPORT_SVN) PRINTNL %(_XCODEGRPUID6) /* Post Build */ = { PRINTNL isa = PBXShellScriptBuildPhase; PRINTNL buildActionMask = 2147483647; PRINTNL files = ( PRINTNL ); PRINTNL runOnlyForDeploymentPostprocessing = 0; PRINTNL shellPath = /bin/sh; CMDLINE = IF %(I18N) CMDLINE += cd %(!;PATH)\nmkdir -p \"%(I18N)\"\n // CMDLINE += xgettext -p %(I18N) -a -o %(NAME).pot --no-location --from-code=UTF-8\n ENDIF IF %(EXPORT_SVN) IF (%(TYPE)==LIB) CMDLINE += mkdir -p \"%(!;EXPORT_SVN)export/lib/osx/static/$CONFIGURATION\"\ncp -p \"$TARGET_BUILD_DIR/$TARGET_NAME\" \"%(!;EXPORT_SVN)export/lib/osx/static/$CONFIGURATION\" ELIF (%(TYPE)==DLL) CMDLINE += mkdir -p \"%(!;EXPORT_SVN)export/lib/osx/dynamic/$CONFIGURATION\"\ncp -p \"$TARGET_BUILD_DIR/$TARGET_NAME\" \"%(!;EXPORT_SVN)export/lib/osx/dynamic/$CONFIGURATION\" ENDIF ENDIF PRINTNL shellScript = "%(CMDLINE)"; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXShellScriptBuildPhase section */ PRINTNL PRINTNL /* Begin PBXRezBuildPhase section */ FOR EACH USE IF %(HAS_RESOURCE) || %(HAS_REZ) PRINTNL %(XCODEGRPUID10) /* Rez */ = { PRINTNL isa = PBXRezBuildPhase; PRINTNL buildActionMask = 2147483647; PRINTNL files = ( FOR EACH SOURCE IF (%(>NAME)==r) PRINTNL %(_XCODEUID) /* %(!;NAME) in Rez */, ENDIF ENDFOR PRINTNL ); PRINTNL runOnlyForDeploymentPostprocessing = 0; PRINTNL }; ENDIF ENDFOR PRINTNL /* End PBXRezBuildPhase section */ PRINTNL PRINTNL /* Begin PBXSourcesBuildPhase section */ FOR EACH USE PRINTNL %(_XCODEGRPUID2) /* %(NAME) Sources */ = { PRINTNL isa = PBXSourcesBuildPhase; PRINTNL buildActionMask = 2147483647; PRINTNL files = ( FOR EACH SOURCE IF ((%(>NAME)!=r) && (%(>NAME)!=nib)) PRINTNL %(_XCODEUID) /* %(!;NAME) in Sources */, ENDIF ENDFOR PRINTNL ); PRINTNL runOnlyForDeploymentPostprocessing = 0; PRINTNL }; ENDFOR PRINTNL /* End PBXSourcesBuildPhase section */ PRINTNL PRINTNL /* Begin PBXTargetDependency section */ FOR EACH USE FOR EACH USE PRINTNL %(XCODEGRPUID6) /* PBXTargetDependency */ = { PRINTNL isa = PBXTargetDependency; PRINTNL target = %(_XCODEGRPUID3) /* lib%(NAME).a */; PRINTNL targetProxy = %(_XCODEGRPUID5) /* PBXContainerItemProxy */; PRINTNL }; ENDFOR ENDFOR PRINTNL /* End PBXTargetDependency section */ PRINTNL PRINTNL /* Begin PBXVariantGroup section */ FOR EACH USE FOR EACH OSX_STRINGS PRINTNL %(XCODEUID) /* InfoPlist.strings */ = { PRINTNL isa = PBXVariantGroup; PRINTNL children = ( PRINTNL %(_XCODEUID) /* %(NAME) */, PRINTNL ); PRINTNL name = InfoPlist.strings; PRINTNL sourceTree = ""; PRINTNL }; ENDFOR ENDFOR PRINTNL /* End PBXVariantGroup section */ PRINTNL PRINTNL /* Begin XCBuildConfiguration section */ FOR EACH USE PRINTNL %(_XCODEGRPUID4) /* Release */ = { PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { PRINTNL GCC_C_LANGUAGE_STANDARD = gnu99; IF (%(TYPE)!=DLL) PRINTNL GCC_DYNAMIC_NO_PIC = YES; ENDIF IF %(FAVOR_MAX_SPEED) PRINTNL GCC_OPTIMIZATION_LEVEL = 3; PRINTNL OTHER_CFLAGS = "-fomit-frame-pointer"; IFNDEF XCODE4 PRINTNL OTHER_CFLAGS_ppc = "-maltivec"; PRINTNL OTHER_CPLUSPLUSFLAGS_ppc = "-maltivec"; ENDIF PRINTNL OTHER_CPLUSPLUSFLAGS = "-fomit-frame-pointer"; PRINTNL DEPLOYMENT_POSTPROCESSING = YES; PRINTNL STRIP_INSTALLED_PRODUCT = YES; PRINTNL SEPARATE_STRIP = YES; PRINTNL COPY_PHASE_STRIP = YES; ENDIF IFDEF TARGET_IPHONE PRINTNL GCC_THUMB_SUPPORT = NO; IF %(IOSDEPLOYMENTTARGET)!="" PRINTNL IPHONEOS_DEPLOYMENT_TARGET = %(IOSDEPLOYMENTTARGET); ENDIF PRINTNL MACOSX_DEPLOYMENT_TARGET = ""; IF (%(TYPE)==EXE) PRINTNL "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; PRINTNL IPHONE_OPTIMIZE_OPTIONS = "-skip-PNGs"; ENDIF ENDIF IF %(ASMFLAGS)!="" PRINTNL NASM_OTHER_FLAGS = "%(ASMFLAGS)"; ENDIF PRINTNL GCC_PREPROCESSOR_DEFINITIONS = ( PRINTNL NDEBUG, FOR EACH DEFINE PRINTNL "%(NAME)", ENDFOR FOR EACH DEFINE_RELEASE PRINTNL "%(NAME)", ENDFOR PRINTNL ); IF %(USE) || %(LIBS) || %(LIBS_RELEASE) || %(LIBINCLUDE) || %(LIBINCLUDE_RELEASE) || %(ABSLIBINCLUDE) || %(ABSLIBINCLUDE_RELEASE) PRINTNL OTHER_LDFLAGS = ( FOR EACH LIBINCLUDE PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH LIBINCLUDE_RELEASE PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH ABSLIBINCLUDE PRINTNL "-L%(NAME)", ENDFOR FOR EACH ABSLIBINCLUDE_RELEASE PRINTNL "-L%(NAME)", ENDFOR IF (%(TYPE)!=LIB) FOR EACH USEBUILT PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS_RELEASE PRINTNL "-l%(NAME)", ENDFOR ENDIF PRINTNL ); ENDIF PRINTNL OBJROOT = %(!;§BUILDPATH); IF (%(TYPE)==EXE) && (%(PROJECT_PATH)!="") PRINTNL PRODUCT_NAME = %(PROJECT_PATH); ELSE PRINTNL PRODUCT_NAME = %(NAME); ENDIF IF %(INCLUDE) || %(INCLUDE_RELEASE) || %(SYSINCLUDE) || %(ABSINCLUDE_RELEASE) || %(ABSINCLUDE) || %(CONFIG_INCLUDE) PRINTNL USER_HEADER_SEARCH_PATHS = "%(!;@INCLUDE:%=% )%(!;@INCLUDE_RELEASE:%=% )%(!;@SYSINCLUDE:%=% )%(ABSINCLUDE_RELEASE:%=% )%(ABSINCLUDE:%=% )%(!;@CONFIG_INCLUDE:%=% )"; ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); IF %(HAS_REZ) PRINTNL OTHER_REZFLAGS = "-d ppc_$(ppc) -d i386_$(i386)"; ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL WRAPPER_EXTENSION = component; ENDIF PRINTNL INFOPLIST_FILE = %(NAME).plist; ENDIF IF %(PRECOMPILED_HEADER) PRINTNL GCC_PREFIX_HEADER = "%(!;PATH)%(PRECOMPILED_HEADER)"; PRINTNL GCC_PRECOMPILE_PREFIX_HEADER = YES; ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL PRINTNL name = "Release Universal"; ELSE PRINTNL name = "Release"; ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL PRINTNL %(XCODEGRPUID4) /* Debug other */ = { ELSE PRINTNL %(XCODEGRPUID4) /* Debug */ = { ENDIF PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { PRINTNL GCC_C_LANGUAGE_STANDARD = gnu99; IF (%(TYPE)!=DLL) PRINTNL GCC_DYNAMIC_NO_PIC = YES; ENDIF IF %(FAVOR_MAX_SPEED_DEBUG) PRINTNL GCC_OPTIMIZATION_LEVEL = 3; IFDEF XCODE4 PRINTNL OTHER_CFLAGS = "-fomit-frame-pointer"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-fomit-frame-pointer"; ELSE PRINTNL OTHER_CFLAGS = "-fomit-frame-pointer -maltivec"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-fomit-frame-pointer -maltivec"; ENDIF ELSE PRINTNL GCC_OPTIMIZATION_LEVEL = 0; //PRINTNL GCC_ENABLE_FIX_AND_CONTINUE = YES; ENDIF IFDEF TARGET_IPHONE PRINTNL GCC_THUMB_SUPPORT = NO; IF %(IOSDEPLOYMENTTARGET)!="" PRINTNL IPHONEOS_DEPLOYMENT_TARGET = %(IOSDEPLOYMENTTARGET); ENDIF PRINTNL MACOSX_DEPLOYMENT_TARGET = ""; IF (%(TYPE)==EXE) PRINTNL "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; PRINTNL IPHONE_OPTIMIZE_OPTIONS = "-skip-PNGs"; ENDIF ENDIF IF %(DEFINE) || %(DEFINE_DEBUG) PRINTNL GCC_PREPROCESSOR_DEFINITIONS = ( FOR EACH DEFINE PRINTNL "%(NAME)", ENDFOR FOR EACH DEFINE_DEBUG PRINTNL "%(NAME)", ENDFOR PRINTNL ); ENDIF IF %(USE) || %(LIBS) || %(LIBS_DEBUG) || %(LIBINCLUDE) || %(LIBINCLUDE_DEBUG) || %(ABSLIBINCLUDE) || %(ABSLIBINCLUDE_DEBUG) PRINTNL OTHER_LDFLAGS = ( FOR EACH LIBINCLUDE PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH LIBINCLUDE_DEBUG PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH ABSLIBINCLUDE PRINTNL "-L%(NAME)", ENDFOR FOR EACH ABSLIBINCLUDE_DEBUG PRINTNL "-L%(NAME)", ENDFOR IF (%(TYPE)!=LIB) FOR EACH USEBUILT PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS_DEBUG PRINTNL "-l%(NAME)", ENDFOR ENDIF PRINTNL ); ENDIF PRINTNL OBJROOT = %(!;§BUILDPATH); IF (%(TYPE)==EXE) && (%(PROJECT_PATH)!="") PRINTNL PRODUCT_NAME = %(PROJECT_PATH); ELSE PRINTNL PRODUCT_NAME = %(NAME); ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); IF %(INCLUDE) || %(INCLUDE_DEBUG) || %(SYSINCLUDE) || %(ABSINCLUDE_DEBUG) || %(ABSINCLUDE) || %(CONFIG_INCLUDE) PRINTNL USER_HEADER_SEARCH_PATHS = "%(!;@INCLUDE:%=% )%(!;@INCLUDE_DEBUG:%=% )%(!;@SYSINCLUDE:%=% )%(ABSINCLUDE_DEBUG:%=% )%(ABSINCLUDE:%=% )%(!;@CONFIG_INCLUDE:%=% )"; ENDIF IF %(HAS_REZ) PRINTNL OTHER_REZFLAGS = "-d ppc_$(ppc) -d i386_$(i386)"; ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL WRAPPER_EXTENSION = component; ENDIF PRINTNL INFOPLIST_FILE = %(NAME).plist; ENDIF IF %(PRECOMPILED_HEADER) PRINTNL GCC_PREFIX_HEADER = "%(!;PATH)%(PRECOMPILED_HEADER)"; PRINTNL GCC_PRECOMPILE_PREFIX_HEADER = YES; ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL IFDEF IX86_64 PRINTNL name = "Debug x86_64"; ELSE PRINTNL name = "Debug ppc"; ENDIF ELSE PRINTNL name = Debug; ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL PRINTNL %(_XCODEGRPUID8) /* Debug i386 */ = { PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { PRINTNL GCC_C_LANGUAGE_STANDARD = gnu99; IF (%(TYPE)!=DLL) PRINTNL GCC_DYNAMIC_NO_PIC = YES; ENDIF IF %(FAVOR_MAX_SPEED_DEBUG) PRINTNL GCC_OPTIMIZATION_LEVEL = 3; PRINTNL OTHER_CFLAGS = "-fomit-frame-pointer"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-fomit-frame-pointer"; ELSE PRINTNL GCC_OPTIMIZATION_LEVEL = 0; //PRINTNL GCC_ENABLE_FIX_AND_CONTINUE = YES; ENDIF IF %(ASMFLAGS)!="" PRINTNL NASM_OTHER_FLAGS = "%(ASMFLAGS)"; ENDIF IF %(DEFINE) || %(DEFINE_DEBUG) PRINTNL GCC_PREPROCESSOR_DEFINITIONS = ( FOR EACH DEFINE PRINTNL "%(NAME)", ENDFOR FOR EACH DEFINE_DEBUG PRINTNL "%(NAME)", ENDFOR PRINTNL ); ENDIF IF %(USE) || %(LIBS) || %(LIBS_DEBUG) || %(LIBINCLUDE) || %(LIBINCLUDE_DEBUG) || %(ABSLIBINCLUDE) || %(ABSLIBINCLUDE_DEBUG) PRINTNL OTHER_LDFLAGS = ( FOR EACH LIBINCLUDE PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH LIBINCLUDE_DEBUG PRINTNL "-L%(!;NAME)", ENDFOR FOR EACH ABSLIBINCLUDE PRINTNL "-L%(NAME)", ENDFOR FOR EACH ABSLIBINCLUDE_DEBUG PRINTNL "-L%(NAME)", ENDFOR IF (%(TYPE)!=LIB) FOR EACH USEBUILT PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS PRINTNL "-l%(NAME)", ENDFOR FOR EACH LIBS_DEBUG PRINTNL "-l%(NAME)", ENDFOR ENDIF PRINTNL ); ENDIF PRINTNL OBJROOT = %(!;§BUILDPATH); IF (%(TYPE)==EXE) && (%(PROJECT_PATH)!="") PRINTNL PRODUCT_NAME = %(PROJECT_PATH); ELSE PRINTNL PRODUCT_NAME = %(NAME); ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); IF %(INCLUDE) || %(INCLUDE_DEBUG) || %(SYSINCLUDE) || %(ABSINCLUDE_DEBUG) || %(ABSINCLUDE) || %(CONFIG_INCLUDE) PRINTNL USER_HEADER_SEARCH_PATHS = "%(!;@INCLUDE:%=% )%(!;@INCLUDE_DEBUG:%=% )%(!;@SYSINCLUDE:%=% )%(ABSINCLUDE_DEBUG:%=% )%(ABSINCLUDE:%=% )%(!;@CONFIG_INCLUDE:%=% )"; ENDIF IF %(HAS_REZ) PRINTNL OTHER_REZFLAGS = "-d ppc_$(ppc) -d i386_$(i386)"; ENDIF IF (%(TYPE)==EXE) || (%(TYPE)==DLL) IF %(OSX_DLL_TYPE)=="Bundle" PRINTNL WRAPPER_EXTENSION = component; ENDIF PRINTNL INFOPLIST_FILE = %(NAME).plist; ENDIF IF %(PRECOMPILED_HEADER) PRINTNL GCC_PREFIX_HEADER = "%(!;PATH)%(PRECOMPILED_HEADER)"; PRINTNL GCC_PRECOMPILE_PREFIX_HEADER = YES; ENDIF PRINTNL }; PRINTNL name = "Debug i386"; PRINTNL }; ENDIF ENDFOR IFDEF OSX_UNIVERSAL PRINTNL 00277BB40B5E830800EA36F7 /* Debug other */ = { ELSE PRINTNL 00277BB40B5E830800EA36F7 /* Debug */ = { ENDIF PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { IF %(ARCHS) PRINTNL ARCHS = %(ARCHS); ELSE IFDEF IX86_64 PRINTNL ARCHS = "$(ARCHS_STANDARD_64_BIT)"; ELSE PRINTNL ARCHS = ppc; ENDIF ENDIF // PRINTNL BUILD_VARIANTS = debug; PRINTNL GCC_MODEL_TUNING = G5; PRINTNL COPY_PHASE_STRIP = NO; IFNDEF XCODE4 PRINTNL GCC_ALTIVEC_EXTENSIONS = YES; ENDIF PRINTNL GCC_WARN_ABOUT_RETURN_TYPE = YES; PRINTNL GCC_WARN_UNUSED_VARIABLE = YES; PRINTNL GCC_VERSION = "%(GCC_VERSION)"; PRINTNL ONLY_LINK_ESSENTIAL_SYMBOLS = YES; // PRINTNL ZERO_LINK = YES; IFDEF OSX_UNIVERSAL PRINTNL PREBINDING = NO; ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); PRINTNL OBJROOT = %(!;§BUILDPATH); IFDEF OSX_UNIVERSAL IFDEF XCODE4 PRINTNL OTHER_CFLAGS = "-force_cpusubtype_ALL"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-force_cpusubtype_ALL"; ELSE PRINTNL OTHER_CFLAGS = "-force_cpusubtype_ALL -maltivec"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-force_cpusubtype_ALL -maltivec"; ENDIF ENDIF IF %(ASMFLAGS)!="" PRINTNL NASM_OTHER_FLAGS = "%(ASMFLAGS)"; ENDIF IF %(SDK) PRINTNL SDKROOT = %(SDK); ENDIF IF %(DEVICEFAMILY) PRINTNL TARGETED_DEVICE_FAMILY = %(DEVICEFAMILY); ENDIF IF %(SDK_PATH) PRINTNL USER_HEADER_SEARCH_PATHS = %(SDK_PATH)/include; ENDIF IF %(CC_PREFIX) PRINTNL CC = "%(CC_PREFIX)gcc"; PRINTNL CXX = "%(CC_PREFIX)gcc"; PRINTNL LD = "%(CC_PREFIX)gcc"; PRINTNL STRIP = "%(CC_PREFIX)strip"; ENDIF IF %(FRAMEWORK_PATH) || %(HAS_PRIVATE_FRAMEWORK) PRINTNL FRAMEWORK_SEARCH_PATHS = ( PRINTNL "$(inherited)", IF %(FRAMEWORK_PATH) PRINTNL %(FRAMEWORK_PATH), ENDIF IF %(HAS_PRIVATE_FRAMEWORK) PRINTNL "\"$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks\"", ENDIF PRINTNL ); ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL IFDEF IX86_64 PRINTNL name = "Debug x86_64"; ELSE PRINTNL name = "Debug ppc"; ENDIF ELSE PRINTNL name = Debug; ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL PRINTNL 00177BB40B5E830800EA36F7 /* Debug i386 */ = { PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { IF %(ARCHS) PRINTNL ARCHS = %(ARCHS); ELSE PRINTNL ARCHS = i386; ENDIF // PRINTNL BUILD_VARIANTS = debug; PRINTNL GCC_MODEL_TUNING = G5; PRINTNL COPY_PHASE_STRIP = NO; IFNDEF XCODE4 PRINTNL GCC_ALTIVEC_EXTENSIONS = YES; ENDIF PRINTNL GCC_WARN_ABOUT_RETURN_TYPE = YES; PRINTNL GCC_WARN_UNUSED_VARIABLE = YES; PRINTNL GCC_VERSION = "%(GCC_VERSION)"; PRINTNL ONLY_LINK_ESSENTIAL_SYMBOLS = YES; // PRINTNL ZERO_LINK = YES; IFDEF OSX_UNIVERSAL PRINTNL PREBINDING = NO; ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); PRINTNL OBJROOT = %(!;§BUILDPATH); PRINTNL OTHER_CFLAGS = "-force_cpusubtype_ALL"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-force_cpusubtype_ALL"; IF %(ASMFLAGS)!="" PRINTNL NASM_OTHER_FLAGS = "%(ASMFLAGS)"; ENDIF IFNDEF XCODE4 PRINTNL SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk; ENDIF IF %(SDK_PATH) PRINTNL USER_HEADER_SEARCH_PATHS = %(SDK_PATH)/include; ENDIF IF %(CC_PREFIX) PRINTNL CC = "%(CC_PREFIX)gcc"; PRINTNL CXX = "%(CC_PREFIX)gcc"; PRINTNL LD = "%(CC_PREFIX)gcc"; PRINTNL STRIP = "%(CC_PREFIX)strip"; ENDIF IF %(FRAMEWORK_PATH) || %(HAS_PRIVATE_FRAMEWORK) PRINTNL FRAMEWORK_SEARCH_PATHS = ( PRINTNL "$(inherited)", IF %(FRAMEWORK_PATH) PRINTNL %(FRAMEWORK_PATH), ENDIF IF %(HAS_PRIVATE_FRAMEWORK) PRINTNL "\"$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks\"", ENDIF PRINTNL ); ENDIF PRINTNL }; PRINTNL name = "Debug i386"; PRINTNL }; ENDIF IFDEF OSX_UNIVERSAL PRINTNL 00377BB50B5E830800EA36F7 /* Release Universal */ = { ELSE PRINTNL 00377BB50B5E830800EA36F7 /* Release */ = { ENDIF PRINTNL isa = XCBuildConfiguration; PRINTNL buildSettings = { IF %(ARCHS) PRINTNL ARCHS = %(ARCHS); ELSE IFDEF OSX_UNIVERSAL IFDEF IX86_64 PRINTNL ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; ELSE PRINTNL ARCHS = ( PRINTNL i386, PRINTNL ppc, PRINTNL ); ENDIF ELSE PRINTNL ARCHS = ppc; ENDIF ENDIF PRINTNL GCC_GENERATE_DEBUGGING_SYMBOLS = NO; PRINTNL GCC_SYMBOLS_PRIVATE_EXTERN = YES; PRINTNL GCC_MODEL_TUNING = G5; // PRINTNL COPY_PHASE_STRIP = YES; PRINTNL DEPLOYMENT_POSTPROCESSING = YES; IFNDEF XCODE4 PRINTNL GCC_ALTIVEC_EXTENSIONS = YES; ENDIF PRINTNL GCC_WARN_ABOUT_RETURN_TYPE = YES; PRINTNL GCC_WARN_UNUSED_VARIABLE = YES; PRINTNL GCC_VERSION = "%(GCC_VERSION)"; PRINTNL DEAD_CODE_STRIPPING = YES; // PRINTNL ZERO_LINK = YES; IFDEF OSX_UNIVERSAL PRINTNL PREBINDING = NO; ENDIF PRINTNL SYMROOT = %(¯!;§OUTPUTPATH); PRINTNL OBJROOT = %(!;§BUILDPATH); // PRINTNL OTHER_CFLAGS = "-force_cpusubtype_ALL -maltivec"; // PRINTNL OTHER_CPLUSPLUSFLAGS = "-force_cpusubtype_ALL -maltivec"; PRINTNL OTHER_CFLAGS = "-force_cpusubtype_ALL"; PRINTNL OTHER_CPLUSPLUSFLAGS = "-force_cpusubtype_ALL"; IF %(ASMFLAGS)!="" PRINTNL NASM_OTHER_FLAGS = "%(ASMFLAGS)"; ENDIF IF %(SDK) PRINTNL SDKROOT = %(SDK); ENDIF IF %(DEVICEFAMILY) PRINTNL TARGETED_DEVICE_FAMILY = %(DEVICEFAMILY); ENDIF IF %(SDK_PATH) PRINTNL USER_HEADER_SEARCH_PATHS = %(SDK_PATH)/include; ENDIF IF %(CC_PREFIX) PRINTNL CC = "%(CC_PREFIX)gcc"; PRINTNL CXX = "%(CC_PREFIX)gcc"; PRINTNL LD = "%(CC_PREFIX)gcc"; PRINTNL STRIP = "%(CC_PREFIX)strip"; ENDIF IF %(FRAMEWORK_PATH) || %(HAS_PRIVATE_FRAMEWORK) PRINTNL FRAMEWORK_SEARCH_PATHS = ( PRINTNL "$(inherited)", IF %(FRAMEWORK_PATH) PRINTNL %(FRAMEWORK_PATH), ENDIF IF %(HAS_PRIVATE_FRAMEWORK) PRINTNL "\"$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks\"", ENDIF PRINTNL ); ENDIF PRINTNL }; IFDEF OSX_UNIVERSAL PRINTNL name = "Release Universal"; ELSE PRINTNL name = "Release"; ENDIF PRINTNL }; PRINTNL /* End XCBuildConfiguration section */ PRINTNL PRINTNL /* Begin XCConfigurationList section */ FOR EACH USE PRINTNL %(XCODEGRPUID5) /* Build configuration list for PBXNativeTarget "%(NAME)" */ = { PRINTNL isa = XCConfigurationList; PRINTNL buildConfigurations = ( IFDEF OSX_UNIVERSAL PRINTNL %(_XCODEGRPUID4) /* Release Universal */, PRINTNL %(XCODEGRPUID4) /* Debug other */, PRINTNL %(_XCODEGRPUID8) /* Debug i386 */, ELSE PRINTNL %(_XCODEGRPUID4) /* Release */, PRINTNL %(XCODEGRPUID4) /* Debug */, ENDIF PRINTNL ); PRINTNL defaultConfigurationIsVisible = 0; IFDEF OSX_UNIVERSAL PRINTNL defaultConfigurationName = "Release Universal"; ELSE PRINTNL defaultConfigurationName = Release; ENDIF PRINTNL }; ENDFOR IFDEF USE_MAKEFILE PRINTNL D92591D40C6B42CE00BBDBBC /* Build configuration list for PBXLegacyTarget "%(NAME)" */ = { ELSE PRINTNL AA277BB30B5E830800EA36F7 /* Build configuration list for PBXProject "%(NAME)" */ = { ENDIF PRINTNL isa = XCConfigurationList; PRINTNL buildConfigurations = ( IFDEF OSX_UNIVERSAL PRINTNL 00377BB50B5E830800EA36F7 /* Release Universal */, PRINTNL 00177BB40B5E830800EA36F7 /* Debug i386 */, PRINTNL 00277BB40B5E830800EA36F7 /* Debug other */, ELSE PRINTNL 00377BB50B5E830800EA36F7 /* Release */, PRINTNL 00277BB40B5E830800EA36F7 /* Debug */, ENDIF PRINTNL ); PRINTNL defaultConfigurationIsVisible = 0; IFDEF OSX_UNIVERSAL PRINTNL defaultConfigurationName = "Release Universal"; ELSE PRINTNL defaultConfigurationName = Release; ENDIF PRINTNL }; PRINTNL /* End XCConfigurationList section */ PRINTNL }; PRINTNL rootObject = 91B15E841AA80083484172DE /* Project object */; PRINTNL } ENDFOR bcmatroska2-5.3.101/corec/tools/coremake/xcode24_universal.build000066400000000000000000000002561462133141200244730ustar00rootroot00000000000000#define OSX_UNIVERSAL #define IX86 #define POWERPC SDK = /Developer/SDKs/MacOSX10.4u.sdk FRAMEWORK_PATH = / GCC_VERSION = 4.0 XCODECOMPATVERSION = 2.4 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode4.build000066400000000000000000000003071462133141200223160ustar00rootroot00000000000000#define OSX_UNIVERSAL #define IX86 #define IX86_64 #define XCODE4 SDK = macosx10.6 FRAMEWORK_PATH = / GCC_VERSION = com.apple.compilers.llvm.clang.1_0 XCODECOMPATVERSION = 3.2 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_ios4.build000066400000000000000000000004301462133141200231650ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define TARGET_IPHONE_DEVICE #define ARM #define TARGET_ALWAYS_STATIC SDK = iphoneos4.1 IOSDEPLOYMENTTARGET = 3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 ARCHS = "$(ARCHS_STANDARD_32_BIT)" DEVICEFAMILY = 1 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_ios4_simu.build000066400000000000000000000004031462133141200242220ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define IX86 #define TARGET_ALWAYS_STATIC SDK = iphonesimulator4.1 IOSDEPLOYMENTTARGET = 3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 ARCHS = "$(ARCHS_STANDARD_32_BIT)" DEVICEFAMILY = 1 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_ipad_simu.build000066400000000000000000000004071462133141200242650ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define IX86 #define TARGET_ALWAYS_STATIC SDK = iphonesimulator3.2 IOSDEPLOYMENTTARGET = 3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 ARCHS = "$(ARCHS_STANDARD_32_BIT)" DEVICEFAMILY = "1,2" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_iphone.build000066400000000000000000000003551462133141200235770ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define TARGET_IPHONE_DEVICE #define ARM #define TARGET_ALWAYS_STATIC SDK = iphoneos3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.1 ARCHS = "$(ARCHS_STANDARD_32_BIT)" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_iphone_dev.build000066400000000000000000000006171462133141200244360ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_DEV #define ARM // dummy SDK location //SDK = /Developer/SDKs/iPhone.sdk SDK_PATH = /usr/local/arm-apple-darwin CC_PREFIX = /usr/local/bin/arm-apple-darwin- FRAMEWORK_PATH = /usr/local/share/iphone-filesystem/ ARCHS = arm #define USE_MAKEFILE CCFLAGS=%(CCFLAGS) -DTARGET_IPHONE -DTARGET_IPHONE_DEV -DARM -arch arm -mdynamic-no-pic #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_iphone_ipad.build000066400000000000000000000004341462133141200245720ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define TARGET_IPHONE_DEVICE #define ARM #define TARGET_ALWAYS_STATIC SDK = iphoneos4.1 IOSDEPLOYMENTTARGET = 3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 ARCHS = "$(ARCHS_STANDARD_32_BIT)" DEVICEFAMILY = "1,2" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_iphone_simulator.build000066400000000000000000000003301462133141200256670ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define IX86 #define TARGET_ALWAYS_STATIC SDK = iphonesimulator3.0 XCODECOMPATVERSION = 3.1 GCC_VERSION = 4.2 ARCHS = "$(ARCHS_STANDARD_32_BIT)" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_iphone_uni.build000066400000000000000000000003611462133141200244470ustar00rootroot00000000000000#define TARGET_IPHONE #define TARGET_IPHONE_SDK #define TARGET_IPHONE_DEVICE #define ARM #define TARGET_ALWAYS_STATIC SDK = iphoneos3.0 GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.1 ARCHS = "$(ARCHS_UNIVERSAL_IPHONE_OS)" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_uni.build000066400000000000000000000002561462133141200231100ustar00rootroot00000000000000#define OSX_UNIVERSAL #define IX86 #define POWERPC SDK = /Developer/SDKs/MacOSX10.4u.sdk FRAMEWORK_PATH = / GCC_VERSION = 4.0 XCODECOMPATVERSION = 3.1 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_uni64.build000066400000000000000000000002511462133141200232550ustar00rootroot00000000000000#define OSX_UNIVERSAL #define IX86 #define IX86_64 #define POWERPC SDK = macosx10.5 FRAMEWORK_PATH = / GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_x86.build000066400000000000000000000002021462133141200227310ustar00rootroot00000000000000#define IX86 SDK = macosx10.5 FRAMEWORK_PATH = / GCC_VERSION = 4.2 XCODECOMPATVERSION = 3.2 ARCHS = "i386" #include "xcode.inc" bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/000077500000000000000000000000001462133141200222425ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/000077500000000000000000000000001462133141200243325ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/English.lproj/000077500000000000000000000000001462133141200270505ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/English.lproj/InfoPlist.strings000066400000000000000000000001341462133141200323700ustar00rootroot00000000000000ÿþ/* Localized versions of Info.plist keys */ bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/Info.plist000066400000000000000000000015331462133141200263040ustar00rootroot00000000000000 CFBundleDevelopmentRegion English CFBundleExecutable ${EXECUTABLE_NAME} CFBundleName ${PRODUCT_NAME} CFBundleIconFile CFBundleIdentifier com.corecodec.yasm CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType BNDL CFBundleSignature ???? CFBundleVersion 1.0 NSPrincipalClass XCPluginHasUI NO LoadAtLaunch YES bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/YasmPlugin.xcodeproj/000077500000000000000000000000001462133141200304165ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/YasmPlugin.xcodeproj/project.pbxproj000066400000000000000000000246021462133141200334760ustar00rootroot00000000000000// !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 45; objects = { /* Begin PBXBuildFile section */ 8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C167DFE841241C02AAC07 /* InfoPlist.strings */; }; 8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */; }; C5314B7510DF08EE00ADF655 /* yasm.xcspec in Resources */ = {isa = PBXBuildFile; fileRef = C5314B7410DF08EE00ADF655 /* yasm.xcspec */; }; C5BD289C10D6B01100DB31A3 /* yasm.pbfilespec in Resources */ = {isa = PBXBuildFile; fileRef = C5BD289910D6B01100DB31A3 /* yasm.pbfilespec */; }; C5BD289D10D6B01100DB31A3 /* yasm.xcbuildrules in Resources */ = {isa = PBXBuildFile; fileRef = C5BD289A10D6B01100DB31A3 /* yasm.xcbuildrules */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 089C1672FE841209C02AAC07 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = ""; }; 089C167EFE841241C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; }; 089C167FFE841241C02AAC07 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = ""; }; 32DBCF630370AF2F00C91783 /* GasPP_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GasPP_Prefix.pch; sourceTree = ""; }; 8D5B49B6048680CD000E48DA /* Yasm.xcplugin */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Yasm.xcplugin; sourceTree = BUILT_PRODUCTS_DIR; }; 8D5B49B7048680CD000E48DA /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C5314B7410DF08EE00ADF655 /* yasm.xcspec */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xcspec; path = yasm.xcspec; sourceTree = ""; }; C5BD289910D6B01100DB31A3 /* yasm.pbfilespec */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.pbfilespec; path = yasm.pbfilespec; sourceTree = ""; }; C5BD289A10D6B01100DB31A3 /* yasm.xcbuildrules */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = yasm.xcbuildrules; sourceTree = ""; }; D2F7E65807B2D6F200F64583 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = /System/Library/Frameworks/CoreData.framework; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 8D5B49B3048680CD000E48DA /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 089C166AFE841209C02AAC07 /* ArmAppleDarwin */ = { isa = PBXGroup; children = ( 08FB77AFFE84173DC02AAC07 /* Classes */, 32C88E010371C26100C91783 /* Other Sources */, 089C167CFE841241C02AAC07 /* Resources */, 089C1671FE841209C02AAC07 /* Frameworks and Libraries */, 19C28FB8FE9D52D311CA2CBB /* Products */, ); name = ArmAppleDarwin; sourceTree = ""; }; 089C1671FE841209C02AAC07 /* Frameworks and Libraries */ = { isa = PBXGroup; children = ( 1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */, 1058C7AEFEA557BF11CA2CBB /* Other Frameworks */, ); name = "Frameworks and Libraries"; sourceTree = ""; }; 089C167CFE841241C02AAC07 /* Resources */ = { isa = PBXGroup; children = ( C5BD289910D6B01100DB31A3 /* yasm.pbfilespec */, C5BD289A10D6B01100DB31A3 /* yasm.xcbuildrules */, 8D5B49B7048680CD000E48DA /* Info.plist */, 089C167DFE841241C02AAC07 /* InfoPlist.strings */, C5314B7410DF08EE00ADF655 /* yasm.xcspec */, ); name = Resources; sourceTree = ""; }; 08FB77AFFE84173DC02AAC07 /* Classes */ = { isa = PBXGroup; children = ( ); name = Classes; sourceTree = ""; }; 1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */ = { isa = PBXGroup; children = ( 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */, ); name = "Linked Frameworks"; sourceTree = ""; }; 1058C7AEFEA557BF11CA2CBB /* Other Frameworks */ = { isa = PBXGroup; children = ( 089C167FFE841241C02AAC07 /* AppKit.framework */, D2F7E65807B2D6F200F64583 /* CoreData.framework */, 089C1672FE841209C02AAC07 /* Foundation.framework */, ); name = "Other Frameworks"; sourceTree = ""; }; 19C28FB8FE9D52D311CA2CBB /* Products */ = { isa = PBXGroup; children = ( 8D5B49B6048680CD000E48DA /* Yasm.xcplugin */, ); name = Products; sourceTree = ""; }; 32C88E010371C26100C91783 /* Other Sources */ = { isa = PBXGroup; children = ( 32DBCF630370AF2F00C91783 /* GasPP_Prefix.pch */, ); name = "Other Sources"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 8D5B49AC048680CD000E48DA /* GasPreprocessor */ = { isa = PBXNativeTarget; buildConfigurationList = 1DEB913A08733D840010E9CD /* Build configuration list for PBXNativeTarget "GasPreprocessor" */; buildPhases = ( 8D5B49AF048680CD000E48DA /* Resources */, 8D5B49B1048680CD000E48DA /* Sources */, 8D5B49B3048680CD000E48DA /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = GasPreprocessor; productInstallPath = "$(HOME)/Library/Bundles"; productName = ArmAppleDarwin; productReference = 8D5B49B6048680CD000E48DA /* Yasm.xcplugin */; productType = "com.apple.product-type.bundle"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 089C1669FE841209C02AAC07 /* Project object */ = { isa = PBXProject; buildConfigurationList = 1DEB913E08733D840010E9CD /* Build configuration list for PBXProject "YasmPlugin" */; compatibilityVersion = "Xcode 3.1"; hasScannedForEncodings = 1; mainGroup = 089C166AFE841209C02AAC07 /* ArmAppleDarwin */; projectDirPath = ""; projectRoot = ""; targets = ( 8D5B49AC048680CD000E48DA /* GasPreprocessor */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 8D5B49AF048680CD000E48DA /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */, C5BD289C10D6B01100DB31A3 /* yasm.pbfilespec in Resources */, C5BD289D10D6B01100DB31A3 /* yasm.xcbuildrules in Resources */, C5314B7510DF08EE00ADF655 /* yasm.xcspec in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 8D5B49B1048680CD000E48DA /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 089C167DFE841241C02AAC07 /* InfoPlist.strings */ = { isa = PBXVariantGroup; children = ( 089C167EFE841241C02AAC07 /* English */, ); name = InfoPlist.strings; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 1DEB913B08733D840010E9CD /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; COPY_PHASE_STRIP = NO; GCC_DYNAMIC_NO_PIC = NO; GCC_ENABLE_FIX_AND_CONTINUE = YES; GCC_MODEL_TUNING = G5; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = ArmAppleDarwin_Prefix.pch; INFOPLIST_FILE = Info.plist; INSTALL_PATH = "$(HOME)/Library/Bundles"; PRODUCT_NAME = Yasm; WRAPPER_EXTENSION = xcplugin; }; name = Debug; }; 1DEB913C08733D840010E9CD /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_MODEL_TUNING = G5; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = ArmAppleDarwin_Prefix.pch; INFOPLIST_FILE = Info.plist; INSTALL_PATH = "$(HOME)/Library/Bundles"; PRODUCT_NAME = Yasm; WRAPPER_EXTENSION = xcplugin; }; name = Release; }; 1DEB913F08733D840010E9CD /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; ARCHS = "$(ARCHS_STANDARD_32_BIT)"; GCC_C_LANGUAGE_STANDARD = c99; GCC_OPTIMIZATION_LEVEL = 0; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; ONLY_ACTIVE_ARCH = YES; PREBINDING = NO; SDKROOT = macosx10.5; }; name = Debug; }; 1DEB914008733D840010E9CD /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; ARCHS = "$(ARCHS_STANDARD_32_BIT)"; GCC_C_LANGUAGE_STANDARD = c99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; PREBINDING = NO; SDKROOT = macosx10.5; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 1DEB913A08733D840010E9CD /* Build configuration list for PBXNativeTarget "GasPreprocessor" */ = { isa = XCConfigurationList; buildConfigurations = ( 1DEB913B08733D840010E9CD /* Debug */, 1DEB913C08733D840010E9CD /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 1DEB913E08733D840010E9CD /* Build configuration list for PBXProject "YasmPlugin" */ = { isa = XCConfigurationList; buildConfigurations = ( 1DEB913F08733D840010E9CD /* Debug */, 1DEB914008733D840010E9CD /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 089C1669FE841209C02AAC07 /* Project object */; } bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/YasmPlugin_Prefix.pch000066400000000000000000000002401462133141200304270ustar00rootroot00000000000000// // Prefix header for all source files of the 'ArmAppleDarwin' target in the 'ArmAppleDarwin' project. // #ifdef __OBJC__ #import #endif bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/yasm.pbfilespec000066400000000000000000000004061462133141200273410ustar00rootroot00000000000000( { Identifier = sourcecode.yasm; BasedOn = sourcecode; Extensions = (yasm); Name = "Yasm assembly files"; ComputerLanguage = asm.i386; Language = "xcode.lang.asm.i386"; AppliesToBuildRules = yes; }, )bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/yasm.xcbuildrules000066400000000000000000000001771462133141200277370ustar00rootroot00000000000000 ( { Name = "Yasm Assembler Source Rule"; FileType = "sourcecode.yasm"; CompilerSpec = "com.corecodec.compilers.yasm"; } )bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPlugin/yasm.xcspec000066400000000000000000000024731462133141200265200ustar00rootroot00000000000000{ Type = Compiler; Identifier = "com.corecodec.compilers.yasm"; Name = Yasm; Vendor = C0R3; Description = "Assemble Using Yasm"; CommandLine = "/usr/local/coremake/bin/yasm $(InputFile) [options] -o $(ObjectsDir)/$(InputFileBase)$(InputFileBaseUniquefier).o"; RuleName = "Yasm $(ObjectsDir)/$(InputFileBase)$(InputFileBaseUniquefier).o $(InputFile)"; ExecDescription = "Assemble $(InputFile)"; Architectures = ( i386, ); Languages = ( "asm.i386", ); InputFileTypes = ( "sourcecode.yasm", ); SynthesizeBuildRule = Yes; Outputs = ( "$(ObjectsDir)/$(InputFileBase)$(InputFileBaseUniquefier).o", ); CommandOutputParser = "XCGccCommandOutputParser"; Options = ( { Name = "NASM_OUTPUT_FILE_FORMAT"; Type = String; DefaultValue = macho; "CommandLinePrefixFlag" = "-f"; }, { Name = "NASM_PREINCLUDE_FILE"; Type = String; Category = BuildOptions; DefaultValue = ""; CommandLineFlag = "-P"; }, { Name = "HEADER_SEARCH_PATHS"; Type = PathList; DefaultValue = ""; "CommandLinePrefixFlag" = "-I"; }, { Name = "NASM_OTHER_FLAGS"; Type = StringList; Category = BuildOptions; DefaultValue = ""; "CommandLinePrefixFlag" = ""; }, { Name = "build_file_compiler_flags"; Type = StringList; DefaultValue = ""; "CommandLinePrefixFlag" = ""; }, ); }bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPluginInstaller.pmdoc/000077500000000000000000000000001462133141200273115ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPluginInstaller.pmdoc/01base-contents.xml000066400000000000000000000020471462133141200327440ustar00rootroot00000000000000bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPluginInstaller.pmdoc/01base.xml000066400000000000000000000014221462133141200311050ustar00rootroot00000000000000com.coremake.yasmplugin.base.pkg1.0base/relocatableinstallFrom.isRelativeTypeparent01base-contents.xml/CVS$/\.svn$/\.cvsignore$/\.cvspass$/\.DS_Store$bcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/YasmPluginInstaller.pmdoc/index.xml000066400000000000000000000010471462133141200311440ustar00rootroot00000000000000com.coremake.yasmplugin01base.xmlbcmatroska2-5.3.101/corec/tools/coremake/xcode_yasm/build-yasm-plugin.sh000066400000000000000000000012601462133141200261370ustar00rootroot00000000000000#!/bin/sh curl -O http://www.tortall.net/projects/yasm/releases/yasm-1.0.1.tar.gz tar -xvzf yasm-1.0.1.tar.gz pushd yasm-1.0.1 ./configure make popd # make a directory location for yasm to reside mkdir -p base/usr/local/coremake/bin #copy yasm to destination directory cp yasm-1.0.1/yasm base/usr/local/coremake/bin/ #build the Xcode plugin pushd YasmPlugin xcodebuild -configuration "Release" build popd mkdir -p base/Developer/Library/Xcode/Plug-ins cp -R YasmPlugin/build/Release/Yasm.xcplugin base/Developer/Library/Xcode/Plug-ins #make the package /Developer/usr/bin/packagemaker -v --doc "YasmPluginInstaller.pmdoc" -o YasmPlugin.pkg --target 10.5 -i com.CoreCodec.yasmplugin;bcmatroska2-5.3.101/corec/tools/tools.proj000066400000000000000000000000241462133141200203510ustar00rootroot00000000000000#include "*/*.proj" bcmatroska2-5.3.101/libebml2/000077500000000000000000000000001462133141200155565ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/CMakeLists.txt000066400000000000000000000025031462133141200203160ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2016 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ add_library(bcmatroska2-ebml-objects OBJECT ebmlmain.c ebmlelement.c ebmlmaster.c ebmlbinary.c ebmlstring.c ebmlnumber.c ebmlcrc.c ebmldate.c ebmlvoid.c ) set_target_properties(bcmatroska2-ebml-objects PROPERTIES POSITION_INDEPENDENT_CODE TRUE) install(DIRECTORY ebml DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) bcmatroska2-5.3.101/libebml2/ebml/000077500000000000000000000000001462133141200164755ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/ebml/ebml.h000066400000000000000000000313011462133141200175630ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBEBML2_H #define LIBEBML2_H #include "corec/node/node.h" #include "corec/helpers/file/file.h" #if defined(CONFIG_EBML_UNICODE) #include "corec/helpers/parser/parser.h" #endif #ifdef __cplusplus extern "C" { #endif #define CONTEXT_LIBEBML_VERSION 0x400 #define EBML_MAX_VERSION 1 #define EBML_MAX_ID 4 #define EBML_MAX_SIZE 8 #define SCOPE_PARTIAL_DATA 0 // read all data, except inside some binary elements (useful for binary data with a (internal) header) #define SCOPE_ALL_DATA 1 #define SCOPE_NO_DATA 2 // base classes #define EBML_ELEMENT_CLASS FOURCC('E','B','E','L') #define EBML_BINARY_CLASS FOURCC('E','B','I','N') #define EBML_DATE_CLASS FOURCC('E','B','D','T') #define EBML_INTEGER_CLASS FOURCC('E','B','I','T') #define EBML_SINTEGER_CLASS FOURCC('E','B','S','I') #define EBML_FLOAT_CLASS FOURCC('E','B','F','L') #define EBML_MASTER_CLASS FOURCC('E','B','M','T') #define EBML_STRING_CLASS FOURCC('E','B','S','G') #define EBML_UNISTRING_CLASS FOURCC('E','B','S','U') #define EBML_BOOLEAN_CLASS FOURCC('E','B','B','O') // global classes #define EBML_CRC_CLASS FOURCC('E','B','C','R') #define EBML_VOID_CLASS FOURCC('E','B','V','D') #define EBML_DUMMY_ID FOURCC('E','B','D','U') #define EBML_ELEMENT_INFINITESIZE 0x100 #define EBML_ELEMENT_OBJECT 0x101 #if defined(EBML2_EXPORTS) #define EBML_DLL DLLEXPORT #elif defined(EBML2_IMPORTS) #define EBML_DLL DLLIMPORT #else #define EBML_DLL #endif typedef struct ebml_context ebml_context; typedef struct ebml_parser_context ebml_parser_context; typedef struct ebml_semantic ebml_semantic; typedef struct ebml_element ebml_element; typedef struct ebml_crc ebml_crc; typedef struct ebml_master ebml_master; typedef struct ebml_integer ebml_integer; typedef struct ebml_string ebml_string; typedef struct ebml_binary ebml_binary; typedef struct ebml_integer ebml_date; typedef struct ebml_float ebml_float; typedef struct ebml_dummy ebml_dummy; struct ebml_semantic { bool_t Mandatory; bool_t Unique; const ebml_context *eClass; int DisabledProfile; // PROFILE_MATROSKA_V1 and others }; struct ebml_parser_context { const ebml_context *Context; const ebml_parser_context *UpContext; filepos_t EndPosition; int Profile; }; typedef struct ebml_element_vmt { nodetree_vmt Base; bool_t (*ValidateSize)(const void*); err_t (*ReadData)(void*, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC); #if defined(CONFIG_EBML_WRITING) err_t (*RenderData)(void*, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered); #endif bool_t (*IsDefaultValue)(const void*); bool_t (*DefaultIsSet)(const void*); filepos_t (*UpdateDataSize)(void*, bool_t bWithDefault, bool_t bForceWithoutMandatory); bool_t (*NeedsDataSizeUpdate)(const void*, bool_t bWithDefault); int (*Cmp)(const void*, const void*); ebml_element *(*Copy)(const void*, const void *Cookie); // internal call only void (*PostCreate)(void*, bool_t SetDefault); } ebml_element_vmt; #define EBML_ElementValidateSize(p) VMT_FUNC(p,ebml_element_vmt)->ValidateSize(p) #define EBML_ElementReadData(p,i,c,d,s,r) VMT_FUNC(p,ebml_element_vmt)->ReadData(p,i,c,d,s,r) #define EBML_ElementRenderData(p,s,f,k,r) VMT_FUNC(p,ebml_element_vmt)->RenderData(p,s,f,k,r) #define EBML_ElementIsDefaultValue(p) VMT_FUNC(p,ebml_element_vmt)->IsDefaultValue(p) #define EBML_ElementUpdateSize(p,k,f) VMT_FUNC(p,ebml_element_vmt)->UpdateDataSize(p,k,f) #define EBML_ElementNeedsDataSizeUpdate(p,d) VMT_FUNC(p,ebml_element_vmt)->NeedsDataSizeUpdate(p,d) #define EBML_ElementCmp(p,e) VMT_FUNC(p,ebml_element_vmt)->Cmp(p,e) #define EBML_ElementCopy(p,c) VMT_FUNC(p,ebml_element_vmt)->Copy(p,c) EBML_DLL err_t EBML_Init(nodecontext *p); EBML_DLL err_t EBML_Done(nodecontext *p); EBML_DLL ebml_element *EBML_ElementCreate(anynode *Any, const ebml_context *Context, bool_t SetDefault, const void *Cookie); EBML_DLL ebml_element *EBML_FindNextId(stream *Input, const ebml_context *Context, size_t MaxDataSize); EBML_DLL ebml_element *EBML_FindNextElement(stream *Input, const ebml_parser_context *Context, int *UpperLevels, bool_t AllowDummy); EBML_DLL uint8_t EBML_CodedSizeLength(filepos_t Length, uint8_t SizeLength, bool_t bSizeIsFinite); // TODO: turn into a macro ? EBML_DLL uint8_t EBML_CodedSizeLengthSigned(filepos_t Length, uint8_t SizeLength); // TODO: turn into a macro ? EBML_DLL uint8_t EBML_CodedValueLength(filepos_t Length, size_t CodedSize, uint8_t *OutBuffer, bool_t bSizeIsFinite); // TODO: turn into a macro ? EBML_DLL uint8_t EBML_CodedValueLengthSigned(filepos_t Length, size_t CodedSize, uint8_t * OutBuffer); // TODO: turn into a macro ? EBML_DLL filepos_t EBML_ReadCodedSizeValue(const uint8_t *InBuffer, size_t *BufferSize, filepos_t *SizeUnknown); EBML_DLL filepos_t EBML_ReadCodedSizeSignedValue(const uint8_t *InBuffer, size_t *BufferSize, filepos_t *SizeUnknown); EBML_DLL void EBML_ElementGetName(const ebml_element *Element, tchar_t *Out, size_t OutLen); EBML_DLL const char *EBML_ElementGetClassName(const ebml_element *Element); EBML_DLL const ebml_context *EBML_ElementContext(const ebml_element *Element); EBML_DLL ebml_element *EBML_ElementSkipData(ebml_element *Element, stream *Input, const ebml_parser_context *Context, ebml_element *TestReadElt, bool_t AllowDummy); EBML_DLL bool_t EBML_ElementIsFiniteSize(const ebml_element *Element); EBML_DLL void EBML_ElementSetInfiniteSize(const ebml_element *Element, bool_t Set); EBML_DLL bool_t EBML_ElementInfiniteForceSize(ebml_element *Element, filepos_t NewSize); EBML_DLL bool_t EBML_ElementIsDummy(const ebml_element *Element); EBML_DLL fourcc_t EBML_ElementClassID(const ebml_element *Element); EBML_DLL filepos_t EBML_ElementPosition(const ebml_element *Element); EBML_DLL filepos_t EBML_ElementPositionData(const ebml_element *Element); EBML_DLL filepos_t EBML_ElementPositionEnd(const ebml_element *Element); EBML_DLL void EBML_ElementForcePosition(ebml_element *Element, filepos_t Pos); EBML_DLL filepos_t EBML_ElementFullSize(const ebml_element *Element, bool_t bWithDefault); EBML_DLL filepos_t EBML_ElementDataSize(const ebml_element *Element, bool_t bWithDefault); EBML_DLL void EBML_ElementForceDataSize(ebml_element *Element, filepos_t Size); EBML_DLL uint8_t EBML_ElementSizeLength(const ebml_element *Element); EBML_DLL void EBML_ElementSetSizeLength(ebml_element *Element, uint8_t SizeLength); /// 0 (for auto) to EBML_MAX_SIZE EBML_DLL bool_t EBML_ElementIsType(const ebml_element *Element, const ebml_context *Context); #if defined(CONFIG_EBML_WRITING) // TODO: replace the list of bools by flags ? EBML_DLL err_t EBML_ElementRender(ebml_element *Element, stream *Output, bool_t bWithDefault, bool_t bKeepPosition, bool_t bForceWithoutMandatory, filepos_t *Rendered); EBML_DLL err_t EBML_ElementRenderHead(ebml_element *Element, stream *Output, bool_t bKeepPosition, filepos_t *Rendered); #endif // type specific routines EBML_DLL ebml_element *EBML_MasterFindFirstElt(ebml_master *Element, const ebml_context *Context, bool_t bCreateIfNull, bool_t SetDefault); EBML_DLL err_t EBML_MasterAppend(ebml_master *Element, ebml_element *Append); EBML_DLL err_t EBML_MasterRemove(ebml_master *Element, ebml_element *Remove); EBML_DLL ebml_element *EBML_MasterFindNextElt(ebml_master *Element, const ebml_element *Current, bool_t bCreateIfNull, bool_t SetDefault); EBML_DLL ebml_element *EBML_MasterAddElt(ebml_master *Element, const ebml_context *Context, bool_t SetDefault); EBML_DLL size_t EBML_MasterCount(const ebml_master *Element); EBML_DLL void EBML_MasterClear(ebml_master *Element); // clear the list (the children and not freed) EBML_DLL void EBML_MasterErase(ebml_master *Element); EBML_DLL void EBML_MasterAddMandatory(ebml_master *Element, bool_t SetDefault); // add the mandatory elements EBML_DLL bool_t EBML_MasterCheckMandatory(const ebml_master *Element, bool_t bWithDefault); EBML_DLL void EBML_MasterSort(ebml_master *Element, arraycmp Cmp, const void* CmpParam); EBML_DLL bool_t EBML_MasterUseChecksum(ebml_master *Element, bool_t Use); EBML_DLL bool_t EBML_MasterIsChecksumValid(const ebml_master *Element); #define EBML_MasterGetChild(e,c) EBML_MasterFindFirstElt(e,c,1,1) #define EBML_MasterFindChild(e,c) EBML_MasterFindFirstElt((ebml_master*)e,c,0,0) #define EBML_MasterNextChild(e,c) EBML_MasterFindNextElt((ebml_master*)e,(ebml_element*)c,0,0) #define EBML_MasterChildren(p) ((ebml_element*)NodeTree_Children(p)) #define EBML_MasterNext(p) ((ebml_element*)NodeTree_Next(p)) #define EBML_ElementParent(p) ((ebml_element*)NodeTree_Parent(p)) EBML_DLL int64_t EBML_IntegerValue(const ebml_integer *Element); EBML_DLL void EBML_IntegerSetValue(ebml_integer *Element, int64_t Value); EBML_DLL double EBML_FloatValue(const ebml_float *Element); EBML_DLL void EBML_FloatSetValue(ebml_float *Element, double Value); EBML_DLL err_t EBML_StringSetValue(ebml_string *Element,const char *Value); #if defined(CONFIG_EBML_UNICODE) EBML_DLL err_t EBML_UniStringSetValue(ebml_string *Element,const tchar_t *Value); #endif EBML_DLL void EBML_StringGet(ebml_string *Element,tchar_t *Out, size_t OutLen); EBML_DLL datetime_t EBML_DateTime(const ebml_date *Element); EBML_DLL err_t EBML_DateSetDateTime(ebml_date *Element, datetime_t Date); EBML_DLL err_t EBML_BinarySetData(ebml_binary *Element, const uint8_t *Data, size_t DataSize); EBML_DLL const uint8_t *EBML_BinaryGetData(ebml_binary *Element); #if defined(CONFIG_EBML_WRITING) EBML_DLL bool_t EBML_VoidSetFullSize(ebml_element *Void, filepos_t); EBML_DLL filepos_t EBML_VoidReplaceWith(ebml_element *Void, ebml_element *Replaced, stream *Output, bool_t ComeBackAfterward, bool_t bWithDefault); #endif EBML_DLL size_t EBML_FillBufferID(uint8_t *Buffer, size_t BufSize, fourcc_t Id); EBML_DLL size_t EBML_IdToString(tchar_t *Out, size_t OutLen, fourcc_t Id); EBML_DLL fourcc_t EBML_BufferToID(const uint8_t *Buffer); #define MASTER_CHECK_PROFILE_INVALID 0 #define MASTER_CHECK_MISSING_MANDATORY 1 #define MASTER_CHECK_MULTIPLE_UNIQUE 2 typedef bool_t (*ContextCallback)(void *cookie, int type, const tchar_t *ClassName, const ebml_element*); EBML_DLL void EBML_MasterCheckContext(ebml_master *Element, int ProfileMask, ContextCallback callback, void *cookie); #if defined(EBML_LEGACY_API) #define CONTEXT_CONST #else #define CONTEXT_CONST const #endif // EBML contexts extern CONTEXT_CONST ebml_context EBML_ContextHead; extern CONTEXT_CONST ebml_context EBML_ContextDummy; extern CONTEXT_CONST ebml_context EBML_ContextVersion; extern CONTEXT_CONST ebml_context EBML_ContextReadVersion; extern CONTEXT_CONST ebml_context EBML_ContextMaxIdLength; extern CONTEXT_CONST ebml_context EBML_ContextMaxSizeLength; extern CONTEXT_CONST ebml_context EBML_ContextDocType; extern CONTEXT_CONST ebml_context EBML_ContextDocTypeVersion; extern CONTEXT_CONST ebml_context EBML_ContextDocTypeReadVersion; extern CONTEXT_CONST ebml_context EBML_ContextEbmlVoid; extern CONTEXT_CONST ebml_context EBML_ContextEbmlCrc32; //extern const ebml_context EBML_ContextGlobals; extern const ebml_semantic EBML_SemanticGlobals[]; #ifdef __cplusplus } #endif #endif /* LIBEBML2_H */ bcmatroska2-5.3.101/libebml2/ebml/ebml_internal.h000066400000000000000000000063401462133141200214640ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBEBML2_INTERNAL_H #define LIBEBML2_INTERNAL_H /* * ONLY INCLUDE THIS FILE IF YOU PLAN TO CREATE YOUR OWN EBML-BASED CLASS */ #include "corec/node/node.h" #ifdef __cplusplus extern "C" { #endif INTERNAL_C_API size_t GetIdLength(fourcc_t Id); struct ebml_context { fourcc_t Id; fourcc_t Class; // TODO: store a pointer to make creation faster bool_t HasDefault; intptr_t DefaultValue; const char *ElementName; // TODO: create sub class so we don't have to assign it all the time const ebml_semantic *Semantic; // table with last element class set to NULL const ebml_semantic *GlobalContext; // table with last element class set to NULL void (*PostCreate)(ebml_element *p, const void *Cookie); }; struct ebml_element { nodetree Base; filepos_t DataSize; // size of the data inside the element filepos_t ElementPosition; filepos_t SizePosition; // TODO: is this needed since we have the ElementPosition and SizeLength ? const ebml_context *Context; int DefaultSize; int8_t SizeLength; boolmem_t bValueIsSet; boolmem_t bNeedDataSizeUpdate; }; struct ebml_master { ebml_element Base; int CheckSumStatus; // 0: not set, 1: requested/invalid, 2: verified }; struct ebml_string { ebml_element Base; const char *Buffer; // UTF-8 internal storage }; struct ebml_integer { ebml_element Base; int64_t Value; }; struct ebml_float { ebml_element Base; double Value; }; struct ebml_binary { ebml_element Base; array Data; }; struct ebml_dummy { ebml_binary Base; ebml_context DummyContext; }; #ifdef __cplusplus } #endif #endif /* LIBEBML2_INTERNAL_H */ bcmatroska2-5.3.101/libebml2/ebmlbinary.c000066400000000000000000000122021462133141200200430ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" static err_t ReadData(ebml_binary *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } if (!ArrayResize(&Element->Data,(size_t)Element->Base.DataSize,0)) { Result = ERR_OUT_OF_MEMORY; goto failed; } Result = Stream_Read(Input,ARRAYBEGIN(Element->Data,void),(size_t)Element->Base.DataSize,NULL); if (Result == ERR_NONE) Element->Base.bValueIsSet = 1; failed: return Result; } #if defined(CONFIG_EBML_WRITING) static err_t RenderData(ebml_binary *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { size_t Written; err_t Err = Stream_Write(Output,ARRAYBEGIN(Element->Data,uint8_t),ARRAYCOUNT(Element->Data,uint8_t),&Written); if (Rendered) *Rendered = Written; return Err; } #endif static void Delete(ebml_binary *Element) { ArrayClear(&Element->Data); } static bool_t IsDefaultValue(const ebml_binary *Element) { return 0; // TODO: a default binary value needs a size too (use a structure to set the value in the structure) } static filepos_t UpdateDataSize(ebml_binary *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { Element->Base.DataSize = ARRAYCOUNT(Element->Data,uint8_t); return INHERITED(Element,ebml_element_vmt,EBML_BINARY_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static bool_t ValidateSize(const ebml_element *p) { return EBML_ElementIsFiniteSize(p); } static ebml_binary *Copy(const ebml_binary *Element, const void *Cookie) { ebml_binary *Result = (ebml_binary*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { ArrayCopy(&Result->Data,&Element->Data); Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; } return Result; } META_START(EBMLBinary_Class,EBML_BINARY_CLASS) META_CLASS(SIZE,sizeof(ebml_binary)) META_CLASS(DELETE,Delete) META_DATA(TYPE_ARRAY,0,ebml_binary,Data) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSize) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) META_END(EBML_ELEMENT_CLASS) err_t EBML_BinarySetData(ebml_binary *Element, const uint8_t *Data, size_t DataSize) { if (!ArrayResize(&Element->Data,DataSize,0)) return ERR_OUT_OF_MEMORY; memcpy(ARRAYBEGIN(Element->Data,void),Data,DataSize); Element->Base.DataSize = DataSize; Element->Base.bNeedDataSizeUpdate = 0; Element->Base.bValueIsSet = 1; return ERR_NONE; } const uint8_t *EBML_BinaryGetData(ebml_binary *Element) { if (!ARRAYCOUNT(Element->Data,uint8_t)) return NULL; return ARRAYBEGIN(Element->Data,uint8_t); } bcmatroska2-5.3.101/libebml2/ebmlcrc.c000066400000000000000000000304221462133141200173320ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" struct ebml_crc { ebml_element Base; uint32_t CRC; }; /* Compute the CRC 32 IEEE Little Endian */ const uint32_t CRC32_NEGL = 0xffffffffL; const uint32_t m_tab[] = { #ifdef IS_BIG_ENDIAN 0x00000000L, 0x96300777L, 0x2c610eeeL, 0xba510999L, 0x19c46d07L, 0x8ff46a70L, 0x35a563e9L, 0xa395649eL, 0x3288db0eL, 0xa4b8dc79L, 0x1ee9d5e0L, 0x88d9d297L, 0x2b4cb609L, 0xbd7cb17eL, 0x072db8e7L, 0x911dbf90L, 0x6410b71dL, 0xf220b06aL, 0x4871b9f3L, 0xde41be84L, 0x7dd4da1aL, 0xebe4dd6dL, 0x51b5d4f4L, 0xc785d383L, 0x56986c13L, 0xc0a86b64L, 0x7af962fdL, 0xecc9658aL, 0x4f5c0114L, 0xd96c0663L, 0x633d0ffaL, 0xf50d088dL, 0xc8206e3bL, 0x5e10694cL, 0xe44160d5L, 0x727167a2L, 0xd1e4033cL, 0x47d4044bL, 0xfd850dd2L, 0x6bb50aa5L, 0xfaa8b535L, 0x6c98b242L, 0xd6c9bbdbL, 0x40f9bcacL, 0xe36cd832L, 0x755cdf45L, 0xcf0dd6dcL, 0x593dd1abL, 0xac30d926L, 0x3a00de51L, 0x8051d7c8L, 0x1661d0bfL, 0xb5f4b421L, 0x23c4b356L, 0x9995bacfL, 0x0fa5bdb8L, 0x9eb80228L, 0x0888055fL, 0xb2d90cc6L, 0x24e90bb1L, 0x877c6f2fL, 0x114c6858L, 0xab1d61c1L, 0x3d2d66b6L, 0x9041dc76L, 0x0671db01L, 0xbc20d298L, 0x2a10d5efL, 0x8985b171L, 0x1fb5b606L, 0xa5e4bf9fL, 0x33d4b8e8L, 0xa2c90778L, 0x34f9000fL, 0x8ea80996L, 0x18980ee1L, 0xbb0d6a7fL, 0x2d3d6d08L, 0x976c6491L, 0x015c63e6L, 0xf4516b6bL, 0x62616c1cL, 0xd8306585L, 0x4e0062f2L, 0xed95066cL, 0x7ba5011bL, 0xc1f40882L, 0x57c40ff5L, 0xc6d9b065L, 0x50e9b712L, 0xeab8be8bL, 0x7c88b9fcL, 0xdf1ddd62L, 0x492dda15L, 0xf37cd38cL, 0x654cd4fbL, 0x5861b24dL, 0xce51b53aL, 0x7400bca3L, 0xe230bbd4L, 0x41a5df4aL, 0xd795d83dL, 0x6dc4d1a4L, 0xfbf4d6d3L, 0x6ae96943L, 0xfcd96e34L, 0x468867adL, 0xd0b860daL, 0x732d0444L, 0xe51d0333L, 0x5f4c0aaaL, 0xc97c0dddL, 0x3c710550L, 0xaa410227L, 0x10100bbeL, 0x86200cc9L, 0x25b56857L, 0xb3856f20L, 0x09d466b9L, 0x9fe461ceL, 0x0ef9de5eL, 0x98c9d929L, 0x2298d0b0L, 0xb4a8d7c7L, 0x173db359L, 0x810db42eL, 0x3b5cbdb7L, 0xad6cbac0L, 0x2083b8edL, 0xb6b3bf9aL, 0x0ce2b603L, 0x9ad2b174L, 0x3947d5eaL, 0xaf77d29dL, 0x1526db04L, 0x8316dc73L, 0x120b63e3L, 0x843b6494L, 0x3e6a6d0dL, 0xa85a6a7aL, 0x0bcf0ee4L, 0x9dff0993L, 0x27ae000aL, 0xb19e077dL, 0x44930ff0L, 0xd2a30887L, 0x68f2011eL, 0xfec20669L, 0x5d5762f7L, 0xcb676580L, 0x71366c19L, 0xe7066b6eL, 0x761bd4feL, 0xe02bd389L, 0x5a7ada10L, 0xcc4add67L, 0x6fdfb9f9L, 0xf9efbe8eL, 0x43beb717L, 0xd58eb060L, 0xe8a3d6d6L, 0x7e93d1a1L, 0xc4c2d838L, 0x52f2df4fL, 0xf167bbd1L, 0x6757bca6L, 0xdd06b53fL, 0x4b36b248L, 0xda2b0dd8L, 0x4c1b0aafL, 0xf64a0336L, 0x607a0441L, 0xc3ef60dfL, 0x55df67a8L, 0xef8e6e31L, 0x79be6946L, 0x8cb361cbL, 0x1a8366bcL, 0xa0d26f25L, 0x36e26852L, 0x95770cccL, 0x03470bbbL, 0xb9160222L, 0x2f260555L, 0xbe3bbac5L, 0x280bbdb2L, 0x925ab42bL, 0x046ab35cL, 0xa7ffd7c2L, 0x31cfd0b5L, 0x8b9ed92cL, 0x1daede5bL, 0xb0c2649bL, 0x26f263ecL, 0x9ca36a75L, 0x0a936d02L, 0xa906099cL, 0x3f360eebL, 0x85670772L, 0x13570005L, 0x824abf95L, 0x147ab8e2L, 0xae2bb17bL, 0x381bb60cL, 0x9b8ed292L, 0x0dbed5e5L, 0xb7efdc7cL, 0x21dfdb0bL, 0xd4d2d386L, 0x42e2d4f1L, 0xf8b3dd68L, 0x6e83da1fL, 0xcd16be81L, 0x5b26b9f6L, 0xe177b06fL, 0x7747b718L, 0xe65a0888L, 0x706a0fffL, 0xca3b0666L, 0x5c0b0111L, 0xff9e658fL, 0x69ae62f8L, 0xd3ff6b61L, 0x45cf6c16L, 0x78e20aa0L, 0xeed20dd7L, 0x5483044eL, 0xc2b30339L, 0x612667a7L, 0xf71660d0L, 0x4d476949L, 0xdb776e3eL, 0x4a6ad1aeL, 0xdc5ad6d9L, 0x660bdf40L, 0xf03bd837L, 0x53aebca9L, 0xc59ebbdeL, 0x7fcfb247L, 0xe9ffb530L, 0x1cf2bdbdL, 0x8ac2bacaL, 0x3093b353L, 0xa6a3b424L, 0x0536d0baL, 0x9306d7cdL, 0x2957de54L, 0xbf67d923L, 0x2e7a66b3L, 0xb84a61c4L, 0x021b685dL, 0x942b6f2aL, 0x37be0bb4L, 0xa18e0cc3L, 0x1bdf055aL, 0x8def022dL #else 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL #endif }; #ifdef IS_BIG_ENDIAN # define CRC32_INDEX(c) (c >> 24) # define CRC32_SHIFTED(c) (c << 8) #else # define CRC32_INDEX(c) (c & 0xff) # define CRC32_SHIFTED(c) (c >> 8) #endif static bool_t ValidateSize(const ebml_element *p) { return EBML_ElementIsFiniteSize(p) && (p->DataSize == 4); } static err_t ReadData(ebml_crc *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; uint32_t CRCbuffer; Result = Stream_Read(Input,&CRCbuffer,4,NULL); if (Result == ERR_NONE) { Element->CRC = LOAD32LE(&CRCbuffer); Element->Base.bValueIsSet = 1; } return Result; } #if defined(CONFIG_EBML_WRITING) static err_t RenderData(ebml_crc *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { err_t Result; size_t Written = 0; uint8_t Buf[4]; STORE32LE(Buf,Element->CRC); Result = Stream_Write(Output, Buf, 4, &Written); if (Rendered) *Rendered = Written; return Result; } #endif static ebml_crc *Copy(const ebml_crc *Element, const void *Cookie) { ebml_crc *Result = (ebml_crc*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { Result->CRC = Element->CRC; Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; } return Result; } static bool_t IsDefaultValue(const ebml_element *Element) { return 0; // CRC has no default value } static err_t Create(ebml_crc *Element) { Element->CRC = CRC32_NEGL; Element->Base.bNeedDataSizeUpdate = 0; Element->Base.DataSize = 4; return ERR_NONE; } META_START(EBMLCRC_Class,EBML_CRC_CLASS) META_CLASS(SIZE,sizeof(ebml_crc)) META_CLASS(CREATE,Create) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSize) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END(EBML_ELEMENT_CLASS) bool_t EBML_CRCMatches(ebml_crc *CRC, const uint8_t *Buf, size_t Size) { uint32_t testCRC = CRC32_NEGL; assert(CRC->Base.bValueIsSet); /* TODO: needed for non aligned memory ? for(; !aligned(Buf) && Size > 0; Size--) testCRC = m_tab[CRC32_INDEX(testCRC) ^ *Buf++] ^ CRC32_SHIFTED(testCRC); */ while (Size >= 4) { testCRC ^= *(const uint32_t *)Buf; testCRC = m_tab[CRC32_INDEX(testCRC)] ^ CRC32_SHIFTED(testCRC); testCRC = m_tab[CRC32_INDEX(testCRC)] ^ CRC32_SHIFTED(testCRC); testCRC = m_tab[CRC32_INDEX(testCRC)] ^ CRC32_SHIFTED(testCRC); testCRC = m_tab[CRC32_INDEX(testCRC)] ^ CRC32_SHIFTED(testCRC); Size -= 4; Buf += 4; } while (Size--) testCRC = m_tab[CRC32_INDEX(testCRC) ^ *Buf++] ^ CRC32_SHIFTED(testCRC); testCRC ^= CRC32_NEGL; return (CRC->CRC == testCRC); } void EBML_CRCAddBuffer(ebml_crc *CRC, const uint8_t *Buf, size_t Size) { while (Size >= 4) { CRC->CRC ^= *(const uint32_t *)Buf; CRC->CRC = m_tab[CRC32_INDEX(CRC->CRC)] ^ CRC32_SHIFTED(CRC->CRC); CRC->CRC = m_tab[CRC32_INDEX(CRC->CRC)] ^ CRC32_SHIFTED(CRC->CRC); CRC->CRC = m_tab[CRC32_INDEX(CRC->CRC)] ^ CRC32_SHIFTED(CRC->CRC); CRC->CRC = m_tab[CRC32_INDEX(CRC->CRC)] ^ CRC32_SHIFTED(CRC->CRC); Size -= 4; Buf += 4; } while (Size--) CRC->CRC = m_tab[CRC32_INDEX(CRC->CRC) ^ *Buf++] ^ CRC32_SHIFTED(CRC->CRC); } void EBML_CRCFinalize(ebml_crc *CRC) { CRC->CRC ^= CRC32_NEGL; CRC->Base.DataSize = 4; CRC->Base.bValueIsSet = 1; } bcmatroska2-5.3.101/libebml2/ebmlcrc.h000066400000000000000000000035431462133141200173430ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __LIBEBML_CRC_H #define __LIBEBML_CRC_H extern bool_t EBML_CRCMatches(ebml_crc *CRC, const uint8_t *Buf, size_t Size); extern void EBML_CRCAddBuffer(ebml_crc *CRC, const uint8_t *Buf, size_t Size); extern void EBML_CRCFinalize(ebml_crc *CRC); #endif /* __LIBEBML_CRC_H */bcmatroska2-5.3.101/libebml2/ebmldate.c000066400000000000000000000072571462133141200175120ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" datetime_t EBML_DateTime(const ebml_date *Element) { assert(Node_IsPartOf(Element,EBML_DATE_CLASS)); if (!Element->Base.bValueIsSet) return 0; return (datetime_t)Scale32(Element->Value,1,1000000000); // nanoseconds to seconds } err_t EBML_DateSetDateTime(ebml_date *Element, datetime_t Date) { if (Date == INVALID_DATETIME_T) return ERR_INVALID_PARAM; EBML_IntegerSetValue(Element, Scale64(Date,1000000000,1)); // seconds to nanoseconds return ERR_NONE; } static bool_t ValidateSize(const ebml_element *p) { return EBML_ElementIsFiniteSize(p) && (p->DataSize == 8 || p->DataSize == 0); } static err_t ReadData(ebml_date *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; int DataSize; uint8_t Value[8]; Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } assert(Element->Base.DataSize<=8); Result = Stream_Read(Input,Value,(size_t)Element->Base.DataSize,NULL); if (Result != ERR_NONE) goto failed; #ifdef IS_BIG_ENDIAN memcpy(&Element->Value,Value,Element->Base.DataSize); #else Element->Value = 0; for (DataSize=0;DataSizeBase.DataSize;++DataSize) ((uint8_t*)&Element->Value)[DataSize] = Value[Element->Base.DataSize-DataSize-1]; #endif Element->Base.bValueIsSet = 1; failed: return Result; } static void PostCreate(ebml_date *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_DATE_CLASS)->PostCreate(Element, SetDefault); Element->Base.DefaultSize = 8; Element->Base.bNeedDataSizeUpdate = 0; } META_START(EBMLDate_Class,EBML_DATE_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreate) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSize) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_END(EBML_SINTEGER_CLASS) bcmatroska2-5.3.101/libebml2/ebmlelement.c000066400000000000000000000262201462133141200202150ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" static bool_t ValidateSize(const ebml_element *p) { return 1; } static void PostCreate(ebml_element *Element, bool_t SetDefault) { Element->DefaultSize = -1; Element->ElementPosition = INVALID_FILEPOS_T; Element->SizePosition = INVALID_FILEPOS_T; } static bool_t NeedsDataSizeUpdate(ebml_element *Element, bool_t bWithDefault) { if (!Element->bNeedDataSizeUpdate) return 0; if (!bWithDefault && EBML_ElementIsDefaultValue(Element)) return 0; return 1; } static filepos_t UpdateDataSize(ebml_element *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (!bWithDefault && EBML_ElementIsDefaultValue(Element)) return 0; if (Element->DefaultSize > Element->DataSize) Element->DataSize = Element->DefaultSize; Element->bNeedDataSizeUpdate = 0; #if !defined(NDEBUG) assert(!EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)); #endif return Element->DataSize; } static err_t Create(ebml_element *Element) { Element->DataSize = INVALID_FILEPOS_T; Element->bNeedDataSizeUpdate = 1; return ERR_NONE; } META_START(EBMLElement_Class,EBML_ELEMENT_CLASS) META_CLASS(SIZE,sizeof(ebml_element)) META_CLASS(VMT_SIZE,sizeof(ebml_element_vmt)) META_CLASS(FLAGS,CFLAG_ABSTRACT) META_CLASS(CREATE,Create) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreate) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSize) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSize) META_VMT(TYPE_FUNC,ebml_element_vmt,NeedsDataSizeUpdate,NeedsDataSizeUpdate) META_PARAM(TYPE,EBML_ELEMENT_INFINITESIZE,TYPE_BOOLEAN) META_DYNAMIC(TYPE_BOOLEAN,EBML_ELEMENT_INFINITESIZE) META_PARAM(TYPE,EBML_ELEMENT_OBJECT,TYPE_PTR) META_DYNAMIC(TYPE_PTR,EBML_ELEMENT_OBJECT) META_END_CONTINUE(NODETREE_CLASS) META_START_CONTINUE(EBML_DUMMY_ID) META_CLASS(SIZE,sizeof(ebml_dummy)) META_END(EBML_BINARY_CLASS) bool_t EBML_ElementIsFiniteSize(const ebml_element *Element) { return (Node_GetData((const node*)Element,EBML_ELEMENT_INFINITESIZE,TYPE_BOOLEAN) == 0); } void EBML_ElementSetInfiniteSize(const ebml_element *Element, bool_t Set) { bool_t b = Set; Node_SetData((node*)Element,EBML_ELEMENT_INFINITESIZE,TYPE_BOOLEAN,&b); } bool_t EBML_ElementIsDummy(const ebml_element *Element) { return Node_IsPartOf(Element,EBML_DUMMY_ID); } ebml_element *EBML_ElementSkipData(ebml_element *p, stream *Input, const ebml_parser_context *Context, ebml_element *TestReadElt, bool_t AllowDummyElt) { ebml_element *Result = NULL; if (EBML_ElementIsFiniteSize(p)) { assert(TestReadElt == NULL); assert(p->ElementPosition < p->SizePosition); Stream_Seek(Input, EBML_ElementPositionEnd(p), SEEK_SET); } else { // read elements until an upper element is found int bUpperElement = 0; // trick to call FindNextID correctly Result = EBML_FindNextElement(Input, Context, &bUpperElement, AllowDummyElt); if (Result != NULL) Stream_Seek(Input, EBML_ElementPositionData(Result), SEEK_SET); } return Result; } const ebml_context *EBML_ElementContext(const ebml_element *Element) { return Element->Context; } filepos_t EBML_ElementFullSize(const ebml_element *Element, bool_t bWithDefault) { if (!bWithDefault && EBML_ElementIsDefaultValue(Element)) return INVALID_FILEPOS_T; // won't be saved return Element->DataSize + GetIdLength(Element->Context->Id) + EBML_CodedSizeLength(Element->DataSize, Element->SizeLength, EBML_ElementIsFiniteSize(Element)); } filepos_t EBML_ElementDataSize(const ebml_element *Element, bool_t bWithDefault) { return Element->DataSize; } void EBML_ElementForceDataSize(ebml_element *Element, filepos_t Size) { Element->DataSize = Size; } uint8_t EBML_ElementSizeLength(const ebml_element *Element) { return Element->SizeLength; } void EBML_ElementSetSizeLength(ebml_element *Element, uint8_t SizeLength) { Element->SizeLength = SizeLength; } bool_t EBML_ElementIsType(const ebml_element *Element, const ebml_context *Context) { return Element->Context->Id == Context->Id; } fourcc_t EBML_ElementClassID(const ebml_element *Element) { return Element->Context->Id; } filepos_t EBML_ElementPosition(const ebml_element *Element) { return Element->ElementPosition; } void EBML_ElementForcePosition(ebml_element *Element, filepos_t Pos) { Element->ElementPosition = Pos; } filepos_t EBML_ElementPositionData(const ebml_element *Element) { if (!EBML_ElementIsFiniteSize(Element)) { if (!Element->SizeLength) return INVALID_FILEPOS_T; return Element->SizePosition + Element->SizeLength; } else return Element->SizePosition + EBML_CodedSizeLength(Element->DataSize,Element->SizeLength,1); } filepos_t EBML_ElementPositionEnd(const ebml_element *Element) { if (!EBML_ElementIsFiniteSize(Element)) return INVALID_FILEPOS_T; // the end position is unknown else return Element->SizePosition + EBML_CodedSizeLength(Element->DataSize,Element->SizeLength,1) + Element->DataSize; } bool_t EBML_ElementInfiniteForceSize(ebml_element *Element, filepos_t NewSize) { int OldSizeLen; filepos_t OldSize; assert(!EBML_ElementIsFiniteSize(Element)); if (EBML_ElementIsFiniteSize(Element)) return 0; OldSizeLen = EBML_CodedSizeLength(Element->DataSize, Element->SizeLength, EBML_ElementIsFiniteSize(Element)); OldSize = Element->DataSize; Element->DataSize = NewSize; if (EBML_CodedSizeLength(Element->DataSize, Element->SizeLength, EBML_ElementIsFiniteSize(Element)) == OldSizeLen) { EBML_ElementSetInfiniteSize(Element,1); return 1; } Element->DataSize = OldSize; return 0; } size_t GetIdLength(fourcc_t Id) { if ((Id & 0xFFFFFF00)==0) return 1; if ((Id & 0xFFFF0000)==0) return 2; if ((Id & 0xFF000000)==0) return 3; return 4; } size_t EBML_FillBufferID(uint8_t *Buffer, size_t BufSize, fourcc_t Id) { size_t i,FinalHeadSize = GetIdLength(Id); if (BufSize < FinalHeadSize) return 0; for (i=0;i> (i<<3)); return FinalHeadSize; } size_t EBML_IdToString(tchar_t *Out, size_t OutLen, fourcc_t Id) { size_t i,FinalHeadSize = GetIdLength(Id); if (OutLen < FinalHeadSize*4+1) return 0; Out[0] = 0; for (i=0;i<4;++i) { if (Out[0] || (Id >> 8*(3-i)) & 0xFF) stcatprintf_s(Out,OutLen,T("[%02X]"),(Id >> 8*(3-i)) & 0xFF); } return FinalHeadSize*4; } fourcc_t EBML_BufferToID(const uint8_t *Buffer) { if (Buffer[0] & 0x80) return (fourcc_t)Buffer[0]; if (Buffer[0] & 0x40) return (fourcc_t)((Buffer[0] << 8) + Buffer[1]); if (Buffer[0] & 0x20) return (fourcc_t)((Buffer[0] << 16) + (Buffer[1] << 8) + Buffer[2]); if (Buffer[0] & 0x10) return (fourcc_t)((Buffer[0] << 24) + (Buffer[1] << 16) + (Buffer[2] << 8) + Buffer[3]); return 0; } #if defined(CONFIG_EBML_WRITING) err_t EBML_ElementRender(ebml_element *Element, stream *Output, bool_t bWithDefault, bool_t bKeepPosition, bool_t bForceWithoutMandatory, filepos_t *Rendered) { err_t Result; filepos_t _Rendered,WrittenSize; #if !defined(NDEBUG) filepos_t SupposedSize; #endif if (!Rendered) Rendered = &_Rendered; *Rendered = 0; assert(Element->bValueIsSet || (bWithDefault && EBML_ElementIsDefaultValue(Element))); // an element is been rendered without a value set !!! // it may be a mandatory element without a default value if (!(Element->bValueIsSet || (bWithDefault && EBML_ElementIsDefaultValue(Element)))) return ERR_INVALID_DATA; if (!bWithDefault && EBML_ElementIsDefaultValue(Element)) return ERR_INVALID_DATA; #if !defined(NDEBUG) if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) SupposedSize = EBML_ElementUpdateSize(Element, bWithDefault, bForceWithoutMandatory); else SupposedSize = Element->DataSize; #else if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) EBML_ElementUpdateSize(Element, bWithDefault, bForceWithoutMandatory); #endif Result = EBML_ElementRenderHead(Element, Output, bKeepPosition, &WrittenSize); *Rendered += WrittenSize; if (Result != ERR_NONE) return Result; Result = EBML_ElementRenderData(Element, Output, bForceWithoutMandatory, bWithDefault, &WrittenSize); #if !defined(NDEBUG) if (SupposedSize != INVALID_FILEPOS_T) assert(WrittenSize == SupposedSize); #endif *Rendered += WrittenSize; return Result; } err_t EBML_ElementRenderHead(ebml_element *Element, stream *Output, bool_t bKeepPosition, filepos_t *Rendered) { err_t Err; uint8_t FinalHead[4+8]; // Class D + 64 bits coded size size_t i,FinalHeadSize; int CodedSize; filepos_t PosAfter,PosBefore = Stream_Seek(Output,0,SEEK_CUR); FinalHeadSize = EBML_FillBufferID(FinalHead,sizeof(FinalHead),Element->Context->Id); CodedSize = EBML_CodedSizeLength(Element->DataSize, Element->SizeLength, EBML_ElementIsFiniteSize(Element)); EBML_CodedValueLength(Element->DataSize, CodedSize, &FinalHead[FinalHeadSize], EBML_ElementIsFiniteSize(Element)); FinalHeadSize += CodedSize; Err = Stream_Write(Output, FinalHead, FinalHeadSize, &i); PosAfter = Stream_Seek(Output,0,SEEK_CUR); if (!bKeepPosition) { Element->ElementPosition = PosAfter - FinalHeadSize; Element->SizePosition = Element->ElementPosition + GetIdLength(Element->Context->Id); } if (Rendered) *Rendered = PosAfter - PosBefore; return Err; } #endif void EBML_ElementGetName(const ebml_element *Element, tchar_t *Out, size_t OutLen) { Node_FromStr(Element,Out,OutLen,Element->Context->ElementName); } const char *EBML_ElementGetClassName(const ebml_element *Element) { return Element->Context->ElementName; }bcmatroska2-5.3.101/libebml2/ebmlmain.c000066400000000000000000000554041462133141200175160ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" #if defined(EBML_LIBRARY) # if defined(EBML_LEGACY_API) # include "ebml2_legacy_project.h" # else # include "ebml2_project.h" # endif #endif extern const nodemeta BufStream_Class[]; extern const nodemeta MemStream_Class[]; extern const nodemeta Streams_Class[]; #if defined(CONFIG_EBML_UNICODE) extern const nodemeta LangStr_Class[]; extern const nodemeta UrlPart_Class[]; # if defined(CONFIG_STDIO) extern const nodemeta Stdio_Class[]; # endif #endif extern const nodemeta EBMLElement_Class[]; extern const nodemeta EBMLMaster_Class[]; extern const nodemeta EBMLBinary_Class[]; extern const nodemeta EBMLString_Class[]; extern const nodemeta EBMLInteger_Class[]; extern const nodemeta EBMLCRC_Class[]; extern const nodemeta EBMLDate_Class[]; extern const nodemeta EBMLVoid_Class[]; err_t EBML_Init(nodecontext *p) { // TODO: only when used as standalone (no coremake & core-c in the rest of the project) #if defined(EBML_LIBRARY) tchar_t LibName[MAXPATH]; tcscpy_s(LibName,TSIZEOF(LibName),PROJECT_NAME T(" v") PROJECT_VERSION); Node_SetData(p,CONTEXT_LIBEBML_VERSION,TYPE_STRING,LibName); #endif NodeRegisterClassEx((nodemodule*)p,BufStream_Class); NodeRegisterClassEx((nodemodule*)p,MemStream_Class); NodeRegisterClassEx((nodemodule*)p,Streams_Class); #if defined(CONFIG_EBML_UNICODE) NodeRegisterClassEx((nodemodule*)p,LangStr_Class); NodeRegisterClassEx((nodemodule*)p,UrlPart_Class); # if defined(CONFIG_STDIO) NodeRegisterClassEx((nodemodule*)p,Stdio_Class); # endif #endif NodeRegisterClassEx((nodemodule*)p,EBMLElement_Class); NodeRegisterClassEx((nodemodule*)p,EBMLMaster_Class); NodeRegisterClassEx((nodemodule*)p,EBMLBinary_Class); NodeRegisterClassEx((nodemodule*)p,EBMLString_Class); NodeRegisterClassEx((nodemodule*)p,EBMLInteger_Class); NodeRegisterClassEx((nodemodule*)p,EBMLDate_Class); NodeRegisterClassEx((nodemodule*)p,EBMLCRC_Class); NodeRegisterClassEx((nodemodule*)p,EBMLVoid_Class); return ERR_NONE; } err_t EBML_Done(nodecontext *p) { return ERR_NONE; } CONTEXT_CONST ebml_context EBML_ContextDummy = {0xFF, EBML_DUMMY_ID, 0, 0, "DummyElement", NULL, NULL}; CONTEXT_CONST ebml_context EBML_ContextVersion = {0x4286, EBML_INTEGER_CLASS, 1, EBML_MAX_VERSION, "EBMLVersion", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextReadVersion = {0x42F7, EBML_INTEGER_CLASS, 1, EBML_MAX_VERSION, "EBMLReadVersion", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextMaxIdLength = {0x42F2, EBML_INTEGER_CLASS, 1, EBML_MAX_ID, "EBMLMaxIdLength", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextMaxSizeLength = {0x42F3, EBML_INTEGER_CLASS, 1, EBML_MAX_SIZE, "EBMLMaxSizeLength", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextDocType = {0x4282, EBML_STRING_CLASS, 1, (intptr_t)"matroska", "EBMLDocType", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextDocTypeVersion = {0x4287, EBML_INTEGER_CLASS, 1, 1, "EBMLDocTypeVersion", NULL, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextDocTypeReadVersion = {0x4285, EBML_INTEGER_CLASS, 1, 1, "EBMLDocTypeReadVersion", NULL, EBML_SemanticGlobals}; static const ebml_semantic EBML_SemanticHead[] = { {1, 1, &EBML_ContextVersion}, {1, 1, &EBML_ContextReadVersion}, {1, 1, &EBML_ContextMaxIdLength}, {1, 1, &EBML_ContextMaxSizeLength}, {1, 1, &EBML_ContextDocType}, {1, 1, &EBML_ContextDocTypeVersion}, {1, 1, &EBML_ContextDocTypeReadVersion}, {0, 0, NULL} // end of the table }; CONTEXT_CONST ebml_context EBML_ContextHead = {0x1A45DFA3, EBML_MASTER_CLASS, 0, 0, "EBMLHead\0mfthis", EBML_SemanticHead, EBML_SemanticGlobals}; CONTEXT_CONST ebml_context EBML_ContextEbmlVoid = {0xEC, EBML_VOID_CLASS, 0, 0, "EBMLVoid", NULL, NULL}; CONTEXT_CONST ebml_context EBML_ContextEbmlCrc32 = {0xBF, EBML_CRC_CLASS, 0, 0, "EBMLCrc32", NULL, NULL}; const ebml_semantic EBML_SemanticGlobals[] = { {0, 0, &EBML_ContextEbmlVoid}, {0, 1, &EBML_ContextEbmlCrc32}, {0, 0, NULL} // end of the table }; static const ebml_context EBML_ContextGlobals = {0, 0, 0, 0, "GlobalContext", EBML_SemanticGlobals, EBML_SemanticGlobals}; filepos_t EBML_ReadCodedSizeValue(const uint8_t *InBuffer, size_t *BufferSize, filepos_t *SizeUnknown) { uint8_t SizeBitMask = 1 << 7; filepos_t Result = 0x7F; unsigned int SizeIdx, PossibleSizeLength = 0; uint8_t PossibleSize[8]; unsigned int i; *SizeUnknown = 0x7F; // the last bit is discarded when computing the size for (SizeIdx = 0; SizeIdx < *BufferSize && SizeIdx < 8; SizeIdx++) { if (InBuffer[0] & (SizeBitMask >> SizeIdx)) { // ID found PossibleSizeLength = SizeIdx + 1; SizeBitMask >>= SizeIdx; for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) { PossibleSize[SizeIdx] = InBuffer[SizeIdx]; } for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) { Result <<= 7; Result |= 0xFF; } Result = 0; Result |= PossibleSize[0] & ~SizeBitMask; for (i = 1; iClass); if (Result!=NULL) { Result->Context = Context; #if defined(EBML_LEGACY_API) assert(Context->PostCreate); // for projects with legacy access #endif if (Context->PostCreate) Context->PostCreate(Result,Cookie); VMT_FUNC(Result,ebml_element_vmt)->PostCreate(Result, SetDefault); } return Result; } static ebml_element *CreateElement(anynode *Any, const uint8_t *PossibleId, int8_t IdLength, const ebml_context *Context, ebml_master *Parent) { ebml_element *Result; assert(Context!=NULL); if (EBML_IdMatch(PossibleId, IdLength, Context->Id)) { Result = EBML_ElementCreate(Any,Context,0,NULL); } else { Result = EBML_ElementCreate(Any,&EBML_ContextDummy,0,NULL); if (Result!=NULL) { // Fill a temp context ebml_dummy *Dummy = (ebml_dummy*)Result; memcpy(&Dummy->DummyContext,&EBML_ContextDummy,sizeof(Dummy->DummyContext)); Dummy->DummyContext.Id = EBML_IdFromBuffer(PossibleId,IdLength); Result->Context = &Dummy->DummyContext; } } if (Result && Parent) { assert(Node_IsPartOf(Parent,EBML_MASTER_CLASS)); EBML_MasterAppend(Parent,Result); } return Result; } static ebml_element *EBML_ElementCreateUsingContext(void *AnyNode, const uint8_t *PossibleId, int8_t IdLength, const ebml_parser_context *Context, int *LowLevel, bool_t IsGlobalContext, bool_t bAllowDummy) { int MaxLowerLevel=1; //TODO: remove ? // unsigned int ContextIndex; ebml_element *Result = NULL; const ebml_semantic *Semantic; if (!Context || !Context->Context || !Context->Context->Semantic) return NULL; // elements at the current level for (Semantic=Context->Context->Semantic;Semantic->eClass;Semantic++) { if (EBML_IdMatch(PossibleId, IdLength, Semantic->eClass->Id)) // && (bAllowDummy || bAllowOutOfProfile || !(Context->Profile & Semantic->DisabledProfile))) { Result = EBML_ElementCreate(AnyNode,Semantic->eClass,0,NULL); return Result; } } // global elements assert(Context->Context->GlobalContext != NULL); // global should always exist, at least the EBML ones if (Context->Context->GlobalContext == Context->Context->Semantic) return NULL; else { ebml_context ContextGlobals; ebml_parser_context GlobalContext; ContextGlobals.Semantic = Context->Context->GlobalContext; ContextGlobals.GlobalContext = Context->Context->GlobalContext; GlobalContext.Context = &ContextGlobals; GlobalContext.UpContext = Context; GlobalContext.EndPosition = INVALID_FILEPOS_T; GlobalContext.Profile = Context->Profile; (*LowLevel)--; MaxLowerLevel--; // recursive is good, but be carefull... Result = EBML_ElementCreateUsingContext(AnyNode,PossibleId,IdLength,&GlobalContext,LowLevel,1,bAllowDummy); if (Result) return Result; (*LowLevel)++; MaxLowerLevel++; } #ifdef TODO // parent elements if (Context.MasterElt != NULL && aID == Context.MasterElt->GlobalId) { (*LowLevel)++; // already one level up (same as context) return &Context.MasterElt->Create(); } #endif // check wether it's not part of an upper context if (Context->UpContext != NULL) { (*LowLevel)++; MaxLowerLevel++; return EBML_ElementCreateUsingContext(AnyNode, PossibleId, IdLength, Context->UpContext, LowLevel, IsGlobalContext, bAllowDummy); } // dummy fallback if (!IsGlobalContext && bAllowDummy && IdLength!=0) { (*LowLevel) = 0; Result = CreateElement(AnyNode,PossibleId,IdLength,Context->Context,NULL); } return Result; } ebml_element *EBML_FindNextId(stream *Input, const ebml_context *Context, size_t MaxDataSize) { filepos_t aElementPosition, aSizePosition; filepos_t SizeFound=0, SizeUnknown; int ReadSize; uint8_t BitMask; uint8_t PossibleId[4]; uint8_t PossibleSize[8]; // we don't support size stored in more than 64 bits bool_t bElementFound = 0; int8_t PossibleID_Length = 0; size_t _SizeLength; uint8_t PossibleSizeLength = 0; ebml_element *Result = NULL; while (!bElementFound) { aElementPosition = Stream_Seek(Input,0,SEEK_CUR); ReadSize = 0; BitMask = 1 << 7; for (;;) { if (Stream_ReadOneOrMore(Input,&PossibleId[PossibleID_Length], 1, NULL)!=ERR_NONE) break; ReadSize++; if (ReadSize == PossibleID_Length) return NULL; // No more data ? if (++PossibleID_Length > 4) return NULL; // we don't support element IDs over class D if (PossibleId[0] & BitMask) { bElementFound = 1; break; } BitMask >>= 1; } // read the data size aSizePosition = Stream_Seek(Input,0,SEEK_CUR); do { if (PossibleSizeLength >= 8) // Size is larger than 8 bytes return NULL; if (Stream_ReadOneOrMore(Input,&PossibleSize[PossibleSizeLength++], 1, NULL)!=ERR_NONE) break; ReadSize++; _SizeLength = PossibleSizeLength; SizeFound = EBML_ReadCodedSizeValue(&PossibleSize[0], &_SizeLength, &SizeUnknown); } while (_SizeLength == 0); } // look for the ID in the provided context Result = CreateElement(Input, PossibleId, PossibleID_Length, Context,NULL); assert(Result != NULL); #if 0 if (PossibleID_Length==4) printf("Elt: size %d id %d %02X%02X%02X%02X\n",SizeFound,PossibleID_Length,PossibleId[0],PossibleId[1],PossibleId[2],PossibleId[3]); else if (PossibleID_Length==3) printf("Elt: size %d id %d %02X%02X%02X\n",SizeFound,PossibleID_Length,PossibleId[0],PossibleId[1],PossibleId[2]); else if (PossibleID_Length==2) printf("Elt: size %d id %d %02X%02X\n",SizeFound,PossibleID_Length,PossibleId[0],PossibleId[1]); else if (PossibleID_Length==1) printf("Elt: size %d id %d %02X\n",SizeFound,PossibleID_Length,PossibleId[0]); #endif Result->SizeLength = PossibleSizeLength; Result->DataSize = SizeFound; if (!EBML_ElementValidateSize(Result) || (SizeFound != SizeUnknown && MaxDataSize < (size_t)Result->DataSize)) { NodeDelete((node*)Result); return NULL; } Result->ElementPosition = aElementPosition; Result->SizePosition = aSizePosition; return Result; } uint8_t EBML_CodedSizeLength(filepos_t Length, uint8_t SizeLength, bool_t bSizeIsFinite) { int CodedSize; if (!bSizeIsFinite) CodedSize = 1; else { // prepare the head of the size (000...01xxxxxx) // optimal size if (Length < 127) // 2^7 - 1 CodedSize = 1; else if (Length < 16383) // 2^14 - 1 CodedSize = 2; else if (Length < 2097151) // 2^21 - 1 CodedSize = 3; else if (Length < 268435455) // 2^28 - 1 CodedSize = 4; else CodedSize = 5; } if (SizeLength && CodedSize < SizeLength) // defined size CodedSize = SizeLength; return (uint8_t)CodedSize; } uint8_t EBML_CodedSizeLengthSigned(filepos_t Length, uint8_t SizeLength) { int CodedSize; // prepare the head of the size (000...01xxxxxx) // optimal size if (Length > -64 && Length < 64) // 2^6 CodedSize = 1; else if (Length > -8192 && Length < 8192) // 2^13 CodedSize = 2; else if (Length > -1048576 && Length < 1048576) // 2^20 CodedSize = 3; else if (Length > -134217728 && Length < 134217728) // 2^27 CodedSize = 4; else CodedSize = 5; if (SizeLength > 0 && CodedSize < SizeLength) // defined size CodedSize = SizeLength; return (uint8_t)CodedSize; } uint8_t EBML_CodedValueLength(filepos_t Length, size_t CodedSize, uint8_t *OutBuffer, bool_t bSizeIsFinite) { int _SizeMask = 0xFF; size_t i; #if 0 if (CodedSize==3) printf("%08X ",(int)Length); #endif if (!bSizeIsFinite) Length=MAX_FILEPOS; OutBuffer[0] = (uint8_t)(1 << (8 - CodedSize)); for (i=1; i>= 8; _SizeMask >>= 1; } // first one use a OR with the "EBML size head" OutBuffer[0] |= Length & 0xFF & _SizeMask; #if 0 if (CodedSize==3) printf("%02X%02X%02X\n",OutBuffer[0],OutBuffer[1],OutBuffer[2]); #endif return (uint8_t)CodedSize; } uint8_t EBML_CodedValueLengthSigned(filepos_t Length, size_t CodedSize, uint8_t * OutBuffer) { if (Length > -64 && Length < 64) // 2^6 Length += 63; else if (Length > -8192 && Length < 8192) // 2^13 Length += 8191; else if (Length > -1048576 && Length < 1048576) // 2^20 Length += 1048575; else if (Length > -134217728 && Length < 134217728) // 2^27 Length += 134217727; return EBML_CodedValueLength(Length, CodedSize, OutBuffer, 1); } ebml_element *EBML_FindNextElement(stream *Input, const ebml_parser_context *pContext, int *UpperLevels, bool_t AllowDummyElt) { uint8_t PossibleID_Length = 0; uint8_t PossibleIdNSize[16]; int PossibleSizeLength; filepos_t SizeUnknown; int8_t SizeIdx,ReadIndex = 0; // trick for the algo, start index at 0 uint32_t ReadSize = 0; filepos_t SizeFound; bool_t bFound; int UpperLevel_original = *UpperLevels; filepos_t CurrentPos; filepos_t StartPos = Stream_Seek(Input,0,SEEK_CUR); ebml_parser_context OrigContext; const ebml_parser_context *Context = &OrigContext; if (StartPos == INVALID_FILEPOS_T) return NULL; assert(Context != NULL); OrigContext = *pContext; // adjust the Context to allow the StartPos to make sense while (Context && Context->EndPosition != INVALID_FILEPOS_T && (StartPos >= Context->EndPosition)) { if (Context->UpContext==NULL) break; Context = Context->UpContext; (*UpperLevels)++; } do { size_t _SizeLength; // read a potential ID do { uint8_t IdBitMask = 1 << 7; assert(ReadIndex < 16); // build the ID with the current Read Buffer bFound = 0; for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) { if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) { // ID found PossibleID_Length = SizeIdx + 1; IdBitMask >>= SizeIdx; bFound = 1; break; } } if (bFound) break; if (Context->EndPosition == StartPos+ReadSize) break; // we should not read further than our limit if (ReadIndex >= 4) { // ID not found // shift left the read octets memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex); } if (Stream_ReadOneOrMore(Input,&PossibleIdNSize[ReadIndex++], 1, NULL)!=ERR_NONE) return NULL; // no more data ? ReadSize++; } while (!bFound); SizeIdx = ReadIndex; ReadIndex = ReadIndex - PossibleID_Length; // read the data size PossibleSizeLength = ReadIndex; bFound = 0; while (1) { _SizeLength = PossibleSizeLength; SizeFound = EBML_ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], &_SizeLength, &SizeUnknown); if (_SizeLength != 0) { bFound = 1; break; } if (PossibleSizeLength >= 8) break; if (Context->EndPosition == StartPos+ReadSize) break; // we should not read further than our limit if (Stream_ReadOneOrMore(Input,&PossibleIdNSize[SizeIdx++], 1, NULL)!=ERR_NONE) return NULL; ReadSize++; PossibleSizeLength++; } CurrentPos = Stream_Seek(Input,0,SEEK_CUR); if (bFound) { // make sure the element we found is contained in the Context if (SizeFound != SizeUnknown) { while (Context && Context->EndPosition != INVALID_FILEPOS_T && (CurrentPos + SizeFound - SizeIdx > Context->EndPosition)) { if (AllowDummyElt || Context->UpContext==NULL) { bFound = 0; break; } Context = Context->UpContext; (*UpperLevels)++; } } } if (bFound) { // find the element in the context and use the correct creator int LevelChange = 0; ebml_element *Result = EBML_ElementCreateUsingContext(Input, PossibleIdNSize, PossibleID_Length, Context, &LevelChange, 0, AllowDummyElt); if (Result != NULL) { if (AllowDummyElt || !EBML_ElementIsDummy(Result)) { assert(_SizeLength <= 8); Result->SizeLength = (int8_t)_SizeLength; Result->DataSize = SizeFound; if (AllowDummyElt && !EBML_ElementValidateSize(Result) && !EBML_ElementIsDummy(Result)) { // the element has a good ID but wrong size, so replace with a dummy NodeDelete((node*)Result); Result = CreateElement(Input, PossibleIdNSize, PossibleID_Length, &EBML_ContextDummy, NULL); Result->SizeLength = (int8_t)_SizeLength; Result->DataSize = SizeFound; } // LevelChange values // -1 : global element // 0 : child // 1 : same level // + : further parent if (EBML_ElementValidateSize(Result)) { if (SizeFound == SizeUnknown) { EBML_ElementSetInfiniteSize(Result, 1); Result->DataSize = INVALID_FILEPOS_T; } if (LevelChange > 0) *UpperLevels += LevelChange; Result->SizePosition = CurrentPos - SizeIdx + PossibleID_Length; Result->ElementPosition = Result->SizePosition - PossibleID_Length; // place the file at the beggining of the data Stream_Seek(Input,Result->SizePosition + _SizeLength,SEEK_SET); return Result; } } NodeDelete((node*)Result); } } if (Context->EndPosition!=INVALID_FILEPOS_T && Context->EndPosition <= CurrentPos) { if (AllowDummyElt) { int LevelChange = 0; ebml_element *Result = EBML_ElementCreateUsingContext(Input, PossibleIdNSize, PossibleID_Length, Context, &LevelChange, 0, 1); if (Result != NULL) { if (LevelChange > 0) *UpperLevels += LevelChange; Result->SizePosition = CurrentPos - SizeIdx + PossibleID_Length; Result->ElementPosition = Result->SizePosition - PossibleID_Length; Result->DataSize = 0; Result->SizeLength = (int8_t)(Context->EndPosition - Result->SizePosition); // place the file at the end of the element Stream_Seek(Input,Context->EndPosition,SEEK_SET); return Result; } } break; // we should not read further than our limit } // recover all the data in the buffer minus one byte ReadIndex = SizeIdx - 1; memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex); *UpperLevels = UpperLevel_original; OrigContext = *pContext; Context = &OrigContext; } while (Context->EndPosition==INVALID_FILEPOS_T || (Context->EndPosition > CurrentPos - SizeIdx + PossibleID_Length)); return NULL; } bcmatroska2-5.3.101/libebml2/ebmlmaster.c000066400000000000000000000606371462133141200200710ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" #include "ebmlcrc.h" ebml_element *EBML_MasterAddElt(ebml_master *Element, const ebml_context *Context, bool_t SetDefault) { ebml_element *i; #if !defined(NDEBUG) // check if the sub Context is legal in this Element bool_t IsLegal = 0; const ebml_semantic * Semantic; const ebml_context *ParentContext = Element->Base.Context; for (Semantic=ParentContext->Semantic;Semantic->eClass;Semantic++) { if (Semantic->eClass->Id == Context->Id) { IsLegal = 1; break; } } if (!IsLegal) { for (Semantic=ParentContext->GlobalContext;Semantic->eClass;Semantic++) { if (Semantic->eClass->Id == Context->Id) { IsLegal = 1; break; } } } if (!IsLegal) return NULL; #endif i = EBML_ElementCreate(Element,Context,SetDefault,NULL); if (i && EBML_MasterAppend(Element,i)!=ERR_NONE) { NodeDelete((node*)i); i = NULL; } return i; } ebml_element *EBML_MasterFindFirstElt(ebml_master *Element, const ebml_context *Context, bool_t bCreateIfNull, bool_t SetDefault) { ebml_element *i; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) { if (i->Context->Id == Context->Id) break; } if (!i && bCreateIfNull) i = EBML_MasterAddElt(Element,Context,SetDefault); return i; } ebml_element *EBML_MasterFindNextElt(ebml_master *Element, const ebml_element *Current, bool_t bCreateIfNull, bool_t SetDefault) { ebml_element *i; if (!Current) return NULL; for (i=EBML_MasterNext(Current);i;i=EBML_MasterNext(i)) { if (i->Context->Id == Current->Context->Id) break; } if (!i && bCreateIfNull) i = EBML_MasterAddElt(Element,Current->Context,SetDefault); return i; } err_t EBML_MasterAppend(ebml_master *Element, ebml_element *Append) { err_t Result; assert(Node_IsPartOf(Element,EBML_MASTER_CLASS)); Result = NodeTree_SetParent(Append,Element,NULL); if (Result==ERR_NONE) { Element->Base.bNeedDataSizeUpdate = 1; Element->Base.bValueIsSet = 1; } return Result; } err_t EBML_MasterRemove(ebml_master *Element, ebml_element *Append) { err_t Result = NodeTree_SetParent(Append,NULL,NULL); return Result; } size_t EBML_MasterCount(const ebml_master *Element) { size_t Result = 0; ebml_element *i; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) ++Result; return Result; } static int EbmlCmp(const ebml_element* Element, const ebml_element** a,const ebml_element** b) { if ((*a)->Context->Id == (*b)->Context->Id) return EBML_ElementCmp(*a,*b); return 0; } void EBML_MasterSort(ebml_master *Element, arraycmp Cmp, const void* CmpParam) { array Elts; ebml_element *i,**j; ArrayInit(&Elts); for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) ArrayAppend(&Elts,&i,sizeof(i),64); if (Cmp) ArraySort(&Elts,ebml_element*,Cmp,CmpParam,0); else ArraySort(&Elts,ebml_element*,(arraycmp)EbmlCmp,Element,0); // refill the master with the new order EBML_MasterClear(Element); i = NULL; for (j=ARRAYBEGIN(Elts,ebml_element*);j!=ARRAYEND(Elts,ebml_element*);++j) { NodeTree_SetParent(*j,Element,NULL); i = *j; } ArrayClear(&Elts); } void EBML_MasterClear(ebml_master *Element) { ebml_element *i = EBML_MasterChildren(Element); while (i) { NodeTree_SetParent(i,NULL,NULL); i = EBML_MasterChildren(Element); } } void EBML_MasterErase(ebml_master *Element) { while (Element->Base.Base.Children) NodeTree_DetachAndRelease(Element->Base.Base.Children); } static bool_t IsDefaultValue(const ebml_element *Element) { return 0; // TODO: a master element has the default value if all the sub elements are unique and have the default value #if 0 const ebml_semantic *i; for (i=Element->Context->Semantic;i->eClass;++i) { if (!i->Unique) return 0; if (i->Mandatory && !EBML_MasterFindChild(Element,i->eClass)) return 0; } return 1; #endif } static bool_t CheckMandatory(const ebml_master *Element, bool_t bWithDefault) { const ebml_semantic *i; for (i=Element->Base.Context->Semantic;i->eClass;++i) { if (i->Mandatory && !EBML_MasterFindChild(Element,i->eClass) && (bWithDefault || !i->eClass->HasDefault)) return 0; } return 1; } bool_t EBML_MasterCheckMandatory(const ebml_master *Element, bool_t bWithDefault) { ebml_element *Child; if (!CheckMandatory(Element, bWithDefault)) return 0; for (Child = EBML_MasterChildren(Element); Child; Child = EBML_MasterNext(Child)) { if (Node_IsPartOf(Child,EBML_MASTER_CLASS) && !EBML_MasterCheckMandatory((ebml_master*)Child, bWithDefault)) return 0; } return 1; } static bool_t NeedsDataSizeUpdate(ebml_element *Element, bool_t bWithDefault) { ebml_element *i; if (INHERITED(Element,ebml_element_vmt,EBML_MASTER_CLASS)->NeedsDataSizeUpdate(Element, bWithDefault)) return 1; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) { if (EBML_ElementNeedsDataSizeUpdate(i,bWithDefault)) return 1; } return 0; } static filepos_t UpdateDataSize(ebml_master *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) { ebml_element *i; //if (!EBML_ElementIsFiniteSize((ebml_element*)Element)) // return INVALID_FILEPOS_T; if (!bForceWithoutMandatory) { assert(CheckMandatory((ebml_master*)Element, bWithDefault)); } if (Element->CheckSumStatus) Element->Base.DataSize = 6; else Element->Base.DataSize = 0; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) { if (!bWithDefault && EBML_ElementIsDefaultValue(i)) continue; EBML_ElementUpdateSize(i,bWithDefault,bForceWithoutMandatory); assert(!EBML_ElementNeedsDataSizeUpdate(i, bWithDefault)); if (i->DataSize == INVALID_FILEPOS_T) return INVALID_FILEPOS_T; Element->Base.DataSize += EBML_ElementFullSize(i,bWithDefault); } #ifdef TODO if (bChecksumUsed) { Element->DataSize += EBML_ElementFullSize(Element->Checksum,bWithDefault); } #endif } return INHERITED(Element,ebml_element_vmt,EBML_MASTER_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } void EBML_MasterAddMandatory(ebml_master *Element, bool_t SetDefault) { const ebml_semantic *i; for (i=Element->Base.Context->Semantic;i->eClass;++i) { if (i->Mandatory && i->Unique) EBML_MasterFindFirstElt(Element,i->eClass,1,SetDefault); } } static void PostCreate(ebml_master *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_MASTER_CLASS)->PostCreate(Element, SetDefault); if (SetDefault) { EBML_MasterAddMandatory(Element, SetDefault); Element->Base.bValueIsSet = 1; } } static err_t ReadData(ebml_master *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { int UpperEltFound = 0; bool_t bFirst = 1; ebml_element *SubElement = NULL; ebml_crc *CRCElement = NULL; stream *ReadStream = Input; array CrcBuffer; uint8_t *CRCData = NULL; size_t CRCDataSize; // remove all existing elements, including the mandatory ones... NodeTree_Clear((nodetree*)Element); Element->Base.bValueIsSet = 0; // read blocks and discard the ones we don't care about if (Element->Base.DataSize > 0 || !EBML_ElementIsFiniteSize((ebml_element*)Element)) { ebml_parser_context Context; filepos_t MaxSizeToRead; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) return ERR_END_OF_FILE; MaxSizeToRead = Element->Base.DataSize; Context.UpContext = ParserContext; Context.Context = Element->Base.Context; Context.EndPosition = EBML_ElementPositionEnd((ebml_element*)Element); Context.Profile = ParserContext->Profile; SubElement = EBML_FindNextElement(Input,&Context,&UpperEltFound,AllowDummyElt); while (SubElement && UpperEltFound<=0 && (!EBML_ElementIsFiniteSize((ebml_element*)Element) || EBML_ElementPositionEnd(SubElement) <= EBML_ElementPositionEnd((ebml_element*)Element))) { if (!AllowDummyElt && EBML_ElementIsDummy(SubElement)) { // TODO: this should never happen EBML_ElementSkipData(SubElement,ReadStream,&Context,NULL,AllowDummyElt); NodeDelete((node*)SubElement); // forget this unknown element SubElement = NULL; } else { if (EBML_ElementReadData(SubElement,ReadStream,&Context,AllowDummyElt, Scope, DepthCheckCRC?DepthCheckCRC-1:0)==ERR_NONE) { if (bFirst && DepthCheckCRC && Scope!=SCOPE_NO_DATA && EBML_ElementIsType(SubElement, &EBML_ContextEbmlCrc32) && CRCElement==NULL) { if (EBML_ElementIsFiniteSize((ebml_element*)Element)) { if (Node_IsPartOf(Input, MEMSTREAM_CLASS)) { filepos_t DataPos = Stream_Seek(Input,EBML_ElementPositionEnd(SubElement),SEEK_SET); filepos_t OffSet; Node_GET(Input,MEMSTREAM_OFFSET,&OffSet); Node_GET(Input,MEMSTREAM_PTR,&CRCData); CRCData += (DataPos - OffSet); CRCDataSize = (size_t)(EBML_ElementDataSize((ebml_element*)Element,1) - EBML_ElementFullSize(SubElement,1)); Stream_Read(Input, CRCData, CRCDataSize, NULL); } else { // read the rest of the element in memory to avoid reading it a second time later ArrayInit(&CrcBuffer); if (ArrayResize(&CrcBuffer, (size_t)(EBML_ElementPositionEnd((ebml_element*)Element) - EBML_ElementPositionEnd(SubElement)), 0)) { CRCData = ARRAYBEGIN(CrcBuffer,uint8_t); CRCDataSize = ARRAYCOUNT(CrcBuffer,uint8_t); ReadStream = (stream*)NodeCreate(Element, MEMSTREAM_CLASS); if (ReadStream==NULL) { ReadStream=Input; // revert back to normal reading ArrayClear(&CrcBuffer); } else { filepos_t Offset = EBML_ElementPositionEnd(SubElement); Node_Set(ReadStream, MEMSTREAM_DATA, CRCData, CRCDataSize); Node_SET(ReadStream, MEMSTREAM_OFFSET, &Offset); Stream_Seek(Input,EBML_ElementPositionEnd(SubElement),SEEK_SET); if (Stream_Read(Input, CRCData, CRCDataSize, NULL)!=ERR_NONE) { ReadStream=Input; // revert back to normal reading ArrayClear(&CrcBuffer); } } } } CRCElement = (ebml_crc*)SubElement; } bFirst = 0; } if (CRCElement != (ebml_crc*)SubElement) EBML_MasterAppend(Element,SubElement); // just in case EBML_ElementSkipData(SubElement,ReadStream,&Context,NULL,AllowDummyElt); } else { NodeDelete((node*)SubElement); SubElement = NULL; } } if (SubElement) MaxSizeToRead = EBML_ElementPositionEnd((ebml_element*)Element) - EBML_ElementPositionEnd(SubElement); // even if it's the default value if (UpperEltFound > 0) { UpperEltFound--; if (UpperEltFound > 0 || (EBML_ElementIsFiniteSize((ebml_element*)Element) && MaxSizeToRead <= 0)) goto processCrc; continue; } if (UpperEltFound < 0) { UpperEltFound++; if (UpperEltFound < 0) goto processCrc; } if (EBML_ElementIsFiniteSize((ebml_element*)Element) && MaxSizeToRead <= 0) { goto processCrc;// this level is finished } SubElement = EBML_FindNextElement(ReadStream,&Context,&UpperEltFound,AllowDummyElt); } } processCrc: if (CRCData!=NULL) { Element->CheckSumStatus = EBML_CRCMatches(CRCElement, CRCData, CRCDataSize)?2:1; if (CRCData == ARRAYBEGIN(CrcBuffer,uint8_t)) { StreamClose(ReadStream); ArrayClear(&CrcBuffer); } } Element->Base.bValueIsSet = 1; if (UpperEltFound>0) // move back to the upper element beginning so that the next loop can find it { assert(SubElement!=NULL); Stream_Seek(Input,SubElement->ElementPosition,SEEK_SET); } return ERR_NONE; } bool_t EBML_MasterUseChecksum(ebml_master *Element, bool_t Use) { if (Use && Element->CheckSumStatus==0) { Element->Base.bNeedDataSizeUpdate = 1; Element->CheckSumStatus = 1; return 1; } if (!Use && Element->CheckSumStatus) { Element->Base.bNeedDataSizeUpdate = 1; Element->CheckSumStatus = 0; return 1; } return 0; } bool_t EBML_MasterIsChecksumValid(const ebml_master *Element) { return (Element->CheckSumStatus!=1); } #if defined(CONFIG_EBML_WRITING) static err_t InternalRender(ebml_master *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { ebml_element *i; filepos_t ItemRendered; err_t Err = ERR_NONE; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) { if (!bWithDefault && EBML_ElementIsDefaultValue(i)) continue; Err = EBML_ElementRender(i,Output, bWithDefault, 0, bForceWithoutMandatory, &ItemRendered); if (Err!=ERR_NONE) return Err; *Rendered += ItemRendered; } return Err; } static err_t RenderData(ebml_master *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { filepos_t _Rendered; err_t Err = ERR_NONE; if (!Rendered) Rendered = &_Rendered; *Rendered = 0; if (!bForceWithoutMandatory) { assert(CheckMandatory((ebml_master*)Element, bWithDefault)); } if (!Element->CheckSumStatus) Err = InternalRender(Element, Output, bForceWithoutMandatory, bWithDefault, Rendered); else { // render to memory, compute the CRC, write the CRC and then the virtual data array TmpBuf; bool_t IsMemory = Node_IsPartOf(Output,MEMSTREAM_CLASS); ArrayInit(&TmpBuf); if (!IsMemory && !ArrayResize(&TmpBuf, (size_t)Element->Base.DataSize - 6, 0)) Err = ERR_OUT_OF_MEMORY; else { ebml_crc *CrcElt = (ebml_crc*)EBML_ElementCreate(Element, &EBML_ContextEbmlCrc32, 0, NULL); if (!CrcElt) Err = ERR_OUT_OF_MEMORY; else { if (!IsMemory) { stream *VOutput = (stream*)NodeCreate(Element, MEMSTREAM_CLASS); if (!VOutput) Err = ERR_OUT_OF_MEMORY; else { filepos_t Offset = Stream_Seek(Output,0,SEEK_CUR) + 6; Node_Set(VOutput, MEMSTREAM_DATA, ARRAYBEGIN(TmpBuf,uint8_t), ARRAYCOUNT(TmpBuf,uint8_t)); Node_SET(VOutput, MEMSTREAM_OFFSET, &Offset); Err = InternalRender(Element, VOutput, bForceWithoutMandatory, bWithDefault, Rendered); assert(Err!=ERR_NONE || *Rendered == ARRAYCOUNT(TmpBuf,uint8_t)); if (Err==ERR_NONE) { filepos_t CrcSize; EBML_CRCAddBuffer(CrcElt, ARRAYBEGIN(TmpBuf,uint8_t), ARRAYCOUNT(TmpBuf,uint8_t)); EBML_CRCFinalize(CrcElt); Err = EBML_ElementRender((ebml_element*)CrcElt, Output, bWithDefault, 0, bForceWithoutMandatory, &CrcSize); if (Err==ERR_NONE) { size_t Written; Err = Stream_Write(Output, ARRAYBEGIN(TmpBuf,uint8_t), ARRAYCOUNT(TmpBuf,uint8_t), &Written); assert(Err!=ERR_NONE || Written == *Rendered); *Rendered = Written + CrcSize; } } StreamClose(VOutput); } } else { filepos_t VirtualPos = Stream_Seek(Output,6,SEEK_CUR); // pass the CRC for now Err = InternalRender(Element, Output, bForceWithoutMandatory, bWithDefault, Rendered); if (Err==ERR_NONE) { filepos_t CrcSize; uint8_t *Data; Node_GET(Output,MEMSTREAM_OFFSET,&CrcSize); Node_GET(Output,MEMSTREAM_PTR,&Data); EBML_CRCAddBuffer(CrcElt, Data + (VirtualPos - CrcSize), (size_t)Element->Base.DataSize-6); EBML_CRCFinalize(CrcElt); Stream_Seek(Output,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET); Err = EBML_ElementRender((ebml_element*)CrcElt, Output, bWithDefault, 0, bForceWithoutMandatory, &CrcSize); *Rendered = *Rendered + CrcSize; Stream_Seek(Output,EBML_ElementPositionEnd((ebml_element*)Element),SEEK_SET); } } NodeDelete((node*)CrcElt); } } ArrayClear(&TmpBuf); } return Err; } #endif static ebml_element *Copy(const ebml_master *Element, const void *Cookie) { ebml_element *i, *Elt; ebml_master *Result = (ebml_master*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { EBML_MasterErase(Result); // delete the children elements created by default Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; Result->CheckSumStatus = Element->CheckSumStatus; for (i=EBML_MasterChildren(Element);i;i=EBML_MasterNext(i)) { Elt = EBML_ElementCopy(i,Cookie); if (!Elt || EBML_MasterAppend(Result, Elt)!=ERR_NONE) { NodeDelete((node*)Result); Result = NULL; break; } } } return (ebml_element*)Result; } static void RemoveChild(ebml_master* p,ebml_element* Child) { p->Base.bNeedDataSizeUpdate = 1; INHERITED(p,nodetree_vmt,EBML_MASTER_CLASS)->RemoveChild(p,Child); } static void AddChild(ebml_master* p,ebml_element* Child,ebml_element* Before) { p->Base.bNeedDataSizeUpdate = 1; INHERITED(p,nodetree_vmt,EBML_MASTER_CLASS)->AddChild(p,Child,Before); } META_START(EBMLMaster_Class,EBML_MASTER_CLASS) META_CLASS(SIZE,sizeof(ebml_master)) META_VMT(TYPE_FUNC,nodetree_vmt,AddChild,AddChild) META_VMT(TYPE_FUNC,nodetree_vmt,RemoveChild,RemoveChild) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreate) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSize) META_VMT(TYPE_FUNC,ebml_element_vmt,NeedsDataSizeUpdate,NeedsDataSizeUpdate) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END(EBML_ELEMENT_CLASS) void EBML_MasterCheckContext(ebml_master *Element, int ProfileMask, bool_t (*ErrCallback)(void *cookie, int type, const tchar_t *ClassName, const ebml_element*), void *cookie) { tchar_t ClassString[MAXPATH]; ebml_element *i, *SubElt; const ebml_semantic *s; for (i=EBML_MasterChildren(Element);i;i=i?EBML_MasterNext(i):NULL) { if (!Node_IsPartOf(i,EBML_DUMMY_ID)) { for (s=Element->Base.Context->Semantic; s->eClass; ++s) { if (s->eClass->Id == i->Context->Id) { if (s->DisabledProfile & ProfileMask) { Node_FromStr(Element,ClassString,TSIZEOF(ClassString),s->eClass->ElementName); if (ErrCallback && ErrCallback(cookie,MASTER_CHECK_PROFILE_INVALID,ClassString,i)) { EBML_MasterRemove(Element,i); // make sure it doesn't remain in the list NodeDelete((node*)i); i=EBML_MasterChildren(Element); break; } } if (s->Unique && (SubElt=EBML_MasterFindChild(Element,s->eClass)) && (SubElt=EBML_MasterNextChild(Element,SubElt))) { Node_FromStr(Element,ClassString,TSIZEOF(ClassString),s->eClass->ElementName); if (ErrCallback && ErrCallback(cookie,MASTER_CHECK_MULTIPLE_UNIQUE,ClassString,SubElt)) { EBML_MasterRemove(Element,i); // make sure it doesn't remain in the list NodeDelete((node*)i); i=EBML_MasterChildren(Element); break; } } break; } } } } for (s=Element->Base.Context->Semantic; s->eClass; ++s) { if (s->Mandatory && !s->eClass->HasDefault && !EBML_MasterFindChild(Element,s->eClass)) { Node_FromStr(Element,ClassString,TSIZEOF(ClassString),s->eClass->ElementName); if (ErrCallback) ErrCallback(cookie,MASTER_CHECK_MISSING_MANDATORY,ClassString,NULL); } } } bcmatroska2-5.3.101/libebml2/ebmlnumber.c000066400000000000000000000363621462133141200200640ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" static err_t ReadDataInt(ebml_integer *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; char Buffer[8]; int i; assert(Element->Base.DataSize <= 8); Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } Result = Stream_Read(Input,Buffer,(size_t)Element->Base.DataSize,NULL); if (Result != ERR_NONE) return Result; Element->Value = 0; for (i=0; i<(int)Element->Base.DataSize; i++) { Element->Value <<= 8; Element->Value |= (uint8_t)Buffer[i]; } Element->Base.bValueIsSet = 1; failed: return Result; } static err_t ReadDataSignedInt(ebml_integer *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; char Buffer[8]; int i; assert(Element->Base.DataSize <= 8); Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } Result = Stream_Read(Input,Buffer,(size_t)Element->Base.DataSize,NULL); if (Result != ERR_NONE) goto failed; if (Buffer[0] & 0x80) // check wether it's a positive or negative value Element->Value = -1; else Element->Value = 0; for (i=0; i<(int)Element->Base.DataSize; i++) { Element->Value <<= 8; Element->Value |= Buffer[i]; } Element->Base.bValueIsSet = 1; failed: return Result; } #if defined(CONFIG_EBML_WRITING) static err_t RenderDataSignedInt(ebml_integer *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { uint8_t FinalData[8]; // we don't handle more than 64 bits integers size_t i; int64_t TempValue = Element->Value; err_t Err; if (Element->Base.SizeLength > EBML_MAX_SIZE) return 0; // integers larger than 64 bits are not supported if (Element->Base.DataSize == 0) return 0; // nothing to write TempValue = Element->Value; if (Element->Base.DefaultSize > Element->Base.DataSize) { for (i=Element->Base.DefaultSize - (int)Element->Base.DataSize - 1;i;--i) FinalData[i-1] = 0; i = Element->Base.DefaultSize - (int)Element->Base.DataSize; } else i=(size_t)Element->Base.DataSize; for (;i;--i) { FinalData[i-1] = (uint8_t)(TempValue & 0xFF); TempValue >>= 8; } if (Element->Base.DefaultSize > Element->Base.DataSize) Err = Stream_Write(Output,FinalData,(size_t)Element->Base.DefaultSize,&i); else Err = Stream_Write(Output,FinalData,(size_t)Element->Base.DataSize,&i); if (Rendered) *Rendered = i; return Err; } static err_t RenderDataInt(ebml_integer *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { uint8_t FinalData[8]; // we don't handle more than 64 bits integers size_t i; uint64_t TempValue = Element->Value; err_t Err; if (Element->Base.SizeLength > EBML_MAX_SIZE) return 0; // integers larger than 64 bits are not supported if (Element->Base.DataSize == 0) return 0; // nothing to write TempValue = Element->Value; if (Element->Base.DefaultSize > Element->Base.DataSize) { for (i=Element->Base.DefaultSize - (int)Element->Base.DataSize - 1;i;--i) FinalData[i-1] = 0; i = Element->Base.DefaultSize - (int)Element->Base.DataSize; } else i=(size_t)Element->Base.DataSize; for (;i;--i) { FinalData[i-1] = (uint8_t)(TempValue & 0xFF); TempValue >>= 8; } if (Element->Base.DefaultSize > Element->Base.DataSize) Err = Stream_Write(Output,FinalData,(size_t)Element->Base.DefaultSize,&i); else Err = Stream_Write(Output,FinalData,(size_t)Element->Base.DataSize,&i); if (Rendered) *Rendered = i; return Err; } static err_t RenderDataFloat(ebml_float *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { err_t Err; size_t i = 0; if (Element->Base.DataSize == 8) { union { uint32_t i; double f; } data; uint64_t Buf; data.f = Element->Value; Buf = LOAD64BE(&data.i); Err = Stream_Write(Output,&Buf,8,&i); } else { union { uint32_t i; float f; } data; uint32_t Buf; data.f = (float)Element->Value; Buf = LOAD32BE(&data.i); Err = Stream_Write(Output,&Buf,4,&i); } if (Rendered) *Rendered = i; return Err; } #endif static bool_t ValidateSizeInt(const ebml_element *p) { return EBML_ElementIsFiniteSize(p) && (p->DataSize <= 8); } static bool_t ValidateSizeFloat(const ebml_element *p) { return EBML_ElementIsFiniteSize(p) && (p->DataSize == 8 || p->DataSize == 4); } static err_t ReadDataFloat(ebml_float *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { uint8_t Value[8]; err_t Result; assert(Element->Base.DataSize == 8 || Element->Base.DataSize == 4); Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } Result = Stream_Read(Input,Value,min((size_t)Element->Base.DataSize,sizeof(Value)),NULL); // min is for code safety if (Result != ERR_NONE) goto failed; if (Element->Base.DataSize == 4) { union { float f; uint32_t i; } data; data.i = LOAD32BE(Value); Element->Value = data.f; Element->Base.bValueIsSet = 1; } else if (Element->Base.DataSize == 8) { union { double f; uint64_t i; } data; data.i = LOAD64BE(Value); Element->Value = data.f; Element->Base.bValueIsSet = 1; } else Result = ERR_INVALID_PARAM; failed: return Result; } static bool_t IsDefaultValueInt(const ebml_integer *Element) { return Element->Base.Context->HasDefault && (!Element->Base.bValueIsSet || (Element->Value == (int64_t)Element->Base.Context->DefaultValue)); } static bool_t IsDefaultValueFloat(const ebml_float *Element) { return Element->Base.Context->HasDefault && (!Element->Base.bValueIsSet || (Element->Value == (double)Element->Base.Context->DefaultValue)); } static filepos_t UpdateSizeSignedInt(ebml_integer *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) { if (Element->Value <= 0x7F && Element->Value >= (-0x80)) { Element->Base.DataSize = 1; } else if (Element->Value <= 0x7FFF && Element->Value >= (-0x8000)) { Element->Base.DataSize = 2; } else if (Element->Value <= 0x7FFFFF && Element->Value >= (-0x800000)) { Element->Base.DataSize = 3; } else if (Element->Value <= (int64_t)(0x7FFFFFFF) && Element->Value >= -(int64_t)(0x80000000)) { Element->Base.DataSize = 4; } else if (Element->Value <= 0x7FFFFFFFFF && Element->Value >= (-0x8000000000)) { Element->Base.DataSize = 5; } else if (Element->Value <= 0x7FFFFFFFFFFF && Element->Value >= (-0x800000000000)) { Element->Base.DataSize = 6; } else if (Element->Value <= 0x7FFFFFFFFFFFFF && Element->Value >= (-0x80000000000000)) { Element->Base.DataSize = 7; } else Element->Base.DataSize = 8; } return INHERITED(Element,ebml_element_vmt,EBML_SINTEGER_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static filepos_t UpdateSizeInt(ebml_integer *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) { if ((uint64_t)Element->Value <= 0xFF) { Element->Base.DataSize = 1; } else if ((uint64_t)Element->Value <= 0xFFFF) { Element->Base.DataSize = 2; } else if ((uint64_t)Element->Value <= 0xFFFFFF) { Element->Base.DataSize = 3; } else if ((uint64_t)Element->Value <= 0xFFFFFFFF) { Element->Base.DataSize = 4; } else if ((uint64_t)Element->Value <= 0xFFFFFFFFFF) { Element->Base.DataSize = 5; } else if ((uint64_t)Element->Value <= 0xFFFFFFFFFFFF) { Element->Base.DataSize = 6; } else if ((uint64_t)Element->Value <= 0xFFFFFFFFFFFFFF) { Element->Base.DataSize = 7; } else Element->Base.DataSize = 8; } return INHERITED(Element,ebml_element_vmt,EBML_INTEGER_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static void PostCreateInt(ebml_element *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_INTEGER_CLASS)->PostCreate(Element, SetDefault); Element->DefaultSize = 1; if (SetDefault && Element->Context->HasDefault) EBML_IntegerSetValue((ebml_integer*)Element, Element->Context->DefaultValue); } static void PostCreateSignedInt(ebml_element *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_SINTEGER_CLASS)->PostCreate(Element, SetDefault); Element->DefaultSize = 1; if (SetDefault && Element->Context->HasDefault) EBML_IntegerSetValue((ebml_integer*)Element, Element->Context->DefaultValue); } static void PostCreateFloat(ebml_element *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_FLOAT_CLASS)->PostCreate(Element, SetDefault); Element->DefaultSize = 4; if (SetDefault && Element->Context->HasDefault) EBML_FloatSetValue((ebml_float*)Element, Element->Context->DefaultValue); } static ebml_integer *CopyInt(const ebml_integer *Element, const void *Cookie) { ebml_integer *Result = (ebml_integer*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { Result->Value = Element->Value; Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; } return Result; } static ebml_float *CopyFloat(const ebml_float *Element, const void *Cookie) { ebml_float *Result = (ebml_float*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { Result->Value = Element->Value; Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; } return Result; } META_START(EBMLInteger_Class,EBML_INTEGER_CLASS) META_CLASS(SIZE,sizeof(ebml_integer)) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValueInt) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSizeInt) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadDataInt) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderDataInt) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateSizeInt) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreateInt) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,CopyInt) META_END_CONTINUE(EBML_ELEMENT_CLASS) META_START_CONTINUE(EBML_SINTEGER_CLASS) META_CLASS(SIZE,sizeof(ebml_integer)) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValueInt) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSizeInt) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadDataSignedInt) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderDataSignedInt) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateSizeSignedInt) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreateSignedInt) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,CopyInt) META_END_CONTINUE(EBML_ELEMENT_CLASS) META_START_CONTINUE(EBML_BOOLEAN_CLASS) META_END_CONTINUE(EBML_INTEGER_CLASS) META_START_CONTINUE(EBML_FLOAT_CLASS) META_CLASS(SIZE,sizeof(ebml_float)) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValueFloat) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSizeFloat) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadDataFloat) META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreateFloat) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderDataFloat) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,CopyFloat) META_END(EBML_ELEMENT_CLASS) void EBML_IntegerSetValue(ebml_integer *Element, int64_t Value) { Element->Value = Value; Element->Base.bValueIsSet = 1; Element->Base.bNeedDataSizeUpdate = 1; } int64_t EBML_IntegerValue(const ebml_integer *Element) { #if !defined(NDEBUG) assert(Node_IsPartOf(Element,EBML_INTEGER_CLASS) || Node_IsPartOf(Element,EBML_SINTEGER_CLASS)); assert(Element->Base.bValueIsSet); #endif return Element->Value; } double EBML_FloatValue(const ebml_float *Element) { #if !defined(NDEBUG) assert(Element->Base.bValueIsSet); #endif return Element->Value; } void EBML_FloatSetValue(ebml_float *Element, double Value) { Element->Value = Value; Element->Base.bValueIsSet = 1; Element->Base.bNeedDataSizeUpdate = 1; } bcmatroska2-5.3.101/libebml2/ebmlstring.c000066400000000000000000000210211462133141200200640ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" #if defined(CONFIG_EBML_UNICODE) err_t EBML_UniStringSetValue(ebml_string *Element,const tchar_t *Value) { char Data[2048]; if (!Node_IsPartOf(Element,EBML_UNISTRING_CLASS)) return ERR_INVALID_DATA; Node_ToUTF8(Element,Data,sizeof(Data)-1,Value); Data[sizeof(Data)-1] = 0; return EBML_StringSetValue(Element,Data); } #endif err_t EBML_StringSetValue(ebml_string *Element,const char *Value) { if (Element->Base.bValueIsSet && Element->Buffer) free((char*)Element->Buffer); Element->Buffer = strdup(Value); Element->Base.bValueIsSet = 1; Element->Base.DataSize = strlen(Element->Buffer); Element->Base.bNeedDataSizeUpdate = 0; return ERR_NONE; } void EBML_StringGet(ebml_string *Element,tchar_t *Out, size_t OutLen) { if (!Element->Buffer) { if (OutLen) *Out = 0; } else { #if defined(CONFIG_EBML_UNICODE) if (Node_IsPartOf(Element,EBML_UNISTRING_CLASS)) Node_FromUTF8(Element,Out,OutLen,Element->Buffer); else #endif Node_FromStr(Element,Out,OutLen,Element->Buffer); } } static err_t ReadData(ebml_string *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result; char *Buffer; Element->Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { return ERR_READ; } Buffer = malloc((size_t)Element->Base.DataSize+1); if (!Buffer) return ERR_OUT_OF_MEMORY; Result = Stream_Read(Input,Buffer,(size_t)Element->Base.DataSize,NULL); if (Result != ERR_NONE) goto failed; Buffer[Element->Base.DataSize] = 0; Element->Buffer = Buffer; Element->Base.bValueIsSet = 1; return ERR_NONE; failed: free(Buffer); Element->Buffer = NULL; return Result; } #if defined(CONFIG_EBML_WRITING) static err_t RenderData(ebml_string *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { size_t Written; err_t Err = Stream_Write(Output,Element->Buffer,(size_t)Element->Base.DataSize,&Written); if (Rendered) *Rendered = Written; if ((Err == ERR_NONE) && (Element->Base.DefaultSize > (int)Element->Base.DataSize)) { char *Padding = malloc(Element->Base.DefaultSize - (int)Element->Base.DataSize); if (!Padding) return ERR_OUT_OF_MEMORY; memset(Padding,0,Element->Base.DefaultSize - (int)Element->Base.DataSize); Err = Stream_Write(Output,Padding,Element->Base.DefaultSize - (int)Element->Base.DataSize,&Written); if (Rendered) *Rendered += Written; free(Padding); } return Err; } #endif #if 0 err_t EBML_AsciiStringRead(ebml_string *Element, stream *Input, tchar_t *Out, size_t OutLen) { if (Node_IsPartOf(Element,EBML_STRING_CLASS)) return ERR_INVALID_DATA; else { err_t Result = EBML_ElementReadData(Element, Input); if (Result != ERR_NONE) return Result; Node_FromStr(Element,Out,OutLen,Element->Buffer); return Result; } } err_t EBML_UnicodeStringRead(ebml_string *Element, stream *Input, tchar_t *Out, size_t OutLen) { if (Node_IsPartOf(Element,EBML_UNISTRING_CLASS)) return ERR_INVALID_DATA; else { err_t Result = EBML_ElementReadData(Element, Input); if (Result != ERR_NONE) return Result; Node_FromUTF8(Element,Out,OutLen,Element->Buffer); return Result; } } #endif static void Delete(ebml_string *p) { if (p->Buffer) free((char*)p->Buffer); } static filepos_t UpdateDataSize(ebml_string *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) Element->Base.DataSize = strlen(Element->Buffer); return INHERITED(Element,ebml_element_vmt,EBML_STRING_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static filepos_t UpdateDataSizeUni(ebml_string *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) Element->Base.DataSize = strlen(Element->Buffer); return INHERITED(Element,ebml_element_vmt,EBML_UNISTRING_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static bool_t IsDefaultValue(const ebml_string *Element) { return Element->Base.Context->HasDefault && (!Element->Base.bValueIsSet || strcmp(Element->Buffer,(const char*)Element->Base.Context->DefaultValue)==0); } static void PostCreateString(ebml_element *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_STRING_CLASS)->PostCreate(Element, SetDefault); if (SetDefault && Element->Context->HasDefault) EBML_StringSetValue((ebml_string*)Element, (const char *)Element->Context->DefaultValue); } static void PostCreateUniString(ebml_element *Element, bool_t SetDefault) { INHERITED(Element,ebml_element_vmt,EBML_UNISTRING_CLASS)->PostCreate(Element, SetDefault); if (SetDefault && Element->Context->HasDefault) EBML_StringSetValue((ebml_string*)Element, (const char *)Element->Context->DefaultValue); } static ebml_string *Copy(const ebml_string *Element, const void *Cookie) { ebml_string *Result = (ebml_string*)EBML_ElementCreate(Element,Element->Base.Context,0,Cookie); if (Result) { Result->Buffer = strdup(Element->Buffer); Result->Base.bValueIsSet = Element->Base.bValueIsSet; Result->Base.DataSize = Element->Base.DataSize; Result->Base.ElementPosition = Element->Base.ElementPosition; Result->Base.SizeLength = Element->Base.SizeLength; Result->Base.SizePosition = Element->Base.SizePosition; Result->Base.bNeedDataSizeUpdate = Element->Base.bNeedDataSizeUpdate; } return Result; } META_START(EBMLString_Class,EBML_STRING_CLASS) META_CLASS(SIZE,sizeof(ebml_string)) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreateString) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) META_END_CONTINUE(EBML_ELEMENT_CLASS) META_START_CONTINUE(EBML_UNISTRING_CLASS) META_CLASS(SIZE,sizeof(ebml_string)) META_CLASS(DELETE,Delete) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSizeUni) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,PostCreate,PostCreateUniString) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) META_END(EBML_ELEMENT_CLASS) bcmatroska2-5.3.101/libebml2/ebmlvoid.c000066400000000000000000000131241462133141200175240ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ebml/ebml.h" #include "ebml/ebml_internal.h" static bool_t IsDefaultValue(const ebml_element *Element) { return 0; } static err_t ReadData(ebml_element *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { EBML_ElementSkipData(Element,Input,ParserContext,NULL,AllowDummyElt); return ERR_NONE; } #if defined(CONFIG_EBML_WRITING) static err_t RenderData(ebml_element *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { size_t Written, Left = (size_t)Element->DataSize; err_t Err = ERR_NONE; uint8_t Buf[2*1024]; // write 2 KB chunks at a time memset(Buf,0,sizeof(Buf)); while (Err==ERR_NONE && Left) { Err = Stream_Write(Output,Buf,min(Left,sizeof(Buf)),&Written); if (Err == ERR_NONE) Left -= min(Left,sizeof(Buf)); } if (Rendered) *Rendered = Element->DataSize - Left; return Err; } #endif static ebml_element *Copy(const ebml_element *Element, const void *Cookie) { ebml_element *Result = EBML_ElementCreate(Element,Element->Context,0,Cookie); if (Result) { Result->bValueIsSet = Element->bValueIsSet; Result->DataSize = Element->DataSize; Result->ElementPosition = Element->ElementPosition; Result->SizeLength = Element->SizeLength; Result->SizePosition = Element->SizePosition; Result->bNeedDataSizeUpdate = Element->bNeedDataSizeUpdate; } return Result; } META_START(EBMLVoid_Class,EBML_VOID_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,IsDefaultValue,IsDefaultValue) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,Copy) META_END(EBML_ELEMENT_CLASS) #if defined(CONFIG_EBML_WRITING) bool_t EBML_VoidSetFullSize(ebml_element *Void, filepos_t DataSize) { assert(Node_IsPartOf(Void,EBML_VOID_CLASS)); Void->DataSize = DataSize - 1 - EBML_CodedSizeLength(DataSize,0,1); // 1 is the length of the Void ID Void->bValueIsSet = 1; Void->bNeedDataSizeUpdate = 0; return Void->DataSize >= 0; } filepos_t EBML_VoidReplaceWith(ebml_element *Void, ebml_element *ReplacedWith, stream *Output, bool_t ComeBackAfterward, bool_t bWithDefault) { filepos_t CurrentPosition; assert(Node_IsPartOf(Void,EBML_VOID_CLASS)); EBML_ElementUpdateSize(ReplacedWith,bWithDefault,0); if (EBML_ElementFullSize(Void,1) < EBML_ElementFullSize(ReplacedWith,1)) // the element can't be written here ! return INVALID_FILEPOS_T; if (EBML_ElementFullSize(Void,1) - EBML_ElementFullSize(ReplacedWith,1) == 1) // there is not enough space to put a filling element return INVALID_FILEPOS_T; CurrentPosition = Stream_Seek(Output,0,SEEK_CUR); Stream_Seek(Output,Void->ElementPosition,SEEK_SET); EBML_ElementRender(ReplacedWith,Output,bWithDefault,0,1,NULL); if (EBML_ElementFullSize(Void,1) - EBML_ElementFullSize(ReplacedWith,1) > 1) { // fill the rest with another void element ebml_element *aTmp = EBML_ElementCreate(Void,Void->Context,0,NULL); if (aTmp) { filepos_t HeadBefore,HeadAfter; EBML_VoidSetFullSize(aTmp, EBML_ElementFullSize(Void,1) - EBML_ElementFullSize(ReplacedWith,1)); HeadBefore = EBML_ElementFullSize(aTmp,1) - aTmp->DataSize; aTmp->DataSize = aTmp->DataSize - EBML_CodedSizeLength(aTmp->DataSize, aTmp->SizeLength, EBML_ElementIsFiniteSize(aTmp)); HeadAfter = EBML_ElementFullSize(aTmp,1) - aTmp->DataSize; if (HeadBefore != HeadAfter) aTmp->SizeLength = (int8_t)(EBML_CodedSizeLength(aTmp->DataSize, aTmp->SizeLength, EBML_ElementIsFiniteSize(aTmp)) - (HeadAfter - HeadBefore)); EBML_ElementRenderHead(aTmp,Output,0,NULL); NodeDelete((node*)aTmp); } } if (ComeBackAfterward) Stream_Seek(Output,CurrentPosition,SEEK_SET); return EBML_ElementFullSize(Void,1); } #endif bcmatroska2-5.3.101/libebml2/legacy/000077500000000000000000000000001462133141200170225ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/legacy/ebml/000077500000000000000000000000001462133141200177415ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlBinary.h000066400000000000000000000050171462133141200221410ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_BINARY_H #define _EBML2_EBML_BINARY_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlBinary : public EbmlElement { public: EbmlBinary(const ebml_context &ec, ebml_element *WithNode = NULL) :EbmlElement(ec,WithNode) {} void CopyBuffer(const void *Buffer, size_t BufferSize); void SetBuffer(const binary *Buffer, size_t BufferSize); virtual EbmlElement * Clone() const; const binary* GetBuffer() const; binary* GetBuffer(); // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_BINARY_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlConfig.h000066400000000000000000000050341462133141200221210ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_CONFIG_H #define _EBML2_EBML_CONFIG_H #include "corec/corec.h" #define LIBEBML_NAMESPACE libebml typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef uint8_t binary; #define countof(x) (sizeof(x)/sizeof(*(x))) #ifdef __GNUC__ #define EBML_PRETTYLONGINT(c) (c ## ll) #else // __GNUC__ #define EBML_PRETTYLONGINT(c) (c) #endif // __GNUC__ namespace LIBEBML_NAMESPACE { enum endianess { big_endian, ///< PowerPC, Alpha, 68000 little_endian ///< x86, x64, (most) ARM, (most) MIPS }; class big_int16 { public: big_int16(int16_t); big_int16(); void Fill(binary *Buffer) const; void Eval(const binary *Buffer); operator int16() const; private: int16_t Value; }; }; #endif // _EBML2_EBML_CONFIG_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlContexts.h000066400000000000000000000037111462133141200225230ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_CONTEXTS_H #define _EBML2_EBML_CONTEXTS_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { const EbmlSemanticContext & GetEbmlGlobal_Context(); }; #ifdef __cplusplus extern "C" { #endif extern void ebml_init(); extern void ebml_done(); #ifdef __cplusplus } #endif #endif // _EBML2_EBML_CONTEXTS_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlCrc32.h000066400000000000000000000034641462133141200215750ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_CRC32_H #define _EBML2_EBML_CRC32_H #include "ebml/EbmlBinary.h" namespace LIBEBML_NAMESPACE { DECLARE_EBML_BINARY(EbmlCrc32) }; }; #endif // _EBML2_EBML_CRC32_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlDate.h000066400000000000000000000051021462133141200215650ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_DATE_H #define _EBML2_EBML_DATE_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlDate : public EbmlElement { public: EbmlDate(const ebml_context &ec, ebml_element *WithNode = NULL) :EbmlElement(ec, WithNode) {} virtual EbmlElement * Clone() const; datetime_t GetEpochDate() const; /*! \brief set the date with a UNIX/C/EPOCH form \param NewDate UNIX/C date in UTC (no timezone) */ void SetEpochDate(int32_t NewDate); virtual bool IsSmallerThan(const EbmlElement *Cmp) const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_DATE_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlDummy.h000066400000000000000000000033141462133141200220060ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_DUMMY_H #define _EBML2_EBML_DUMMY_H #endif // _EBML2_EBML_DUMMY_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlElement.h000066400000000000000000000365441462133141200223170ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_ELEMENT_H #define _EBML2_EBML_ELEMENT_H #include "ebml/EbmlConfig.h" #include "ebml/EbmlId.h" #include "ebml/IOCallback.h" #include "ebml/ebml.h" #define EBML_BINARY_LEGACY_CLASS FOURCC('E','B','B','C') #define EBML_DATE_LEGACY_CLASS FOURCC('E','B','B','D') #define EBML_INTEGER_LEGACY_CLASS FOURCC('E','B','B','I') #define EBML_SINTEGER_LEGACY_CLASS FOURCC('E','B','B','S') #define EBML_FLOAT_LEGACY_CLASS FOURCC('E','B','B','F') #define EBML_MASTER_LEGACY_CLASS FOURCC('E','B','B','M') #define EBML_STRING_LEGACY_CLASS FOURCC('E','B','B','G') #define EBML_UNISTRING_LEGACY_CLASS FOURCC('E','B','B','U') #define DECLARE_EBML_CONTEXT(x) #define DECLARE_EBML_MASTER(x) DECLARE_EBML_CONTEXT(x) \ class x : public EbmlMaster { \ public: x(ebml_element *WithNode = NULL); \ EBML_CONCRETE_CLASS(x) #define DECLARE_EBML_UINTEGER(x) DECLARE_EBML_CONTEXT(x) \ class x : public EbmlUInteger { \ public: x(ebml_element *WithNode = NULL); \ EBML_CONCRETE_CLASS(x) #define DECLARE_EBML_STRING(x) DECLARE_EBML_CONTEXT(x) \ class x : public EbmlString { \ public: x(ebml_element *WithNode = NULL); \ EBML_CONCRETE_CLASS(x) #define DECLARE_EBML_BINARY(x) DECLARE_EBML_CONTEXT(x) \ class x : public EbmlBinary { \ public: x(ebml_element *WithNode = NULL); \ EBML_CONCRETE_CLASS(x) #define DECLARE_EBML_VOID(x) DECLARE_EBML_CONTEXT(x) \ class x : public EbmlElement { \ public: x(ebml_element *WithNode = NULL); \ EBML_CONCRETE_CLASS(x) #define DEFINE_SEMANTIC_CONTEXT(x) #define DEFINE_START_SEMANTIC(x) static const ebml_semantic EBML_Semantic##x[] = { #define DEFINE_END_SEMANTIC(x) {0, 0, NULL}}; // end of the table #define DEFINE_SEMANTIC_ITEM(m,u,c) {m, u, &c::EBML_Context##c}, #define EBML_CONCRETE_CLASS(x) \ public: \ operator const EbmlId (void) const { return EbmlId(EBML_Context##x.Id); } \ virtual EbmlElement * Clone() const { return new x(*this); } \ virtual operator const ebml_context &() const { return EBML_Context##x; } \ static const ebml_context EBML_Context##x; \ static const ebml_context & GetContext() { return EBML_Context##x; } \ static void PostCreate(ebml_element *p, const void *Cookie) { if (!Cookie) Cookie=new x(p); Node_Set(p,EBML_ELEMENT_OBJECT,&Cookie,sizeof(Cookie)); } #define DEFINE_xxx_CONTEXT(x,global) \ const ebml_context EBML_Context##x = {0, EBML_MASTER_LEGACY_CLASS, 0, 0, "##x", EBML_Semantic##x, NULL}; #define DEFINE_EBML_MASTER(x,id,parent,name) DEFINE_xxx_MASTER(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_MASTER(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_MASTER_LEGACY_CLASS, 0, 0, name, EBML_Semantic##x, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlMaster(EBML_Context##x, WithNode) {} #define DEFINE_EBML_MASTER_CONS(x,id,parent,name) DEFINE_xxx_MASTER_CONS(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_MASTER_CONS(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_MASTER_LEGACY_CLASS, 0, 0, name, EBML_Semantic##x, global, x::PostCreate}; \ #define DEFINE_xxx_MASTER_ORPHAN(x,id,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_MASTER_LEGACY_CLASS, 0, 0, name, EBML_Semantic##x, global, x::PostCreate}; \ #define DEFINE_EBML_UINTEGER(x,id,parent,name) DEFINE_xxx_UINTEGER(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_UINTEGER(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_INTEGER_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlUInteger(EBML_Context##x, WithNode) {} #define DEFINE_EBML_UINTEGER_DEF(x,id,parent,name,defval) DEFINE_xxx_UINTEGER_DEF(x,id,parent,name,global,defval) #define DEFINE_xxx_UINTEGER_DEF(x,id,parent,name,global,defval) \ const ebml_context x::EBML_Context##x = {id, EBML_INTEGER_LEGACY_CLASS, 1, defval, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlUInteger(EBML_Context##x, defval, WithNode) {} #define DEFINE_EBML_SINTEGER(x,id,parent,name) DEFINE_xxx_SINTEGER(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_SINTEGER(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_SINTEGER_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlSInteger(EBML_Context##x, WithNode) {} #define DEFINE_EBML_SINTEGER_CONS(x,id,parent,name) DEFINE_xxx_SINTEGER_CONS(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_SINTEGER_CONS(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_SINTEGER_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ #define DEFINE_EBML_FLOAT(x,id,parent,name) DEFINE_xxx_FLOAT(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_FLOAT(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_FLOAT_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlFloat(EBML_Context##x, EbmlFloat::FLOAT_32, WithNode) {} #define DEFINE_EBML_FLOAT64(x,id,parent,name) DEFINE_xxx_FLOAT64(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_FLOAT64(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_FLOAT_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlFloat(EBML_Context##x, EbmlFloat::FLOAT_64, WithNode) {} #define DEFINE_EBML_FLOAT_DEF(x,id,parent,name,defval) DEFINE_xxx_FLOAT_DEF(x,id,parent,name,EBML_SemanticGlobal,defval) #define DEFINE_xxx_FLOAT_DEF(x,id,parent,name,global,defval) \ const ebml_context x::EBML_Context##x = {id, EBML_FLOAT_LEGACY_CLASS, 1, (intptr_t)defval, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlFloat(EBML_Context##x, defval, EbmlFloat::FLOAT_32, WithNode) {} #define DEFINE_EBML_UNISTRING(x,id,parent,name) DEFINE_xxx_UNISTRING(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_UNISTRING(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_UNISTRING_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlUnicodeString(EBML_Context##x, WithNode) {} #define DEFINE_EBML_STRING(x,id,parent,name) DEFINE_xxx_STRING(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_STRING(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_STRING_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlString(EBML_Context##x, WithNode) {} #define DEFINE_EBML_STRING_DEF(x,id,parent,name,defval) DEFINE_xxx_STRING_DEF(x,id,parent,name,EBML_SemanticGlobal,defval) #define DEFINE_xxx_STRING_DEF(x,id,parent,name,global,defval) \ const ebml_context x::EBML_Context##x = {id, EBML_STRING_LEGACY_CLASS, 1, (intptr_t)defval, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlString(EBML_Context##x, defval, WithNode) {} #define DEFINE_xxx_BINARY(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_BINARY_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlBinary(EBML_Context##x, WithNode) {} #define DEFINE_xxx_BINARY_CONS(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_BINARY_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ #define DEFINE_EBML_BINARY_GLOBAL(x,id,name) DEFINE_xxx_BINARY_GLOBAL(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_BINARY_GLOBAL(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_BINARY_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlBinary(EBML_Context##x, WithNode) {} #define DEFINE_EBML_VOID_GLOBAL(x,id,name) \ const ebml_context x::EBML_Context##x = {id, EBML_VOID_CLASS, 0, 0, name, NULL, EBML_SemanticGlobal, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlElement(EBML_Context##x, WithNode) {} #define DEFINE_EBML_DATE(x,id,parent,name) DEFINE_xxx_DATE(x,id,parent,name,EBML_SemanticGlobal) #define DEFINE_xxx_DATE(x,id,parent,name,global) \ const ebml_context x::EBML_Context##x = {id, EBML_DATE_LEGACY_CLASS, 0, 0, name, NULL, global, x::PostCreate}; \ x::x(ebml_element *WithNode) :EbmlDate(EBML_Context##x, WithNode) {} #define EBML_DEF_SEP , #define EBML_DEF_CONS const ebml_context &ec #define EBML_DEF_PARAM ec #define EBML_DEF_BINARY_INIT EbmlBinary(ec, WithNode) #define EBML_DEF_BINARY_CTX(x) EBML_Context##x #define EBML_DEF_BINARY(x) EbmlBinary(EBML_Context##x, WithNode) #define EBML_DEF_SINTEGER(x) EbmlSInteger(EBML_Context##x, WithNode) #define EBML_EXTRA_PARAM ebml_element *WithNode = NULL #define EBML_EXTRA_CALL WithNode #define EBML_EXTRA_DEF ebml_element *WithNode #define EBML_ID(ref) ref::EBML_Context##ref.Id #define EBML_INFO(ref) ref::EBML_Context##ref #define EBML_CLASS_SEMCONTEXT(ref) EBML_Context##ref #define EBML_CLASS_CALLBACK(ref) ref::EBML_Context##ref #define EBML_CONTEXT(e) static_cast(*(e)) #define EBML_NAME(e) (e)->DebugName() #define EBML_INFO_ID(cb) (cb).Id #define EBML_INFO_CONTEXT(cb) cb #define EBML_INFO_NAME(cb) (cb).ElementName #define EBML_CLASS_CONTEXT(ref) ref::EBML_Context##ref #define EBML_SEM_UNIQUE(s) (s).Unique #define EBML_SEM_CONTEXT(s) ((const EbmlSemanticContext)*(s).eClass) // EbmlSemantic/ebml_semantic -> EbmlSemanticContext #define EBML_SEM_CREATE(s) CreateEbmlElement(s) #define EBML_CTX_SIZE(c) (c).GetSize() // EbmlSemanticContext -> size_t #define EBML_CTX_IDX(c,i) (c).GetSemantic(i) // EbmlSemanticContext -> EbmlSemantic / ebml_semantic #define EBML_CTX_IDX_INFO(c,i) *(c).GetSemantic(i).eClass // EbmlSemanticContext -> EbmlCallbacks / ebml_context #define EBML_CTX_IDX_ID(c,i) (c).GetSemantic(i).eClass->Id // EbmlSemanticContext -> EbmlId namespace LIBEBML_NAMESPACE { typedef int ScopeMode; class EbmlSemanticContext; class EbmlElement; class EbmlStream; EbmlElement & CreateEbmlElement(const ebml_semantic &); typedef ebml_context EbmlCallbacks; typedef ebml_semantic EbmlSemantic; class EbmlSemanticContext { public: EbmlSemanticContext(const ebml_context &); bool operator!=(const EbmlSemanticContext & Elt) const; ~EbmlSemanticContext(); inline size_t GetSize() const { return Size; } const ebml_context * GetContext() const; const EbmlSemantic & GetSemantic(size_t i) const; private: size_t Size; const ebml_context & Context; // ebml_parser_context *pContext; }; class EbmlElement { public: virtual ~EbmlElement(); void SetSizeLength(size_t); filepos_t Render(IOCallback & output, bool bWithDefault = false, bool bKeepPosition = false, bool bForceRender = false); virtual bool SetSizeInfinite(bool bIsInfinite = true); filepos_t GetElementPosition() const; size_t HeadSize() const; filepos_t ElementSize(bool bWithDefault = false) const; bool IsFiniteSize() const; virtual filepos_t GetSize() const; size_t GetSizeLength() const; virtual operator const EbmlId () const = 0; virtual EbmlElement * Clone() const = 0; /*! \brief Force the size of an element \warning only possible if the size is "undefined" */ bool ForceSize(filepos_t NewSize); /*! \brief set the default size of an element */ virtual void SetDefaultSize(filepos_t aDefaultSize); filepos_t OverwriteHead(IOCallback & output, bool bKeepPosition = false); virtual void Read(EbmlStream & inDataStream, const EbmlSemanticContext & Context, int & UpperEltFound, EbmlElement * & FoundElt, bool AllowDummyElt = false, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual void Read(EbmlStream & inDataStream, const ebml_parser_context & Context, int & UpperEltFound, EbmlElement * & FoundElt, bool AllowDummyElt = false, ScopeMode ReadFully = SCOPE_ALL_DATA); EbmlElement * SkipData(EbmlStream & DataStream, const EbmlSemanticContext & Context, EbmlElement * TestReadElt = NULL, bool AllowDummyElt = false); virtual bool IsSmallerThan(const EbmlElement *Cmp) const; void SetValueIsSet(bool Set = true); void SetSize_(filepos_t); bool ValueIsSet() const; const char* DebugName() const; inline ebml_element *GetNode() { return Node; } inline const ebml_element *GetNode() const { return Node; } virtual operator const ebml_context &() const = 0; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA) = 0; virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false) = 0; virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false) = 0; /// update the Size of the Data stored before rendering protected: EbmlElement(const ebml_context &, ebml_element *WithNode = NULL); ebml_element *Node; static err_t Deleting(EbmlElement *p, nodeevt *Evt); }; size_t CodedSizeLength(filepos_t Length, size_t SizeLength, bool bSizeIsFinite = true); size_t CodedSizeLengthSigned(filepos_t Length, size_t SizeLength); size_t CodedValueLengthSigned(filepos_t Length, size_t CodedSize, binary * OutBuffer); size_t CodedValueLength(filepos_t Length, size_t CodedSize, binary * OutBuffer); filepos_t ReadCodedSizeValue(const binary * InBuffer, uint32_t & BufferSize, uint64_t & SizeUnknown); filepos_t ReadCodedSizeSignedValue(const binary * InBuffer, uint32_t & BufferSize, uint64_t & SizeUnknown); extern const ebml_semantic EBML_SemanticGlobal[]; }; #endif // _EBML2_EBML_ELEMENT_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlFloat.h000066400000000000000000000052401462133141200217600ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_FLOAT_H #define _EBML2_EBML_FLOAT_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlFloat : public EbmlElement { public: enum Precision { FLOAT_32 ,FLOAT_64 }; EbmlFloat(const ebml_context &, Precision prec = FLOAT_32, ebml_element *WithNode = NULL); EbmlFloat(const ebml_context &, double DefaultValue, Precision prec = FLOAT_32, ebml_element *WithNode = NULL); operator double() const; double operator =(double val); virtual bool IsSmallerThan(const EbmlElement *Cmp) const; void SetPrecision(Precision prec = FLOAT_32); virtual EbmlElement * Clone() const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_FLOAT_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlHead.h000066400000000000000000000034641462133141200215620ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_HEAD_H #define _EBML2_EBML_HEAD_H #include "ebml/EbmlMaster.h" namespace LIBEBML_NAMESPACE { DECLARE_EBML_MASTER(EbmlHead) }; }; #endif // _EBML2_EBML_HEAD_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlId.h000066400000000000000000000042221462133141200212460ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_ID_H #define _EBML2_EBML_ID_H #include "ebml/EbmlConfig.h" #define EBML_ID_LENGTH(x) (x).GetLength() #define EBML_ID_VALUE(x) (fourcc_t)(x) namespace LIBEBML_NAMESPACE { class EbmlId { public: EbmlId(uint32_t Id, size_t Size); EbmlId(const binary aValue[4], size_t aLength); EbmlId(fourcc_t Id); void Fill(binary * Buffer) const; operator fourcc_t() const; size_t GetLength() const; private: fourcc_t Value; }; }; #endif // _EBML2_EBML_ID_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlMaster.h000066400000000000000000000117171462133141200221540ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_MASTER_H #define _EBML2_EBML_MASTER_H #include "ebml/EbmlElement.h" #define EBML_MASTER_ITERATOR EbmlMaster_itr #define EBML_MASTER_CONST_ITERATOR EbmlMaster_itr #define EBML_MASTER_RITERATOR EbmlMaster_rev_itr #define EBML_MASTER_CONST_RITERATOR EbmlMaster_rev_itr namespace LIBEBML_NAMESPACE { class EbmlMaster; class EbmlMaster_itr { public: EbmlElement* operator*() const; EbmlMaster_itr& operator++(); bool operator!=(const EbmlMaster_itr &) const; bool operator==(const EbmlMaster_itr &) const; }; class EbmlMaster_rev_itr { public: EbmlElement* operator*() const; EbmlMaster_rev_itr& operator--(); bool operator!=(const EbmlMaster_rev_itr &) const; bool operator==(const EbmlMaster_rev_itr &) const; }; class EbmlMaster : public EbmlElement { public: EbmlMaster(const ebml_context &, ebml_element *WithNode = NULL); EbmlElement *FindElt(const ebml_context & Kind) const; EbmlElement *FindFirstElt(const ebml_context & Kind) const; EbmlElement *FindFirstElt(const ebml_context & Kind, const bool bCreateIfNull) const; EbmlElement *FindNextElt(const EbmlElement & Past) const; EbmlElement *FindNextElt(const EbmlElement & Past, const bool bCreateIfNull); EbmlElement *AddNewElt(const ebml_context & Kind); bool InsertElement(EbmlElement & element, size_t position = 0); bool PushElement(EbmlElement & element); size_t ListSize() const; EbmlElement * operator[](size_t position); const EbmlElement * operator[](size_t position) const; /*! \brief remove all elements, even the mandatory ones */ void RemoveAll(); /*! \brief Remove an element from the list of the master */ void Remove(const EBML_MASTER_ITERATOR & Itr); void Remove(const EBML_MASTER_RITERATOR & Itr); virtual EbmlElement * Clone() const; void Sort(); bool CheckMandatory() const; /*! \brief Remove an element from the list of the master */ void Remove(size_t Index); filepos_t WriteHead(IOCallback & output, size_t SizeLength, bool bWithDefault = false); EBML_MASTER_ITERATOR begin() const; EBML_MASTER_ITERATOR end() const; EBML_MASTER_RITERATOR rbegin() const; EBML_MASTER_RITERATOR rend() const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; template Type & GetChild(EbmlMaster & Master) { return *(static_cast(Master.FindFirstElt(Type::GetContext(), true))); } template Type & GetNextChild(EbmlMaster & Master, const Type & PastElt) { return *(static_cast(Master.FindNextElt(PastElt, true))); } template Type * FindChild(EbmlMaster & Master) { return static_cast(Master.FindFirstElt(Type::GetContext(), false)); } template Type & AddNewChild(EbmlMaster & Master) { return *(static_cast(Master.AddNewElt(Type::GetContext()))); } }; #endif // _EBML2_EBML_MASTER_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlSInteger.h000066400000000000000000000051251462133141200224350ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_SINTEGER_H #define _EBML2_EBML_SINTEGER_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlSInteger : public EbmlElement { public: EbmlSInteger(const ebml_context &ec, ebml_element *WithNode = NULL) :EbmlElement(ec,WithNode) {} operator int64_t() const; virtual EbmlElement * Clone() const; int64_t operator =(int64_t); /*! Set the default size of the integer (usually 1,2,4 or 8) */ void SetDefaultSize(filepos_t nDefaultSize = 1); virtual bool IsSmallerThan(const EbmlElement *Cmp) const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_SINTEGER_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlStream.h000066400000000000000000000042251462133141200221500ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_STREAM_H #define _EBML2_EBML_STREAM_H #include "ebml/IOCallback.h" namespace LIBEBML_NAMESPACE { class EbmlStream { public: EbmlStream(IOCallback &); EbmlElement * FindNextID(const ebml_context & ClassInfos, filepos_t MaxDataSize); EbmlElement * FindNextElement(const ebml_context & Context, int & UpperLevel, filepos_t MaxDataSize, bool AllowDummyElt, size_t MaxLowerLevel = 1); IOCallback & I_O(); private: IOCallback &mIO; }; }; #endif // _EBML2_EBML_STREAM_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlString.h000066400000000000000000000050421462133141200221610ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_STRING_H #define _EBML2_EBML_STRING_H #include #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlString : public EbmlElement { public: EbmlString(const ebml_context &,const char *, ebml_element *WithNode = NULL); EbmlString(const ebml_context &, ebml_element *WithNode = NULL); EbmlString & operator=(const std::string &); EbmlString & operator=(const char *); operator const std::string () const; virtual EbmlElement * Clone() const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_STRING_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlSubHead.h000066400000000000000000000042031462133141200222240ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_SUBHEAD_H #define _EBML2_EBML_SUBHEAD_H #include "ebml/EbmlUInteger.h" #include "ebml/EbmlString.h" namespace LIBEBML_NAMESPACE { DECLARE_EBML_UINTEGER(EVersion) }; DECLARE_EBML_UINTEGER(EReadVersion) }; DECLARE_EBML_UINTEGER(EMaxIdLength) }; DECLARE_EBML_UINTEGER(EMaxSizeLength) }; DECLARE_EBML_STRING(EDocType) }; DECLARE_EBML_UINTEGER(EDocTypeVersion) }; DECLARE_EBML_UINTEGER(EDocTypeReadVersion) }; }; #endif // _EBML2_EBML_SUBHEAD_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlTypes.h000066400000000000000000000031641462133141200220220ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlUInteger.h000066400000000000000000000052171462133141200224410ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_UINTEGER_H #define _EBML2_EBML_UINTEGER_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { class EbmlUInteger : public EbmlElement { public: EbmlUInteger(const ebml_context &,unsigned int, ebml_element *WithNode = NULL); EbmlUInteger(const ebml_context &, ebml_element *WithNode = NULL); operator uint64_t() const; virtual EbmlElement * Clone() const; uint64_t operator =(uint64_t val); /*! Set the default size of the integer (usually 1,2,4 or 8) */ void SetDefaultSize(filepos_t nDefaultSize = 0); virtual bool IsSmallerThan(const EbmlElement *Cmp) const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_UINTEGER_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlUnicodeString.h000066400000000000000000000060731462133141200234750ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_UNICODE_STRING_H #define _EBML2_EBML_UNICODE_STRING_H #include "ebml/EbmlElement.h" namespace LIBEBML_NAMESPACE { /*! \class UTFstring A class storing strings in a wchar_t (ie, in UCS-2 or UCS-4) \note inspired by wstring which is not available everywhere */ class UTFstring { public: UTFstring(); UTFstring(const wchar_t *); UTFstring(const UTFstring &); ~UTFstring(); const wchar_t* c_str() const; bool operator==(const UTFstring&) const; UTFstring & operator=(const UTFstring &); operator const wchar_t*() const; size_t length() const; protected: wchar_t *Buffer; }; class EbmlUnicodeString : public EbmlElement { public: //EbmlUnicodeString(const ebml_context &,const UTFstring &); EbmlUnicodeString(const ebml_context &, ebml_element *WithNode = NULL); EbmlUnicodeString & operator=(const UTFstring &); operator const UTFstring () const; virtual EbmlElement * Clone() const; // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_UNICODE_STRING_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlVersion.h000066400000000000000000000040111462133141200223330ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_VERSION_H #define _EBML2_EBML_VERSION_H #include static const std::string EbmlCodeVersion = "1.0.0"; static const std::string EbmlCodeDate = __TIMESTAMP__; #define LIBEBML_VERSION 0x010000 #if defined(EBML2_LEGACY_PROJECT_VERSION) # if (EBML2_LEGACY_PROJECT_VERSION > LIBEBML_VERSION) # error mismatching LIBEBML_VERSION # endif #endif #endif // _EBML2_EBML_VERSION_H bcmatroska2-5.3.101/libebml2/legacy/ebml/EbmlVoid.h000066400000000000000000000045111462133141200216140ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_EBML_VOID_H #define _EBML2_EBML_VOID_H #include "ebml/EbmlBinary.h" namespace LIBEBML_NAMESPACE { DECLARE_EBML_VOID(EbmlVoid) public: void SetSize(filepos_t); filepos_t ReplaceWith(EbmlElement & EltToReplaceWith, IOCallback & output, bool ComeBackAfterward = true, bool bWithDefault = false); // virtual methods needed for the Core-C counterpart virtual filepos_t ReadData(IOCallback & input, ScopeMode ReadFully = SCOPE_ALL_DATA); virtual filepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault = false); virtual filepos_t UpdateSize(bool bWithDefault = false, bool bForceRender = false); }; }; #endif // _EBML2_EBML_VOID_H bcmatroska2-5.3.101/libebml2/legacy/ebml/IOCallback.h000066400000000000000000000051321462133141200220370ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EBML2_IO_CALLBACK_H #define _EBML2_IO_CALLBACK_H #include #include "ebml/EbmlConfig.h" typedef struct stream stream; typedef struct stream_io stream_io; namespace LIBEBML_NAMESPACE { enum seek_mode { seek_beginning = SEEK_SET, seek_end = SEEK_END, seek_current = SEEK_CUR }; typedef enum open_mode { MODE_READ, MODE_WRITE, MODE_CREATE, MODE_SAFE } open_mode; class IOCallback { public: IOCallback(); virtual ~IOCallback(); virtual uint32_t read(void* Buffer, size_t Size)=0; virtual size_t write(const void *Buffer,size_t Size)=0; virtual void setFilePointer(int64_t Offset, seek_mode Mode=seek_beginning)=0; virtual uint64_t getFilePointer()=0; virtual void close()=0; void writeFully(const void* Buffer, size_t Size); stream *GetStream(); private: stream_io *Stream; }; }; #endif // _EBML2_IO_CALLBACK_H bcmatroska2-5.3.101/libebml2/legacy/ebml/c/000077500000000000000000000000001462133141200201635ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/legacy/ebml/c/libebml_t.h000066400000000000000000000031641462133141200222710ustar00rootroot00000000000000/* * $Id: ebmlbinary.c 1319 2008-09-19 16:08:57Z robux4 $ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ bcmatroska2-5.3.101/libebml2/legacy/legacy.cpp000066400000000000000000001164611462133141200210030ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "ebml/EbmlElement.h" #include "ebml/EbmlMaster.h" #include "ebml/EbmlString.h" #include "ebml/EbmlUnicodeString.h" #include "ebml/EbmlUInteger.h" #include "ebml/EbmlSInteger.h" #include "ebml/EbmlFloat.h" #include "ebml/EbmlDate.h" #include "ebml/EbmlStream.h" #include "ebml/EbmlVoid.h" #include "ebml/EbmlCrc32.h" #include "ebml/EbmlHead.h" #include "ebml/EbmlSubHead.h" #include "ebml/EbmlContexts.h" #include "ebml2_legacy_project.h" #include "ebml/EbmlVersion.h" #include "ebml/ebml.h" #define IOCALLBACK_STREAM_CLASS FOURCC('I','O','C','B') #define Ebml_Children(x) (ebml_element*)NodeTree_Children(x) #define Ebml_Next(x) (ebml_element*)NodeTree_Next(x) static nodecontext ccContext; using namespace LIBEBML_NAMESPACE; struct stream_io { stream Base; IOCallback *cpp; }; static filepos_t Seek(stream_io* p,filepos_t Pos,int SeekMode) { if (SeekMode == SEEK_CUR) { if (Pos!=0) p->cpp->setFilePointer(Pos,seek_current); return (filepos_t)p->cpp->getFilePointer(); } if (SeekMode == SEEK_SET) { p->cpp->setFilePointer(Pos); return Pos; } if (SeekMode == SEEK_END) { p->cpp->setFilePointer(Pos,seek_end); return (filepos_t)p->cpp->getFilePointer(); } return INVALID_FILEPOS_T; } static err_t Write(stream_io* p,const void* Data,size_t Size, size_t* Written) { size_t _Written; if (!Written) Written = &_Written; _Written = p->cpp->write(Data,Size); if (Written) *Written = _Written; return (_Written==Size)?ERR_NONE:ERR_DEVICE_ERROR; } static err_t Read(stream_io* p,void* Data,size_t Size,size_t* Readed) { uint32_t Read = p->cpp->read(Data,Size); if (Readed) *Readed = Read; return ERR_NONE; } static err_t ReadData(ebml_element *Element, stream_io *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope) { filepos_t DataSize; EbmlElement *Result=NULL; if (Node_Get(Element,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } DataSize = Result->ReadData(*Input->cpp,Scope); if (DataSize==Element->DataSize) return ERR_NONE; return ERR_INVALID_DATA; } filepos_t UpdateSize(ebml_element *Element, bool bWithDefault, bool bForceRender) { filepos_t Size; EbmlElement *Result=NULL; if (Node_Get(Element,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } Size = Result->UpdateSize(bWithDefault!=0, bForceRender!=0); return Size; } #if defined(CONFIG_EBML_WRITING) static err_t RenderData(ebml_element *Element, stream_io *Output, bool_t bForceRender, bool_t bWithDefault, filepos_t *Rendered) { filepos_t Render; EbmlElement *Result=NULL; assert(Output->cpp!=NULL); if (Node_Get(Element,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } if (!Rendered) Rendered = &Render; *Rendered = Result->RenderData(*Output->cpp,bForceRender!=0,bWithDefault!=0); if (*Rendered == INVALID_FILEPOS_T) return ERR_WRITE; return ERR_NONE; } #endif META_START(IOCallback_Class,IOCALLBACK_STREAM_CLASS) META_CLASS(FLAGS,CFLAG_LOCAL) META_CLASS(SIZE,sizeof(stream_io)) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,Write,Write) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_END_CONTINUE(STREAM_CLASS) META_START_CONTINUE(EBML_BINARY_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_BINARY_CLASS) META_START_CONTINUE(EBML_DATE_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_DATE_CLASS) META_START_CONTINUE(EBML_INTEGER_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_INTEGER_CLASS) META_START_CONTINUE(EBML_SINTEGER_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_SINTEGER_CLASS) META_START_CONTINUE(EBML_FLOAT_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_FLOAT_CLASS) META_START_CONTINUE(EBML_MASTER_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(EBML_STRING_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END_CONTINUE(EBML_STRING_CLASS) META_START_CONTINUE(EBML_UNISTRING_LEGACY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateSize,UpdateSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderData) #endif META_END(EBML_UNISTRING_CLASS) DEFINE_START_SEMANTIC(EbmlHead) DEFINE_SEMANTIC_ITEM(true, true, EVersion) DEFINE_SEMANTIC_ITEM(true, true, EReadVersion) DEFINE_SEMANTIC_ITEM(true, true, EDocType) DEFINE_SEMANTIC_ITEM(true, true, EDocTypeVersion) DEFINE_SEMANTIC_ITEM(true, true, EDocTypeReadVersion) DEFINE_SEMANTIC_ITEM(true, true, EMaxIdLength) DEFINE_SEMANTIC_ITEM(true, true, EMaxSizeLength) DEFINE_END_SEMANTIC(EbmlHead) DEFINE_EBML_MASTER (EbmlHead, ::EBML_ContextHead.Id, NULL, ::EBML_ContextHead.ElementName); DEFINE_EBML_UINTEGER (EVersion, ::EBML_ContextVersion.Id, EbmlHead, ::EBML_ContextVersion.ElementName); DEFINE_EBML_UINTEGER (EReadVersion, ::EBML_ContextReadVersion.Id, EbmlHead, ::EBML_ContextReadVersion.ElementName); DEFINE_EBML_STRING_DEF(EDocType, ::EBML_ContextDocType.Id, EbmlHead, ::EBML_ContextDocType.ElementName, "matroska"); DEFINE_EBML_UINTEGER (EDocTypeVersion, ::EBML_ContextDocTypeVersion.Id, EbmlHead, ::EBML_ContextDocTypeVersion.ElementName); DEFINE_EBML_UINTEGER (EDocTypeReadVersion, ::EBML_ContextDocTypeReadVersion.Id, EbmlHead, ::EBML_ContextDocTypeReadVersion.ElementName); DEFINE_EBML_UINTEGER (EMaxIdLength, ::EBML_ContextMaxIdLength.Id, EbmlHead, ::EBML_ContextMaxIdLength.ElementName); DEFINE_EBML_UINTEGER (EMaxSizeLength, ::EBML_ContextMaxSizeLength.Id, EbmlHead, ::EBML_ContextMaxSizeLength.ElementName); void ebml_init() { NodeContext_Init(&ccContext,NULL,NULL,NULL); EBML_Init(&ccContext); NodeRegisterClassEx((nodemodule*)&ccContext,IOCallback_Class); ::EBML_ContextHead.PostCreate = EbmlHead::PostCreate; ::EBML_ContextDocType.PostCreate = EDocType::PostCreate; ::EBML_ContextVersion.PostCreate = EVersion::PostCreate; ::EBML_ContextReadVersion.PostCreate = EReadVersion::PostCreate; ::EBML_ContextDocTypeVersion.PostCreate = EDocTypeVersion::PostCreate; ::EBML_ContextDocTypeReadVersion.PostCreate = EDocTypeReadVersion::PostCreate; ::EBML_ContextMaxSizeLength.PostCreate = EMaxSizeLength::PostCreate; ::EBML_ContextMaxIdLength.PostCreate = EMaxIdLength::PostCreate; } void ebml_done() { EBML_Done(&ccContext); NodeContext_Done(&ccContext); } namespace LIBEBML_NAMESPACE { EbmlElement & DummyCreate() { assert(0); return *static_cast(NULL); } DEFINE_EBML_BINARY_GLOBAL(EbmlCrc32, 0xBF, "EBMLCrc32\0ratamadabapa"); DEFINE_EBML_VOID_GLOBAL(EbmlVoid, 0xEC, "EBMLVoid"); const ebml_semantic EBML_SemanticGlobal[] = { {0, 0, &EbmlVoid::EBML_ContextEbmlVoid}, {0, 1, &EbmlCrc32::EBML_ContextEbmlCrc32}, {0, 0, NULL} // end of the table }; size_t CodedSizeLength(filepos_t Length, size_t SizeLength, bool bSizeIsFinite) { return EBML_CodedSizeLength(Length,(uint8_t)SizeLength,bSizeIsFinite); } size_t CodedValueLength(filepos_t Length, size_t CodedSize, binary * OutBuffer) { return EBML_CodedValueLength(Length, CodedSize, OutBuffer, 1); } size_t CodedSizeLengthSigned(filepos_t Length, size_t SizeLength) { return EBML_CodedSizeLengthSigned(Length, (uint8_t)SizeLength); } size_t CodedValueLengthSigned(filepos_t Length, size_t CodedSize, binary * OutBuffer) { return EBML_CodedValueLengthSigned(Length, CodedSize, OutBuffer); } filepos_t ReadCodedSizeValue(const binary * InBuffer, uint32_t & BufferSize, uint64_t & SizeUnknown) { assert(0); return INVALID_FILEPOS_T; } filepos_t ReadCodedSizeSignedValue(const binary * InBuffer, uint32_t & BufferSize, uint64_t & SizeUnknown) { assert(0); return INVALID_FILEPOS_T; } const EbmlSemanticContext & GetEbmlGlobal_Context() { assert(0); return *((EbmlSemanticContext*)NULL); } big_int16::big_int16(int16_t Val) :Value(Val) { } big_int16::big_int16() { assert(0); } big_int16::operator int16() const { assert(0); return 0; } void big_int16::Fill(binary *Buffer) const { STORE16BE(Buffer,Value); } void big_int16::Eval(const binary *Buffer) { assert(0); } /***************** * EbmlElement ****************/ EbmlElement & CreateEbmlElement(const ebml_semantic &Semantic) { assert(0); return *static_cast(NULL); } err_t EbmlElement::Deleting(EbmlElement *p, nodeevt *Evt) { p->Node = NULL; delete p; return ERR_NONE; } EbmlElement::EbmlElement(const ebml_context & Context, ebml_element *WithNode) :Node(WithNode) { if (!WithNode) Node = EBML_ElementCreate(&ccContext,&Context,0,this); if (!Node) { // TODO: throw some error } Node_AddNotify((node*)Node,NODE_DELETING,(notifyproc)Deleting,this); } EbmlElement::~EbmlElement() { if (Node) { Node_RemoveNotify((node*)Node,NODE_DELETING,(notifyproc)Deleting,this); NodeDelete((node*)Node); } } EbmlElement * EbmlElement::SkipData(EbmlStream & DataStream, const EbmlSemanticContext & Context, EbmlElement * TestReadElt, bool AllowDummyElt) { ebml_parser_context pContext; pContext.Context = Node->Context; ebml_element *i = EBML_ElementSkipData(Node,DataStream.I_O().GetStream(),&pContext,TestReadElt?TestReadElt->Node:NULL,AllowDummyElt); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } filepos_t EbmlElement::UpdateSize(bool bWithDefault, bool bForceRender) { return EBML_ElementUpdateSize(Node, bWithDefault, bForceRender); } bool EbmlElement::IsFiniteSize() const { return EBML_ElementIsFiniteSize(Node)!=0; } size_t EbmlElement::GetSizeLength() const { assert(0); return 0; } filepos_t EbmlElement::GetSize() const { return Node->DataSize; } bool EbmlElement::ValueIsSet() const { return Node->bValueIsSet!=0; } void EbmlElement::SetValueIsSet(bool Set) { Node->bValueIsSet = Set; } bool EbmlElement::SetSizeInfinite(bool bIsInfinite) { EBML_ElementSetInfiniteSize(Node,bIsInfinite); return true; } void EbmlElement::SetDefaultSize(filepos_t aDefaultSize) { assert(0); } void EbmlElement::SetSize_(filepos_t DataSize) { Node->DataSize = DataSize; } bool EbmlElement::ForceSize(filepos_t NewSize) { return EBML_ElementInfiniteForceSize(Node,NewSize)?true:false; } void EbmlElement::SetSizeLength(size_t Size) { Node->SizeLength = (int8_t)Size; } size_t EbmlElement::HeadSize() const { filepos_t Result = EBML_ElementFullSize(Node,1); if (Result != INVALID_FILEPOS_T) Result -= Node->DataSize; return Result; } filepos_t EbmlElement::ElementSize(bool bWithDefault) const { return EBML_ElementFullSize(Node,bWithDefault); } filepos_t EbmlElement::GetElementPosition() const { return Node->ElementPosition; } filepos_t EbmlElement::Render(IOCallback & output, bool bWithDefault, bool bKeepPosition, bool bForceRender) { filepos_t Rendered = INVALID_FILEPOS_T; if (EBML_ElementRender(Node, output.GetStream(), bWithDefault, bKeepPosition, bForceRender, &Rendered)!=ERR_NONE) return INVALID_FILEPOS_T; return Rendered; } filepos_t EbmlElement::OverwriteHead(IOCallback & output, bool bKeepPosition) { if (Node->ElementPosition == INVALID_FILEPOS_T) return INVALID_FILEPOS_T; // the element has not been written filepos_t CurrentPosition = (filepos_t)output.getFilePointer(); output.setFilePointer(GetElementPosition()); if (EBML_ElementRenderHead(Node, output.GetStream(), bKeepPosition, NULL)!=ERR_NONE) return INVALID_FILEPOS_T; if (!bKeepPosition) { output.setFilePointer(CurrentPosition); return CurrentPosition; } return Node->ElementPosition; } void EbmlElement::Read(EbmlStream & inDataStream, const ebml_parser_context & Context, int & UpperEltFound, EbmlElement * & FoundElt, bool AllowDummyElt, ScopeMode ReadFully) { assert(0); } void EbmlElement::Read(EbmlStream & inDataStream, const EbmlSemanticContext & Context, int & UpperEltFound, EbmlElement * & FoundElt, bool AllowDummyElt, ScopeMode ReadFully) { ebml_parser_context ParserContext; ParserContext.Context = Context.GetContext(); ParserContext.EndPosition = Node->ElementPosition + Node->DataSize; ParserContext.UpContext = NULL; err_t Res = EBML_ElementReadData(Node,inDataStream.I_O().GetStream(),&ParserContext,AllowDummyElt,ReadFully); } const char* EbmlElement::DebugName() const { assert(0); return NULL; } bool EbmlElement::IsSmallerThan(const EbmlElement *Cmp) const { return EbmlId(*this) == EbmlId(*Cmp); } /***************** * EbmlSemanticContext ****************/ EbmlSemanticContext::EbmlSemanticContext(const ebml_context & _Context) :Context(_Context) ,Size(0) { const ebml_semantic *s = Context.Semantic; while (s && s->eClass!=NULL) { ++Size; ++s; } } const EbmlSemantic & EbmlSemanticContext::GetSemantic(size_t i) const { assert(i < Size); return Context.Semantic[i]; } bool EbmlSemanticContext::operator!=(const EbmlSemanticContext & Elt) const { return (Size != Elt.Size) || (Context.Id != Elt.Context.Id) || (Context.Semantic != Elt.Context.Semantic); // TODO: handle more } const ebml_context * EbmlSemanticContext::GetContext() const { return &Context; } EbmlSemanticContext::~EbmlSemanticContext() { // delete pContext; } /***************** * EbmlId ****************/ EbmlId::EbmlId(uint32_t Id, size_t Size) :Value(Id) { assert(Size==0); // otherwise we have to make sure the value is OK } EbmlId::EbmlId(const binary aValue[4], size_t aLength) { assert(aLength==0); // otherwise we have to make sure the value is OK } EbmlId::EbmlId(fourcc_t Id) :Value(Id) { } EbmlId::operator fourcc_t() const { return Value; } size_t EbmlId::GetLength() const { return GetIdLength(Value); } void EbmlId::Fill(binary * Buffer) const { size_t i,DataSize = GetIdLength(Value); for (i=0; i> 8*(DataSize-i-1)) & 0xFF; } /***************** * EbmlMaster_itr ****************/ bool EbmlMaster_itr::operator!=(const EbmlMaster_itr &) const { assert(0); return false; } bool EbmlMaster_itr::operator==(const EbmlMaster_itr &) const { assert(0); return false; } EbmlElement* EbmlMaster_itr::operator*() const { assert(0); return NULL; } EbmlMaster_itr& EbmlMaster_itr::operator++() { assert(0); return *this; } /***************** * EbmlMaster_rev_itr ****************/ bool EbmlMaster_rev_itr::operator!=(const EbmlMaster_rev_itr &) const { assert(0); return false; } bool EbmlMaster_rev_itr::operator==(const EbmlMaster_rev_itr &) const { assert(0); return false; } EbmlElement* EbmlMaster_rev_itr::operator*() const { assert(0); return NULL; } EbmlMaster_rev_itr& EbmlMaster_rev_itr::operator--() { assert(0); return *this; } /***************** * EbmlMaster ****************/ EbmlMaster::EbmlMaster(struct ebml_context const &Context, ebml_element *WithNode) :EbmlElement(Context, WithNode) { } filepos_t EbmlMaster::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_MASTER_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlMaster::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_MASTER_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlMaster::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_MASTER_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } EbmlMaster_itr EbmlMaster::begin() const { assert(0); return *static_cast(NULL); } EbmlMaster_itr EbmlMaster::end() const { assert(0); return *static_cast(NULL); } EbmlMaster_rev_itr EbmlMaster::rbegin() const { assert(0); return *static_cast(NULL); } EbmlMaster_rev_itr EbmlMaster::rend() const { assert(0); return *static_cast(NULL); } bool EbmlMaster::CheckMandatory() const { assert(0); return true; } filepos_t EbmlMaster::WriteHead(IOCallback & output, size_t SizeLength, bool bWithDefault) { filepos_t Rendered = INVALID_FILEPOS_T; Node->SizeLength = (int8_t)SizeLength; EBML_ElementUpdateSize(Node,bWithDefault, 0); if (EBML_ElementRenderHead(Node, output.GetStream(), 0, &Rendered)!=ERR_NONE) return INVALID_FILEPOS_T; return Rendered; } static int EbmlCmp(const ebml_element* Element, const ebml_element** a,const ebml_element** b) { EbmlElement *A=NULL; EbmlElement *B=NULL; if (Node_Get((node*)*a,EBML_ELEMENT_OBJECT,&A,sizeof(A))!=ERR_NONE) { assert(0); } if (Node_Get((node*)*b,EBML_ELEMENT_OBJECT,&B,sizeof(B))!=ERR_NONE) { assert(0); } if (B->IsSmallerThan(A)) return 1; else return 0; } void EbmlMaster::Sort() { EBML_MasterSort(Node, (arraycmp)EbmlCmp, this); } void EbmlMaster::RemoveAll() { EBML_MasterClear(Node); } size_t EbmlMaster::ListSize() const { return EBML_MasterCount(Node); } bool EbmlMaster::InsertElement(EbmlElement & element, size_t position) { assert(0); return false; } bool EbmlMaster::PushElement(EbmlElement & element) { return EBML_MasterAppend(Node,element.GetNode())==ERR_NONE; } EbmlElement *EbmlMaster::AddNewElt(const EbmlCallbacks & Kind) { ebml_element *i = EBML_MasterAddElt(Node,&Kind,0); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement *EbmlMaster::FindElt(const ebml_context & Kind) const { ebml_element *i = EBML_MasterFindChild(Node,&Kind); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement *EbmlMaster::FindFirstElt(const ebml_context & Kind) const { ebml_element *i = EBML_MasterFindFirstElt(Node,&Kind,0,0); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement *EbmlMaster::FindFirstElt(const ebml_context & Kind, const bool bCreateIfNull) const { ebml_element *i = EBML_MasterFindFirstElt(Node,&Kind,bCreateIfNull,0); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement *EbmlMaster::FindNextElt(const EbmlElement & Past) const { assert(0); return NULL; } EbmlElement *EbmlMaster::FindNextElt(const EbmlElement & Past, const bool bCreateIfNull) { ebml_element *i = EBML_MasterFindNextElt(Node,Past.GetNode(),bCreateIfNull,0); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } void EbmlMaster::Remove(size_t Index) { assert(0); } void EbmlMaster::Remove(const EbmlMaster_itr & Item) { assert(0); } void EbmlMaster::Remove(const EbmlMaster_rev_itr & Item) { assert(0); } EbmlElement * EbmlMaster::operator[](size_t position) { ebml_element *i = Ebml_Children(Node); while(i && position--) i = Ebml_Next(i); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } const EbmlElement * EbmlMaster::operator[](size_t position) const { ebml_element *i = Ebml_Children(Node); while(i && position--) i = Ebml_Next(i); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement * EbmlMaster::Clone() const { assert(0); return NULL; } /***************** * EbmlBinary ****************/ void EbmlBinary::CopyBuffer(const void *Buffer, size_t BufferSize) { EBML_BinarySetData((ebml_binary*)Node, (const uint8_t*)Buffer, BufferSize); } void EbmlBinary::SetBuffer(const binary *Buffer, size_t BufferSize) { assert(0); } const binary* EbmlBinary::GetBuffer() const { return EBML_BinaryGetData((ebml_binary*)Node); } binary* EbmlBinary::GetBuffer() { return const_cast(EBML_BinaryGetData((ebml_binary*)Node)); } filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_BINARY_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlBinary::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_BINARY_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlBinary::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_BINARY_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } EbmlElement * EbmlBinary::Clone() const { assert(0); return NULL; } /***************** * EbmlString ****************/ EbmlString::EbmlString(const ebml_context &ec, const char *DefaultValue, ebml_element *WithNode) :EbmlElement(ec, WithNode) { Node->bDefaultIsSet = 1; } EbmlString::EbmlString(const ebml_context &ec, ebml_element *WithNode) :EbmlElement(ec, WithNode) { } filepos_t EbmlString::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); // err_t Res = EBML_ElementReadData(Node,input.GetStream(),NULL,0,ReadFully); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_STRING_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlString::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_STRING_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlString::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_STRING_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } EbmlString & EbmlString::operator=(const std::string & Value) { EBML_StringSetValue((ebml_string*)Node,Value.c_str()); return *this; } EbmlString & EbmlString::operator=(const char *Value) { EBML_StringSetValue((ebml_string*)Node,Value); return *this; } EbmlString::operator const std::string() const { return reinterpret_cast(Node)->Buffer; } EbmlElement * EbmlString::Clone() const { assert(0); return NULL; } /***************** * EbmlUnicodeString ****************/ EbmlUnicodeString::EbmlUnicodeString(const ebml_context &ec, ebml_element *WithNode) :EbmlElement(ec, WithNode) { } EbmlUnicodeString & EbmlUnicodeString::operator=(const UTFstring &val) { EBML_UniStringSetValue((ebml_string*)Node,val); return *this; } filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_UNISTRING_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlUnicodeString::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_UNISTRING_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlUnicodeString::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_UNISTRING_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } EbmlUnicodeString::operator const UTFstring() const { ebml_string *Value = (ebml_string*)Node; wchar_t TmpStr[MAXLINE]; charconv *c = CharConvOpen(CHARSET_UTF8,CHARSET_WCHAR); CharConvTS(c, TmpStr, sizeof(TmpStr)/sizeof(wchar_t),Value->Buffer); CharConvClose(c); return UTFstring(TmpStr); } EbmlElement * EbmlUnicodeString::Clone() const { assert(0); return NULL; } /***************** * UTFstring ****************/ UTFstring::UTFstring(const wchar_t* value) :Buffer(NULL) { size_t Size = wcslen(value); Buffer = new wchar_t[(Size+1)*sizeof(wchar_t)]; if (Buffer) memcpy(Buffer,value,(Size+1)*sizeof(wchar_t)); } UTFstring::UTFstring() :Buffer(NULL) { } UTFstring::UTFstring(const UTFstring &Clone) :Buffer(NULL) { size_t Size = wcslen(Clone.Buffer); Buffer = new wchar_t[(Size+1)*sizeof(wchar_t)]; if (Buffer) memcpy(Buffer,Clone.Buffer,(Size+1)*sizeof(wchar_t)); } UTFstring::~UTFstring() { delete[] Buffer; } UTFstring & UTFstring::operator=(const UTFstring & Clone) { delete[] Buffer; size_t Size = wcslen(Clone.Buffer); Buffer = new wchar_t[(Size+1)*sizeof(wchar_t)]; if (Buffer) memcpy(Buffer,Clone.Buffer,(Size+1)*sizeof(wchar_t)); return *this; } const wchar_t* UTFstring::c_str() const { assert(0); return NULL; } UTFstring::operator const wchar_t*() const { return Buffer; } bool UTFstring::operator==(const UTFstring &Cmp) const { size_t Size1 = wcslen(Buffer); size_t Size2 = wcslen(Cmp.Buffer); if (Size1 != Size2) return false; return memcmp(Buffer,Cmp.Buffer,(Size1+1)*sizeof(wchar_t))==0; } size_t UTFstring::length() const { return wcslen(Buffer); } /***************** * EbmlUInteger ****************/ EbmlUInteger::EbmlUInteger(const ebml_context &ec, ebml_element *WithNode) :EbmlElement(ec, WithNode) { } EbmlUInteger::EbmlUInteger(const ebml_context &ec, unsigned int DefaultValue, ebml_element *WithNode) :EbmlElement(ec, WithNode) { Node->bDefaultIsSet = 1; } filepos_t EbmlUInteger::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_INTEGER_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlUInteger::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_INTEGER_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlUInteger::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_INTEGER_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } void EbmlUInteger::SetDefaultSize(filepos_t aDefaultSize) { Node->DefaultSize = aDefaultSize; } EbmlUInteger::operator uint64_t() const { return reinterpret_cast(Node)->Value; } uint64_t EbmlUInteger::operator =(uint64_t val) { reinterpret_cast(Node)->Value = val; Node->bValueIsSet = 1; return val; } EbmlElement * EbmlUInteger::Clone() const { assert(0); return NULL; } bool EbmlUInteger::IsSmallerThan(const EbmlElement *Cmp) const { if (EbmlId(*this) == EbmlId(*Cmp)) { const EbmlUInteger *_Cmp = static_cast(Cmp); return reinterpret_cast(Node)->Value < reinterpret_cast(_Cmp->Node)->Value; } else return false; } /***************** * EbmlSInteger ****************/ filepos_t EbmlSInteger::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_SINTEGER_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlSInteger::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_SINTEGER_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlSInteger::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_SINTEGER_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } void EbmlSInteger::SetDefaultSize(filepos_t aDefaultSize) { Node->DefaultSize = aDefaultSize; } int64_t EbmlSInteger::operator =(int64_t val) { reinterpret_cast(Node)->Value = val; return reinterpret_cast(Node)->Value; } EbmlSInteger::operator int64_t() const { return reinterpret_cast(Node)->Value; } EbmlElement * EbmlSInteger::Clone() const { assert(0); return NULL; } bool EbmlSInteger::IsSmallerThan(const EbmlElement *Cmp) const { if (EbmlId(*this) == EbmlId(*Cmp)) { const EbmlSInteger *_Cmp = static_cast(Cmp); return reinterpret_cast(Node)->Value < reinterpret_cast(_Cmp->Node)->Value; } else return false; } /***************** * EbmlFloat ****************/ EbmlFloat::EbmlFloat(const ebml_context &ec, double DefaultValue, Precision prec, ebml_element *WithNode) :EbmlElement(ec, WithNode) { SetPrecision(prec); Node->bDefaultIsSet = 1; } EbmlFloat::EbmlFloat(const ebml_context &ec, Precision prec, ebml_element *WithNode) :EbmlElement(ec, WithNode) { SetPrecision(prec); } filepos_t EbmlFloat::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_FLOAT_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlFloat::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_FLOAT_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlFloat::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_FLOAT_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } EbmlFloat::operator double() const { return reinterpret_cast(Node)->Value; } double EbmlFloat::operator =(double val) { ((ebml_float*)Node)->Value = val; Node->bValueIsSet = 1; return val; } void EbmlFloat::SetPrecision(Precision prec) { if (prec==FLOAT_32) Node->DataSize = 4; else Node->DataSize = 8; } bool EbmlFloat::IsSmallerThan(const EbmlElement *Cmp) const { if (EbmlId(*this) == EbmlId(*Cmp)) { const EbmlFloat *_Cmp = static_cast(Cmp); return reinterpret_cast(Node)->Value < reinterpret_cast(_Cmp->Node)->Value; } else return false; } EbmlElement * EbmlFloat::Clone() const { assert(0); return NULL; } /***************** * EbmlDate ****************/ filepos_t EbmlDate::ReadData(IOCallback & input, ScopeMode ReadFully) { filepos_t Now = (filepos_t)input.getFilePointer(); err_t Res = INHERITED(Node,ebml_element_vmt,EBML_DATE_LEGACY_CLASS)->ReadData(Node,input.GetStream(),NULL,0,ReadFully); if (Res != ERR_NONE) return INVALID_FILEPOS_T; return (filepos_t)input.getFilePointer() - Now; } filepos_t EbmlDate::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_DATE_LEGACY_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlDate::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_DATE_LEGACY_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } datetime_t EbmlDate::GetEpochDate() const { return EBML_DateTime(reinterpret_cast(Node)) + 978307200; // 1st January 2001 to January 1, 1970 } void EbmlDate::SetEpochDate(int32_t NewDate) { EBML_DateSetDateTime(reinterpret_cast(Node),NewDate - 978307200); // January 1, 1970 to 1st January 2001 } bool EbmlDate::IsSmallerThan(const EbmlElement *Cmp) const { if (EbmlId(*this) == EbmlId(*Cmp)) { const EbmlDate *_Cmp = static_cast(Cmp); return reinterpret_cast(Node)->Value < reinterpret_cast(_Cmp->Node)->Value; } else return false; } EbmlElement * EbmlDate::Clone() const { assert(0); return NULL; } /***************** * EbmlVoid ****************/ filepos_t EbmlVoid::ReadData(IOCallback & input, ScopeMode ReadFully) { return 0; // do nothing } filepos_t EbmlVoid::RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault) { filepos_t Rendered; err_t Err = INHERITED(Node,ebml_element_vmt,EBML_VOID_CLASS)->RenderData(Node,output.GetStream(),bForceRender,bSaveDefault,&Rendered); if (Err!=ERR_NONE) return ERR_WRITE; return Rendered; } filepos_t EbmlVoid::UpdateSize(bool bWithDefault, bool bForceRender) { return INHERITED(Node,ebml_element_vmt,EBML_VOID_CLASS)->UpdateSize(Node,bWithDefault,bForceRender); } filepos_t EbmlVoid::ReplaceWith(EbmlElement & EltToReplaceWith, IOCallback & output, bool ComeBackAfterward, bool bWithDefault) { return EBML_VoidReplaceWith(Node, EltToReplaceWith.GetNode(), output.GetStream(), ComeBackAfterward, bWithDefault); } void EbmlVoid::SetSize(filepos_t Size) { EBML_VoidSetSize(Node,Size); } /***************** * IOCallback ****************/ IOCallback::IOCallback() :Stream(NULL) { } IOCallback::~IOCallback() { if (Stream) NodeDelete((node*)Stream); } void IOCallback::writeFully(const void* Buffer, size_t Size) { assert(Stream!=NULL); Stream_Write(Stream,Buffer,Size,NULL); // TODO: handle errors and ERR_NEED_MORE_DATA } stream *IOCallback::GetStream() { if (Stream==NULL) { Stream = (stream_io*)NodeCreate(&ccContext,IOCALLBACK_STREAM_CLASS); Stream->cpp = this; } return (stream *)Stream; } /***************** * EbmlStream ****************/ EbmlStream::EbmlStream(IOCallback & IO) :mIO(IO) { } IOCallback & EbmlStream::I_O() { return mIO; } EbmlElement * EbmlStream::FindNextID(const ebml_context & Context, filepos_t MaxDataSize) { ebml_element *i = EBML_FindNextId(mIO.GetStream(),&Context,MaxDataSize); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } EbmlElement * EbmlStream::FindNextElement(const ebml_context & Context, int & UpperLevel, filepos_t MaxDataSize, bool AllowDummyElt, size_t MaxLowerLevel) { ebml_parser_context pContext; pContext.Context = &Context; pContext.UpContext = NULL; pContext.EndPosition = INVALID_FILEPOS_T; ebml_element *i = EBML_FindNextElement(mIO.GetStream(),&pContext,&UpperLevel,AllowDummyElt); if (i) { EbmlElement *Result=NULL; if (Node_Get(i,EBML_ELEMENT_OBJECT,&Result,sizeof(Result))!=ERR_NONE) { assert(0); } return Result; } return NULL; } }; bcmatroska2-5.3.101/libebml2/legacy/legacy.proj000066400000000000000000000013771462133141200211720ustar00rootroot00000000000000#include "*/*.proj" DLL ebml2_legacy { USE ebml2_group EXPINCLUDE . EXPINCLUDE .. EXPDEFINE EBML_STRICT_API DEFINE EBML_LEGACY_API SOURCE legacy.cpp HEADER ebml/EbmlBinary.h HEADER ebml/EbmlConfig.h HEADER ebml/EbmlContexts.h HEADER ebml/EbmlCrc32.h HEADER ebml/EbmlDate.h HEADER ebml/EbmlDummy.h HEADER ebml/EbmlElement.h HEADER ebml/EbmlFloat.h HEADER ebml/EbmlHead.h HEADER ebml/EbmlId.h HEADER ebml/EbmlMaster.h HEADER ebml/EbmlSInteger.h HEADER ebml/EbmlStream.h HEADER ebml/EbmlString.h HEADER ebml/EbmlSubHead.h HEADER ebml/EbmlTypes.h HEADER ebml/EbmlUInteger.h HEADER ebml/EbmlUnicodeString.h HEADER ebml/EbmlVersion.h HEADER ebml/EbmlVoid.h HEADER ebml/IOCallback.h HEADER ebml/c/libebml_t.h } bcmatroska2-5.3.101/libebml2/libebml2.proj000066400000000000000000000017321462133141200201450ustar00rootroot00000000000000#include "*/*.proj" GROUP ebml2_group { PROJECT_NAME "libebml2" PROJECT_VERSION 0.21.1 PROJECT_VENDOR "Matroska" EXPDEFINE HAS_EBML2 INCLUDE . EXPINCLUDE . IF CONFIG_EBML2_LIB USEINCLUDE node ELSE USE node USE file USE date IF (CONFIG_EBML_UNICODE || COREMAKE_UNICODE) USE parser ENDIF ENDIF IF COREMAKE_UNICODE DEFINE CONFIG_EBML_UNICODE EXPDEFINE CONFIG_EBML_UNICODE ENDIF HEADER ebml/ebml.h HEADER ebml/ebml_internal.h SOURCE ebmlmain.c SOURCE ebmlelement.c {class EBMLElement_Class} SOURCE ebmlmaster.c {class EBMLMaster_Class} SOURCE ebmlbinary.c {class EBMLBinary_Class} SOURCE ebmlstring.c {class EBMLString_Class} SOURCE ebmlnumber.c {class EBMLInteger_Class} SOURCE ebmlcrc.c {class EBMLCRC_Class} SOURCE ebmldate.c {class EBMLDate_Class} SOURCE ebmlvoid.c {class EBMLVoid_Class} HEADER ebmlcrc.h } DLL ebml2 { DEFINE EBML_LIBRARY USE ebml2_group EXPINCLUDE . } bcmatroska2-5.3.101/libebml2/test/000077500000000000000000000000001462133141200165355ustar00rootroot00000000000000bcmatroska2-5.3.101/libebml2/test/ebmltree.c000066400000000000000000000167011462133141200205050ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "ebml/ebml.h" #include "ebmltree_stdafx.h" static ebml_element *OutputElement(ebml_element *Element, const ebml_parser_context *Context, stream *Input, int *Level) { int LevelPrint; for (LevelPrint=0;LevelPrint<*Level;++LevelPrint) fprintf(stdout,"+ "); fprintf(stdout,"%s: ",Element->Context->ElementName); if (Node_IsPartOf(Element,EBML_MASTER_CLASS)) { int UpperElement = 0; ebml_element *SubElement,*NewElement; ebml_parser_context SubContext; fprintf(stdout,"(master) [%d bytes]\r\n",(int)Element->Size); SubContext.UpContext = Context; SubContext.Context = Element->Context; SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, EBML_INFINITE, 1); while (SubElement != NULL && UpperElement<=0 && (SubElement->ElementPosition < (Element->Size + Element->SizePosition + Element->SizeLength) || *Level==-1)) { // a sub element == not higher level and contained inside the current element (*Level)++; NewElement = OutputElement(SubElement, &SubContext, Input, Level); NodeDelete((node*)SubElement); if (NewElement) SubElement = NewElement; else SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, EBML_INFINITE, 1); (*Level)--; if (UpperElement < 0) *Level += UpperElement; } if (UpperElement < 0) // global element *Level += UpperElement+1; else *Level -= UpperElement-1; return SubElement; //EBML_ElementSkipData(Element, Input, Element->Context, NULL, 0); } else if (Node_IsPartOf(Element,EBML_STRING_CLASS) || Node_IsPartOf(Element,EBML_UNISTRING_CLASS)) { //tchar_t UnicodeString[MAXDATA]; //EBML_StringRead((ebml_string*)Element,Input,UnicodeString,TSIZEOF(UnicodeString)); if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA)==ERR_NONE) fprintf(stdout,"%s\r\n",((ebml_string*)Element)->Buffer); else fprintf(stdout,"\r\n"); } else if (Node_IsPartOf(Element,EBML_DATE_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA)==ERR_NONE) { datepack_t Date; datetime_t DateTime = EBML_DateTime((ebml_date*)Element); GetDatePacked(DateTime,&Date); fprintf(stdout,"%04d-%02d-%02d %02d:%02d:%02d\r\n",Date.Year,Date.Month,Date.Day,Date.Hour,Date.Minute,Date.Second); } else fprintf(stdout,"\r\n"); } else if (Node_IsPartOf(Element,EBML_INTEGER_CLASS) || Node_IsPartOf(Element,EBML_SINTEGER_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA)==ERR_NONE) { if (Node_IsPartOf(Element,EBML_SINTEGER_CLASS)) fprintf(stdout,"%ld\r\n",(int)((ebml_integer*)Element)->Value); else fprintf(stdout,"%lu\r\n",(int)((ebml_integer*)Element)->Value); } else fprintf(stdout,"\r\n"); } else if (Node_IsPartOf(Element,EBML_FLOAT_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA)==ERR_NONE) fprintf(stdout,"%f\r\n",((ebml_float*)Element)->Value); else fprintf(stdout,"\r\n"); } else if (EBML_ElementIsDummy(Element)) { #ifdef IS_BIG_ENDIAN fprintf(stdout,"%x\r\n",Element->Context->Id); #else fourcc_t Id = Element->Context->Id; while (Id & 0xFF) { fprintf(stdout,"[%x]",Id & 0xFF); Id >>= 8; } fprintf(stdout,"\r\n"); #endif EBML_ElementSkipData(Element, Input, Context, NULL, 0); } else if (Node_IsPartOf(Element,EBML_BINARY_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA)==ERR_NONE) { uint8_t *Data = ARRAYBEGIN(((ebml_binary*)Element)->Data,uint8_t); fprintf(stdout,"%02X %02X %02X %02X.. (%d)\r\n",Data[0],Data[1],Data[2],Data[3],Element->Size); } else fprintf(stdout,"\r\n"); } // TODO: handle crc32 else { #ifdef IS_BIG_ENDIAN fprintf(stdout,"\r\n",Element->Context->Id); #else fourcc_t Id = Element->Context->Id; fprintf(stdout,">= 8; } fprintf(stdout,">\r\n",Element->Context->Id); #endif EBML_ElementSkipData(Element, Input, Context, NULL, 0); } return NULL; } static void OutputTree(stream *Input) { ebml_element *Element = EBML_ElementCreate(Input,&EBML_ContextHead,0); if (Element) { int Level = -1; OutputElement(Element, NULL, Input, &Level); NodeDelete((node*)Element); } } int main(int argc, const char *argv[]) { #if defined(CONFIG_EBML_UNICODE) parsercontext p; #else nodecontext p; #endif stream *Input; if (argc != 2) { fprintf(stderr, "Usage: ebmltree [ebml_file]\r\n"); return 1; } // Core-C init phase #if defined(CONFIG_EBML_UNICODE) ParserContext_Init(&p,NULL,NULL,NULL); #else NodeContext_Init(&p,NULL,NULL,NULL); #endif StdAfx_Init((nodemodule*)&p); // EBML Init EBML_Init((nodecontext*)&p); // open the file to parse Input = StreamOpen(&p,argv[1],SFLAG_RDONLY); if (Input == NULL) fprintf(stderr, "error: ebmltree cannot open file \"%s\"\r\n",argv[1]); else { OutputTree(Input); StreamClose(Input); } // EBML ending EBML_Done((nodecontext*)&p); // Core-C ending #if defined(CONFIG_EBML_UNICODE) ParserContext_Done(&p); #else NodeContext_Done(&p); #endif return 0; } bcmatroska2-5.3.101/libebml2/test/test.proj000066400000000000000000000001251462133141200204060ustar00rootroot00000000000000CON ebmltree { USE ebml2 SOURCE ebmltree.c } GROUP ebmltests { USE ebmltree } bcmatroska2-5.3.101/libmatroska2/000077500000000000000000000000001462133141200164605ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/CMakeLists.txt000066400000000000000000000056211462133141200212240ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2016-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ set(MATROSKA2_SOURCE_FILES matroskamain.c matroskablock.c matroska_sem.c ) set(LIBS ) if(WIN32 AND NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsPhone" AND NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsStore") list(APPEND LIBS Winmm) endif() add_library(bcmatroska2 $ $ ${MATROSKA2_SOURCE_FILES}) set_target_properties(bcmatroska2 PROPERTIES VERSION 0.0.0 SOVERSION 0) set_target_properties(bcmatroska2 PROPERTIES POSITION_INDEPENDENT_CODE TRUE) if(APPLE) target_link_libraries(bcmatroska2 PRIVATE "-framework Foundation") if(IOS) target_link_libraries(bcmatroska2 PRIVATE "-framework CoreFoundation") endif() endif() target_include_directories(bcmatroska2 PRIVATE ../libebml2 .) target_include_directories(bcmatroska2 INTERFACE $ $ $ $ $ $ $ PRIVATE ../libebml2 . ) target_link_libraries(bcmatroska2 PUBLIC ${BCToolbox_TARGET}) if(LIBS) target_link_libraries(bcmatroska2 PRIVATE ${LIBS}) endif() if(MSVC AND BUILD_SHARED_LIBS) install(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE CONFIGURATIONS Debug RelWithDebInfo ) endif() install(TARGETS bcmatroska2 EXPORT ${PROJECT_NAME}Targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE ) install(DIRECTORY matroska DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) bcmatroska2-5.3.101/libmatroska2/MatroskaParser/000077500000000000000000000000001462133141200214165ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/MatroskaParser/MatroskaParser.c000066400000000000000000001424271462133141200245320ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MatroskaParser.h" #define MAX_TRACKS 32 // safety #if defined(TARGET_WIN) #define snprintf _snprintf #endif #define HAALI_STREAM_CLASS FOURCC('H','A','L','S') typedef struct haali_stream { stream Base; InputStream *io; } haali_stream; struct MatroskaFile { haali_stream *Input; ebml_element *Segment; ebml_element *SegmentInfo; ebml_element *TrackList; ebml_element *CueList; SegmentInfo Seg; ebml_parser_context L0Context; ebml_parser_context L1Context; ebml_element *CurrentCluster; matroska_block *CurrentBlock; size_t CurrentFrame; ebml_parser_context ClusterContext; filepos_t pSegmentInfo; filepos_t pTracks; filepos_t pCues; filepos_t pAttachments; filepos_t pChapters; filepos_t pTags; filepos_t pFirstCluster; int trackMask; int flags; array Tracks; array Tags; array Chapters; array Attachments; }; void mkv_SetTrackMask(MatroskaFile *File, int Mask) { File->trackMask = Mask; // TODO: the original code is handling a queue } void mkv_GetTags(MatroskaFile *File, Tag **pTags, unsigned *Count) { *pTags = ARRAYBEGIN(File->Tags,Tag); *Count = ARRAYCOUNT(File->Tags,Tag); } void mkv_GetAttachments(MatroskaFile *File, Attachment **pAttachements, unsigned *Count) { *pAttachements = ARRAYBEGIN(File->Attachments,Attachment); *Count = ARRAYCOUNT(File->Attachments,Attachment); } void mkv_GetChapters(MatroskaFile *File, Chapter **pChapters, unsigned *Count) { *pChapters = ARRAYBEGIN(File->Chapters,Chapter); *Count = ARRAYCOUNT(File->Chapters,Chapter); } TrackInfo *mkv_GetTrackInfo(MatroskaFile *File, size_t n) { if (n>=ARRAYCOUNT(File->Tracks,TrackInfo)) return NULL; return ARRAYBEGIN(File->Tracks,TrackInfo) + n; } SegmentInfo *mkv_GetFileInfo(MatroskaFile *File) { return &File->Seg; } size_t mkv_GetNumTracks(MatroskaFile *File) { return ARRAYCOUNT(File->Tracks,TrackInfo); } static bool_t CheckMatroskaHead(ebml_element *Head, char *err_msg, size_t err_msgSize) { tchar_t DocType[MAXPATH]; ebml_element *Elt; Elt = EBML_MasterFindFirstElt(Head,&EBML_ContextReadVersion,1,1); if (!Elt) { strncpy(err_msg,"Out of memory",err_msgSize); return 0; } if (EBML_IntegerValue(Elt) > EBML_MAX_VERSION) { snprintf(err_msg,err_msgSize,"File requires version %d EBML parser",(int)EBML_IntegerValue(Elt)); return 0; } Elt = EBML_MasterFindFirstElt(Head,&EBML_ContextDocTypeReadVersion,1,1); if (!Elt) { strncpy(err_msg,"Out of memory",err_msgSize); return 0; } if (EBML_IntegerValue(Elt) > MATROSKA_VERSION) { snprintf(err_msg,err_msgSize,"File requires version %d Matroska parser",(int)EBML_IntegerValue(Elt)); return 0; } Elt = EBML_MasterFindFirstElt(Head,&EBML_ContextMaxIdLength,1,1); if (!Elt) { strncpy(err_msg,"Out of memory",err_msgSize); return 0; } if (EBML_IntegerValue(Elt) > EBML_MAX_ID) { snprintf(err_msg,err_msgSize,"File has identifiers longer than %d",(int)EBML_IntegerValue(Elt)); return 0; } Elt = EBML_MasterFindFirstElt(Head,&EBML_ContextMaxSizeLength,1,1); if (!Elt) { strncpy(err_msg,"Out of memory",err_msgSize); return 0; } if (EBML_IntegerValue(Elt) > EBML_MAX_SIZE) { snprintf(err_msg,err_msgSize,"File has integers longer than %d",(int)EBML_IntegerValue(Elt)); return 0; } Elt = EBML_MasterFindFirstElt(Head,&EBML_ContextDocType,1,1); if (!Elt) { strncpy(err_msg,"Out of memory",err_msgSize); return 0; } EBML_StringGet((ebml_string*)Elt,DocType,TSIZEOF(DocType)); if (!tcsisame_ascii(DocType,T("matroska")) && !tcsisame_ascii(DocType,T("webm"))) { snprintf(err_msg,err_msgSize,"Unsupported DocType: %s",((ebml_string*)Elt)->Buffer); return 0; } return 1; } static bool_t parseSeekHead(ebml_element *SeekHead, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; ebml_element *Elt,*EltId; fourcc_t EltID; filepos_t SegStart = EBML_ElementPositionData(File->Segment); assert(SegStart!=INVALID_FILEPOS_T); RContext.Context = SeekHead->Context; if (EBML_ElementIsFiniteSize(SeekHead)) RContext.EndPosition = EBML_ElementPositionEnd(SeekHead); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(SeekHead,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the EBML head",err_msgSize); return 0; } Elt = EBML_MasterFindFirstElt(SeekHead,&MATROSKA_ContextSeek,0,0); while (Elt) { EltId = EBML_MasterFindFirstElt(Elt,&MATROSKA_ContextSeekId,0,0); if (EltId && EltId->DataSize > EBML_MAX_ID) { snprintf(err_msg,err_msgSize,"Invalid ID size in parseSeekEntry: %d",(int)EltId->DataSize); return 0; } EltID = MATROSKA_MetaSeekID((matroska_seekpoint *)Elt); if (EltID == MATROSKA_ContextSegmentInfo.Id) File->pSegmentInfo = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; else if (EltID == MATROSKA_ContextTracks.Id) File->pTracks = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; else if (EltID == MATROSKA_ContextCues.Id) File->pCues = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; else if (EltID == MATROSKA_ContextAttachments.Id) File->pAttachments = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; else if (EltID == MATROSKA_ContextChapters.Id) File->pChapters = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; else if (EltID == MATROSKA_ContextTags.Id) File->pTags = MATROSKA_MetaSeekPosInSegment((matroska_seekpoint *)Elt) + SegStart; Elt = EBML_MasterFindNextElt(SeekHead,Elt,0,0); } return 1; } static bool_t parseSegmentInfo(ebml_element *SegmentInfo, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; ebml_element *Elt; double duration = -1.0; RContext.Context = SegmentInfo->Context; if (EBML_ElementIsFiniteSize(SegmentInfo)) RContext.EndPosition = EBML_ElementPositionEnd(SegmentInfo); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(SegmentInfo,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Segment Info",err_msgSize); File->pSegmentInfo = INVALID_FILEPOS_T; return 0; } File->pSegmentInfo = SegmentInfo->ElementPosition; File->SegmentInfo = SegmentInfo; File->Seg.TimecodeScale = MATROSKA_ContextTimecodeScale.DefaultValue; for (Elt = EBML_MasterChildren(SegmentInfo);Elt;Elt = EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTimecodeScale.Id) { File->Seg.TimecodeScale = EBML_IntegerValue(Elt); if (File->Seg.TimecodeScale==0) { strncpy(err_msg,"Segment timecode scale is zero",err_msgSize); return 0; } } else if (Elt->Context->Id == MATROSKA_ContextDuration.Id) { duration = ((ebml_float*)Elt)->Value; } else if (Elt->Context->Id == MATROSKA_ContextSegmentDate.Id) { File->Seg.DateUTC = EBML_DateTime((ebml_date*)Elt); } else if (Elt->Context->Id == MATROSKA_ContextSegmentTitle.Id) { File->Seg.Title = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.Title,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextMuxingApp.Id) { File->Seg.MuxingApp = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.MuxingApp,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextWritingApp.Id) { File->Seg.WritingApp = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.WritingApp,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextSegmentUid.Id) { if (Elt->DataSize!=16) { snprintf(err_msg,err_msgSize,"SegmentUID size is not %d bytes",(int)Elt->DataSize); return 0; } memcpy(File->Seg.UID,EBML_BinaryGetData((ebml_binary*)Elt),sizeof(File->Seg.UID)); } else if (Elt->Context->Id == MATROSKA_ContextPrevUid.Id) { if (Elt->DataSize!=16) { snprintf(err_msg,err_msgSize,"PrevUID size is not %d bytes",(int)Elt->DataSize); return 0; } memcpy(File->Seg.PrevUID,EBML_BinaryGetData((ebml_binary*)Elt),sizeof(File->Seg.PrevUID)); } else if (Elt->Context->Id == MATROSKA_ContextNextUid.Id) { if (Elt->DataSize!=16) { snprintf(err_msg,err_msgSize,"NextUID size is not %d bytes",(int)Elt->DataSize); return 0; } memcpy(File->Seg.NextUID,EBML_BinaryGetData((ebml_binary*)Elt),sizeof(File->Seg.NextUID)); } else if (Elt->Context->Id == MATROSKA_ContextSegmentFilename.Id) { File->Seg.Filename = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.Filename,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextPrevFilename.Id) { File->Seg.PrevFilename = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.Filename,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextNextFilename.Id) { File->Seg.NextFilename = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(File->Seg.Filename,((ebml_string*)Elt)->Buffer); } } if (duration > 0.0) File->Seg.Duration = (timecode_t)(duration * File->Seg.TimecodeScale); return 1; } static void releaseTrackEntry(TrackInfo *track, InputStream *io) { if (track->CodecPrivate) io->memfree(io, track->CodecPrivate); if (track->Name) io->memfree(io, track->Name); } static bool_t parseTrackEntry(ebml_element *Track, MatroskaFile *File, char *err_msg, size_t err_msgSize) { TrackInfo track,*Tracks; ebml_element *Elt,*TElt; if (ARRAYCOUNT(File->Tracks,TrackInfo) >= MAX_TRACKS) return 0; memset(&track,0,sizeof(track)); track.DefaultDuration = INVALID_TIMECODE_T; track.Enabled = MATROSKA_ContextTrackEnabled.DefaultValue; track.Default = MATROSKA_ContextTrackDefault.DefaultValue; track.Lacing = MATROSKA_ContextTrackLacing.DefaultValue; track.DecodeAll = MATROSKA_ContextTrackCodecDecodeAll.DefaultValue; track.TimecodeScale = (float)MATROSKA_ContextTrackTimecodeScale.DefaultValue; memcpy(track.Language, "eng", 4); for (Elt = EBML_MasterChildren(Track);Elt;Elt = EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTrackNumber.Id) track.Number = (int)EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextTrackNumber.Id) track.UID = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextTrackType.Id) { if (EBML_IntegerValue(Elt)==0 || EBML_IntegerValue(Elt)>254) { snprintf(err_msg,err_msgSize,"Invalid track type: %d",(int)EBML_IntegerValue(Elt)); goto fail; } track.Type = (uint8_t)EBML_IntegerValue(Elt); } else if (Elt->Context->Id == MATROSKA_ContextTrackEnabled.Id) track.Enabled = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextTrackDefault.Id) track.Default = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextTrackLacing.Id) track.Lacing = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextTrackCodecDecodeAll.Id) track.DecodeAll = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextTrackMinCache.Id) { if (EBML_IntegerValue(Elt) > 0xFF) { snprintf(err_msg,err_msgSize,"MinCache is too large: %d",(int)EBML_IntegerValue(Elt)); goto fail; } track.MinCache = (uint8_t)EBML_IntegerValue(Elt); } else if (Elt->Context->Id == MATROSKA_ContextTrackMaxCache.Id) { if (EBML_IntegerValue(Elt) > 0x7FFFFFFF) { snprintf(err_msg,err_msgSize,"MaxCache is too large: %d",(int)EBML_IntegerValue(Elt)); goto fail; } track.MaxCache = (size_t)EBML_IntegerValue(Elt); } else if (Elt->Context->Id == MATROSKA_ContextTrackDefaultDuration.Id) track.DefaultDuration = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextTrackTimecodeScale.Id) track.TimecodeScale = (float)((ebml_float*)Elt)->Value; else if (Elt->Context->Id == MATROSKA_ContextTrackMaxBlockAdditionID.Id) track.MaxBlockAdditionID = (size_t)EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextTrackLanguage.Id) { size_t copy = (Elt->DataSize>3) ? 3 : (size_t)Elt->DataSize; memcpy(track.Language,((ebml_string*)Elt)->Buffer,copy); memset(track.Language + copy,0,4-copy); } else if (Elt->Context->Id == MATROSKA_ContextTrackCodecID.Id) { track.CodecID = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(track.CodecID,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextTrackCodecPrivate.Id) { if (Elt->DataSize > 256*1024) { snprintf(err_msg,err_msgSize,"CodecPrivate is too large: %d",(int)EBML_IntegerValue(Elt)); goto fail; } track.CodecPrivateSize = (size_t)(Elt->DataSize); track.CodecPrivate = File->Input->io->memalloc(File->Input->io, track.CodecPrivateSize); memcpy(track.CodecPrivate,EBML_BinaryGetData((ebml_binary*)Elt),track.CodecPrivateSize); } else if (Elt->Context->Id == MATROSKA_ContextTrackOverlay.Id) { if (EBML_IntegerValue(Elt)==0 || EBML_IntegerValue(Elt)>254) { snprintf(err_msg,err_msgSize,"Track number in TrackOverlay is too large: %d",(int)EBML_IntegerValue(Elt)); goto fail; } track.TrackOverlay = (uint8_t)EBML_IntegerValue(Elt); } else if (Elt->Context->Id == MATROSKA_ContextTrackVideo.Id) { for (TElt = EBML_MasterChildren(Elt);TElt;TElt = EBML_MasterNext(TElt)) { if (TElt->Context->Id == MATROSKA_ContextTrackVideoInterlaced.Id) track.AV.Video.Interlaced = EBML_IntegerValue(TElt)!=0; else if (TElt->Context->Id == MATROSKA_ContextTrackVideoStereo.Id) { if (TElt->DataSize > 3) { snprintf(err_msg,err_msgSize,"Invalid stereo mode: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.StereoMode = (uint8_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelWidth.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelWidth is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.PixelWidth = (uint32_t)EBML_IntegerValue(TElt); if (!track.AV.Video.DisplayWidth) track.AV.Video.DisplayWidth = track.AV.Video.PixelWidth; } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelHeight.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelHeight is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.PixelHeight = (uint32_t)EBML_IntegerValue(TElt); if (!track.AV.Video.DisplayHeight) track.AV.Video.DisplayHeight = track.AV.Video.PixelHeight; } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoDisplayWidth.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"DisplayWidth is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.DisplayWidth = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoDisplayHeight.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"DisplayHeight is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.DisplayHeight = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoDisplayUnit.Id) { if (EBML_IntegerValue(TElt) > 2) { snprintf(err_msg,err_msgSize,"DisplayUnit is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.DisplayUnit = (uint8_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoDisplayUnit.Id) { if (EBML_IntegerValue(TElt) > 2) { snprintf(err_msg,err_msgSize,"AspectRatioType is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.AspectRatioType = (uint8_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelCropBottom.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelCropBottom is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.CropB = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelCropTop.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelCropTop is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.CropT = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelCropLeft.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelCropLeft is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.CropL = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoPixelCropRight.Id) { if (EBML_IntegerValue(TElt) > 0xFFFFFFFF) { snprintf(err_msg,err_msgSize,"PixelCropRight is too large: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Video.CropR = (uint32_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoColourSpace.Id) { if (TElt->DataSize != 4) { snprintf(err_msg,err_msgSize,"ColourSpace is too large: %d",TElt->DataSize); goto fail; } track.AV.Video.ColourSpace = LOAD32LE(EBML_BinaryGetData((ebml_binary*)TElt)); } else if (TElt->Context->Id == MATROSKA_ContextTrackVideoGammaValue.Id) track.AV.Video.GammaValue = (float)((ebml_float*)TElt)->Value; } } else if (Elt->Context->Id == MATROSKA_ContextTrackAudio.Id) { track.AV.Audio.Channels = (uint8_t)MATROSKA_ContextTrackAudioChannels.DefaultValue; track.AV.Audio.SamplingFreq = (float)MATROSKA_ContextTrackAudioSamplingFreq.DefaultValue; for (TElt = EBML_MasterChildren(Elt);TElt;TElt = EBML_MasterNext(TElt)) { if (TElt->Context->Id == MATROSKA_ContextTrackAudioSamplingFreq.Id) { track.AV.Audio.SamplingFreq = (float)((ebml_float*)TElt)->Value; } else if (TElt->Context->Id == MATROSKA_ContextTrackAudioOutputSamplingFreq.Id) track.AV.Audio.OutputSamplingFreq = (float)((ebml_float*)TElt)->Value; else if (TElt->Context->Id == MATROSKA_ContextTrackAudioChannels.Id) { if (EBML_IntegerValue(TElt)==0 || EBML_IntegerValue(TElt)>0xFF) { snprintf(err_msg,err_msgSize,"Invalid Channels value: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Audio.Channels = (uint8_t)EBML_IntegerValue(TElt); } else if (TElt->Context->Id == MATROSKA_ContextTrackAudioBitDepth.Id) { if (EBML_IntegerValue(TElt)==0 || EBML_IntegerValue(TElt)>0xFF) { snprintf(err_msg,err_msgSize,"Invalid BitDepth value: %d",(int)EBML_IntegerValue(TElt)); goto fail; } track.AV.Audio.BitDepth = (uint8_t)EBML_IntegerValue(TElt); } } if (!track.AV.Audio.OutputSamplingFreq) track.AV.Audio.OutputSamplingFreq = track.AV.Audio.SamplingFreq; } // TODO: ContentEncoding } if (!track.CodecID) { strncpy(err_msg,"Track has no Codec ID",err_msgSize); goto fail; } // check for duplicate track UID entries if (track.UID) { for (Tracks=ARRAYBEGIN(File->Tracks,TrackInfo);Tracks!=ARRAYEND(File->Tracks,TrackInfo);++Tracks) { if (Tracks->UID == track.UID) { snprintf(err_msg,err_msgSize,"A track with UID 0x" PRIx64 " already exists",track.UID); goto fail; } } } ArrayAppend(&File->Tracks,&track,sizeof(track),256); return 1; fail: releaseTrackEntry(&track, File->Input->io); return 0; } static bool_t parseTracks(ebml_element *Tracks, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; ebml_element *Elt; RContext.Context = Tracks->Context; if (EBML_ElementIsFiniteSize(Tracks)) RContext.EndPosition = EBML_ElementPositionEnd(Tracks); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(Tracks,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Tracks",err_msgSize); File->pTracks = INVALID_FILEPOS_T; return 0; } File->pTracks = Tracks->ElementPosition; for (Elt = EBML_MasterChildren(Tracks);Elt;Elt = EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTrackEntry.Id) if (!parseTrackEntry(Elt, File, err_msg, err_msgSize)) break; } File->TrackList = Tracks; return 1; } static bool_t parseCues(ebml_element *Cues, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; RContext.Context = Cues->Context; if (EBML_ElementIsFiniteSize(Cues)) RContext.EndPosition = EBML_ElementPositionEnd(Cues); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(Cues,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Cues",err_msgSize); File->pCues = INVALID_FILEPOS_T; return 0; } File->pCues = Cues->ElementPosition; File->CueList = Cues; return 1; } static bool_t parseAttachments(ebml_element *Attachments, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; ebml_element *Elt, *Elt2; size_t Count; Attachment *At; RContext.Context = Attachments->Context; if (EBML_ElementIsFiniteSize(Attachments)) RContext.EndPosition = EBML_ElementPositionEnd(Attachments); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(Attachments,(stream*)File->Input,&RContext,1,SCOPE_PARTIAL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Attachments",err_msgSize); File->pAttachments = INVALID_FILEPOS_T; return 0; } File->pAttachments = Attachments->ElementPosition; Count=0; Elt = EBML_MasterFindFirstElt(Attachments, &MATROSKA_ContextAttachedFile, 0,0); while (Elt) { ++Count; Elt = EBML_MasterFindNextElt(Attachments, Elt, 0,0); } ArrayResize(&File->Attachments,Count*sizeof(Attachment),0); ArrayZero(&File->Attachments); for (Elt = EBML_MasterFindFirstElt(Attachments, &MATROSKA_ContextAttachedFile, 0,0),At=ARRAYBEGIN(File->Attachments,Attachment); At!=ARRAYEND(File->Attachments,Attachment); ++At, Elt = EBML_MasterFindNextElt(Attachments, Elt, 0,0)) { At->Length = INVALID_FILEPOS_T; At->Position = INVALID_FILEPOS_T; for (Elt2=EBML_MasterChildren(Elt);Elt2;Elt2=EBML_MasterNext(Elt2)) { if (Elt2->Context->Id == MATROSKA_ContextAttachedFileName.Id) { At->Name = File->Input->io->memalloc(File->Input->io, (size_t)(Elt2->DataSize+1)); strcpy(At->Name,((ebml_string*)Elt2)->Buffer); } else if (Elt2->Context->Id == MATROSKA_ContextAttachedFileData.Id) { At->Position = EBML_ElementPositionData(Elt2); At->Length = Elt2->DataSize; } else if (Elt2->Context->Id == MATROSKA_ContextAttachedFileUID.Id) At->UID = EBML_IntegerValue(Elt2); else if (Elt2->Context->Id == MATROSKA_ContextAttachedFileMimeType.Id) { At->MimeType = File->Input->io->memalloc(File->Input->io, (size_t)(Elt2->DataSize+1)); strcpy(At->MimeType,((ebml_string*)Elt2)->Buffer); } else if (Elt2->Context->Id == MATROSKA_ContextAttachedFileDescription.Id) { At->Description = File->Input->io->memalloc(File->Input->io, (size_t)(Elt2->DataSize+1)); strcpy(At->Description,((ebml_string*)Elt2)->Buffer); } } } return 1; } static bool_t addChapterDisplay(ebml_element *ChapterDisplay, MatroskaFile *File, struct Chapter *Chapter) { struct ChapterDisplay *pDisplay,Display; ebml_element *Elt; if (!ArrayAppend(&Chapter->aDisplays,&Display,sizeof(struct ChapterDisplay),512)) return 0; pDisplay = ARRAYEND(Chapter->aDisplays,struct ChapterDisplay)-1; memset(pDisplay,0,sizeof(*pDisplay)); memcpy(pDisplay->Language, (char*)MATROSKA_ContextChapterLanguage.DefaultValue, 4); for (Elt=EBML_MasterChildren(ChapterDisplay); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextChapterString.Id) { pDisplay->String = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(pDisplay->String,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextChapterLanguage.Id) { size_t copy = (Elt->DataSize>3) ? 3 : (size_t)Elt->DataSize; memcpy(pDisplay->Language,((ebml_string*)Elt)->Buffer,copy); memset(pDisplay->Language + copy,0,4-copy); } else if (Elt->Context->Id == MATROSKA_ContextChapterCountry.Id) { size_t copy = (Elt->DataSize>3) ? 3 : (size_t)Elt->DataSize; memcpy(pDisplay->Country,((ebml_string*)Elt)->Buffer,copy); memset(pDisplay->Country+ copy,0,4-copy); } } return 1; } static bool_t parseChapter(ebml_element *Chapter, MatroskaFile *File, char *err_msg, size_t err_msgSize, struct Chapter *Parent, array *Editions) { struct Chapter *pChapter,Chap; ebml_element *Elt; pChapter = &Chap; for (Elt=EBML_MasterChildren(Chapter); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextChapterAtom.Id) { if (!ArrayAppend(&Parent->aChildren,&Chap,sizeof(Chap),512)) return 0; pChapter = ARRAYEND(Parent->aChildren,struct Chapter)-1; memset(pChapter,0,sizeof(*pChapter)); pChapter->Start = INVALID_TIMECODE_T; if (!parseChapter(Elt,File,err_msg,err_msgSize,pChapter,NULL)) ArrayRemove(&Parent->aChildren,struct Chapter,pChapter,NULL,NULL); } // Atom else if (Elt->Context->Id == MATROSKA_ContextChapterUID.Id) Parent->UID = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextChapterTimeStart.Id) Parent->Start = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextChapterTimeEnd.Id) Parent->End = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextChapterHidden.Id) Parent->Hidden = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextChapterEnabled.Id) Parent->Enabled = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextChapterDisplay.Id) addChapterDisplay(Elt, File, Parent); // Edition else if (Elt->Context->Id == MATROSKA_ContextEditionUID.Id) Parent->UID = EBML_IntegerValue(Elt); else if (Elt->Context->Id == MATROSKA_ContextEditionHidden.Id) Parent->Hidden = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextEditionDefault.Id) Parent->Default = EBML_IntegerValue(Elt)!=0; else if (Elt->Context->Id == MATROSKA_ContextEditionOrdered.Id) Parent->Ordered = EBML_IntegerValue(Elt)!=0; } Parent->nChildren = ARRAYCOUNT(Parent->aChildren,struct Chapter); Parent->Children = ARRAYBEGIN(Parent->aChildren,struct Chapter); Parent->nDisplay = ARRAYCOUNT(Parent->aDisplays,struct ChapterDisplay); Parent->Display = ARRAYBEGIN(Parent->aDisplays,struct ChapterDisplay); return 1; } static bool_t parseChapters(ebml_element *Chapters, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; struct Chapter *pChapter,Chap; ebml_element *Elt; RContext.Context = Chapters->Context; if (EBML_ElementIsFiniteSize(Chapters)) RContext.EndPosition = EBML_ElementPositionEnd(Chapters); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(Chapters,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Chapters",err_msgSize); File->pChapters = INVALID_FILEPOS_T; return 0; } File->pChapters = Chapters->ElementPosition; pChapter = &Chap; memset(pChapter,0,sizeof(*pChapter)); Chap.Start = INVALID_TIMECODE_T; Chap.Ordered = MATROSKA_ContextEditionOrdered.DefaultValue; Chap.Hidden = MATROSKA_ContextEditionHidden.DefaultValue; Chap.Default = MATROSKA_ContextEditionDefault.DefaultValue; for (Elt=EBML_MasterChildren(Chapters); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextChapterEntry.Id) { if (!ArrayAppend(&File->Chapters,&Chap,sizeof(Chap),512)) return 0; pChapter = ARRAYEND(File->Chapters,struct Chapter)-1; if (!parseChapter(Elt, File, err_msg, err_msgSize, pChapter, &File->Chapters)) ArrayRemove(&File->Chapters,struct Chapter,pChapter,NULL,NULL); } } return 1; } static bool_t parseTargets(ebml_element *Targets, MatroskaFile *File, char *err_msg, size_t err_msgSize, struct Tag *Parent) { ebml_element *Elt; uint8_t Level; struct Target *pTarget,Target; Elt = EBML_MasterFindFirstElt(Targets, &MATROSKA_ContextTagTargetTypeValue, 1, 1); if (!Elt || EBML_IntegerValue(Elt) > 0xFF) return 0; Level = (uint8_t)EBML_IntegerValue(Elt); pTarget = &Target; memset(pTarget,0,sizeof(*pTarget)); for (Elt=EBML_MasterChildren(Targets); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTagTargetTrackUID.Id) { if (!ArrayAppend(&Parent->aTargets,&Target,sizeof(Target),512)) return 0; pTarget = ARRAYEND(Parent->aTargets,struct Target)-1; pTarget->Type = TARGET_TRACK; pTarget->UID = EBML_IntegerValue(Elt); pTarget->Level = Level; } else if (Elt->Context->Id == MATROSKA_ContextTagTargetChapterUID.Id) { if (!ArrayAppend(&Parent->aTargets,&Target,sizeof(Target),512)) return 0; pTarget = ARRAYEND(Parent->aTargets,struct Target)-1; pTarget->Type = TARGET_CHAPTER; pTarget->UID = EBML_IntegerValue(Elt); pTarget->Level = Level; } else if (Elt->Context->Id == MATROSKA_ContextTagTargetAttachmentUID.Id) { if (!ArrayAppend(&Parent->aTargets,&Target,sizeof(Target),512)) return 0; pTarget = ARRAYEND(Parent->aTargets,struct Target)-1; pTarget->Type = TARGET_ATTACHMENT; pTarget->UID = EBML_IntegerValue(Elt); pTarget->Level = Level; } else if (Elt->Context->Id == MATROSKA_ContextTagTargetEditionUID.Id) { if (!ArrayAppend(&Parent->aTargets,&Target,sizeof(Target),512)) return 0; pTarget = ARRAYEND(Parent->aTargets,struct Target)-1; pTarget->Type = TARGET_EDITION; pTarget->UID = EBML_IntegerValue(Elt); pTarget->Level = Level; } } return 1; } static bool_t parseSimpleTag(ebml_element *SimpleTag, MatroskaFile *File, char *err_msg, size_t err_msgSize, struct Tag *Parent) { ebml_element *Elt; struct SimpleTag simpleTag; memset(&simpleTag,0,sizeof(simpleTag)); simpleTag.Default = MATROSKA_ContextTagDefault.DefaultValue; memcpy(simpleTag.Language, (const char*)MATROSKA_ContextTagLanguage.DefaultValue, 4); for (Elt=EBML_MasterChildren(SimpleTag); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTagName.Id) { simpleTag.Name = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(simpleTag.Name,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextTagString.Id) { simpleTag.Value = File->Input->io->memalloc(File->Input->io, (size_t)(Elt->DataSize+1)); strcpy(simpleTag.Value,((ebml_string*)Elt)->Buffer); } else if (Elt->Context->Id == MATROSKA_ContextTagLanguage.Id) { size_t copy = (Elt->DataSize>3) ? 3 : (size_t)Elt->DataSize; memcpy(simpleTag.Language,((ebml_string*)Elt)->Buffer,copy); memset(simpleTag.Language + copy,0,4-copy); } else if (Elt->Context->Id == MATROSKA_ContextTagString.Id) simpleTag.Default = EBML_IntegerValue(Elt)!=0; } if (!simpleTag.Value || !simpleTag.Name || !ArrayAppend(&Parent->aSimpleTags,&simpleTag,sizeof(simpleTag),256)) { if (simpleTag.Value) File->Input->io->memfree(File->Input->io, simpleTag.Value); if (simpleTag.Name) File->Input->io->memfree(File->Input->io, simpleTag.Name); return 0; } Elt = EBML_MasterFindFirstElt(SimpleTag, &MATROSKA_ContextSimpleTag, 0, 0); while (Elt) { parseSimpleTag(Elt, File, err_msg, err_msgSize, Parent); Elt = EBML_MasterFindNextElt(SimpleTag, Elt, 0, 0); } return 1; } static bool_t parseTag(ebml_element *Tag, MatroskaFile *File, char *err_msg, size_t err_msgSize, struct Tag *Parent) { ebml_element *Elt; for (Elt=EBML_MasterChildren(Tag); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTagTargets.Id) parseTargets(Elt,File,err_msg,err_msgSize,Parent); else if (Elt->Context->Id == MATROSKA_ContextSimpleTag.Id) parseSimpleTag(Elt,File,err_msg,err_msgSize,Parent); } Parent->Targets = ARRAYBEGIN(Parent->aTargets,struct Target); Parent->nTargets = ARRAYCOUNT(Parent->aTargets,struct Target); Parent->SimpleTags = ARRAYBEGIN(Parent->aSimpleTags,struct SimpleTag); Parent->nSimpleTags = ARRAYCOUNT(Parent->aSimpleTags,struct SimpleTag); return 1; } static bool_t parseTags(ebml_element *Tags, MatroskaFile *File, char *err_msg, size_t err_msgSize) { ebml_parser_context RContext; struct Tag *pTag,Tag; ebml_element *Elt; RContext.Context = Tags->Context; if (EBML_ElementIsFiniteSize(Tags)) RContext.EndPosition = EBML_ElementPositionEnd(Tags); else RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = &File->L1Context; if (EBML_ElementReadData(Tags,(stream*)File->Input,&RContext,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the Tags",err_msgSize); File->pTags = INVALID_FILEPOS_T; return 0; } File->pTags = Tags->ElementPosition; pTag = &Tag; memset(pTag,0,sizeof(*pTag)); for (Elt=EBML_MasterChildren(Tags); Elt; Elt=EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextTag.Id) { if (!ArrayAppend(&File->Tags,&Tag,sizeof(Tag),512)) return 0; pTag = ARRAYEND(File->Tags,struct Tag)-1; if (!parseTag(Elt, File, err_msg, err_msgSize, pTag)) ArrayRemove(&File->Tags,struct Tag,pTag,NULL,NULL); } } return 1; } MatroskaFile *mkv_Open(InputStream *io, char *err_msg, size_t err_msgSize) { int UpperLevel; ebml_element *Head, *Elt; MatroskaFile *File = io->memalloc(io,sizeof(*File)); if (!File) { strncpy(err_msg,"Out of memory",err_msgSize); return NULL; } memset(File,0,sizeof(*File)); File->pSegmentInfo = INVALID_FILEPOS_T; File->pTracks = INVALID_FILEPOS_T; File->pCues = INVALID_FILEPOS_T; File->pAttachments = INVALID_FILEPOS_T; File->pChapters = INVALID_FILEPOS_T; File->pTags = INVALID_FILEPOS_T; File->pFirstCluster = INVALID_FILEPOS_T; io->progress(io,0,0); io->ioseek(io,0,SEEK_SET); // find a segment File->Input = (haali_stream*)NodeCreate(io->AnyNode,HAALI_STREAM_CLASS); if (!File->Input) { strncpy(err_msg,"Out of memory",err_msgSize); return NULL; } File->Input->io = io; File->L0Context.Context = &MATROSKA_ContextStream; File->L0Context.EndPosition = File->Input->io->getfilesize(File->Input->io); File->L0Context.UpContext = NULL; UpperLevel = 0; Head = EBML_FindNextElement((stream*)File->Input,&File->L0Context,&UpperLevel,0); if (!Head) { strncpy(err_msg,"Out of memory",err_msgSize); return NULL; } if (Head->Context->Id == MATROSKA_ContextSegment.Id) { strncpy(err_msg,"First element in file is not EBML",err_msgSize); return NULL; } if (EBML_ElementReadData(Head,(stream*)File->Input,&File->L0Context,1,SCOPE_ALL_DATA)!=ERR_NONE) { strncpy(err_msg,"Failed to read the EBML head",err_msgSize); NodeDelete((node*)Head); return NULL; } if (!CheckMatroskaHead(Head,err_msg,err_msgSize)) { NodeDelete((node*)Head); return NULL; } NodeDelete((node*)Head); File->Segment = EBML_FindNextElement((stream*)File->Input,&File->L0Context,&UpperLevel,0); if (!File->Segment) { strncpy(err_msg,"No segments found in the file",err_msgSize); return NULL; } // we want to read data until we find a seekhead or a trackinfo File->L1Context.Context = File->Segment->Context; if (EBML_ElementIsFiniteSize(File->Segment)) File->L1Context.EndPosition = EBML_ElementPositionEnd(File->Segment); else File->L1Context.EndPosition = INVALID_FILEPOS_T; File->L1Context.UpContext = &File->L0Context; UpperLevel = 0; Head = EBML_FindNextElement((stream*)File->Input,&File->L1Context,&UpperLevel,0); while (Head && (!EBML_ElementIsFiniteSize(File->Segment) || EBML_ElementPositionEnd(File->Segment) >= EBML_ElementPositionEnd(Head))) { if (Head->Context->Id == MATROSKA_ContextSeekHead.Id) { parseSeekHead(Head, File, err_msg, err_msgSize); NodeDelete((node*)Head); } else if (Head->Context->Id == MATROSKA_ContextSegmentInfo.Id) parseSegmentInfo(Head, File, err_msg, err_msgSize); else if (Head->Context->Id == MATROSKA_ContextTracks.Id) parseTracks(Head, File, err_msg, err_msgSize); else if (Head->Context->Id == MATROSKA_ContextCues.Id) parseCues(Head, File, err_msg, err_msgSize); else if (Head->Context->Id == MATROSKA_ContextAttachments.Id) { parseAttachments(Head, File, err_msg, err_msgSize); NodeDelete((node*)Head); } else if (Head->Context->Id == MATROSKA_ContextChapters.Id) { parseChapters(Head, File, err_msg, err_msgSize); NodeDelete((node*)Head); } else if (Head->Context->Id == MATROSKA_ContextTags.Id) { parseTags(Head, File, err_msg, err_msgSize); NodeDelete((node*)Head); } else { if (Head->Context->Id==MATROSKA_ContextCluster.Id && File->pFirstCluster==INVALID_FILEPOS_T) File->pFirstCluster = Head->ElementPosition; Elt = EBML_ElementSkipData(Head,(stream*)File->Input,&File->L1Context,NULL,1); NodeDelete((node*)Head); if (Elt) { Head = Elt; continue; } } Head = EBML_FindNextElement((stream*)File->Input,&File->L1Context,&UpperLevel,0); } if (File->CueList && File->SegmentInfo) { for (Elt = EBML_MasterChildren(File->CueList);Elt;Elt = EBML_MasterNext(Elt)) { if (Elt->Context->Id == MATROSKA_ContextCuePoint.Id) MATROSKA_LinkCueSegmentInfo((matroska_cuepoint*)Elt, File->SegmentInfo); } MATROSKA_CuesSort(File->CueList); } return File; } static void releaseAttachments(array *Attachments, MatroskaFile *File) { Attachment *At; for (At=ARRAYBEGIN(File->Attachments,Attachment); At!=ARRAYEND(File->Attachments,Attachment); ++At) { if (At->Name) File->Input->io->memfree(File->Input->io, At->Name); if (At->MimeType) File->Input->io->memfree(File->Input->io, At->MimeType); if (At->Description) File->Input->io->memfree(File->Input->io, At->Description); } ArrayClear(Attachments); } static void releaseChapterDisplays(array *ChapterDisplays, MatroskaFile *File) { struct ChapterDisplay *pChapter; for (pChapter = ARRAYBEGIN(*ChapterDisplays,struct ChapterDisplay); pChapter != ARRAYEND(*ChapterDisplays,struct ChapterDisplay); ++pChapter) File->Input->io->memfree(File->Input->io, pChapter->String); ArrayClear(ChapterDisplays); } static void releaseChapters(array *Chapters, MatroskaFile *File) { struct Chapter *pChapter; for (pChapter = ARRAYBEGIN(*Chapters,struct Chapter); pChapter != ARRAYEND(*Chapters,struct Chapter); ++pChapter) { releaseChapterDisplays(&pChapter->aDisplays, File); releaseChapters(&pChapter->aChildren,File); } ArrayClear(Chapters); } static void releaseSimpleTags(array *SimpleTags, MatroskaFile *File) { struct SimpleTag *pSimpleTag; for (pSimpleTag = ARRAYBEGIN(*SimpleTags,struct SimpleTag); pSimpleTag != ARRAYEND(*SimpleTags,struct SimpleTag); ++pSimpleTag) { if (pSimpleTag->Name) File->Input->io->memfree(File->Input->io, pSimpleTag->Name); if (pSimpleTag->Value) File->Input->io->memfree(File->Input->io, pSimpleTag->Value); } ArrayClear(SimpleTags); } static void releaseTags(array *Tags, MatroskaFile *File) { struct Tag *pTag; for (pTag = ARRAYBEGIN(*Tags,struct Tag); pTag != ARRAYEND(*Tags,struct Tag); ++pTag) { releaseSimpleTags(&pTag->aSimpleTags, File); ArrayClear(&pTag->aTargets); } ArrayClear(Tags); } void mkv_Close(MatroskaFile *File) { if (File->Seg.Filename) File->Input->io->memfree(File->Input->io, File->Seg.Filename); if (File->Seg.PrevFilename) File->Input->io->memfree(File->Input->io, File->Seg.PrevFilename); if (File->Seg.NextFilename) File->Input->io->memfree(File->Input->io, File->Seg.NextFilename); if (File->Seg.Title) File->Input->io->memfree(File->Input->io, File->Seg.Title); if (File->Seg.MuxingApp) File->Input->io->memfree(File->Input->io, File->Seg.MuxingApp); if (File->Seg.WritingApp) File->Input->io->memfree(File->Input->io, File->Seg.WritingApp); ArrayClear(&File->Tracks); releaseAttachments(&File->Attachments, File); releaseChapters(&File->Chapters, File); releaseTags(&File->Tags, File); if (File->TrackList) NodeDelete((node*)File->TrackList); if (File->CueList) NodeDelete((node*)File->CueList); if (File->SegmentInfo) NodeDelete((node*)File->SegmentInfo); if (File->Segment) NodeDelete((node*)File->Segment); if (File->Input) NodeDelete((node*)File->Input); } int mkv_ReadFrame(MatroskaFile *File, int mask, unsigned int *track, ulonglong *StartTime, ulonglong *EndTime, ulonglong *FilePos, unsigned int *FrameSize, void** FrameRef, unsigned int *FrameFlags) { ebml_element *Elt = NULL,*Elt2; TrackInfo *tr; int16_t TrackNum; matroska_frame Frame; bool_t Skip; unsigned int Track; int UpperLevel = 0; if (FrameFlags) *FrameFlags = 0; if (!track) track = &Track; *track = (unsigned int)-1; for (;;) { if (!File->CurrentCluster) { for (;;) { if (!Elt) Elt = EBML_FindNextElement((stream*)File->Input,&File->L1Context,&UpperLevel,0); File->CurrentCluster = Elt; if (!File->CurrentCluster) return EOF; if (UpperLevel) { // TODO: changing segments not supported yet NodeDelete((node*)File->CurrentCluster); return EOF; } if (File->CurrentCluster->Context->Id == MATROSKA_ContextCluster.Id) break; Elt = File->CurrentCluster; File->CurrentCluster = EBML_ElementSkipData(File->CurrentCluster,(stream*)File->Input,&File->L1Context,NULL,1); NodeDelete((node*)Elt); Elt = NULL; } MATROSKA_LinkClusterReadSegmentInfo((matroska_cluster*)File->CurrentCluster,File->SegmentInfo,1); File->ClusterContext.Context = &MATROSKA_ContextCluster; if (EBML_ElementIsFiniteSize(File->CurrentCluster)) File->ClusterContext.EndPosition = EBML_ElementPositionEnd(File->CurrentCluster); else File->ClusterContext.EndPosition = INVALID_FILEPOS_T; File->ClusterContext.UpContext = &File->L1Context; File->CurrentBlock = NULL; File->CurrentFrame = 0; } Elt = NULL; while (!File->CurrentBlock) { if (!Elt) { UpperLevel = 0; Elt = EBML_FindNextElement((stream*)File->Input,&File->ClusterContext,&UpperLevel,1); } if (!Elt || UpperLevel>0) { NodeDelete((node*)File->CurrentCluster); File->CurrentCluster = NULL; --UpperLevel; break; // go to the next Cluster } Skip = 0; if (Elt->Context->Id == MATROSKA_ContextClusterTimecode.Id) { if (EBML_ElementReadData(Elt,(stream*)File->Input,&File->ClusterContext,1, SCOPE_ALL_DATA)!=ERR_NONE) return EOF; // TODO: memory leak Elt2 = EBML_MasterFindFirstElt(File->CurrentCluster,&MATROSKA_ContextClusterTimecode,1,1); if (!Elt2) return EOF; // TODO: memory leak EBML_IntegerSetValue((ebml_integer*)Elt2,EBML_IntegerValue(Elt)); NodeDelete((node*)Elt); Elt = NULL; } else if (Elt->Context->Id == MATROSKA_ContextClusterSimpleBlock.Id) { if (EBML_ElementReadData(Elt,(stream*)File->Input,&File->ClusterContext,1, SCOPE_PARTIAL_DATA)!=ERR_NONE) return EOF; // TODO: memory leak TrackNum = MATROSKA_BlockTrackNum((matroska_block*)Elt); for (*track=0, tr=ARRAYBEGIN(File->Tracks,TrackInfo);tr!=ARRAYEND(File->Tracks,TrackInfo);++tr,(*track)++) if (TrackNum==tr->Number) break; if (tr==ARRAYEND(File->Tracks,TrackInfo) || (1<<*track & File->trackMask)!=0) Skip = 1; else { EBML_MasterAppend(File->CurrentCluster, Elt); MATROSKA_LinkBlockWithReadTracks((matroska_block*)Elt,File->TrackList,1); MATROSKA_LinkBlockReadSegmentInfo((matroska_block*)Elt,File->SegmentInfo,1); File->CurrentBlock = (matroska_block*)Elt; } } else if (Elt->Context->Id == MATROSKA_ContextClusterBlockGroup.Id) { if (EBML_ElementReadData(Elt,(stream*)File->Input,&File->ClusterContext,1, SCOPE_PARTIAL_DATA)!=ERR_NONE) return EOF; // TODO: memory leak Elt2 = EBML_MasterFindFirstElt(Elt, &MATROSKA_ContextClusterBlock, 0, 0); if (!Elt2) Skip = 1; else { TrackNum = MATROSKA_BlockTrackNum((matroska_block*)Elt2); for (*track=0, tr=ARRAYBEGIN(File->Tracks,TrackInfo);tr!=ARRAYEND(File->Tracks,TrackInfo);++tr,(*track)++) if (TrackNum==tr->Number) break; if (tr==ARRAYEND(File->Tracks,TrackInfo) || (1<<*track & File->trackMask)!=0) Skip = 1; else { EBML_MasterAppend(File->CurrentCluster, Elt); MATROSKA_LinkBlockWithReadTracks((matroska_block*)Elt2,File->TrackList,1); MATROSKA_LinkBlockReadSegmentInfo((matroska_block*)Elt2,File->SegmentInfo,1); File->CurrentBlock = (matroska_block*)Elt2; } } } else Skip = 1; if (Skip) { Elt2 = Elt; Elt = EBML_ElementSkipData(Elt2,(stream*)File->Input,&File->L1Context,NULL,1); NodeDelete((node*)Elt2); } } if (File->CurrentCluster && File->CurrentBlock) break; } assert(File->CurrentBlock!=NULL); if (MATROSKA_BlockGetFrame(File->CurrentBlock,File->CurrentFrame,&Frame,0)!=ERR_NONE) return -1; // TODO: memory leaks if (*track==(unsigned int)-1) { TrackNum = MATROSKA_BlockTrackNum(File->CurrentBlock); for (*track=0, tr=ARRAYBEGIN(File->Tracks,TrackInfo);tr!=ARRAYEND(File->Tracks,TrackInfo);++tr,(*track)++) if (TrackNum==tr->Number) break; } if (Frame.Timecode!=INVALID_TIMECODE_T) { if (StartTime) *StartTime = Frame.Timecode; if (EndTime && Frame.Duration != INVALID_TIMECODE_T) *EndTime = Frame.Timecode + Frame.Duration; } if (FilePos) *FilePos = ((ebml_element*)File->CurrentBlock)->ElementPosition; if (FrameFlags) { if (Frame.Timecode == INVALID_TIMECODE_T) *FrameFlags |= FRAME_UNKNOWN_START; if (Frame.Duration == INVALID_TIMECODE_T) *FrameFlags |= FRAME_UNKNOWN_END; if (MATROSKA_BlockKeyframe(File->CurrentBlock)) *FrameFlags |= FRAME_KF; } MATROSKA_BlockSkipToFrame(File->CurrentBlock, (stream*)File->Input, File->CurrentFrame); *FrameRef = File->Input->io->makeref(File->Input->io,MATROSKA_BlockGetLength(File->CurrentBlock,File->CurrentFrame++)); if (File->CurrentFrame >= MATROSKA_BlockGetFrameCount(File->CurrentBlock)) { File->CurrentBlock = NULL; File->CurrentFrame = 0; } return 0; } static void SeekToPos(MatroskaFile *File, filepos_t SeekPos) { if (File->CurrentBlock) { NodeDelete((node*)File->CurrentBlock); File->CurrentBlock = NULL; } File->CurrentFrame = 0; if (File->CurrentCluster && File->CurrentCluster->ElementPosition!=SeekPos) { NodeDelete((node*)File->CurrentCluster); File->CurrentCluster = NULL; } File->Input->io->ioseek(File->Input->io,SeekPos,SEEK_SET); } void mkv_Seek(MatroskaFile *File, timecode_t timecode, int flags) { matroska_cuepoint *CuePoint; filepos_t SeekPos; if (File->flags & MKVF_AVOID_SEEKS || File->pFirstCluster==INVALID_FILEPOS_T || timecode==INVALID_TIMECODE_T) return; if (timecode==0) { SeekToPos(File, File->pFirstCluster); return; } if (!File->CueList) return; CuePoint = MATROSKA_CuesGetTimecodeStart(File->CueList,timecode); if (CuePoint==NULL) return; SeekPos = MATROSKA_CuePosInSegment(CuePoint) + EBML_ElementPositionData(File->Segment); SeekToPos(File, SeekPos); } int mkv_TruncFloat(float f) { return (int)f; } static filepos_t Seek(haali_stream *p ,filepos_t Pos,int SeekMode) { if (!(Pos == 0 && SeekMode==SEEK_CUR)) p->io->ioseek(p->io,Pos,SeekMode); return p->io->iotell(p->io); } static err_t Read(haali_stream* p,void* Data,size_t Size,size_t* pReaded) { size_t Readed; if (!pReaded) pReaded = &Readed; *pReaded = p->io->ioread(p->io,Data,Size); if (Size && *pReaded!=Size) return ERR_END_OF_FILE; return ERR_NONE; } META_START(HaaliStream_Class,HAALI_STREAM_CLASS) META_CLASS(SIZE,sizeof(haali_stream)) META_VMT(TYPE_FUNC,stream_vmt,Seek,Seek) META_VMT(TYPE_FUNC,stream_vmt,Read,Read) META_END(STREAM_CLASS) bcmatroska2-5.3.101/libmatroska2/MatroskaParser/MatroskaParser.h000066400000000000000000000141511462133141200245270ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MATROSKA_PARSER_H #define MATROSKA_PARSER_H #include "matroska/matroska.h" typedef int64_t longlong; typedef uint64_t ulonglong; typedef struct InputStream { int (*read)(struct InputStream *cc, filepos_t pos, void *buffer, size_t count); filepos_t (*scan)(struct InputStream *cc, filepos_t start, unsigned signature); size_t (*getcachesize)(struct InputStream *cc); filepos_t (*getfilesize)(struct InputStream *cc); const char *(*geterror)(struct InputStream *cc); int (*progress)(struct InputStream *cc, filepos_t cur, filepos_t max); int (*ioreadch)(struct InputStream *inf); int (*ioread)(struct InputStream *inf,void *buffer,int count); void (*ioseek)(struct InputStream *inf,longlong where,int how); filepos_t (*iotell)(struct InputStream *inf); void* (*makeref)(struct InputStream *inf,int count); void (*releaseref)(struct InputStream *inf,void* ref); void *(*memalloc)(struct InputStream *cc,size_t size); void *(*memrealloc)(struct InputStream *cc,void *mem,size_t newsize); void (*memfree)(struct InputStream *cc,void *mem); #if defined(NO_MATROSKA2_GLOBAL) anynode *AnyNode; #endif } InputStream; typedef struct TrackInfo { int Number; uint8_t Type; uint64_t UID; uint8_t *CodecPrivate; size_t CodecPrivateSize; timecode_t DefaultDuration; char *CodecID; char *Name; char Language[4]; bool_t Enabled; bool_t Default; bool_t Lacing; bool_t DecodeAll; float TimecodeScale; int TrackOverlay; uint8_t MinCache; size_t MaxCache; size_t MaxBlockAdditionID; union { struct { uint8_t StereoMode; uint8_t DisplayUnit; uint8_t AspectRatioType; uint32_t PixelWidth; uint32_t PixelHeight; uint32_t DisplayWidth; uint32_t DisplayHeight; uint32_t CropL, CropT, CropR, CropB; unsigned int ColourSpace; float GammaValue; //struct { unsigned int Interlaced:1; //}; } Video; struct { float SamplingFreq; float OutputSamplingFreq; uint8_t Channels; uint8_t BitDepth; } Audio; } AV; } TrackInfo; typedef struct Attachment { filepos_t Position; filepos_t Length; uint64_t UID; char* Name; char* Description; char* MimeType; } Attachment; typedef struct ChapterDisplay { char *String; char Language[4]; char Country[4]; } ChapterDisplay; typedef struct Chapter { size_t nChildren; struct Chapter *Children; size_t nDisplay; struct ChapterDisplay *Display; timecode_t Start; timecode_t End; uint64_t UID; bool_t Enabled; bool_t Ordered; bool_t Default; bool_t Hidden; array aChildren; // Chapter array aDisplays; // ChapterDisplay } Chapter; typedef struct Target { uint64_t UID; uint8_t Type; uint8_t Level; }; // Tag Target types #define TARGET_TRACK 0 #define TARGET_CHAPTER 1 #define TARGET_ATTACHMENT 2 #define TARGET_EDITION 3 typedef struct SimpleTag { char *Name; char *Value; char Language[4]; bool_t Default; } SimpleTag; typedef struct Tag { size_t nSimpleTags; SimpleTag *SimpleTags; size_t nTargets; struct Target *Targets; array aTargets; // Target array aSimpleTags; // SimpleTag } Tag; typedef struct SegmentInfo { uint8_t UID[16]; uint8_t PrevUID[16]; uint8_t NextUID[16]; char *Filename; char *PrevFilename; char *NextFilename; char *Title; char *MuxingApp; char *WritingApp; timecode_t TimecodeScale; timecode_t Duration; datetime_t DateUTC; } SegmentInfo; typedef struct MatroskaFile MatroskaFile; #define MKVF_AVOID_SEEKS 1 /* use sequential reading only */ MatroskaFile *mkv_Open(InputStream *io, char *err_msg, size_t err_msgSize); void mkv_Close(MatroskaFile *File); SegmentInfo *mkv_GetFileInfo(MatroskaFile *File); size_t mkv_GetNumTracks(MatroskaFile *File); TrackInfo *mkv_GetTrackInfo(MatroskaFile *File, size_t n); void mkv_SetTrackMask(MatroskaFile *File, int Mask); #define FRAME_UNKNOWN_START 0x00000001 #define FRAME_UNKNOWN_END 0x00000002 #define FRAME_KF 0x00000004 int mkv_ReadFrame(MatroskaFile *File, int mask, unsigned int *track, ulonglong *StartTime, ulonglong *EndTime, ulonglong *FilePos, unsigned int *FrameSize, void** FrameRef, unsigned int *FrameFlags); #define MKVF_SEEK_TO_PREV_KEYFRAME 1 void mkv_Seek(MatroskaFile *File, timecode_t timecode, int flags); void mkv_GetTags(MatroskaFile *File, Tag **, unsigned *Count); void mkv_GetAttachments(MatroskaFile *File, Attachment **, unsigned *Count); void mkv_GetChapters(MatroskaFile *File, Chapter **, unsigned *Count); int mkv_TruncFloat(float f); #endif /* MATROSKA_PARSER_H */ bcmatroska2-5.3.101/libmatroska2/bzip2/000077500000000000000000000000001462133141200175065ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/bzip2/CHANGES000066400000000000000000000262311462133141200205050ustar00rootroot00000000000000 ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ 0.9.0 ~~~~~ First version. 0.9.0a ~~~~~~ Removed 'ranlib' from Makefile, since most modern Unix-es don't need it, or even know about it. 0.9.0b ~~~~~~ Fixed a problem with error reporting in bzip2.c. This does not effect the library in any way. Problem is: versions 0.9.0 and 0.9.0a (of the program proper) compress and decompress correctly, but give misleading error messages (internal panics) when an I/O error occurs, instead of reporting the problem correctly. This shouldn't give any data loss (as far as I can see), but is confusing. Made the inline declarations disappear for non-GCC compilers. 0.9.0c ~~~~~~ Fixed some problems in the library pertaining to some boundary cases. This makes the library behave more correctly in those situations. The fixes apply only to features (calls and parameters) not used by bzip2.c, so the non-fixedness of them in previous versions has no effect on reliability of bzip2.c. In bzlib.c: * made zero-length BZ_FLUSH work correctly in bzCompress(). * fixed bzWrite/bzRead to ignore zero-length requests. * fixed bzread to correctly handle read requests after EOF. * wrong parameter order in call to bzDecompressInit in bzBuffToBuffDecompress. Fixed. In compress.c: * changed setting of nGroups in sendMTFValues() so as to do a bit better on small files. This _does_ effect bzip2.c. 0.9.5a ~~~~~~ Major change: add a fallback sorting algorithm (blocksort.c) to give reasonable behaviour even for very repetitive inputs. Nuked --repetitive-best and --repetitive-fast since they are no longer useful. Minor changes: mostly a whole bunch of small changes/ bugfixes in the driver (bzip2.c). Changes pertaining to the user interface are: allow decompression of symlink'd files to stdout decompress/test files even without .bz2 extension give more accurate error messages for I/O errors when compressing/decompressing to stdout, don't catch control-C read flags from BZIP2 and BZIP environment variables decline to break hard links to a file unless forced with -f allow -c flag even with no filenames preserve file ownerships as far as possible make -s -1 give the expected block size (100k) add a flag -q --quiet to suppress nonessential warnings stop decoding flags after --, so files beginning in - can be handled resolved inconsistent naming: bzcat or bz2cat ? bzip2 --help now returns 0 Programming-level changes are: fixed syntax error in GET_LL4 for Borland C++ 5.02 let bzBuffToBuffDecompress return BZ_DATA_ERROR{_MAGIC} fix overshoot of mode-string end in bzopen_or_bzdopen wrapped bzlib.h in #ifdef __cplusplus ... extern "C" { ... } close file handles under all error conditions added minor mods so it compiles with DJGPP out of the box fixed Makefile so it doesn't give problems with BSD make fix uninitialised memory reads in dlltest.c 0.9.5b ~~~~~~ Open stdin/stdout in binary mode for DJGPP. 0.9.5c ~~~~~~ Changed BZ_N_OVERSHOOT to be ... + 2 instead of ... + 1. The + 1 version could cause the sorted order to be wrong in some extremely obscure cases. Also changed setting of quadrant in blocksort.c. 0.9.5d ~~~~~~ The only functional change is to make bzlibVersion() in the library return the correct string. This has no effect whatsoever on the functioning of the bzip2 program or library. Added a couple of casts so the library compiles without warnings at level 3 in MS Visual Studio 6.0. Included a Y2K statement in the file Y2K_INFO. All other changes are minor documentation changes. 1.0 ~~~ Several minor bugfixes and enhancements: * Large file support. The library uses 64-bit counters to count the volume of data passing through it. bzip2.c is now compiled with -D_FILE_OFFSET_BITS=64 to get large file support from the C library. -v correctly prints out file sizes greater than 4 gigabytes. All these changes have been made without assuming a 64-bit platform or a C compiler which supports 64-bit ints, so, except for the C library aspect, they are fully portable. * Decompression robustness. The library/program should be robust to any corruption of compressed data, detecting and handling _all_ corruption, instead of merely relying on the CRCs. What this means is that the program should never crash, given corrupted data, and the library should always return BZ_DATA_ERROR. * Fixed an obscure race-condition bug only ever observed on Solaris, in which, if you were very unlucky and issued control-C at exactly the wrong time, both input and output files would be deleted. * Don't run out of file handles on test/decompression when large numbers of files have invalid magic numbers. * Avoid library namespace pollution. Prefix all exported symbols with BZ2_. * Minor sorting enhancements from my DCC2000 paper. * Advance the version number to 1.0, so as to counteract the (false-in-this-case) impression some people have that programs with version numbers less than 1.0 are in some way, experimental, pre-release versions. * Create an initial Makefile-libbz2_so to build a shared library. Yes, I know I should really use libtool et al ... * Make the program exit with 2 instead of 0 when decompression fails due to a bad magic number (ie, an invalid bzip2 header). Also exit with 1 (as the manual claims :-) whenever a diagnostic message would have been printed AND the corresponding operation is aborted, for example bzip2: Output file xx already exists. When a diagnostic message is printed but the operation is not aborted, for example bzip2: Can't guess original name for wurble -- using wurble.out then the exit value 0 is returned, unless some other problem is also detected. I think it corresponds more closely to what the manual claims now. 1.0.1 ~~~~~ * Modified dlltest.c so it uses the new BZ2_ naming scheme. * Modified makefile-msc to fix minor build probs on Win2k. * Updated README.COMPILATION.PROBLEMS. There are no functionality changes or bug fixes relative to version 1.0.0. This is just a documentation update + a fix for minor Win32 build problems. For almost everyone, upgrading from 1.0.0 to 1.0.1 is utterly pointless. Don't bother. 1.0.2 ~~~~~ A bug fix release, addressing various minor issues which have appeared in the 18 or so months since 1.0.1 was released. Most of the fixes are to do with file-handling or documentation bugs. To the best of my knowledge, there have been no data-loss-causing bugs reported in the compression/decompression engine of 1.0.0 or 1.0.1. Note that this release does not improve the rather crude build system for Unix platforms. The general plan here is to autoconfiscate/ libtoolise 1.0.2 soon after release, and release the result as 1.1.0 or perhaps 1.2.0. That, however, is still just a plan at this point. Here are the changes in 1.0.2. Bug-reporters and/or patch-senders in parentheses. * Fix an infinite segfault loop in 1.0.1 when a directory is encountered in -f (force) mode. (Trond Eivind Glomsrod, Nicholas Nethercote, Volker Schmidt) * Avoid double fclose() of output file on certain I/O error paths. (Solar Designer) * Don't fail with internal error 1007 when fed a long stream (> 48MB) of byte 251. Also print useful message suggesting that 1007s may be caused by bad memory. (noticed by Juan Pedro Vallejo, fixed by me) * Fix uninitialised variable silly bug in demo prog dlltest.c. (Jorj Bauer) * Remove 512-MB limitation on recovered file size for bzip2recover on selected platforms which support 64-bit ints. At the moment all GCC supported platforms, and Win32. (me, Alson van der Meulen) * Hard-code header byte values, to give correct operation on platforms using EBCDIC as their native character set (IBM's OS/390). (Leland Lucius) * Copy file access times correctly. (Marty Leisner) * Add distclean and check targets to Makefile. (Michael Carmack) * Parameterise use of ar and ranlib in Makefile. Also add $(LDFLAGS). (Rich Ireland, Bo Thorsen) * Pass -p (create parent dirs as needed) to mkdir during make install. (Jeremy Fusco) * Dereference symlinks when copying file permissions in -f mode. (Volker Schmidt) * Majorly simplify implementation of uInt64_qrm10. (Bo Lindbergh) * Check the input file still exists before deleting the output one, when aborting in cleanUpAndFail(). (Joerg Prante, Robert Linden, Matthias Krings) Also a bunch of patches courtesy of Philippe Troin, the Debian maintainer of bzip2: * Wrapper scripts (with manpages): bzdiff, bzgrep, bzmore. * Spelling changes and minor enhancements in bzip2.1. * Avoid race condition between creating the output file and setting its interim permissions safely, by using fopen_output_safely(). No changes to bzip2recover since there is no issue with file permissions there. * do not print senseless report with -v when compressing an empty file. * bzcat -f works on non-bzip2 files. * do not try to escape shell meta-characters on unix (the shell takes care of these). * added --fast and --best aliases for -1 -9 for gzip compatibility. 1.0.3 (15 Feb 05) ~~~~~~~~~~~~~~~~~ Fixes some minor bugs since the last version, 1.0.2. * Further robustification against corrupted compressed data. There are currently no known bitstreams which can cause the decompressor to crash, loop or access memory which does not belong to it. If you are using bzip2 or the library to decompress bitstreams from untrusted sources, an upgrade to 1.0.3 is recommended. This fixes CAN-2005-1260. * The documentation has been converted to XML, from which html and pdf can be derived. * Various minor bugs in the documentation have been fixed. * Fixes for various compilation warnings with newer versions of gcc, and on 64-bit platforms. * The BZ_NO_STDIO cpp symbol was not properly observed in 1.0.2. This has been fixed. 1.0.4 (20 Dec 06) ~~~~~~~~~~~~~~~~~ Fixes some minor bugs since the last version, 1.0.3. * Fix file permissions race problem (CAN-2005-0953). * Avoid possible segfault in BZ2_bzclose. From Coverity's NetBSD scan. * 'const'/prototype cleanups in the C code. * Change default install location to /usr/local, and handle multiple 'make install's without error. * Sanitise file names more carefully in bzgrep. Fixes CAN-2005-0758 to the extent that applies to bzgrep. * Use 'mktemp' rather than 'tempfile' in bzdiff. * Tighten up a couple of assertions in blocksort.c following automated analysis. * Fix minor doc/comment bugs. 1.0.5 (10 Dec 07) ~~~~~~~~~~~~~~~~~ Security fix only. Fixes CERT-FI 20469 as it applies to bzip2. 1.0.6 (6 Sept 10) ~~~~~~~~~~~~~~~~~ * Security fix for CVE-2010-0405. This was reported by Mikolaj Izdebski. * Make the documentation build on Ubuntu 10.04 bcmatroska2-5.3.101/libmatroska2/bzip2/LICENSE000066400000000000000000000035551462133141200205230ustar00rootroot00000000000000 -------------------------------------------------------------------------- This program, "bzip2", the associated library "libbzip2", and all documentation, are copyright (C) 1996-2010 Julian R Seward. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Julian Seward, jseward@bzip.org bzip2/libbzip2 version 1.0.6 of 6 September 2010 -------------------------------------------------------------------------- bcmatroska2-5.3.101/libmatroska2/bzip2/Makefile000066400000000000000000000142361462133141200211540ustar00rootroot00000000000000# ------------------------------------------------------------------ # This file is part of bzip2/libbzip2, a program and library for # lossless, block-sorting data compression. # # bzip2/libbzip2 version 1.0.6 of 6 September 2010 # Copyright (C) 1996-2010 Julian Seward # # Please read the WARNING, DISCLAIMER and PATENTS sections in the # README file. # # This program is released under the terms of the license contained # in the file LICENSE. # ------------------------------------------------------------------ SHELL=/bin/sh # To assist in cross-compiling CC=gcc AR=ar RANLIB=ranlib LDFLAGS= BIGFILES=-D_FILE_OFFSET_BITS=64 CFLAGS=-Wall -Winline -O2 -g $(BIGFILES) # Where you want it installed when you do 'make install' PREFIX=/usr/local OBJS= blocksort.o \ huffman.o \ crctable.o \ randtable.o \ compress.o \ decompress.o \ bzlib.o all: libbz2.a bzip2 bzip2recover test bzip2: libbz2.a bzip2.o $(CC) $(CFLAGS) $(LDFLAGS) -o bzip2 bzip2.o -L. -lbz2 bzip2recover: bzip2recover.o $(CC) $(CFLAGS) $(LDFLAGS) -o bzip2recover bzip2recover.o libbz2.a: $(OBJS) rm -f libbz2.a $(AR) cq libbz2.a $(OBJS) @if ( test -f $(RANLIB) -o -f /usr/bin/ranlib -o \ -f /bin/ranlib -o -f /usr/ccs/bin/ranlib ) ; then \ echo $(RANLIB) libbz2.a ; \ $(RANLIB) libbz2.a ; \ fi check: test test: bzip2 @cat words1 ./bzip2 -1 < sample1.ref > sample1.rb2 ./bzip2 -2 < sample2.ref > sample2.rb2 ./bzip2 -3 < sample3.ref > sample3.rb2 ./bzip2 -d < sample1.bz2 > sample1.tst ./bzip2 -d < sample2.bz2 > sample2.tst ./bzip2 -ds < sample3.bz2 > sample3.tst cmp sample1.bz2 sample1.rb2 cmp sample2.bz2 sample2.rb2 cmp sample3.bz2 sample3.rb2 cmp sample1.tst sample1.ref cmp sample2.tst sample2.ref cmp sample3.tst sample3.ref @cat words3 install: bzip2 bzip2recover if ( test ! -d $(PREFIX)/bin ) ; then mkdir -p $(PREFIX)/bin ; fi if ( test ! -d $(PREFIX)/lib ) ; then mkdir -p $(PREFIX)/lib ; fi if ( test ! -d $(PREFIX)/man ) ; then mkdir -p $(PREFIX)/man ; fi if ( test ! -d $(PREFIX)/man/man1 ) ; then mkdir -p $(PREFIX)/man/man1 ; fi if ( test ! -d $(PREFIX)/include ) ; then mkdir -p $(PREFIX)/include ; fi cp -f bzip2 $(PREFIX)/bin/bzip2 cp -f bzip2 $(PREFIX)/bin/bunzip2 cp -f bzip2 $(PREFIX)/bin/bzcat cp -f bzip2recover $(PREFIX)/bin/bzip2recover chmod a+x $(PREFIX)/bin/bzip2 chmod a+x $(PREFIX)/bin/bunzip2 chmod a+x $(PREFIX)/bin/bzcat chmod a+x $(PREFIX)/bin/bzip2recover cp -f bzip2.1 $(PREFIX)/man/man1 chmod a+r $(PREFIX)/man/man1/bzip2.1 cp -f bzlib.h $(PREFIX)/include chmod a+r $(PREFIX)/include/bzlib.h cp -f libbz2.a $(PREFIX)/lib chmod a+r $(PREFIX)/lib/libbz2.a cp -f bzgrep $(PREFIX)/bin/bzgrep ln -s -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzegrep ln -s -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzfgrep chmod a+x $(PREFIX)/bin/bzgrep cp -f bzmore $(PREFIX)/bin/bzmore ln -s -f $(PREFIX)/bin/bzmore $(PREFIX)/bin/bzless chmod a+x $(PREFIX)/bin/bzmore cp -f bzdiff $(PREFIX)/bin/bzdiff ln -s -f $(PREFIX)/bin/bzdiff $(PREFIX)/bin/bzcmp chmod a+x $(PREFIX)/bin/bzdiff cp -f bzgrep.1 bzmore.1 bzdiff.1 $(PREFIX)/man/man1 chmod a+r $(PREFIX)/man/man1/bzgrep.1 chmod a+r $(PREFIX)/man/man1/bzmore.1 chmod a+r $(PREFIX)/man/man1/bzdiff.1 echo ".so man1/bzgrep.1" > $(PREFIX)/man/man1/bzegrep.1 echo ".so man1/bzgrep.1" > $(PREFIX)/man/man1/bzfgrep.1 echo ".so man1/bzmore.1" > $(PREFIX)/man/man1/bzless.1 echo ".so man1/bzdiff.1" > $(PREFIX)/man/man1/bzcmp.1 clean: rm -f *.o libbz2.a bzip2 bzip2recover \ sample1.rb2 sample2.rb2 sample3.rb2 \ sample1.tst sample2.tst sample3.tst blocksort.o: blocksort.c @cat words0 $(CC) $(CFLAGS) -c blocksort.c huffman.o: huffman.c $(CC) $(CFLAGS) -c huffman.c crctable.o: crctable.c $(CC) $(CFLAGS) -c crctable.c randtable.o: randtable.c $(CC) $(CFLAGS) -c randtable.c compress.o: compress.c $(CC) $(CFLAGS) -c compress.c decompress.o: decompress.c $(CC) $(CFLAGS) -c decompress.c bzlib.o: bzlib.c $(CC) $(CFLAGS) -c bzlib.c bzip2.o: bzip2.c $(CC) $(CFLAGS) -c bzip2.c bzip2recover.o: bzip2recover.c $(CC) $(CFLAGS) -c bzip2recover.c distclean: clean rm -f manual.ps manual.html manual.pdf DISTNAME=bzip2-1.0.6 dist: check manual rm -f $(DISTNAME) ln -s -f . $(DISTNAME) tar cvf $(DISTNAME).tar \ $(DISTNAME)/blocksort.c \ $(DISTNAME)/huffman.c \ $(DISTNAME)/crctable.c \ $(DISTNAME)/randtable.c \ $(DISTNAME)/compress.c \ $(DISTNAME)/decompress.c \ $(DISTNAME)/bzlib.c \ $(DISTNAME)/bzip2.c \ $(DISTNAME)/bzip2recover.c \ $(DISTNAME)/bzlib.h \ $(DISTNAME)/bzlib_private.h \ $(DISTNAME)/Makefile \ $(DISTNAME)/LICENSE \ $(DISTNAME)/bzip2.1 \ $(DISTNAME)/bzip2.1.preformatted \ $(DISTNAME)/bzip2.txt \ $(DISTNAME)/words0 \ $(DISTNAME)/words1 \ $(DISTNAME)/words2 \ $(DISTNAME)/words3 \ $(DISTNAME)/sample1.ref \ $(DISTNAME)/sample2.ref \ $(DISTNAME)/sample3.ref \ $(DISTNAME)/sample1.bz2 \ $(DISTNAME)/sample2.bz2 \ $(DISTNAME)/sample3.bz2 \ $(DISTNAME)/dlltest.c \ $(DISTNAME)/manual.html \ $(DISTNAME)/manual.pdf \ $(DISTNAME)/manual.ps \ $(DISTNAME)/README \ $(DISTNAME)/README.COMPILATION.PROBLEMS \ $(DISTNAME)/README.XML.STUFF \ $(DISTNAME)/CHANGES \ $(DISTNAME)/libbz2.def \ $(DISTNAME)/libbz2.dsp \ $(DISTNAME)/dlltest.dsp \ $(DISTNAME)/makefile.msc \ $(DISTNAME)/unzcrash.c \ $(DISTNAME)/spewG.c \ $(DISTNAME)/mk251.c \ $(DISTNAME)/bzdiff \ $(DISTNAME)/bzdiff.1 \ $(DISTNAME)/bzmore \ $(DISTNAME)/bzmore.1 \ $(DISTNAME)/bzgrep \ $(DISTNAME)/bzgrep.1 \ $(DISTNAME)/Makefile-libbz2_so \ $(DISTNAME)/bz-common.xsl \ $(DISTNAME)/bz-fo.xsl \ $(DISTNAME)/bz-html.xsl \ $(DISTNAME)/bzip.css \ $(DISTNAME)/entities.xml \ $(DISTNAME)/manual.xml \ $(DISTNAME)/format.pl \ $(DISTNAME)/xmlproc.sh gzip -v $(DISTNAME).tar # For rebuilding the manual from sources on my SuSE 9.1 box MANUAL_SRCS= bz-common.xsl bz-fo.xsl bz-html.xsl bzip.css \ entities.xml manual.xml manual: manual.html manual.ps manual.pdf manual.ps: $(MANUAL_SRCS) ./xmlproc.sh -ps manual.xml manual.pdf: $(MANUAL_SRCS) ./xmlproc.sh -pdf manual.xml manual.html: $(MANUAL_SRCS) ./xmlproc.sh -html manual.xml bcmatroska2-5.3.101/libmatroska2/bzip2/README000066400000000000000000000166361462133141200204020ustar00rootroot00000000000000 This is the README for bzip2/libzip2. This version is fully compatible with the previous public releases. ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in this file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ Complete documentation is available in Postscript form (manual.ps), PDF (manual.pdf) or html (manual.html). A plain-text version of the manual page is available as bzip2.txt. HOW TO BUILD -- UNIX Type 'make'. This builds the library libbz2.a and then the programs bzip2 and bzip2recover. Six self-tests are run. If the self-tests complete ok, carry on to installation: To install in /usr/local/bin, /usr/local/lib, /usr/local/man and /usr/local/include, type make install To install somewhere else, eg, /xxx/yyy/{bin,lib,man,include}, type make install PREFIX=/xxx/yyy If you are (justifiably) paranoid and want to see what 'make install' is going to do, you can first do make -n install or make -n install PREFIX=/xxx/yyy respectively. The -n instructs make to show the commands it would execute, but not actually execute them. HOW TO BUILD -- UNIX, shared library libbz2.so. Do 'make -f Makefile-libbz2_so'. This Makefile seems to work for Linux-ELF (RedHat 7.2 on an x86 box), with gcc. I make no claims that it works for any other platform, though I suspect it probably will work for most platforms employing both ELF and gcc. bzip2-shared, a client of the shared library, is also built, but not self-tested. So I suggest you also build using the normal Makefile, since that conducts a self-test. A second reason to prefer the version statically linked to the library is that, on x86 platforms, building shared objects makes a valuable register (%ebx) unavailable to gcc, resulting in a slowdown of 10%-20%, at least for bzip2. Important note for people upgrading .so's from 0.9.0/0.9.5 to version 1.0.X. All the functions in the library have been renamed, from (eg) bzCompress to BZ2_bzCompress, to avoid namespace pollution. Unfortunately this means that the libbz2.so created by Makefile-libbz2_so will not work with any program which used an older version of the library. I do encourage library clients to make the effort to upgrade to use version 1.0, since it is both faster and more robust than previous versions. HOW TO BUILD -- Windows 95, NT, DOS, Mac, etc. It's difficult for me to support compilation on all these platforms. My approach is to collect binaries for these platforms, and put them on the master web site (http://www.bzip.org). Look there. However (FWIW), bzip2-1.0.X is very standard ANSI C and should compile unmodified with MS Visual C. If you have difficulties building, you might want to read README.COMPILATION.PROBLEMS. At least using MS Visual C++ 6, you can build from the unmodified sources by issuing, in a command shell: nmake -f makefile.msc (you may need to first run the MSVC-provided script VCVARS32.BAT so as to set up paths to the MSVC tools correctly). VALIDATION Correct operation, in the sense that a compressed file can always be decompressed to reproduce the original, is obviously of paramount importance. To validate bzip2, I used a modified version of Mark Nelson's churn program. Churn is an automated test driver which recursively traverses a directory structure, using bzip2 to compress and then decompress each file it encounters, and checking that the decompressed data is the same as the original. Please read and be aware of the following: WARNING: This program and library (attempts to) compress data by performing several non-trivial transformations on it. Unless you are 100% familiar with *all* the algorithms contained herein, and with the consequences of modifying them, you should NOT meddle with the compression or decompression machinery. Incorrect changes can and very likely *will* lead to disastrous loss of data. DISCLAIMER: I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE USE OF THIS PROGRAM/LIBRARY, HOWSOEVER CAUSED. Every compression of a file implies an assumption that the compressed file can be decompressed to reproduce the original. Great efforts in design, coding and testing have been made to ensure that this program works correctly. However, the complexity of the algorithms, and, in particular, the presence of various special cases in the code which occur with very low but non-zero probability make it impossible to rule out the possibility of bugs remaining in the program. DO NOT COMPRESS ANY DATA WITH THIS PROGRAM UNLESS YOU ARE PREPARED TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL NOT BE RECOVERABLE. That is not to say this program is inherently unreliable. Indeed, I very much hope the opposite is true. bzip2/libbzip2 has been carefully constructed and extensively tested. PATENTS: To the best of my knowledge, bzip2/libbzip2 does not use any patented algorithms. However, I do not have the resources to carry out a patent search. Therefore I cannot give any guarantee of the above statement. WHAT'S NEW IN 0.9.0 (as compared to 0.1pl2) ? * Approx 10% faster compression, 30% faster decompression * -t (test mode) is a lot quicker * Can decompress concatenated compressed files * Programming interface, so programs can directly read/write .bz2 files * Less restrictive (BSD-style) licensing * Flag handling more compatible with GNU gzip * Much more documentation, i.e., a proper user manual * Hopefully, improved portability (at least of the library) WHAT'S NEW IN 0.9.5 ? * Compression speed is much less sensitive to the input data than in previous versions. Specifically, the very slow performance caused by repetitive data is fixed. * Many small improvements in file and flag handling. * A Y2K statement. WHAT'S NEW IN 1.0.0 ? See the CHANGES file. WHAT'S NEW IN 1.0.2 ? See the CHANGES file. WHAT'S NEW IN 1.0.3 ? See the CHANGES file. WHAT'S NEW IN 1.0.4 ? See the CHANGES file. WHAT'S NEW IN 1.0.5 ? See the CHANGES file. WHAT'S NEW IN 1.0.6 ? See the CHANGES file. I hope you find bzip2 useful. Feel free to contact me at jseward@bzip.org if you have any suggestions or queries. Many people mailed me with comments, suggestions and patches after the releases of bzip-0.15, bzip-0.21, and bzip2 versions 0.1pl2, 0.9.0, 0.9.5, 1.0.0, 1.0.1, 1.0.2 and 1.0.3, and the changes in bzip2 are largely a result of this feedback. I thank you for your comments. bzip2's "home" is http://www.bzip.org/ Julian Seward jseward@bzip.org Cambridge, UK. 18 July 1996 (version 0.15) 25 August 1996 (version 0.21) 7 August 1997 (bzip2, version 0.1) 29 August 1997 (bzip2, version 0.1pl2) 23 August 1998 (bzip2, version 0.9.0) 8 June 1999 (bzip2, version 0.9.5) 4 Sept 1999 (bzip2, version 0.9.5d) 5 May 2000 (bzip2, version 1.0pre8) 30 December 2001 (bzip2, version 1.0.2pre1) 15 February 2005 (bzip2, version 1.0.3) 20 December 2006 (bzip2, version 1.0.4) 10 December 2007 (bzip2, version 1.0.5) 6 Sept 2010 (bzip2, version 1.0.6) bcmatroska2-5.3.101/libmatroska2/bzip2/blocksort.c000066400000000000000000000737461462133141200216750ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Block sorting machinery ---*/ /*--- blocksort.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------*/ /*--- Fallback O(N log(N)^2) sorting ---*/ /*--- algorithm, for repetitive blocks ---*/ /*---------------------------------------------*/ /*---------------------------------------------*/ static __inline__ void fallbackSimpleSort ( UInt32* fmap, UInt32* eclass, Int32 lo, Int32 hi ) { Int32 i, j, tmp; UInt32 ec_tmp; if (lo == hi) return; if (hi - lo > 3) { for ( i = hi-4; i >= lo; i-- ) { tmp = fmap[i]; ec_tmp = eclass[tmp]; for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 ) fmap[j-4] = fmap[j]; fmap[j-4] = tmp; } } for ( i = hi-1; i >= lo; i-- ) { tmp = fmap[i]; ec_tmp = eclass[tmp]; for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ ) fmap[j-1] = fmap[j]; fmap[j-1] = tmp; } } /*---------------------------------------------*/ #define fswap(zz1, zz2) \ { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } #define fvswap(zzp1, zzp2, zzn) \ { \ Int32 yyp1 = (zzp1); \ Int32 yyp2 = (zzp2); \ Int32 yyn = (zzn); \ while (yyn > 0) { \ fswap(fmap[yyp1], fmap[yyp2]); \ yyp1++; yyp2++; yyn--; \ } \ } #define fmin(a,b) ((a) < (b)) ? (a) : (b) #define fpush(lz,hz) { stackLo[sp] = lz; \ stackHi[sp] = hz; \ sp++; } #define fpop(lz,hz) { sp--; \ lz = stackLo[sp]; \ hz = stackHi[sp]; } #define FALLBACK_QSORT_SMALL_THRESH 10 #define FALLBACK_QSORT_STACK_SIZE 100 static void fallbackQSort3 ( UInt32* fmap, UInt32* eclass, Int32 loSt, Int32 hiSt ) { Int32 unLo, unHi, ltLo, gtHi, n, m; Int32 sp, lo, hi; UInt32 med, r, r3; Int32 stackLo[FALLBACK_QSORT_STACK_SIZE]; Int32 stackHi[FALLBACK_QSORT_STACK_SIZE]; r = 0; sp = 0; fpush ( loSt, hiSt ); while (sp > 0) { AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 ); fpop ( lo, hi ); if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) { fallbackSimpleSort ( fmap, eclass, lo, hi ); continue; } /* Random partitioning. Median of 3 sometimes fails to avoid bad cases. Median of 9 seems to help but looks rather expensive. This too seems to work but is cheaper. Guidance for the magic constants 7621 and 32768 is taken from Sedgewick's algorithms book, chapter 35. */ r = ((r * 7621) + 1) % 32768; r3 = r % 3; if (r3 == 0) med = eclass[fmap[lo]]; else if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else med = eclass[fmap[hi]]; unLo = ltLo = lo; unHi = gtHi = hi; while (1) { while (1) { if (unLo > unHi) break; n = (Int32)eclass[fmap[unLo]] - (Int32)med; if (n == 0) { fswap(fmap[unLo], fmap[ltLo]); ltLo++; unLo++; continue; }; if (n > 0) break; unLo++; } while (1) { if (unLo > unHi) break; n = (Int32)eclass[fmap[unHi]] - (Int32)med; if (n == 0) { fswap(fmap[unHi], fmap[gtHi]); gtHi--; unHi--; continue; }; if (n < 0) break; unHi--; } if (unLo > unHi) break; fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--; } AssertD ( unHi == unLo-1, "fallbackQSort3(2)" ); if (gtHi < ltLo) continue; n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n); m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m); n = lo + unLo - ltLo - 1; m = hi - (gtHi - unHi) + 1; if (n - lo > hi - m) { fpush ( lo, n ); fpush ( m, hi ); } else { fpush ( m, hi ); fpush ( lo, n ); } } } #undef fmin #undef fpush #undef fpop #undef fswap #undef fvswap #undef FALLBACK_QSORT_SMALL_THRESH #undef FALLBACK_QSORT_STACK_SIZE /*---------------------------------------------*/ /* Pre: nblock > 0 eclass exists for [0 .. nblock-1] ((UChar*)eclass) [0 .. nblock-1] holds block ptr exists for [0 .. nblock-1] Post: ((UChar*)eclass) [0 .. nblock-1] holds block All other areas of eclass destroyed fmap [0 .. nblock-1] holds sorted order bhtab [ 0 .. 2+(nblock/32) ] destroyed */ #define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31)) #define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31)) #define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31))) #define WORD_BH(zz) bhtab[(zz) >> 5] #define UNALIGNED_BH(zz) ((zz) & 0x01f) static void fallbackSort ( UInt32* fmap, UInt32* eclass, UInt32* bhtab, Int32 nblock, Int32 verb ) { Int32 ftab[257]; Int32 ftabCopy[256]; Int32 H, i, j, k, l, r, cc, cc1; Int32 nNotDone; Int32 nBhtab; UChar* eclass8 = (UChar*)eclass; /*-- Initial 1-char radix sort to generate initial fmap and initial BH bits. --*/ if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); for (i = 0; i < 257; i++) ftab[i] = 0; for (i = 0; i < nblock; i++) ftab[eclass8[i]]++; for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i]; for (i = 1; i < 257; i++) ftab[i] += ftab[i-1]; for (i = 0; i < nblock; i++) { j = eclass8[i]; k = ftab[j] - 1; ftab[j] = k; fmap[k] = i; } nBhtab = 2 + (nblock / 32); for (i = 0; i < nBhtab; i++) bhtab[i] = 0; for (i = 0; i < 256; i++) SET_BH(ftab[i]); /*-- Inductively refine the buckets. Kind-of an "exponential radix sort" (!), inspired by the Manber-Myers suffix array construction algorithm. --*/ /*-- set sentinel bits for block-end detection --*/ for (i = 0; i < 32; i++) { SET_BH(nblock + 2*i); CLEAR_BH(nblock + 2*i + 1); } /*-- the log(N) loop --*/ H = 1; while (1) { if (verb >= 4) VPrintf1 ( " depth %6d has ", H ); j = 0; for (i = 0; i < nblock; i++) { if (ISSET_BH(i)) j = i; k = fmap[i] - H; if (k < 0) k += nblock; eclass[k] = j; } nNotDone = 0; r = -1; while (1) { /*-- find the next non-singleton bucket --*/ k = r + 1; while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; if (ISSET_BH(k)) { while (WORD_BH(k) == 0xffffffff) k += 32; while (ISSET_BH(k)) k++; } l = k - 1; if (l >= nblock) break; while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++; if (!ISSET_BH(k)) { while (WORD_BH(k) == 0x00000000) k += 32; while (!ISSET_BH(k)) k++; } r = k - 1; if (r >= nblock) break; /*-- now [l, r] bracket current bucket --*/ if (r > l) { nNotDone += (r - l + 1); fallbackQSort3 ( fmap, eclass, l, r ); /*-- scan bucket and generate header bits-- */ cc = -1; for (i = l; i <= r; i++) { cc1 = eclass[fmap[i]]; if (cc != cc1) { SET_BH(i); cc = cc1; }; } } } if (verb >= 4) VPrintf1 ( "%6d unresolved strings\n", nNotDone ); H *= 2; if (H > nblock || nNotDone == 0) break; } /*-- Reconstruct the original block in eclass8 [0 .. nblock-1], since the previous phase destroyed it. --*/ if (verb >= 4) VPrintf0 ( " reconstructing block ...\n" ); j = 0; for (i = 0; i < nblock; i++) { while (ftabCopy[j] == 0) j++; ftabCopy[j]--; eclass8[fmap[i]] = (UChar)j; } AssertH ( j < 256, 1005 ); } #undef SET_BH #undef CLEAR_BH #undef ISSET_BH #undef WORD_BH #undef UNALIGNED_BH /*---------------------------------------------*/ /*--- The main, O(N^2 log(N)) sorting ---*/ /*--- algorithm. Faster for "normal" ---*/ /*--- non-repetitive blocks. ---*/ /*---------------------------------------------*/ /*---------------------------------------------*/ static __inline__ Bool mainGtU ( UInt32 i1, UInt32 i2, UChar* block, UInt16* quadrant, UInt32 nblock, Int32* budget ) { Int32 k; UChar c1, c2; UInt16 s1, s2; AssertD ( i1 != i2, "mainGtU" ); /* 1 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 2 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 3 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 4 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 5 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 6 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 7 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 8 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 9 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 10 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 11 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; /* 12 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); i1++; i2++; k = nblock + 8; do { /* 1 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 2 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 3 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 4 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 5 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 6 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 7 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; /* 8 */ c1 = block[i1]; c2 = block[i2]; if (c1 != c2) return (c1 > c2); s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) return (s1 > s2); i1++; i2++; if (i1 >= nblock) i1 -= nblock; if (i2 >= nblock) i2 -= nblock; k -= 8; (*budget)--; } while (k >= 0); return False; } /*---------------------------------------------*/ /*-- Knuth's increments seem to work better than Incerpi-Sedgewick here. Possibly because the number of elems to sort is usually small, typically <= 20. --*/ static Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, 2391484 }; static void mainSimpleSort ( UInt32* ptr, UChar* block, UInt16* quadrant, Int32 nblock, Int32 lo, Int32 hi, Int32 d, Int32* budget ) { Int32 i, j, h, bigN, hp; UInt32 v; bigN = hi - lo + 1; if (bigN < 2) return; hp = 0; while (incs[hp] < bigN) hp++; hp--; for (; hp >= 0; hp--) { h = incs[hp]; i = lo + h; while (True) { /*-- copy 1 --*/ if (i > hi) break; v = ptr[i]; j = i; while ( mainGtU ( ptr[j-h]+d, v+d, block, quadrant, nblock, budget ) ) { ptr[j] = ptr[j-h]; j = j - h; if (j <= (lo + h - 1)) break; } ptr[j] = v; i++; /*-- copy 2 --*/ if (i > hi) break; v = ptr[i]; j = i; while ( mainGtU ( ptr[j-h]+d, v+d, block, quadrant, nblock, budget ) ) { ptr[j] = ptr[j-h]; j = j - h; if (j <= (lo + h - 1)) break; } ptr[j] = v; i++; /*-- copy 3 --*/ if (i > hi) break; v = ptr[i]; j = i; while ( mainGtU ( ptr[j-h]+d, v+d, block, quadrant, nblock, budget ) ) { ptr[j] = ptr[j-h]; j = j - h; if (j <= (lo + h - 1)) break; } ptr[j] = v; i++; if (*budget < 0) return; } } } /*---------------------------------------------*/ /*-- The following is an implementation of an elegant 3-way quicksort for strings, described in a paper "Fast Algorithms for Sorting and Searching Strings", by Robert Sedgewick and Jon L. Bentley. --*/ #define mswap(zz1, zz2) \ { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } #define mvswap(zzp1, zzp2, zzn) \ { \ Int32 yyp1 = (zzp1); \ Int32 yyp2 = (zzp2); \ Int32 yyn = (zzn); \ while (yyn > 0) { \ mswap(ptr[yyp1], ptr[yyp2]); \ yyp1++; yyp2++; yyn--; \ } \ } static __inline__ UChar mmed3 ( UChar a, UChar b, UChar c ) { UChar t; if (a > b) { t = a; a = b; b = t; }; if (b > c) { b = c; if (a > b) b = a; } return b; } #define mmin(a,b) ((a) < (b)) ? (a) : (b) #define mpush(lz,hz,dz) { stackLo[sp] = lz; \ stackHi[sp] = hz; \ stackD [sp] = dz; \ sp++; } #define mpop(lz,hz,dz) { sp--; \ lz = stackLo[sp]; \ hz = stackHi[sp]; \ dz = stackD [sp]; } #define mnextsize(az) (nextHi[az]-nextLo[az]) #define mnextswap(az,bz) \ { Int32 tz; \ tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \ tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \ tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; } #define MAIN_QSORT_SMALL_THRESH 20 #define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT) #define MAIN_QSORT_STACK_SIZE 100 static void mainQSort3 ( UInt32* ptr, UChar* block, UInt16* quadrant, Int32 nblock, Int32 loSt, Int32 hiSt, Int32 dSt, Int32* budget ) { Int32 unLo, unHi, ltLo, gtHi, n, m, med; Int32 sp, lo, hi, d; Int32 stackLo[MAIN_QSORT_STACK_SIZE]; Int32 stackHi[MAIN_QSORT_STACK_SIZE]; Int32 stackD [MAIN_QSORT_STACK_SIZE]; Int32 nextLo[3]; Int32 nextHi[3]; Int32 nextD [3]; sp = 0; mpush ( loSt, hiSt, dSt ); while (sp > 0) { AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 ); mpop ( lo, hi, d ); if (hi - lo < MAIN_QSORT_SMALL_THRESH || d > MAIN_QSORT_DEPTH_THRESH) { mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); if (*budget < 0) return; continue; } med = (Int32) mmed3 ( block[ptr[ lo ]+d], block[ptr[ hi ]+d], block[ptr[ (lo+hi)>>1 ]+d] ); unLo = ltLo = lo; unHi = gtHi = hi; while (True) { while (True) { if (unLo > unHi) break; n = ((Int32)block[ptr[unLo]+d]) - med; if (n == 0) { mswap(ptr[unLo], ptr[ltLo]); ltLo++; unLo++; continue; }; if (n > 0) break; unLo++; } while (True) { if (unLo > unHi) break; n = ((Int32)block[ptr[unHi]+d]) - med; if (n == 0) { mswap(ptr[unHi], ptr[gtHi]); gtHi--; unHi--; continue; }; if (n < 0) break; unHi--; } if (unLo > unHi) break; mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--; } AssertD ( unHi == unLo-1, "mainQSort3(2)" ); if (gtHi < ltLo) { mpush(lo, hi, d+1 ); continue; } n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n); m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m); n = lo + unLo - ltLo - 1; m = hi - (gtHi - unHi) + 1; nextLo[0] = lo; nextHi[0] = n; nextD[0] = d; nextLo[1] = m; nextHi[1] = hi; nextD[1] = d; nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1; if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); if (mnextsize(1) < mnextsize(2)) mnextswap(1,2); if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" ); AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" ); mpush (nextLo[0], nextHi[0], nextD[0]); mpush (nextLo[1], nextHi[1], nextD[1]); mpush (nextLo[2], nextHi[2], nextD[2]); } } #undef mswap #undef mvswap #undef mpush #undef mpop #undef mmin #undef mnextsize #undef mnextswap #undef MAIN_QSORT_SMALL_THRESH #undef MAIN_QSORT_DEPTH_THRESH #undef MAIN_QSORT_STACK_SIZE /*---------------------------------------------*/ /* Pre: nblock > N_OVERSHOOT block32 exists for [0 .. nblock-1 +N_OVERSHOOT] ((UChar*)block32) [0 .. nblock-1] holds block ptr exists for [0 .. nblock-1] Post: ((UChar*)block32) [0 .. nblock-1] holds block All other areas of block32 destroyed ftab [0 .. 65536 ] destroyed ptr [0 .. nblock-1] holds sorted order if (*budget < 0), sorting was abandoned */ #define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8]) #define SETMASK (1 << 21) #define CLEARMASK (~(SETMASK)) static void mainSort ( UInt32* ptr, UChar* block, UInt16* quadrant, UInt32* ftab, Int32 nblock, Int32 verb, Int32* budget ) { Int32 i, j, k, ss, sb; Int32 runningOrder[256]; Bool bigDone[256]; Int32 copyStart[256]; Int32 copyEnd [256]; UChar c1; Int32 numQSorted; UInt16 s; if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" ); /*-- set up the 2-byte frequency table --*/ for (i = 65536; i >= 0; i--) ftab[i] = 0; j = block[0] << 8; i = nblock-1; for (; i >= 3; i -= 4) { quadrant[i] = 0; j = (j >> 8) | ( ((UInt16)block[i]) << 8); ftab[j]++; quadrant[i-1] = 0; j = (j >> 8) | ( ((UInt16)block[i-1]) << 8); ftab[j]++; quadrant[i-2] = 0; j = (j >> 8) | ( ((UInt16)block[i-2]) << 8); ftab[j]++; quadrant[i-3] = 0; j = (j >> 8) | ( ((UInt16)block[i-3]) << 8); ftab[j]++; } for (; i >= 0; i--) { quadrant[i] = 0; j = (j >> 8) | ( ((UInt16)block[i]) << 8); ftab[j]++; } /*-- (emphasises close relationship of block & quadrant) --*/ for (i = 0; i < BZ_N_OVERSHOOT; i++) { block [nblock+i] = block[i]; quadrant[nblock+i] = 0; } if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); /*-- Complete the initial radix sort --*/ for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; s = block[0] << 8; i = nblock-1; for (; i >= 3; i -= 4) { s = (s >> 8) | (block[i] << 8); j = ftab[s] -1; ftab[s] = j; ptr[j] = i; s = (s >> 8) | (block[i-1] << 8); j = ftab[s] -1; ftab[s] = j; ptr[j] = i-1; s = (s >> 8) | (block[i-2] << 8); j = ftab[s] -1; ftab[s] = j; ptr[j] = i-2; s = (s >> 8) | (block[i-3] << 8); j = ftab[s] -1; ftab[s] = j; ptr[j] = i-3; } for (; i >= 0; i--) { s = (s >> 8) | (block[i] << 8); j = ftab[s] -1; ftab[s] = j; ptr[j] = i; } /*-- Now ftab contains the first loc of every small bucket. Calculate the running order, from smallest to largest big bucket. --*/ for (i = 0; i <= 255; i++) { bigDone [i] = False; runningOrder[i] = i; } { Int32 vv; Int32 h = 1; do h = 3 * h + 1; while (h <= 256); do { h = h / 3; for (i = h; i <= 255; i++) { vv = runningOrder[i]; j = i; while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) { runningOrder[j] = runningOrder[j-h]; j = j - h; if (j <= (h - 1)) goto zero; } zero: runningOrder[j] = vv; } } while (h != 1); } /*-- The main sorting loop. --*/ numQSorted = 0; for (i = 0; i <= 255; i++) { /*-- Process big buckets, starting with the least full. Basically this is a 3-step process in which we call mainQSort3 to sort the small buckets [ss, j], but also make a big effort to avoid the calls if we can. --*/ ss = runningOrder[i]; /*-- Step 1: Complete the big bucket [ss] by quicksorting any unsorted small buckets [ss, j], for j != ss. Hopefully previous pointer-scanning phases have already completed many of the small buckets [ss, j], so we don't have to sort them at all. --*/ for (j = 0; j <= 255; j++) { if (j != ss) { sb = (ss << 8) + j; if ( ! (ftab[sb] & SETMASK) ) { Int32 lo = ftab[sb] & CLEARMASK; Int32 hi = (ftab[sb+1] & CLEARMASK) - 1; if (hi > lo) { if (verb >= 4) VPrintf4 ( " qsort [0x%x, 0x%x] " "done %d this %d\n", ss, j, numQSorted, hi - lo + 1 ); mainQSort3 ( ptr, block, quadrant, nblock, lo, hi, BZ_N_RADIX, budget ); numQSorted += (hi - lo + 1); if (*budget < 0) return; } } ftab[sb] |= SETMASK; } } AssertH ( !bigDone[ss], 1006 ); /*-- Step 2: Now scan this big bucket [ss] so as to synthesise the sorted order for small buckets [t, ss] for all t, including, magically, the bucket [ss,ss] too. This will avoid doing Real Work in subsequent Step 1's. --*/ { for (j = 0; j <= 255; j++) { copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK; copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1; } for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) { k = ptr[j]-1; if (k < 0) k += nblock; c1 = block[k]; if (!bigDone[c1]) ptr[ copyStart[c1]++ ] = k; } for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { k = ptr[j]-1; if (k < 0) k += nblock; c1 = block[k]; if (!bigDone[c1]) ptr[ copyEnd[c1]-- ] = k; } } AssertH ( (copyStart[ss]-1 == copyEnd[ss]) || /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. Necessity for this case is demonstrated by compressing a sequence of approximately 48.5 million of character 251; 1.0.0/1.0.1 will then die here. */ (copyStart[ss] == 0 && copyEnd[ss] == nblock-1), 1007 ) for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK; /*-- Step 3: The [ss] big bucket is now done. Record this fact, and update the quadrant descriptors. Remember to update quadrants in the overshoot area too, if necessary. The "if (i < 255)" test merely skips this updating for the last bucket processed, since updating for the last bucket is pointless. The quadrant array provides a way to incrementally cache sort orderings, as they appear, so as to make subsequent comparisons in fullGtU() complete faster. For repetitive blocks this makes a big difference (but not big enough to be able to avoid the fallback sorting mechanism, exponential radix sort). The precise meaning is: at all times: for 0 <= i < nblock and 0 <= j <= nblock if block[i] != block[j], then the relative values of quadrant[i] and quadrant[j] are meaningless. else { if quadrant[i] < quadrant[j] then the string starting at i lexicographically precedes the string starting at j else if quadrant[i] > quadrant[j] then the string starting at j lexicographically precedes the string starting at i else the relative ordering of the strings starting at i and j has not yet been determined. } --*/ bigDone[ss] = True; if (i < 255) { Int32 bbStart = ftab[ss << 8] & CLEARMASK; Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; Int32 shifts = 0; while ((bbSize >> shifts) > 65534) shifts++; for (j = bbSize-1; j >= 0; j--) { Int32 a2update = ptr[bbStart + j]; UInt16 qVal = (UInt16)(j >> shifts); quadrant[a2update] = qVal; if (a2update < BZ_N_OVERSHOOT) quadrant[a2update + nblock] = qVal; } AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 ); } } if (verb >= 4) VPrintf3 ( " %d pointers, %d sorted, %d scanned\n", nblock, numQSorted, nblock - numQSorted ); } #undef BIGFREQ #undef SETMASK #undef CLEARMASK /*---------------------------------------------*/ /* Pre: nblock > 0 arr2 exists for [0 .. nblock-1 +N_OVERSHOOT] ((UChar*)arr2) [0 .. nblock-1] holds block arr1 exists for [0 .. nblock-1] Post: ((UChar*)arr2) [0 .. nblock-1] holds block All other areas of block destroyed ftab [ 0 .. 65536 ] destroyed arr1 [0 .. nblock-1] holds sorted order */ void BZ2_blockSort ( EState* s ) { UInt32* ptr = s->ptr; UChar* block = s->block; UInt32* ftab = s->ftab; Int32 nblock = s->nblock; Int32 verb = s->verbosity; Int32 wfact = s->workFactor; UInt16* quadrant; Int32 budget; Int32 budgetInit; Int32 i; if (nblock < 10000) { fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); } else { /* Calculate the location for quadrant, remembering to get the alignment right. Assumes that &(block[0]) is at least 2-byte aligned -- this should be ok since block is really the first section of arr2. */ i = nblock+BZ_N_OVERSHOOT; if (i & 1) i++; quadrant = (UInt16*)(&(block[i])); /* (wfact-1) / 3 puts the default-factor-30 transition point at very roughly the same place as with v0.1 and v0.9.0. Not that it particularly matters any more, since the resulting compressed stream is now the same regardless of whether or not we use the main sort or fallback sort. */ if (wfact < 1 ) wfact = 1; if (wfact > 100) wfact = 100; budgetInit = nblock * ((wfact-1) / 3); budget = budgetInit; mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); if (verb >= 3) VPrintf3 ( " %d work, %d block, ratio %5.2f\n", budgetInit - budget, nblock, (float)(budgetInit - budget) / (float)(nblock==0 ? 1 : nblock) ); if (budget < 0) { if (verb >= 2) VPrintf0 ( " too repetitive; using fallback" " sorting algorithm\n" ); fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); } } s->origPtr = -1; for (i = 0; i < s->nblock; i++) if (ptr[i] == 0) { s->origPtr = i; break; }; AssertH( s->origPtr != -1, 1003 ); } /*-------------------------------------------------------------*/ /*--- end blocksort.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/bzip2.c000066400000000000000000001622741462133141200207140ustar00rootroot00000000000000 /*-----------------------------------------------------------*/ /*--- A block-sorting, lossless compressor bzip2.c ---*/ /*-----------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ /* Place a 1 beside your platform, and 0 elsewhere. Generic 32-bit Unix. Also works on 64-bit Unix boxes. This is the default. */ #define BZ_UNIX 1 /*-- Win32, as seen by Jacob Navia's excellent port of (Chris Fraser & David Hanson)'s excellent lcc compiler. Or with MS Visual C. This is selected automatically if compiled by a compiler which defines _WIN32, not including the Cygwin GCC. --*/ #define BZ_LCCWIN32 0 #if defined(_WIN32) && !defined(__CYGWIN__) #undef BZ_LCCWIN32 #define BZ_LCCWIN32 1 #undef BZ_UNIX #define BZ_UNIX 0 #endif /*---------------------------------------------*/ /*-- Some stuff for all platforms. --*/ #include #include #include #include #include #include #include #include "bzlib.h" #define ERROR_IF_EOF(i) { if ((i) == EOF) ioError(); } #define ERROR_IF_NOT_ZERO(i) { if ((i) != 0) ioError(); } #define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) ioError(); } /*---------------------------------------------*/ /*-- Platform-specific stuff. --*/ #if BZ_UNIX # include # include # include # include # include # include # define PATH_SEP '/' # define MY_LSTAT lstat # define MY_STAT stat # define MY_S_ISREG S_ISREG # define MY_S_ISDIR S_ISDIR # define APPEND_FILESPEC(root, name) \ root=snocString((root), (name)) # define APPEND_FLAG(root, name) \ root=snocString((root), (name)) # define SET_BINARY_MODE(fd) /**/ # ifdef __GNUC__ # define NORETURN __attribute__ ((noreturn)) # else # define NORETURN /**/ # endif # ifdef __DJGPP__ # include # include # undef MY_LSTAT # undef MY_STAT # define MY_LSTAT stat # define MY_STAT stat # undef SET_BINARY_MODE # define SET_BINARY_MODE(fd) \ do { \ int retVal = setmode ( fileno ( fd ), \ O_BINARY ); \ ERROR_IF_MINUS_ONE ( retVal ); \ } while ( 0 ) # endif # ifdef __CYGWIN__ # include # include # undef SET_BINARY_MODE # define SET_BINARY_MODE(fd) \ do { \ int retVal = setmode ( fileno ( fd ), \ O_BINARY ); \ ERROR_IF_MINUS_ONE ( retVal ); \ } while ( 0 ) # endif #endif /* BZ_UNIX */ #if BZ_LCCWIN32 # include # include # include # define NORETURN /**/ # define PATH_SEP '\\' # define MY_LSTAT _stat # define MY_STAT _stat # define MY_S_ISREG(x) ((x) & _S_IFREG) # define MY_S_ISDIR(x) ((x) & _S_IFDIR) # define APPEND_FLAG(root, name) \ root=snocString((root), (name)) # define APPEND_FILESPEC(root, name) \ root = snocString ((root), (name)) # define SET_BINARY_MODE(fd) \ do { \ int retVal = setmode ( fileno ( fd ), \ O_BINARY ); \ ERROR_IF_MINUS_ONE ( retVal ); \ } while ( 0 ) #endif /* BZ_LCCWIN32 */ /*---------------------------------------------*/ /*-- Some more stuff for all platforms :-) --*/ typedef char Char; typedef unsigned char Bool; typedef unsigned char UChar; typedef int Int32; typedef unsigned int UInt32; typedef short Int16; typedef unsigned short UInt16; #define True ((Bool)1) #define False ((Bool)0) /*-- IntNative is your platform's `native' int size. Only here to avoid probs with 64-bit platforms. --*/ typedef int IntNative; /*---------------------------------------------------*/ /*--- Misc (file handling) data decls ---*/ /*---------------------------------------------------*/ Int32 verbosity; Bool keepInputFiles, smallMode, deleteOutputOnInterrupt; Bool forceOverwrite, testFailsExist, unzFailsExist, noisy; Int32 numFileNames, numFilesProcessed, blockSize100k; Int32 exitValue; /*-- source modes; F==file, I==stdin, O==stdout --*/ #define SM_I2O 1 #define SM_F2O 2 #define SM_F2F 3 /*-- operation modes --*/ #define OM_Z 1 #define OM_UNZ 2 #define OM_TEST 3 Int32 opMode; Int32 srcMode; #define FILE_NAME_LEN 1034 Int32 longestFileName; Char inName [FILE_NAME_LEN]; Char outName[FILE_NAME_LEN]; Char tmpName[FILE_NAME_LEN]; Char *progName; Char progNameReally[FILE_NAME_LEN]; FILE *outputHandleJustInCase; Int32 workFactor; static void panic ( const Char* ) NORETURN; static void ioError ( void ) NORETURN; static void outOfMemory ( void ) NORETURN; static void configError ( void ) NORETURN; static void crcError ( void ) NORETURN; static void cleanUpAndFail ( Int32 ) NORETURN; static void compressedStreamEOF ( void ) NORETURN; static void copyFileName ( Char*, Char* ); static void* myMalloc ( Int32 ); static void applySavedFileAttrToOutputFile ( IntNative fd ); /*---------------------------------------------------*/ /*--- An implementation of 64-bit ints. Sigh. ---*/ /*--- Roll on widespread deployment of ANSI C9X ! ---*/ /*---------------------------------------------------*/ typedef struct { UChar b[8]; } UInt64; static void uInt64_from_UInt32s ( UInt64* n, UInt32 lo32, UInt32 hi32 ) { n->b[7] = (UChar)((hi32 >> 24) & 0xFF); n->b[6] = (UChar)((hi32 >> 16) & 0xFF); n->b[5] = (UChar)((hi32 >> 8) & 0xFF); n->b[4] = (UChar) (hi32 & 0xFF); n->b[3] = (UChar)((lo32 >> 24) & 0xFF); n->b[2] = (UChar)((lo32 >> 16) & 0xFF); n->b[1] = (UChar)((lo32 >> 8) & 0xFF); n->b[0] = (UChar) (lo32 & 0xFF); } static double uInt64_to_double ( UInt64* n ) { Int32 i; double base = 1.0; double sum = 0.0; for (i = 0; i < 8; i++) { sum += base * (double)(n->b[i]); base *= 256.0; } return sum; } static Bool uInt64_isZero ( UInt64* n ) { Int32 i; for (i = 0; i < 8; i++) if (n->b[i] != 0) return 0; return 1; } /* Divide *n by 10, and return the remainder. */ static Int32 uInt64_qrm10 ( UInt64* n ) { UInt32 rem, tmp; Int32 i; rem = 0; for (i = 7; i >= 0; i--) { tmp = rem * 256 + n->b[i]; n->b[i] = tmp / 10; rem = tmp % 10; } return rem; } /* ... and the Whole Entire Point of all this UInt64 stuff is so that we can supply the following function. */ static void uInt64_toAscii ( char* outbuf, UInt64* n ) { Int32 i, q; UChar buf[32]; Int32 nBuf = 0; UInt64 n_copy = *n; do { q = uInt64_qrm10 ( &n_copy ); buf[nBuf] = q + '0'; nBuf++; } while (!uInt64_isZero(&n_copy)); outbuf[nBuf] = 0; for (i = 0; i < nBuf; i++) outbuf[i] = buf[nBuf-i-1]; } /*---------------------------------------------------*/ /*--- Processing of complete files and streams ---*/ /*---------------------------------------------------*/ /*---------------------------------------------*/ static Bool myfeof ( FILE* f ) { Int32 c = fgetc ( f ); if (c == EOF) return True; ungetc ( c, f ); return False; } /*---------------------------------------------*/ static void compressStream ( FILE *stream, FILE *zStream ) { BZFILE* bzf = NULL; UChar ibuf[5000]; Int32 nIbuf; UInt32 nbytes_in_lo32, nbytes_in_hi32; UInt32 nbytes_out_lo32, nbytes_out_hi32; Int32 bzerr, bzerr_dummy, ret; SET_BINARY_MODE(stream); SET_BINARY_MODE(zStream); if (ferror(stream)) goto errhandler_io; if (ferror(zStream)) goto errhandler_io; bzf = BZ2_bzWriteOpen ( &bzerr, zStream, blockSize100k, verbosity, workFactor ); if (bzerr != BZ_OK) goto errhandler; if (verbosity >= 2) fprintf ( stderr, "\n" ); while (True) { if (myfeof(stream)) break; nIbuf = fread ( ibuf, sizeof(UChar), 5000, stream ); if (ferror(stream)) goto errhandler_io; if (nIbuf > 0) BZ2_bzWrite ( &bzerr, bzf, (void*)ibuf, nIbuf ); if (bzerr != BZ_OK) goto errhandler; } BZ2_bzWriteClose64 ( &bzerr, bzf, 0, &nbytes_in_lo32, &nbytes_in_hi32, &nbytes_out_lo32, &nbytes_out_hi32 ); if (bzerr != BZ_OK) goto errhandler; if (ferror(zStream)) goto errhandler_io; ret = fflush ( zStream ); if (ret == EOF) goto errhandler_io; if (zStream != stdout) { Int32 fd = fileno ( zStream ); if (fd < 0) goto errhandler_io; applySavedFileAttrToOutputFile ( fd ); ret = fclose ( zStream ); outputHandleJustInCase = NULL; if (ret == EOF) goto errhandler_io; } outputHandleJustInCase = NULL; if (ferror(stream)) goto errhandler_io; ret = fclose ( stream ); if (ret == EOF) goto errhandler_io; if (verbosity >= 1) { if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0) { fprintf ( stderr, " no data compressed.\n"); } else { Char buf_nin[32], buf_nout[32]; UInt64 nbytes_in, nbytes_out; double nbytes_in_d, nbytes_out_d; uInt64_from_UInt32s ( &nbytes_in, nbytes_in_lo32, nbytes_in_hi32 ); uInt64_from_UInt32s ( &nbytes_out, nbytes_out_lo32, nbytes_out_hi32 ); nbytes_in_d = uInt64_to_double ( &nbytes_in ); nbytes_out_d = uInt64_to_double ( &nbytes_out ); uInt64_toAscii ( buf_nin, &nbytes_in ); uInt64_toAscii ( buf_nout, &nbytes_out ); fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, " "%5.2f%% saved, %s in, %s out.\n", nbytes_in_d / nbytes_out_d, (8.0 * nbytes_out_d) / nbytes_in_d, 100.0 * (1.0 - nbytes_out_d / nbytes_in_d), buf_nin, buf_nout ); } } return; errhandler: BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1, &nbytes_in_lo32, &nbytes_in_hi32, &nbytes_out_lo32, &nbytes_out_hi32 ); switch (bzerr) { case BZ_CONFIG_ERROR: configError(); break; case BZ_MEM_ERROR: outOfMemory (); break; case BZ_IO_ERROR: errhandler_io: ioError(); break; default: panic ( "compress:unexpected error" ); } panic ( "compress:end" ); /*notreached*/ } /*---------------------------------------------*/ static Bool uncompressStream ( FILE *zStream, FILE *stream ) { BZFILE* bzf = NULL; Int32 bzerr, bzerr_dummy, ret, nread, streamNo, i; UChar obuf[5000]; UChar unused[BZ_MAX_UNUSED]; Int32 nUnused; void* unusedTmpV; UChar* unusedTmp; nUnused = 0; streamNo = 0; SET_BINARY_MODE(stream); SET_BINARY_MODE(zStream); if (ferror(stream)) goto errhandler_io; if (ferror(zStream)) goto errhandler_io; while (True) { bzf = BZ2_bzReadOpen ( &bzerr, zStream, verbosity, (int)smallMode, unused, nUnused ); if (bzf == NULL || bzerr != BZ_OK) goto errhandler; streamNo++; while (bzerr == BZ_OK) { nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 ); if (bzerr == BZ_DATA_ERROR_MAGIC) goto trycat; if ((bzerr == BZ_OK || bzerr == BZ_STREAM_END) && nread > 0) fwrite ( obuf, sizeof(UChar), nread, stream ); if (ferror(stream)) goto errhandler_io; } if (bzerr != BZ_STREAM_END) goto errhandler; BZ2_bzReadGetUnused ( &bzerr, bzf, &unusedTmpV, &nUnused ); if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" ); unusedTmp = (UChar*)unusedTmpV; for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i]; BZ2_bzReadClose ( &bzerr, bzf ); if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" ); if (nUnused == 0 && myfeof(zStream)) break; } closeok: if (ferror(zStream)) goto errhandler_io; if (stream != stdout) { Int32 fd = fileno ( stream ); if (fd < 0) goto errhandler_io; applySavedFileAttrToOutputFile ( fd ); } ret = fclose ( zStream ); if (ret == EOF) goto errhandler_io; if (ferror(stream)) goto errhandler_io; ret = fflush ( stream ); if (ret != 0) goto errhandler_io; if (stream != stdout) { ret = fclose ( stream ); outputHandleJustInCase = NULL; if (ret == EOF) goto errhandler_io; } outputHandleJustInCase = NULL; if (verbosity >= 2) fprintf ( stderr, "\n " ); return True; trycat: if (forceOverwrite) { rewind(zStream); while (True) { if (myfeof(zStream)) break; nread = fread ( obuf, sizeof(UChar), 5000, zStream ); if (ferror(zStream)) goto errhandler_io; if (nread > 0) fwrite ( obuf, sizeof(UChar), nread, stream ); if (ferror(stream)) goto errhandler_io; } goto closeok; } errhandler: BZ2_bzReadClose ( &bzerr_dummy, bzf ); switch (bzerr) { case BZ_CONFIG_ERROR: configError(); break; case BZ_IO_ERROR: errhandler_io: ioError(); break; case BZ_DATA_ERROR: crcError(); case BZ_MEM_ERROR: outOfMemory(); case BZ_UNEXPECTED_EOF: compressedStreamEOF(); case BZ_DATA_ERROR_MAGIC: if (zStream != stdin) fclose(zStream); if (stream != stdout) fclose(stream); if (streamNo == 1) { return False; } else { if (noisy) fprintf ( stderr, "\n%s: %s: trailing garbage after EOF ignored\n", progName, inName ); return True; } default: panic ( "decompress:unexpected error" ); } panic ( "decompress:end" ); return True; /*notreached*/ } /*---------------------------------------------*/ static Bool testStream ( FILE *zStream ) { BZFILE* bzf = NULL; Int32 bzerr, bzerr_dummy, ret, nread, streamNo, i; UChar obuf[5000]; UChar unused[BZ_MAX_UNUSED]; Int32 nUnused; void* unusedTmpV; UChar* unusedTmp; nUnused = 0; streamNo = 0; SET_BINARY_MODE(zStream); if (ferror(zStream)) goto errhandler_io; while (True) { bzf = BZ2_bzReadOpen ( &bzerr, zStream, verbosity, (int)smallMode, unused, nUnused ); if (bzf == NULL || bzerr != BZ_OK) goto errhandler; streamNo++; while (bzerr == BZ_OK) { nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 ); if (bzerr == BZ_DATA_ERROR_MAGIC) goto errhandler; } if (bzerr != BZ_STREAM_END) goto errhandler; BZ2_bzReadGetUnused ( &bzerr, bzf, &unusedTmpV, &nUnused ); if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" ); unusedTmp = (UChar*)unusedTmpV; for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i]; BZ2_bzReadClose ( &bzerr, bzf ); if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" ); if (nUnused == 0 && myfeof(zStream)) break; } if (ferror(zStream)) goto errhandler_io; ret = fclose ( zStream ); if (ret == EOF) goto errhandler_io; if (verbosity >= 2) fprintf ( stderr, "\n " ); return True; errhandler: BZ2_bzReadClose ( &bzerr_dummy, bzf ); if (verbosity == 0) fprintf ( stderr, "%s: %s: ", progName, inName ); switch (bzerr) { case BZ_CONFIG_ERROR: configError(); break; case BZ_IO_ERROR: errhandler_io: ioError(); break; case BZ_DATA_ERROR: fprintf ( stderr, "data integrity (CRC) error in data\n" ); return False; case BZ_MEM_ERROR: outOfMemory(); case BZ_UNEXPECTED_EOF: fprintf ( stderr, "file ends unexpectedly\n" ); return False; case BZ_DATA_ERROR_MAGIC: if (zStream != stdin) fclose(zStream); if (streamNo == 1) { fprintf ( stderr, "bad magic number (file not created by bzip2)\n" ); return False; } else { if (noisy) fprintf ( stderr, "trailing garbage after EOF ignored\n" ); return True; } default: panic ( "test:unexpected error" ); } panic ( "test:end" ); return True; /*notreached*/ } /*---------------------------------------------------*/ /*--- Error [non-] handling grunge ---*/ /*---------------------------------------------------*/ /*---------------------------------------------*/ static void setExit ( Int32 v ) { if (v > exitValue) exitValue = v; } /*---------------------------------------------*/ static void cadvise ( void ) { if (noisy) fprintf ( stderr, "\nIt is possible that the compressed file(s) have become corrupted.\n" "You can use the -tvv option to test integrity of such files.\n\n" "You can use the `bzip2recover' program to attempt to recover\n" "data from undamaged sections of corrupted files.\n\n" ); } /*---------------------------------------------*/ static void showFileNames ( void ) { if (noisy) fprintf ( stderr, "\tInput file = %s, output file = %s\n", inName, outName ); } /*---------------------------------------------*/ static void cleanUpAndFail ( Int32 ec ) { IntNative retVal; struct MY_STAT statBuf; if ( srcMode == SM_F2F && opMode != OM_TEST && deleteOutputOnInterrupt ) { /* Check whether input file still exists. Delete output file only if input exists to avoid loss of data. Joerg Prante, 5 January 2002. (JRS 06-Jan-2002: other changes in 1.0.2 mean this is less likely to happen. But to be ultra-paranoid, we do the check anyway.) */ retVal = MY_STAT ( inName, &statBuf ); if (retVal == 0) { if (noisy) fprintf ( stderr, "%s: Deleting output file %s, if it exists.\n", progName, outName ); if (outputHandleJustInCase != NULL) fclose ( outputHandleJustInCase ); retVal = remove ( outName ); if (retVal != 0) fprintf ( stderr, "%s: WARNING: deletion of output file " "(apparently) failed.\n", progName ); } else { fprintf ( stderr, "%s: WARNING: deletion of output file suppressed\n", progName ); fprintf ( stderr, "%s: since input file no longer exists. Output file\n", progName ); fprintf ( stderr, "%s: `%s' may be incomplete.\n", progName, outName ); fprintf ( stderr, "%s: I suggest doing an integrity test (bzip2 -tv)" " of it.\n", progName ); } } if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) { fprintf ( stderr, "%s: WARNING: some files have not been processed:\n" "%s: %d specified on command line, %d not processed yet.\n\n", progName, progName, numFileNames, numFileNames - numFilesProcessed ); } setExit(ec); exit(exitValue); } /*---------------------------------------------*/ static void panic ( const Char* s ) { fprintf ( stderr, "\n%s: PANIC -- internal consistency error:\n" "\t%s\n" "\tThis is a BUG. Please report it to me at:\n" "\tjseward@bzip.org\n", progName, s ); showFileNames(); cleanUpAndFail( 3 ); } /*---------------------------------------------*/ static void crcError ( void ) { fprintf ( stderr, "\n%s: Data integrity error when decompressing.\n", progName ); showFileNames(); cadvise(); cleanUpAndFail( 2 ); } /*---------------------------------------------*/ static void compressedStreamEOF ( void ) { if (noisy) { fprintf ( stderr, "\n%s: Compressed file ends unexpectedly;\n\t" "perhaps it is corrupted? *Possible* reason follows.\n", progName ); perror ( progName ); showFileNames(); cadvise(); } cleanUpAndFail( 2 ); } /*---------------------------------------------*/ static void ioError ( void ) { fprintf ( stderr, "\n%s: I/O or other error, bailing out. " "Possible reason follows.\n", progName ); perror ( progName ); showFileNames(); cleanUpAndFail( 1 ); } /*---------------------------------------------*/ static void mySignalCatcher ( IntNative n ) { fprintf ( stderr, "\n%s: Control-C or similar caught, quitting.\n", progName ); cleanUpAndFail(1); } /*---------------------------------------------*/ static void mySIGSEGVorSIGBUScatcher ( IntNative n ) { if (opMode == OM_Z) fprintf ( stderr, "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n" "\n" " Possible causes are (most likely first):\n" " (1) This computer has unreliable memory or cache hardware\n" " (a surprisingly common problem; try a different machine.)\n" " (2) A bug in the compiler used to create this executable\n" " (unlikely, if you didn't compile bzip2 yourself.)\n" " (3) A real bug in bzip2 -- I hope this should never be the case.\n" " The user's manual, Section 4.3, has more info on (1) and (2).\n" " \n" " If you suspect this is a bug in bzip2, or are unsure about (1)\n" " or (2), feel free to report it to me at: jseward@bzip.org.\n" " Section 4.3 of the user's manual describes the info a useful\n" " bug report should have. If the manual is available on your\n" " system, please try and read it before mailing me. If you don't\n" " have the manual or can't be bothered to read it, mail me anyway.\n" "\n", progName ); else fprintf ( stderr, "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n" "\n" " Possible causes are (most likely first):\n" " (1) The compressed data is corrupted, and bzip2's usual checks\n" " failed to detect this. Try bzip2 -tvv my_file.bz2.\n" " (2) This computer has unreliable memory or cache hardware\n" " (a surprisingly common problem; try a different machine.)\n" " (3) A bug in the compiler used to create this executable\n" " (unlikely, if you didn't compile bzip2 yourself.)\n" " (4) A real bug in bzip2 -- I hope this should never be the case.\n" " The user's manual, Section 4.3, has more info on (2) and (3).\n" " \n" " If you suspect this is a bug in bzip2, or are unsure about (2)\n" " or (3), feel free to report it to me at: jseward@bzip.org.\n" " Section 4.3 of the user's manual describes the info a useful\n" " bug report should have. If the manual is available on your\n" " system, please try and read it before mailing me. If you don't\n" " have the manual or can't be bothered to read it, mail me anyway.\n" "\n", progName ); showFileNames(); if (opMode == OM_Z) cleanUpAndFail( 3 ); else { cadvise(); cleanUpAndFail( 2 ); } } /*---------------------------------------------*/ static void outOfMemory ( void ) { fprintf ( stderr, "\n%s: couldn't allocate enough memory\n", progName ); showFileNames(); cleanUpAndFail(1); } /*---------------------------------------------*/ static void configError ( void ) { fprintf ( stderr, "bzip2: I'm not configured correctly for this platform!\n" "\tI require Int32, Int16 and Char to have sizes\n" "\tof 4, 2 and 1 bytes to run properly, and they don't.\n" "\tProbably you can fix this by defining them correctly,\n" "\tand recompiling. Bye!\n" ); setExit(3); exit(exitValue); } /*---------------------------------------------------*/ /*--- The main driver machinery ---*/ /*---------------------------------------------------*/ /* All rather crufty. The main problem is that input files are stat()d multiple times before use. This should be cleaned up. */ /*---------------------------------------------*/ static void pad ( Char *s ) { Int32 i; if ( (Int32)strlen(s) >= longestFileName ) return; for (i = 1; i <= longestFileName - (Int32)strlen(s); i++) fprintf ( stderr, " " ); } /*---------------------------------------------*/ static void copyFileName ( Char* to, Char* from ) { if ( strlen(from) > FILE_NAME_LEN-10 ) { fprintf ( stderr, "bzip2: file name\n`%s'\n" "is suspiciously (more than %d chars) long.\n" "Try using a reasonable file name instead. Sorry! :-)\n", from, FILE_NAME_LEN-10 ); setExit(1); exit(exitValue); } strncpy(to,from,FILE_NAME_LEN-10); to[FILE_NAME_LEN-10]='\0'; } /*---------------------------------------------*/ static Bool fileExists ( Char* name ) { FILE *tmp = fopen ( name, "rb" ); Bool exists = (tmp != NULL); if (tmp != NULL) fclose ( tmp ); return exists; } /*---------------------------------------------*/ /* Open an output file safely with O_EXCL and good permissions. This avoids a race condition in versions < 1.0.2, in which the file was first opened and then had its interim permissions set safely. We instead use open() to create the file with the interim permissions required. (--- --- rw-). For non-Unix platforms, if we are not worrying about security issues, simple this simply behaves like fopen. */ static FILE* fopen_output_safely ( Char* name, const char* mode ) { # if BZ_UNIX FILE* fp; IntNative fh; fh = open(name, O_WRONLY|O_CREAT|O_EXCL, S_IWUSR|S_IRUSR); if (fh == -1) return NULL; fp = fdopen(fh, mode); if (fp == NULL) close(fh); return fp; # else return fopen(name, mode); # endif } /*---------------------------------------------*/ /*-- if in doubt, return True --*/ static Bool notAStandardFile ( Char* name ) { IntNative i; struct MY_STAT statBuf; i = MY_LSTAT ( name, &statBuf ); if (i != 0) return True; if (MY_S_ISREG(statBuf.st_mode)) return False; return True; } /*---------------------------------------------*/ /*-- rac 11/21/98 see if file has hard links to it --*/ static Int32 countHardLinks ( Char* name ) { IntNative i; struct MY_STAT statBuf; i = MY_LSTAT ( name, &statBuf ); if (i != 0) return 0; return (statBuf.st_nlink - 1); } /*---------------------------------------------*/ /* Copy modification date, access date, permissions and owner from the source to destination file. We have to copy this meta-info off into fileMetaInfo before starting to compress / decompress it, because doing it afterwards means we get the wrong access time. To complicate matters, in compress() and decompress() below, the sequence of tests preceding the call to saveInputFileMetaInfo() involves calling fileExists(), which in turn establishes its result by attempting to fopen() the file, and if successful, immediately fclose()ing it again. So we have to assume that the fopen() call does not cause the access time field to be updated. Reading of the man page for stat() (man 2 stat) on RedHat 7.2 seems to imply that merely doing open() will not affect the access time. Therefore we merely need to hope that the C library only does open() as a result of fopen(), and not any kind of read()-ahead cleverness. It sounds pretty fragile to me. Whether this carries across robustly to arbitrary Unix-like platforms (or even works robustly on this one, RedHat 7.2) is unknown to me. Nevertheless ... */ #if BZ_UNIX static struct MY_STAT fileMetaInfo; #endif static void saveInputFileMetaInfo ( Char *srcName ) { # if BZ_UNIX IntNative retVal; /* Note use of stat here, not lstat. */ retVal = MY_STAT( srcName, &fileMetaInfo ); ERROR_IF_NOT_ZERO ( retVal ); # endif } static void applySavedTimeInfoToOutputFile ( Char *dstName ) { # if BZ_UNIX IntNative retVal; struct utimbuf uTimBuf; uTimBuf.actime = fileMetaInfo.st_atime; uTimBuf.modtime = fileMetaInfo.st_mtime; retVal = utime ( dstName, &uTimBuf ); ERROR_IF_NOT_ZERO ( retVal ); # endif } static void applySavedFileAttrToOutputFile ( IntNative fd ) { # if BZ_UNIX IntNative retVal; retVal = fchmod ( fd, fileMetaInfo.st_mode ); ERROR_IF_NOT_ZERO ( retVal ); (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid ); /* chown() will in many cases return with EPERM, which can be safely ignored. */ # endif } /*---------------------------------------------*/ static Bool containsDubiousChars ( Char* name ) { # if BZ_UNIX /* On unix, files can contain any characters and the file expansion * is performed by the shell. */ return False; # else /* ! BZ_UNIX */ /* On non-unix (Win* platforms), wildcard characters are not allowed in * filenames. */ for (; *name != '\0'; name++) if (*name == '?' || *name == '*') return True; return False; # endif /* BZ_UNIX */ } /*---------------------------------------------*/ #define BZ_N_SUFFIX_PAIRS 4 const Char* zSuffix[BZ_N_SUFFIX_PAIRS] = { ".bz2", ".bz", ".tbz2", ".tbz" }; const Char* unzSuffix[BZ_N_SUFFIX_PAIRS] = { "", "", ".tar", ".tar" }; static Bool hasSuffix ( Char* s, const Char* suffix ) { Int32 ns = strlen(s); Int32 nx = strlen(suffix); if (ns < nx) return False; if (strcmp(s + ns - nx, suffix) == 0) return True; return False; } static Bool mapSuffix ( Char* name, const Char* oldSuffix, const Char* newSuffix ) { if (!hasSuffix(name,oldSuffix)) return False; name[strlen(name)-strlen(oldSuffix)] = 0; strcat ( name, newSuffix ); return True; } /*---------------------------------------------*/ static void compress ( Char *name ) { FILE *inStr; FILE *outStr; Int32 n, i; struct MY_STAT statBuf; deleteOutputOnInterrupt = False; if (name == NULL && srcMode != SM_I2O) panic ( "compress: bad modes\n" ); switch (srcMode) { case SM_I2O: copyFileName ( inName, (Char*)"(stdin)" ); copyFileName ( outName, (Char*)"(stdout)" ); break; case SM_F2F: copyFileName ( inName, name ); copyFileName ( outName, name ); strcat ( outName, ".bz2" ); break; case SM_F2O: copyFileName ( inName, name ); copyFileName ( outName, (Char*)"(stdout)" ); break; } if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { if (noisy) fprintf ( stderr, "%s: There are no files matching `%s'.\n", progName, inName ); setExit(1); return; } if ( srcMode != SM_I2O && !fileExists ( inName ) ) { fprintf ( stderr, "%s: Can't open input file %s: %s.\n", progName, inName, strerror(errno) ); setExit(1); return; } for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) { if (hasSuffix(inName, zSuffix[i])) { if (noisy) fprintf ( stderr, "%s: Input file %s already has %s suffix.\n", progName, inName, zSuffix[i] ); setExit(1); return; } } if ( srcMode == SM_F2F || srcMode == SM_F2O ) { MY_STAT(inName, &statBuf); if ( MY_S_ISDIR(statBuf.st_mode) ) { fprintf( stderr, "%s: Input file %s is a directory.\n", progName,inName); setExit(1); return; } } if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) { if (noisy) fprintf ( stderr, "%s: Input file %s is not a normal file.\n", progName, inName ); setExit(1); return; } if ( srcMode == SM_F2F && fileExists ( outName ) ) { if (forceOverwrite) { remove(outName); } else { fprintf ( stderr, "%s: Output file %s already exists.\n", progName, outName ); setExit(1); return; } } if ( srcMode == SM_F2F && !forceOverwrite && (n=countHardLinks ( inName )) > 0) { fprintf ( stderr, "%s: Input file %s has %d other link%s.\n", progName, inName, n, n > 1 ? "s" : "" ); setExit(1); return; } if ( srcMode == SM_F2F ) { /* Save the file's meta-info before we open it. Doing it later means we mess up the access times. */ saveInputFileMetaInfo ( inName ); } switch ( srcMode ) { case SM_I2O: inStr = stdin; outStr = stdout; if ( isatty ( fileno ( stdout ) ) ) { fprintf ( stderr, "%s: I won't write compressed data to a terminal.\n", progName ); fprintf ( stderr, "%s: For help, type: `%s --help'.\n", progName, progName ); setExit(1); return; }; break; case SM_F2O: inStr = fopen ( inName, "rb" ); outStr = stdout; if ( isatty ( fileno ( stdout ) ) ) { fprintf ( stderr, "%s: I won't write compressed data to a terminal.\n", progName ); fprintf ( stderr, "%s: For help, type: `%s --help'.\n", progName, progName ); if ( inStr != NULL ) fclose ( inStr ); setExit(1); return; }; if ( inStr == NULL ) { fprintf ( stderr, "%s: Can't open input file %s: %s.\n", progName, inName, strerror(errno) ); setExit(1); return; }; break; case SM_F2F: inStr = fopen ( inName, "rb" ); outStr = fopen_output_safely ( outName, "wb" ); if ( outStr == NULL) { fprintf ( stderr, "%s: Can't create output file %s: %s.\n", progName, outName, strerror(errno) ); if ( inStr != NULL ) fclose ( inStr ); setExit(1); return; } if ( inStr == NULL ) { fprintf ( stderr, "%s: Can't open input file %s: %s.\n", progName, inName, strerror(errno) ); if ( outStr != NULL ) fclose ( outStr ); setExit(1); return; }; break; default: panic ( "compress: bad srcMode" ); break; } if (verbosity >= 1) { fprintf ( stderr, " %s: ", inName ); pad ( inName ); fflush ( stderr ); } /*--- Now the input and output handles are sane. Do the Biz. ---*/ outputHandleJustInCase = outStr; deleteOutputOnInterrupt = True; compressStream ( inStr, outStr ); outputHandleJustInCase = NULL; /*--- If there was an I/O error, we won't get here. ---*/ if ( srcMode == SM_F2F ) { applySavedTimeInfoToOutputFile ( outName ); deleteOutputOnInterrupt = False; if ( !keepInputFiles ) { IntNative retVal = remove ( inName ); ERROR_IF_NOT_ZERO ( retVal ); } } deleteOutputOnInterrupt = False; } /*---------------------------------------------*/ static void uncompress ( Char *name ) { FILE *inStr; FILE *outStr; Int32 n, i; Bool magicNumberOK; Bool cantGuess; struct MY_STAT statBuf; deleteOutputOnInterrupt = False; if (name == NULL && srcMode != SM_I2O) panic ( "uncompress: bad modes\n" ); cantGuess = False; switch (srcMode) { case SM_I2O: copyFileName ( inName, (Char*)"(stdin)" ); copyFileName ( outName, (Char*)"(stdout)" ); break; case SM_F2F: copyFileName ( inName, name ); copyFileName ( outName, name ); for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) if (mapSuffix(outName,zSuffix[i],unzSuffix[i])) goto zzz; cantGuess = True; strcat ( outName, ".out" ); break; case SM_F2O: copyFileName ( inName, name ); copyFileName ( outName, (Char*)"(stdout)" ); break; } zzz: if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { if (noisy) fprintf ( stderr, "%s: There are no files matching `%s'.\n", progName, inName ); setExit(1); return; } if ( srcMode != SM_I2O && !fileExists ( inName ) ) { fprintf ( stderr, "%s: Can't open input file %s: %s.\n", progName, inName, strerror(errno) ); setExit(1); return; } if ( srcMode == SM_F2F || srcMode == SM_F2O ) { MY_STAT(inName, &statBuf); if ( MY_S_ISDIR(statBuf.st_mode) ) { fprintf( stderr, "%s: Input file %s is a directory.\n", progName,inName); setExit(1); return; } } if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) { if (noisy) fprintf ( stderr, "%s: Input file %s is not a normal file.\n", progName, inName ); setExit(1); return; } if ( /* srcMode == SM_F2F implied && */ cantGuess ) { if (noisy) fprintf ( stderr, "%s: Can't guess original name for %s -- using %s\n", progName, inName, outName ); /* just a warning, no return */ } if ( srcMode == SM_F2F && fileExists ( outName ) ) { if (forceOverwrite) { remove(outName); } else { fprintf ( stderr, "%s: Output file %s already exists.\n", progName, outName ); setExit(1); return; } } if ( srcMode == SM_F2F && !forceOverwrite && (n=countHardLinks ( inName ) ) > 0) { fprintf ( stderr, "%s: Input file %s has %d other link%s.\n", progName, inName, n, n > 1 ? "s" : "" ); setExit(1); return; } if ( srcMode == SM_F2F ) { /* Save the file's meta-info before we open it. Doing it later means we mess up the access times. */ saveInputFileMetaInfo ( inName ); } switch ( srcMode ) { case SM_I2O: inStr = stdin; outStr = stdout; if ( isatty ( fileno ( stdin ) ) ) { fprintf ( stderr, "%s: I won't read compressed data from a terminal.\n", progName ); fprintf ( stderr, "%s: For help, type: `%s --help'.\n", progName, progName ); setExit(1); return; }; break; case SM_F2O: inStr = fopen ( inName, "rb" ); outStr = stdout; if ( inStr == NULL ) { fprintf ( stderr, "%s: Can't open input file %s:%s.\n", progName, inName, strerror(errno) ); if ( inStr != NULL ) fclose ( inStr ); setExit(1); return; }; break; case SM_F2F: inStr = fopen ( inName, "rb" ); outStr = fopen_output_safely ( outName, "wb" ); if ( outStr == NULL) { fprintf ( stderr, "%s: Can't create output file %s: %s.\n", progName, outName, strerror(errno) ); if ( inStr != NULL ) fclose ( inStr ); setExit(1); return; } if ( inStr == NULL ) { fprintf ( stderr, "%s: Can't open input file %s: %s.\n", progName, inName, strerror(errno) ); if ( outStr != NULL ) fclose ( outStr ); setExit(1); return; }; break; default: panic ( "uncompress: bad srcMode" ); break; } if (verbosity >= 1) { fprintf ( stderr, " %s: ", inName ); pad ( inName ); fflush ( stderr ); } /*--- Now the input and output handles are sane. Do the Biz. ---*/ outputHandleJustInCase = outStr; deleteOutputOnInterrupt = True; magicNumberOK = uncompressStream ( inStr, outStr ); outputHandleJustInCase = NULL; /*--- If there was an I/O error, we won't get here. ---*/ if ( magicNumberOK ) { if ( srcMode == SM_F2F ) { applySavedTimeInfoToOutputFile ( outName ); deleteOutputOnInterrupt = False; if ( !keepInputFiles ) { IntNative retVal = remove ( inName ); ERROR_IF_NOT_ZERO ( retVal ); } } } else { unzFailsExist = True; deleteOutputOnInterrupt = False; if ( srcMode == SM_F2F ) { IntNative retVal = remove ( outName ); ERROR_IF_NOT_ZERO ( retVal ); } } deleteOutputOnInterrupt = False; if ( magicNumberOK ) { if (verbosity >= 1) fprintf ( stderr, "done\n" ); } else { setExit(2); if (verbosity >= 1) fprintf ( stderr, "not a bzip2 file.\n" ); else fprintf ( stderr, "%s: %s is not a bzip2 file.\n", progName, inName ); } } /*---------------------------------------------*/ static void testf ( Char *name ) { FILE *inStr; Bool allOK; struct MY_STAT statBuf; deleteOutputOnInterrupt = False; if (name == NULL && srcMode != SM_I2O) panic ( "testf: bad modes\n" ); copyFileName ( outName, (Char*)"(none)" ); switch (srcMode) { case SM_I2O: copyFileName ( inName, (Char*)"(stdin)" ); break; case SM_F2F: copyFileName ( inName, name ); break; case SM_F2O: copyFileName ( inName, name ); break; } if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { if (noisy) fprintf ( stderr, "%s: There are no files matching `%s'.\n", progName, inName ); setExit(1); return; } if ( srcMode != SM_I2O && !fileExists ( inName ) ) { fprintf ( stderr, "%s: Can't open input %s: %s.\n", progName, inName, strerror(errno) ); setExit(1); return; } if ( srcMode != SM_I2O ) { MY_STAT(inName, &statBuf); if ( MY_S_ISDIR(statBuf.st_mode) ) { fprintf( stderr, "%s: Input file %s is a directory.\n", progName,inName); setExit(1); return; } } switch ( srcMode ) { case SM_I2O: if ( isatty ( fileno ( stdin ) ) ) { fprintf ( stderr, "%s: I won't read compressed data from a terminal.\n", progName ); fprintf ( stderr, "%s: For help, type: `%s --help'.\n", progName, progName ); setExit(1); return; }; inStr = stdin; break; case SM_F2O: case SM_F2F: inStr = fopen ( inName, "rb" ); if ( inStr == NULL ) { fprintf ( stderr, "%s: Can't open input file %s:%s.\n", progName, inName, strerror(errno) ); setExit(1); return; }; break; default: panic ( "testf: bad srcMode" ); break; } if (verbosity >= 1) { fprintf ( stderr, " %s: ", inName ); pad ( inName ); fflush ( stderr ); } /*--- Now the input handle is sane. Do the Biz. ---*/ outputHandleJustInCase = NULL; allOK = testStream ( inStr ); if (allOK && verbosity >= 1) fprintf ( stderr, "ok\n" ); if (!allOK) testFailsExist = True; } /*---------------------------------------------*/ static void license ( void ) { fprintf ( stderr, "bzip2, a block-sorting file compressor. " "Version %s.\n" " \n" " Copyright (C) 1996-2010 by Julian Seward.\n" " \n" " This program is free software; you can redistribute it and/or modify\n" " it under the terms set out in the LICENSE file, which is included\n" " in the bzip2-1.0.6 source distribution.\n" " \n" " This program is distributed in the hope that it will be useful,\n" " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " LICENSE file for more details.\n" " \n", BZ2_bzlibVersion() ); } /*---------------------------------------------*/ static void usage ( Char *fullProgName ) { fprintf ( stderr, "bzip2, a block-sorting file compressor. " "Version %s.\n" "\n usage: %s [flags and input files in any order]\n" "\n" " -h --help print this message\n" " -d --decompress force decompression\n" " -z --compress force compression\n" " -k --keep keep (don't delete) input files\n" " -f --force overwrite existing output files\n" " -t --test test compressed file integrity\n" " -c --stdout output to standard out\n" " -q --quiet suppress noncritical error messages\n" " -v --verbose be verbose (a 2nd -v gives more)\n" " -L --license display software version & license\n" " -V --version display software version & license\n" " -s --small use less memory (at most 2500k)\n" " -1 .. -9 set block size to 100k .. 900k\n" " --fast alias for -1\n" " --best alias for -9\n" "\n" " If invoked as `bzip2', default action is to compress.\n" " as `bunzip2', default action is to decompress.\n" " as `bzcat', default action is to decompress to stdout.\n" "\n" " If no file names are given, bzip2 compresses or decompresses\n" " from standard input to standard output. You can combine\n" " short flags, so `-v -4' means the same as -v4 or -4v, &c.\n" # if BZ_UNIX "\n" # endif , BZ2_bzlibVersion(), fullProgName ); } /*---------------------------------------------*/ static void redundant ( Char* flag ) { fprintf ( stderr, "%s: %s is redundant in versions 0.9.5 and above\n", progName, flag ); } /*---------------------------------------------*/ /*-- All the garbage from here to main() is purely to implement a linked list of command-line arguments, into which main() copies argv[1 .. argc-1]. The purpose of this exercise is to facilitate the expansion of wildcard characters * and ? in filenames for OSs which don't know how to do it themselves, like MSDOS, Windows 95 and NT. The actual Dirty Work is done by the platform- specific macro APPEND_FILESPEC. --*/ typedef struct zzzz { Char *name; struct zzzz *link; } Cell; /*---------------------------------------------*/ static void *myMalloc ( Int32 n ) { void* p; p = malloc ( (size_t)n ); if (p == NULL) outOfMemory (); return p; } /*---------------------------------------------*/ static Cell *mkCell ( void ) { Cell *c; c = (Cell*) myMalloc ( sizeof ( Cell ) ); c->name = NULL; c->link = NULL; return c; } /*---------------------------------------------*/ static Cell *snocString ( Cell *root, Char *name ) { if (root == NULL) { Cell *tmp = mkCell(); tmp->name = (Char*) myMalloc ( 5 + strlen(name) ); strcpy ( tmp->name, name ); return tmp; } else { Cell *tmp = root; while (tmp->link != NULL) tmp = tmp->link; tmp->link = snocString ( tmp->link, name ); return root; } } /*---------------------------------------------*/ static void addFlagsFromEnvVar ( Cell** argList, Char* varName ) { Int32 i, j, k; Char *envbase, *p; envbase = getenv(varName); if (envbase != NULL) { p = envbase; i = 0; while (True) { if (p[i] == 0) break; p += i; i = 0; while (isspace((Int32)(p[0]))) p++; while (p[i] != 0 && !isspace((Int32)(p[i]))) i++; if (i > 0) { k = i; if (k > FILE_NAME_LEN-10) k = FILE_NAME_LEN-10; for (j = 0; j < k; j++) tmpName[j] = p[j]; tmpName[k] = 0; APPEND_FLAG(*argList, tmpName); } } } } /*---------------------------------------------*/ #define ISFLAG(s) (strcmp(aa->name, (s))==0) IntNative main ( IntNative argc, Char *argv[] ) { Int32 i, j; Char *tmp; Cell *argList; Cell *aa; Bool decode; /*-- Be really really really paranoid :-) --*/ if (sizeof(Int32) != 4 || sizeof(UInt32) != 4 || sizeof(Int16) != 2 || sizeof(UInt16) != 2 || sizeof(Char) != 1 || sizeof(UChar) != 1) configError(); /*-- Initialise --*/ outputHandleJustInCase = NULL; smallMode = False; keepInputFiles = False; forceOverwrite = False; noisy = True; verbosity = 0; blockSize100k = 9; testFailsExist = False; unzFailsExist = False; numFileNames = 0; numFilesProcessed = 0; workFactor = 30; deleteOutputOnInterrupt = False; exitValue = 0; i = j = 0; /* avoid bogus warning from egcs-1.1.X */ /*-- Set up signal handlers for mem access errors --*/ signal (SIGSEGV, mySIGSEGVorSIGBUScatcher); # if BZ_UNIX # ifndef __DJGPP__ signal (SIGBUS, mySIGSEGVorSIGBUScatcher); # endif # endif copyFileName ( inName, (Char*)"(none)" ); copyFileName ( outName, (Char*)"(none)" ); copyFileName ( progNameReally, argv[0] ); progName = &progNameReally[0]; for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++) if (*tmp == PATH_SEP) progName = tmp + 1; /*-- Copy flags from env var BZIP2, and expand filename wildcards in arg list. --*/ argList = NULL; addFlagsFromEnvVar ( &argList, (Char*)"BZIP2" ); addFlagsFromEnvVar ( &argList, (Char*)"BZIP" ); for (i = 1; i <= argc-1; i++) APPEND_FILESPEC(argList, argv[i]); /*-- Find the length of the longest filename --*/ longestFileName = 7; numFileNames = 0; decode = True; for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) { decode = False; continue; } if (aa->name[0] == '-' && decode) continue; numFileNames++; if (longestFileName < (Int32)strlen(aa->name) ) longestFileName = (Int32)strlen(aa->name); } /*-- Determine source modes; flag handling may change this too. --*/ if (numFileNames == 0) srcMode = SM_I2O; else srcMode = SM_F2F; /*-- Determine what to do (compress/uncompress/test/cat). --*/ /*-- Note that subsequent flag handling may change this. --*/ opMode = OM_Z; if ( (strstr ( progName, "unzip" ) != 0) || (strstr ( progName, "UNZIP" ) != 0) ) opMode = OM_UNZ; if ( (strstr ( progName, "z2cat" ) != 0) || (strstr ( progName, "Z2CAT" ) != 0) || (strstr ( progName, "zcat" ) != 0) || (strstr ( progName, "ZCAT" ) != 0) ) { opMode = OM_UNZ; srcMode = (numFileNames == 0) ? SM_I2O : SM_F2O; } /*-- Look at the flags. --*/ for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) break; if (aa->name[0] == '-' && aa->name[1] != '-') { for (j = 1; aa->name[j] != '\0'; j++) { switch (aa->name[j]) { case 'c': srcMode = SM_F2O; break; case 'd': opMode = OM_UNZ; break; case 'z': opMode = OM_Z; break; case 'f': forceOverwrite = True; break; case 't': opMode = OM_TEST; break; case 'k': keepInputFiles = True; break; case 's': smallMode = True; break; case 'q': noisy = False; break; case '1': blockSize100k = 1; break; case '2': blockSize100k = 2; break; case '3': blockSize100k = 3; break; case '4': blockSize100k = 4; break; case '5': blockSize100k = 5; break; case '6': blockSize100k = 6; break; case '7': blockSize100k = 7; break; case '8': blockSize100k = 8; break; case '9': blockSize100k = 9; break; case 'V': case 'L': license(); break; case 'v': verbosity++; break; case 'h': usage ( progName ); exit ( 0 ); break; default: fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name ); usage ( progName ); exit ( 1 ); break; } } } } /*-- And again ... --*/ for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) break; if (ISFLAG("--stdout")) srcMode = SM_F2O; else if (ISFLAG("--decompress")) opMode = OM_UNZ; else if (ISFLAG("--compress")) opMode = OM_Z; else if (ISFLAG("--force")) forceOverwrite = True; else if (ISFLAG("--test")) opMode = OM_TEST; else if (ISFLAG("--keep")) keepInputFiles = True; else if (ISFLAG("--small")) smallMode = True; else if (ISFLAG("--quiet")) noisy = False; else if (ISFLAG("--version")) license(); else if (ISFLAG("--license")) license(); else if (ISFLAG("--exponential")) workFactor = 1; else if (ISFLAG("--repetitive-best")) redundant(aa->name); else if (ISFLAG("--repetitive-fast")) redundant(aa->name); else if (ISFLAG("--fast")) blockSize100k = 1; else if (ISFLAG("--best")) blockSize100k = 9; else if (ISFLAG("--verbose")) verbosity++; else if (ISFLAG("--help")) { usage ( progName ); exit ( 0 ); } else if (strncmp ( aa->name, "--", 2) == 0) { fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name ); usage ( progName ); exit ( 1 ); } } if (verbosity > 4) verbosity = 4; if (opMode == OM_Z && smallMode && blockSize100k > 2) blockSize100k = 2; if (opMode == OM_TEST && srcMode == SM_F2O) { fprintf ( stderr, "%s: -c and -t cannot be used together.\n", progName ); exit ( 1 ); } if (srcMode == SM_F2O && numFileNames == 0) srcMode = SM_I2O; if (opMode != OM_Z) blockSize100k = 0; if (srcMode == SM_F2F) { signal (SIGINT, mySignalCatcher); signal (SIGTERM, mySignalCatcher); # if BZ_UNIX signal (SIGHUP, mySignalCatcher); # endif } if (opMode == OM_Z) { if (srcMode == SM_I2O) { compress ( NULL ); } else { decode = True; for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) { decode = False; continue; } if (aa->name[0] == '-' && decode) continue; numFilesProcessed++; compress ( aa->name ); } } } else if (opMode == OM_UNZ) { unzFailsExist = False; if (srcMode == SM_I2O) { uncompress ( NULL ); } else { decode = True; for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) { decode = False; continue; } if (aa->name[0] == '-' && decode) continue; numFilesProcessed++; uncompress ( aa->name ); } } if (unzFailsExist) { setExit(2); exit(exitValue); } } else { testFailsExist = False; if (srcMode == SM_I2O) { testf ( NULL ); } else { decode = True; for (aa = argList; aa != NULL; aa = aa->link) { if (ISFLAG("--")) { decode = False; continue; } if (aa->name[0] == '-' && decode) continue; numFilesProcessed++; testf ( aa->name ); } } if (testFailsExist && noisy) { fprintf ( stderr, "\n" "You can use the `bzip2recover' program to attempt to recover\n" "data from undamaged sections of corrupted files.\n\n" ); setExit(2); exit(exitValue); } } /* Free the argument list memory to mollify leak detectors (eg) Purify, Checker. Serves no other useful purpose. */ aa = argList; while (aa != NULL) { Cell* aa2 = aa->link; if (aa->name != NULL) free(aa->name); free(aa); aa = aa2; } return exitValue; } /*-----------------------------------------------------------*/ /*--- end bzip2.c ---*/ /*-----------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/bzip2.proj000066400000000000000000000003441462133141200214310ustar00rootroot00000000000000LIB(CONFIG_BZLIB) bzlib { EXPINCLUDE . SOURCE bzlib.c SOURCE crctable.c SOURCE decompress.c SOURCE compress.c SOURCE randtable.c SOURCE huffman.c SOURCE blocksort.c HEADER bzlib.h HEADER bzlib_private.h } bcmatroska2-5.3.101/libmatroska2/bzip2/bzip2.txt000066400000000000000000000450541462133141200213050ustar00rootroot00000000000000 NAME bzip2, bunzip2 - a block-sorting file compressor, v1.0.6 bzcat - decompresses files to stdout bzip2recover - recovers data from damaged bzip2 files SYNOPSIS bzip2 [ -cdfkqstvzVL123456789 ] [ filenames ... ] bunzip2 [ -fkvsVL ] [ filenames ... ] bzcat [ -s ] [ filenames ... ] bzip2recover filename DESCRIPTION bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding. Compression is generally considerably better than that achieved by more conventional LZ77/LZ78-based compressors, and approaches the performance of the PPM family of sta- tistical compressors. The command-line options are deliberately very similar to those of GNU gzip, but they are not identical. bzip2 expects a list of file names to accompany the com- mand-line flags. Each file is replaced by a compressed version of itself, with the name "original_name.bz2". Each compressed file has the same modification date, per- missions, and, when possible, ownership as the correspond- ing original, so that these properties can be correctly restored at decompression time. File name handling is naive in the sense that there is no mechanism for preserv- ing original file names, permissions, ownerships or dates in filesystems which lack these concepts, or have serious file name length restrictions, such as MS-DOS. bzip2 and bunzip2 will by default not overwrite existing files. If you want this to happen, specify the -f flag. If no file names are specified, bzip2 compresses from standard input to standard output. In this case, bzip2 will decline to write compressed output to a terminal, as this would be entirely incomprehensible and therefore pointless. bunzip2 (or bzip2 -d) decompresses all specified files. Files which were not created by bzip2 will be detected and ignored, and a warning issued. bzip2 attempts to guess the filename for the decompressed file from that of the compressed file as follows: filename.bz2 becomes filename filename.bz becomes filename filename.tbz2 becomes filename.tar filename.tbz becomes filename.tar anyothername becomes anyothername.out If the file does not end in one of the recognised endings, .bz2, .bz, .tbz2 or .tbz, bzip2 complains that it cannot guess the name of the original file, and uses the original name with .out appended. As with compression, supplying no filenames causes decom- pression from standard input to standard output. bunzip2 will correctly decompress a file which is the con- catenation of two or more compressed files. The result is the concatenation of the corresponding uncompressed files. Integrity testing (-t) of concatenated compressed files is also supported. You can also compress or decompress files to the standard output by giving the -c flag. Multiple files may be com- pressed and decompressed like this. The resulting outputs are fed sequentially to stdout. Compression of multiple files in this manner generates a stream containing multi- ple compressed file representations. Such a stream can be decompressed correctly only by bzip2 version 0.9.0 or later. Earlier versions of bzip2 will stop after decom- pressing the first file in the stream. bzcat (or bzip2 -dc) decompresses all specified files to the standard output. bzip2 will read arguments from the environment variables BZIP2 and BZIP, in that order, and will process them before any arguments read from the command line. This gives a convenient way to supply default arguments. Compression is always performed, even if the compressed file is slightly larger than the original. Files of less than about one hundred bytes tend to get larger, since the compression mechanism has a constant overhead in the region of 50 bytes. Random data (including the output of most file compressors) is coded at about 8.05 bits per byte, giving an expansion of around 0.5%. As a self-check for your protection, bzip2 uses 32-bit CRCs to make sure that the decompressed version of a file is identical to the original. This guards against corrup- tion of the compressed data, and against undetected bugs in bzip2 (hopefully very unlikely). The chances of data corruption going undetected is microscopic, about one chance in four billion for each file processed. Be aware, though, that the check occurs upon decompression, so it can only tell you that something is wrong. It can't help you recover the original uncompressed data. You can use bzip2recover to try to recover data from damaged files. Return values: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, &c), 2 to indicate a corrupt compressed file, 3 for an internal consistency error (eg, bug) which caused bzip2 to panic. OPTIONS -c --stdout Compress or decompress to standard output. -d --decompress Force decompression. bzip2, bunzip2 and bzcat are really the same program, and the decision about what actions to take is done on the basis of which name is used. This flag overrides that mechanism, and forces bzip2 to decompress. -z --compress The complement to -d: forces compression, regardless of the invocation name. -t --test Check integrity of the specified file(s), but don't decompress them. This really performs a trial decompression and throws away the result. -f --force Force overwrite of output files. Normally, bzip2 will not overwrite existing output files. Also forces bzip2 to break hard links to files, which it otherwise wouldn't do. bzip2 normally declines to decompress files which don't have the correct magic header bytes. If forced (-f), however, it will pass such files through unmodified. This is how GNU gzip behaves. -k --keep Keep (don't delete) input files during compression or decompression. -s --small Reduce memory usage, for compression, decompression and testing. Files are decompressed and tested using a modified algorithm which only requires 2.5 bytes per block byte. This means any file can be decompressed in 2300k of memory, albeit at about half the normal speed. During compression, -s selects a block size of 200k, which limits memory use to around the same figure, at the expense of your compression ratio. In short, if your machine is low on memory (8 megabytes or less), use -s for everything. See MEMORY MANAGEMENT below. -q --quiet Suppress non-essential warning messages. Messages pertaining to I/O errors and other critical events will not be suppressed. -v --verbose Verbose mode -- show the compression ratio for each file processed. Further -v's increase the ver- bosity level, spewing out lots of information which is primarily of interest for diagnostic purposes. -L --license -V --version Display the software version, license terms and conditions. -1 (or --fast) to -9 (or --best) Set the block size to 100 k, 200 k .. 900 k when compressing. Has no effect when decompressing. See MEMORY MANAGEMENT below. The --fast and --best aliases are primarily for GNU gzip compatibility. In particular, --fast doesn't make things signifi- cantly faster. And --best merely selects the default behaviour. -- Treats all subsequent arguments as file names, even if they start with a dash. This is so you can han- dle files with names beginning with a dash, for example: bzip2 -- -myfilename. --repetitive-fast --repetitive-best These flags are redundant in versions 0.9.5 and above. They provided some coarse control over the behaviour of the sorting algorithm in earlier ver- sions, which was sometimes useful. 0.9.5 and above have an improved algorithm which renders these flags irrelevant. MEMORY MANAGEMENT bzip2 compresses large files in blocks. The block size affects both the compression ratio achieved, and the amount of memory needed for compression and decompression. The flags -1 through -9 specify the block size to be 100,000 bytes through 900,000 bytes (the default) respec- tively. At decompression time, the block size used for compression is read from the header of the compressed file, and bunzip2 then allocates itself just enough memory to decompress the file. Since block sizes are stored in compressed files, it follows that the flags -1 to -9 are irrelevant to and so ignored during decompression. Compression and decompression requirements, in bytes, can be estimated as: Compression: 400k + ( 8 x block size ) Decompression: 100k + ( 4 x block size ), or 100k + ( 2.5 x block size ) Larger block sizes give rapidly diminishing marginal returns. Most of the compression comes from the first two or three hundred k of block size, a fact worth bearing in mind when using bzip2 on small machines. It is also important to appreciate that the decompression memory requirement is set at compression time by the choice of block size. For files compressed with the default 900k block size, bunzip2 will require about 3700 kbytes to decompress. To support decompression of any file on a 4 megabyte machine, bunzip2 has an option to decompress using approximately half this amount of memory, about 2300 kbytes. Decompres- sion speed is also halved, so you should use this option only where necessary. The relevant flag is -s. In general, try and use the largest block size memory con- straints allow, since that maximises the compression achieved. Compression and decompression speed are virtu- ally unaffected by block size. Another significant point applies to files which fit in a single block -- that means most files you'd encounter using a large block size. The amount of real memory touched is proportional to the size of the file, since the file is smaller than a block. For example, compressing a file 20,000 bytes long with the flag -9 will cause the compressor to allocate around 7600k of memory, but only touch 400k + 20000 * 8 = 560 kbytes of it. Similarly, the decompressor will allocate 3700k but only touch 100k + 20000 * 4 = 180 kbytes. Here is a table which summarises the maximum memory usage for different block sizes. Also recorded is the total compressed size for 14 files of the Calgary Text Compres- sion Corpus totalling 3,141,622 bytes. This column gives some feel for how compression varies with block size. These figures tend to understate the advantage of larger block sizes for larger files, since the Corpus is domi- nated by smaller files. Compress Decompress Decompress Corpus Flag usage usage -s usage Size -1 1200k 500k 350k 914704 -2 2000k 900k 600k 877703 -3 2800k 1300k 850k 860338 -4 3600k 1700k 1100k 846899 -5 4400k 2100k 1350k 845160 -6 5200k 2500k 1600k 838626 -7 6100k 2900k 1850k 834096 -8 6800k 3300k 2100k 828642 -9 7600k 3700k 2350k 828642 RECOVERING DATA FROM DAMAGED FILES bzip2 compresses files in blocks, usually 900kbytes long. Each block is handled independently. If a media or trans- mission error causes a multi-block .bz2 file to become damaged, it may be possible to recover data from the undamaged blocks in the file. The compressed representation of each block is delimited by a 48-bit pattern, which makes it possible to find the block boundaries with reasonable certainty. Each block also carries its own 32-bit CRC, so damaged blocks can be distinguished from undamaged ones. bzip2recover is a simple program whose purpose is to search for blocks in .bz2 files, and write each block out into its own .bz2 file. You can then use bzip2 -t to test the integrity of the resulting files, and decompress those which are undamaged. bzip2recover takes a single argument, the name of the dam- aged file, and writes a number of files "rec00001file.bz2", "rec00002file.bz2", etc, containing the extracted blocks. The output filenames are designed so that the use of wildcards in subsequent pro- cessing -- for example, "bzip2 -dc rec*file.bz2 > recov- ered_data" -- processes the files in the correct order. bzip2recover should be of most use dealing with large .bz2 files, as these will contain many blocks. It is clearly futile to use it on damaged single-block files, since a damaged block cannot be recovered. If you wish to min- imise any potential data loss through media or transmis- sion errors, you might consider compressing with a smaller block size. PERFORMANCE NOTES The sorting phase of compression gathers together similar strings in the file. Because of this, files containing very long runs of repeated symbols, like "aabaabaabaab ..." (repeated several hundred times) may compress more slowly than normal. Versions 0.9.5 and above fare much better than previous versions in this respect. The ratio between worst-case and average-case compression time is in the region of 10:1. For previous versions, this figure was more like 100:1. You can use the -vvvv option to mon- itor progress in great detail, if you want. Decompression speed is unaffected by these phenomena. bzip2 usually allocates several megabytes of memory to operate in, and then charges all over it in a fairly ran- dom fashion. This means that performance, both for com- pressing and decompressing, is largely determined by the speed at which your machine can service cache misses. Because of this, small changes to the code to reduce the miss rate have been observed to give disproportionately large performance improvements. I imagine bzip2 will per- form best on machines with very large caches. CAVEATS I/O error messages are not as helpful as they could be. bzip2 tries hard to detect I/O errors and exit cleanly, but the details of what the problem is sometimes seem rather misleading. This manual page pertains to version 1.0.6 of bzip2. Com- pressed data created by this version is entirely forwards and backwards compatible with the previous public releases, versions 0.1pl2, 0.9.0, 0.9.5, 1.0.0, 1.0.1, 1.0.2 and above, but with the following exception: 0.9.0 and above can correctly decompress multiple concatenated compressed files. 0.1pl2 cannot do this; it will stop after decompressing just the first file in the stream. bzip2recover versions prior to 1.0.2 used 32-bit integers to represent bit positions in compressed files, so they could not handle compressed files more than 512 megabytes long. Versions 1.0.2 and above use 64-bit ints on some platforms which support them (GNU supported targets, and Windows). To establish whether or not bzip2recover was built with such a limitation, run it without arguments. In any event you can build yourself an unlimited version if you can recompile it with MaybeUInt64 set to be an unsigned 64-bit integer. AUTHOR Julian Seward, jsewardbzip.org. http://www.bzip.org The ideas embodied in bzip2 are due to (at least) the fol- lowing people: Michael Burrows and David Wheeler (for the block sorting transformation), David Wheeler (again, for the Huffman coder), Peter Fenwick (for the structured cod- ing model in the original bzip, and many refinements), and Alistair Moffat, Radford Neal and Ian Witten (for the arithmetic coder in the original bzip). I am much indebted for their help, support and advice. See the man- ual in the source distribution for pointers to sources of documentation. Christian von Roques encouraged me to look for faster sorting algorithms, so as to speed up compres- sion. Bela Lubkin encouraged me to improve the worst-case compression performance. Donna Robinson XMLised the docu- mentation. The bz* scripts are derived from those of GNU gzip. Many people sent patches, helped with portability problems, lent machines, gave advice and were generally helpful. bcmatroska2-5.3.101/libmatroska2/bzip2/bzip2recover.c000066400000000000000000000351141462133141200222720ustar00rootroot00000000000000/*-----------------------------------------------------------*/ /*--- Block recoverer program for bzip2 ---*/ /*--- bzip2recover.c ---*/ /*-----------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ /* This program is a complete hack and should be rewritten properly. It isn't very complicated. */ #include #include #include #include /* This program records bit locations in the file to be recovered. That means that if 64-bit ints are not supported, we will not be able to recover .bz2 files over 512MB (2^32 bits) long. On GNU supported platforms, we take advantage of the 64-bit int support to circumvent this problem. Ditto MSVC. This change occurred in version 1.0.2; all prior versions have the 512MB limitation. */ #ifdef __GNUC__ typedef unsigned long long int MaybeUInt64; # define MaybeUInt64_FMT "%Lu" #else #ifdef _MSC_VER typedef unsigned __int64 MaybeUInt64; # define MaybeUInt64_FMT "%I64u" #else typedef unsigned int MaybeUInt64; # define MaybeUInt64_FMT "%u" #endif #endif typedef unsigned int UInt32; typedef int Int32; typedef unsigned char UChar; typedef char Char; typedef unsigned char Bool; #define True ((Bool)1) #define False ((Bool)0) #define BZ_MAX_FILENAME 2000 Char inFileName[BZ_MAX_FILENAME]; Char outFileName[BZ_MAX_FILENAME]; Char progName[BZ_MAX_FILENAME]; MaybeUInt64 bytesOut = 0; MaybeUInt64 bytesIn = 0; /*---------------------------------------------------*/ /*--- Header bytes ---*/ /*---------------------------------------------------*/ #define BZ_HDR_B 0x42 /* 'B' */ #define BZ_HDR_Z 0x5a /* 'Z' */ #define BZ_HDR_h 0x68 /* 'h' */ #define BZ_HDR_0 0x30 /* '0' */ /*---------------------------------------------------*/ /*--- I/O errors ---*/ /*---------------------------------------------------*/ /*---------------------------------------------*/ static void readError ( void ) { fprintf ( stderr, "%s: I/O error reading `%s', possible reason follows.\n", progName, inFileName ); perror ( progName ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void writeError ( void ) { fprintf ( stderr, "%s: I/O error reading `%s', possible reason follows.\n", progName, inFileName ); perror ( progName ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void mallocFail ( Int32 n ) { fprintf ( stderr, "%s: malloc failed on request for %d bytes.\n", progName, n ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void tooManyBlocks ( Int32 max_handled_blocks ) { fprintf ( stderr, "%s: `%s' appears to contain more than %d blocks\n", progName, inFileName, max_handled_blocks ); fprintf ( stderr, "%s: and cannot be handled. To fix, increase\n", progName ); fprintf ( stderr, "%s: BZ_MAX_HANDLED_BLOCKS in bzip2recover.c, and recompile.\n", progName ); exit ( 1 ); } /*---------------------------------------------------*/ /*--- Bit stream I/O ---*/ /*---------------------------------------------------*/ typedef struct { FILE* handle; Int32 buffer; Int32 buffLive; Char mode; } BitStream; /*---------------------------------------------*/ static BitStream* bsOpenReadStream ( FILE* stream ) { BitStream *bs = malloc ( sizeof(BitStream) ); if (bs == NULL) mallocFail ( sizeof(BitStream) ); bs->handle = stream; bs->buffer = 0; bs->buffLive = 0; bs->mode = 'r'; return bs; } /*---------------------------------------------*/ static BitStream* bsOpenWriteStream ( FILE* stream ) { BitStream *bs = malloc ( sizeof(BitStream) ); if (bs == NULL) mallocFail ( sizeof(BitStream) ); bs->handle = stream; bs->buffer = 0; bs->buffLive = 0; bs->mode = 'w'; return bs; } /*---------------------------------------------*/ static void bsPutBit ( BitStream* bs, Int32 bit ) { if (bs->buffLive == 8) { Int32 retVal = putc ( (UChar) bs->buffer, bs->handle ); if (retVal == EOF) writeError(); bytesOut++; bs->buffLive = 1; bs->buffer = bit & 0x1; } else { bs->buffer = ( (bs->buffer << 1) | (bit & 0x1) ); bs->buffLive++; }; } /*---------------------------------------------*/ /*-- Returns 0 or 1, or 2 to indicate EOF. --*/ static Int32 bsGetBit ( BitStream* bs ) { if (bs->buffLive > 0) { bs->buffLive --; return ( ((bs->buffer) >> (bs->buffLive)) & 0x1 ); } else { Int32 retVal = getc ( bs->handle ); if ( retVal == EOF ) { if (errno != 0) readError(); return 2; } bs->buffLive = 7; bs->buffer = retVal; return ( ((bs->buffer) >> 7) & 0x1 ); } } /*---------------------------------------------*/ static void bsClose ( BitStream* bs ) { Int32 retVal; if ( bs->mode == 'w' ) { while ( bs->buffLive < 8 ) { bs->buffLive++; bs->buffer <<= 1; }; retVal = putc ( (UChar) (bs->buffer), bs->handle ); if (retVal == EOF) writeError(); bytesOut++; retVal = fflush ( bs->handle ); if (retVal == EOF) writeError(); } retVal = fclose ( bs->handle ); if (retVal == EOF) { if (bs->mode == 'w') writeError(); else readError(); } free ( bs ); } /*---------------------------------------------*/ static void bsPutUChar ( BitStream* bs, UChar c ) { Int32 i; for (i = 7; i >= 0; i--) bsPutBit ( bs, (((UInt32) c) >> i) & 0x1 ); } /*---------------------------------------------*/ static void bsPutUInt32 ( BitStream* bs, UInt32 c ) { Int32 i; for (i = 31; i >= 0; i--) bsPutBit ( bs, (c >> i) & 0x1 ); } /*---------------------------------------------*/ static Bool endsInBz2 ( Char* name ) { Int32 n = strlen ( name ); if (n <= 4) return False; return (name[n-4] == '.' && name[n-3] == 'b' && name[n-2] == 'z' && name[n-1] == '2'); } /*---------------------------------------------------*/ /*--- ---*/ /*---------------------------------------------------*/ /* This logic isn't really right when it comes to Cygwin. */ #ifdef _WIN32 # define BZ_SPLIT_SYM '\\' /* path splitter on Windows platform */ #else # define BZ_SPLIT_SYM '/' /* path splitter on Unix platform */ #endif #define BLOCK_HEADER_HI 0x00003141UL #define BLOCK_HEADER_LO 0x59265359UL #define BLOCK_ENDMARK_HI 0x00001772UL #define BLOCK_ENDMARK_LO 0x45385090UL /* Increase if necessary. However, a .bz2 file with > 50000 blocks would have an uncompressed size of at least 40GB, so the chances are low you'll need to up this. */ #define BZ_MAX_HANDLED_BLOCKS 50000 MaybeUInt64 bStart [BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 bEnd [BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 rbStart[BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 rbEnd [BZ_MAX_HANDLED_BLOCKS]; Int32 main ( Int32 argc, Char** argv ) { FILE* inFile; FILE* outFile; BitStream* bsIn, *bsWr; Int32 b, wrBlock, currBlock, rbCtr; MaybeUInt64 bitsRead; UInt32 buffHi, buffLo, blockCRC; Char* p; strcpy ( progName, argv[0] ); inFileName[0] = outFileName[0] = 0; fprintf ( stderr, "bzip2recover 1.0.6: extracts blocks from damaged .bz2 files.\n" ); if (argc != 2) { fprintf ( stderr, "%s: usage is `%s damaged_file_name'.\n", progName, progName ); switch (sizeof(MaybeUInt64)) { case 8: fprintf(stderr, "\trestrictions on size of recovered file: None\n"); break; case 4: fprintf(stderr, "\trestrictions on size of recovered file: 512 MB\n"); fprintf(stderr, "\tto circumvent, recompile with MaybeUInt64 as an\n" "\tunsigned 64-bit int.\n"); break; default: fprintf(stderr, "\tsizeof(MaybeUInt64) is not 4 or 8 -- " "configuration error.\n"); break; } exit(1); } if (strlen(argv[1]) >= BZ_MAX_FILENAME-20) { fprintf ( stderr, "%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n", progName, (int)strlen(argv[1]) ); exit(1); } strcpy ( inFileName, argv[1] ); inFile = fopen ( inFileName, "rb" ); if (inFile == NULL) { fprintf ( stderr, "%s: can't read `%s'\n", progName, inFileName ); exit(1); } bsIn = bsOpenReadStream ( inFile ); fprintf ( stderr, "%s: searching for block boundaries ...\n", progName ); bitsRead = 0; buffHi = buffLo = 0; currBlock = 0; bStart[currBlock] = 0; rbCtr = 0; while (True) { b = bsGetBit ( bsIn ); bitsRead++; if (b == 2) { if (bitsRead >= bStart[currBlock] && (bitsRead - bStart[currBlock]) >= 40) { bEnd[currBlock] = bitsRead-1; if (currBlock > 0) fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT " to " MaybeUInt64_FMT " (incomplete)\n", currBlock, bStart[currBlock], bEnd[currBlock] ); } else currBlock--; break; } buffHi = (buffHi << 1) | (buffLo >> 31); buffLo = (buffLo << 1) | (b & 1); if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI && buffLo == BLOCK_HEADER_LO) || ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI && buffLo == BLOCK_ENDMARK_LO) ) { if (bitsRead > 49) { bEnd[currBlock] = bitsRead-49; } else { bEnd[currBlock] = 0; } if (currBlock > 0 && (bEnd[currBlock] - bStart[currBlock]) >= 130) { fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT " to " MaybeUInt64_FMT "\n", rbCtr+1, bStart[currBlock], bEnd[currBlock] ); rbStart[rbCtr] = bStart[currBlock]; rbEnd[rbCtr] = bEnd[currBlock]; rbCtr++; } if (currBlock >= BZ_MAX_HANDLED_BLOCKS) tooManyBlocks(BZ_MAX_HANDLED_BLOCKS); currBlock++; bStart[currBlock] = bitsRead; } } bsClose ( bsIn ); /*-- identified blocks run from 1 to rbCtr inclusive. --*/ if (rbCtr < 1) { fprintf ( stderr, "%s: sorry, I couldn't find any block boundaries.\n", progName ); exit(1); }; fprintf ( stderr, "%s: splitting into blocks\n", progName ); inFile = fopen ( inFileName, "rb" ); if (inFile == NULL) { fprintf ( stderr, "%s: can't open `%s'\n", progName, inFileName ); exit(1); } bsIn = bsOpenReadStream ( inFile ); /*-- placate gcc's dataflow analyser --*/ blockCRC = 0; bsWr = 0; bitsRead = 0; outFile = NULL; wrBlock = 0; while (True) { b = bsGetBit(bsIn); if (b == 2) break; buffHi = (buffHi << 1) | (buffLo >> 31); buffLo = (buffLo << 1) | (b & 1); if (bitsRead == 47+rbStart[wrBlock]) blockCRC = (buffHi << 16) | (buffLo >> 16); if (outFile != NULL && bitsRead >= rbStart[wrBlock] && bitsRead <= rbEnd[wrBlock]) { bsPutBit ( bsWr, b ); } bitsRead++; if (bitsRead == rbEnd[wrBlock]+1) { if (outFile != NULL) { bsPutUChar ( bsWr, 0x17 ); bsPutUChar ( bsWr, 0x72 ); bsPutUChar ( bsWr, 0x45 ); bsPutUChar ( bsWr, 0x38 ); bsPutUChar ( bsWr, 0x50 ); bsPutUChar ( bsWr, 0x90 ); bsPutUInt32 ( bsWr, blockCRC ); bsClose ( bsWr ); } if (wrBlock >= rbCtr) break; wrBlock++; } else if (bitsRead == rbStart[wrBlock]) { /* Create the output file name, correctly handling leading paths. (31.10.2001 by Sergey E. Kusikov) */ Char* split; Int32 ofs, k; for (k = 0; k < BZ_MAX_FILENAME; k++) outFileName[k] = 0; strcpy (outFileName, inFileName); split = strrchr (outFileName, BZ_SPLIT_SYM); if (split == NULL) { split = outFileName; } else { ++split; } /* Now split points to the start of the basename. */ ofs = split - outFileName; sprintf (split, "rec%5d", wrBlock+1); for (p = split; *p != 0; p++) if (*p == ' ') *p = '0'; strcat (outFileName, inFileName + ofs); if ( !endsInBz2(outFileName)) strcat ( outFileName, ".bz2" ); fprintf ( stderr, " writing block %d to `%s' ...\n", wrBlock+1, outFileName ); outFile = fopen ( outFileName, "wb" ); if (outFile == NULL) { fprintf ( stderr, "%s: can't write `%s'\n", progName, outFileName ); exit(1); } bsWr = bsOpenWriteStream ( outFile ); bsPutUChar ( bsWr, BZ_HDR_B ); bsPutUChar ( bsWr, BZ_HDR_Z ); bsPutUChar ( bsWr, BZ_HDR_h ); bsPutUChar ( bsWr, BZ_HDR_0 + 9 ); bsPutUChar ( bsWr, 0x31 ); bsPutUChar ( bsWr, 0x41 ); bsPutUChar ( bsWr, 0x59 ); bsPutUChar ( bsWr, 0x26 ); bsPutUChar ( bsWr, 0x53 ); bsPutUChar ( bsWr, 0x59 ); } } fprintf ( stderr, "%s: finished\n", progName ); return 0; } /*-----------------------------------------------------------*/ /*--- end bzip2recover.c ---*/ /*-----------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/bzlib.c000066400000000000000000001316531462133141200207650ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Library top-level functions. ---*/ /*--- bzlib.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ /* CHANGES 0.9.0 -- original version. 0.9.0a/b -- no changes in this file. 0.9.0c -- made zero-length BZ_FLUSH work correctly in bzCompress(). fixed bzWrite/bzRead to ignore zero-length requests. fixed bzread to correctly handle read requests after EOF. wrong parameter order in call to bzDecompressInit in bzBuffToBuffDecompress. Fixed. */ #include "bzlib_private.h" /*---------------------------------------------------*/ /*--- Compression stuff ---*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ #ifndef BZ_NO_STDIO void BZ2_bz__AssertH__fail ( int errcode ) { fprintf(stderr, "\n\nbzip2/libbzip2: internal error number %d.\n" "This is a bug in bzip2/libbzip2, %s.\n" "Please report it to me at: jseward@bzip.org. If this happened\n" "when you were using some program which uses libbzip2 as a\n" "component, you should also report this bug to the author(s)\n" "of that program. Please make an effort to report this bug;\n" "timely and accurate bug reports eventually lead to higher\n" "quality software. Thanks. Julian Seward, 10 December 2007.\n\n", errcode, BZ2_bzlibVersion() ); if (errcode == 1007) { fprintf(stderr, "\n*** A special note about internal error number 1007 ***\n" "\n" "Experience suggests that a common cause of i.e. 1007\n" "is unreliable memory or other hardware. The 1007 assertion\n" "just happens to cross-check the results of huge numbers of\n" "memory reads/writes, and so acts (unintendedly) as a stress\n" "test of your memory system.\n" "\n" "I suggest the following: try compressing the file again,\n" "possibly monitoring progress in detail with the -vv flag.\n" "\n" "* If the error cannot be reproduced, and/or happens at different\n" " points in compression, you may have a flaky memory system.\n" " Try a memory-test program. I have used Memtest86\n" " (www.memtest86.com). At the time of writing it is free (GPLd).\n" " Memtest86 tests memory much more thorougly than your BIOSs\n" " power-on test, and may find failures that the BIOS doesn't.\n" "\n" "* If the error can be repeatably reproduced, this is a bug in\n" " bzip2, and I would very much like to hear about it. Please\n" " let me know, and, ideally, save a copy of the file causing the\n" " problem -- without which I will be unable to investigate it.\n" "\n" ); } exit(3); } #endif /*---------------------------------------------------*/ static int bz_config_ok ( void ) { if (sizeof(int) != 4) return 0; if (sizeof(short) != 2) return 0; if (sizeof(char) != 1) return 0; return 1; } /*---------------------------------------------------*/ static void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) { void* v = malloc ( items * size ); return v; } static void default_bzfree ( void* opaque, void* addr ) { if (addr != NULL) free ( addr ); } /*---------------------------------------------------*/ static void prepare_new_block ( EState* s ) { Int32 i; s->nblock = 0; s->numZ = 0; s->state_out_pos = 0; BZ_INITIALISE_CRC ( s->blockCRC ); for (i = 0; i < 256; i++) s->inUse[i] = False; s->blockNo++; } /*---------------------------------------------------*/ static void init_RL ( EState* s ) { s->state_in_ch = 256; s->state_in_len = 0; } static Bool isempty_RL ( EState* s ) { if (s->state_in_ch < 256 && s->state_in_len > 0) return False; else return True; } /*---------------------------------------------------*/ int BZ_API(BZ2_bzCompressInit) ( bz_stream* strm, int blockSize100k, int verbosity, int workFactor ) { Int32 n; EState* s; if (!bz_config_ok()) return BZ_CONFIG_ERROR; if (strm == NULL || blockSize100k < 1 || blockSize100k > 9 || workFactor < 0 || workFactor > 250) return BZ_PARAM_ERROR; if (workFactor == 0) workFactor = 30; if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; if (strm->bzfree == NULL) strm->bzfree = default_bzfree; s = BZALLOC( sizeof(EState) ); if (s == NULL) return BZ_MEM_ERROR; s->strm = strm; s->arr1 = NULL; s->arr2 = NULL; s->ftab = NULL; n = 100000 * blockSize100k; s->arr1 = BZALLOC( n * sizeof(UInt32) ); s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) ); s->ftab = BZALLOC( 65537 * sizeof(UInt32) ); if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) { if (s->arr1 != NULL) BZFREE(s->arr1); if (s->arr2 != NULL) BZFREE(s->arr2); if (s->ftab != NULL) BZFREE(s->ftab); if (s != NULL) BZFREE(s); return BZ_MEM_ERROR; } s->blockNo = 0; s->state = BZ_S_INPUT; s->mode = BZ_M_RUNNING; s->combinedCRC = 0; s->blockSize100k = blockSize100k; s->nblockMAX = 100000 * blockSize100k - 19; s->verbosity = verbosity; s->workFactor = workFactor; s->block = (UChar*)s->arr2; s->mtfv = (UInt16*)s->arr1; s->zbits = NULL; s->ptr = (UInt32*)s->arr1; strm->state = s; strm->total_in_lo32 = 0; strm->total_in_hi32 = 0; strm->total_out_lo32 = 0; strm->total_out_hi32 = 0; init_RL ( s ); prepare_new_block ( s ); return BZ_OK; } /*---------------------------------------------------*/ static void add_pair_to_block ( EState* s ) { Int32 i; UChar ch = (UChar)(s->state_in_ch); for (i = 0; i < s->state_in_len; i++) { BZ_UPDATE_CRC( s->blockCRC, ch ); } s->inUse[s->state_in_ch] = True; switch (s->state_in_len) { case 1: s->block[s->nblock] = (UChar)ch; s->nblock++; break; case 2: s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; break; case 3: s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; break; default: s->inUse[s->state_in_len-4] = True; s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = (UChar)ch; s->nblock++; s->block[s->nblock] = ((UChar)(s->state_in_len-4)); s->nblock++; break; } } /*---------------------------------------------------*/ static void flush_RL ( EState* s ) { if (s->state_in_ch < 256) add_pair_to_block ( s ); init_RL ( s ); } /*---------------------------------------------------*/ #define ADD_CHAR_TO_BLOCK(zs,zchh0) \ { \ UInt32 zchh = (UInt32)(zchh0); \ /*-- fast track the common case --*/ \ if (zchh != zs->state_in_ch && \ zs->state_in_len == 1) { \ UChar ch = (UChar)(zs->state_in_ch); \ BZ_UPDATE_CRC( zs->blockCRC, ch ); \ zs->inUse[zs->state_in_ch] = True; \ zs->block[zs->nblock] = (UChar)ch; \ zs->nblock++; \ zs->state_in_ch = zchh; \ } \ else \ /*-- general, uncommon cases --*/ \ if (zchh != zs->state_in_ch || \ zs->state_in_len == 255) { \ if (zs->state_in_ch < 256) \ add_pair_to_block ( zs ); \ zs->state_in_ch = zchh; \ zs->state_in_len = 1; \ } else { \ zs->state_in_len++; \ } \ } /*---------------------------------------------------*/ static Bool copy_input_until_stop ( EState* s ) { Bool progress_in = False; if (s->mode == BZ_M_RUNNING) { /*-- fast track the common case --*/ while (True) { /*-- block full? --*/ if (s->nblock >= s->nblockMAX) break; /*-- no input? --*/ if (s->strm->avail_in == 0) break; progress_in = True; ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); s->strm->next_in++; s->strm->avail_in--; s->strm->total_in_lo32++; if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; } } else { /*-- general, uncommon case --*/ while (True) { /*-- block full? --*/ if (s->nblock >= s->nblockMAX) break; /*-- no input? --*/ if (s->strm->avail_in == 0) break; /*-- flush/finish end? --*/ if (s->avail_in_expect == 0) break; progress_in = True; ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); s->strm->next_in++; s->strm->avail_in--; s->strm->total_in_lo32++; if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; s->avail_in_expect--; } } return progress_in; } /*---------------------------------------------------*/ static Bool copy_output_until_stop ( EState* s ) { Bool progress_out = False; while (True) { /*-- no output space? --*/ if (s->strm->avail_out == 0) break; /*-- block done? --*/ if (s->state_out_pos >= s->numZ) break; progress_out = True; *(s->strm->next_out) = s->zbits[s->state_out_pos]; s->state_out_pos++; s->strm->avail_out--; s->strm->next_out++; s->strm->total_out_lo32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; } return progress_out; } /*---------------------------------------------------*/ static Bool handle_compress ( bz_stream* strm ) { Bool progress_in = False; Bool progress_out = False; EState* s = strm->state; while (True) { if (s->state == BZ_S_OUTPUT) { progress_out |= copy_output_until_stop ( s ); if (s->state_out_pos < s->numZ) break; if (s->mode == BZ_M_FINISHING && s->avail_in_expect == 0 && isempty_RL(s)) break; prepare_new_block ( s ); s->state = BZ_S_INPUT; if (s->mode == BZ_M_FLUSHING && s->avail_in_expect == 0 && isempty_RL(s)) break; } if (s->state == BZ_S_INPUT) { progress_in |= copy_input_until_stop ( s ); if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) { flush_RL ( s ); BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) ); s->state = BZ_S_OUTPUT; } else if (s->nblock >= s->nblockMAX) { BZ2_compressBlock ( s, False ); s->state = BZ_S_OUTPUT; } else if (s->strm->avail_in == 0) { break; } } } return progress_in || progress_out; } /*---------------------------------------------------*/ int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action ) { Bool progress; EState* s; if (strm == NULL) return BZ_PARAM_ERROR; s = strm->state; if (s == NULL) return BZ_PARAM_ERROR; if (s->strm != strm) return BZ_PARAM_ERROR; preswitch: switch (s->mode) { case BZ_M_IDLE: return BZ_SEQUENCE_ERROR; case BZ_M_RUNNING: if (action == BZ_RUN) { progress = handle_compress ( strm ); return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; } else if (action == BZ_FLUSH) { s->avail_in_expect = strm->avail_in; s->mode = BZ_M_FLUSHING; goto preswitch; } else if (action == BZ_FINISH) { s->avail_in_expect = strm->avail_in; s->mode = BZ_M_FINISHING; goto preswitch; } else return BZ_PARAM_ERROR; case BZ_M_FLUSHING: if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; if (s->avail_in_expect != s->strm->avail_in) return BZ_SEQUENCE_ERROR; progress = handle_compress ( strm ); if (s->avail_in_expect > 0 || !isempty_RL(s) || s->state_out_pos < s->numZ) return BZ_FLUSH_OK; s->mode = BZ_M_RUNNING; return BZ_RUN_OK; case BZ_M_FINISHING: if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; if (s->avail_in_expect != s->strm->avail_in) return BZ_SEQUENCE_ERROR; progress = handle_compress ( strm ); if (!progress) return BZ_SEQUENCE_ERROR; if (s->avail_in_expect > 0 || !isempty_RL(s) || s->state_out_pos < s->numZ) return BZ_FINISH_OK; s->mode = BZ_M_IDLE; return BZ_STREAM_END; } return BZ_OK; /*--not reached--*/ } /*---------------------------------------------------*/ int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm ) { EState* s; if (strm == NULL) return BZ_PARAM_ERROR; s = strm->state; if (s == NULL) return BZ_PARAM_ERROR; if (s->strm != strm) return BZ_PARAM_ERROR; if (s->arr1 != NULL) BZFREE(s->arr1); if (s->arr2 != NULL) BZFREE(s->arr2); if (s->ftab != NULL) BZFREE(s->ftab); BZFREE(strm->state); strm->state = NULL; return BZ_OK; } /*---------------------------------------------------*/ /*--- Decompression stuff ---*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ int BZ_API(BZ2_bzDecompressInit) ( bz_stream* strm, int verbosity, int small ) { DState* s; if (!bz_config_ok()) return BZ_CONFIG_ERROR; if (strm == NULL) return BZ_PARAM_ERROR; if (small != 0 && small != 1) return BZ_PARAM_ERROR; if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; if (strm->bzfree == NULL) strm->bzfree = default_bzfree; s = BZALLOC( sizeof(DState) ); if (s == NULL) return BZ_MEM_ERROR; s->strm = strm; strm->state = s; s->state = BZ_X_MAGIC_1; s->bsLive = 0; s->bsBuff = 0; s->calculatedCombinedCRC = 0; strm->total_in_lo32 = 0; strm->total_in_hi32 = 0; strm->total_out_lo32 = 0; strm->total_out_hi32 = 0; s->smallDecompress = (Bool)small; s->ll4 = NULL; s->ll16 = NULL; s->tt = NULL; s->currBlockNo = 0; s->verbosity = verbosity; return BZ_OK; } /*---------------------------------------------------*/ /* Return True iff data corruption is discovered. Returns False if there is no problem. */ static Bool unRLE_obuf_to_output_FAST ( DState* s ) { UChar k1; if (s->blockRandomised) { while (True) { /* try to finish existing run */ while (True) { if (s->strm->avail_out == 0) return False; if (s->state_out_len == 0) break; *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); s->state_out_len--; s->strm->next_out++; s->strm->avail_out--; s->strm->total_out_lo32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; } /* can a new run be started? */ if (s->nblock_used == s->save_nblock+1) return False; /* Only caused by corrupt data stream? */ if (s->nblock_used > s->save_nblock+1) return True; s->state_out_len = 1; s->state_out_ch = s->k0; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 2; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 3; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; s->state_out_len = ((Int32)k1) + 4; BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; s->nblock_used++; } } else { /* restore */ UInt32 c_calculatedBlockCRC = s->calculatedBlockCRC; UChar c_state_out_ch = s->state_out_ch; Int32 c_state_out_len = s->state_out_len; Int32 c_nblock_used = s->nblock_used; Int32 c_k0 = s->k0; UInt32* c_tt = s->tt; UInt32 c_tPos = s->tPos; char* cs_next_out = s->strm->next_out; unsigned int cs_avail_out = s->strm->avail_out; Int32 ro_blockSize100k = s->blockSize100k; /* end restore */ UInt32 avail_out_INIT = cs_avail_out; Int32 s_save_nblockPP = s->save_nblock+1; unsigned int total_out_lo32_old; while (True) { /* try to finish existing run */ if (c_state_out_len > 0) { while (True) { if (cs_avail_out == 0) goto return_notr; if (c_state_out_len == 1) break; *( (UChar*)(cs_next_out) ) = c_state_out_ch; BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); c_state_out_len--; cs_next_out++; cs_avail_out--; } s_state_out_len_eq_one: { if (cs_avail_out == 0) { c_state_out_len = 1; goto return_notr; }; *( (UChar*)(cs_next_out) ) = c_state_out_ch; BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); cs_next_out++; cs_avail_out--; } } /* Only caused by corrupt data stream? */ if (c_nblock_used > s_save_nblockPP) return True; /* can a new run be started? */ if (c_nblock_used == s_save_nblockPP) { c_state_out_len = 0; goto return_notr; }; c_state_out_ch = c_k0; BZ_GET_FAST_C(k1); c_nblock_used++; if (k1 != c_k0) { c_k0 = k1; goto s_state_out_len_eq_one; }; if (c_nblock_used == s_save_nblockPP) goto s_state_out_len_eq_one; c_state_out_len = 2; BZ_GET_FAST_C(k1); c_nblock_used++; if (c_nblock_used == s_save_nblockPP) continue; if (k1 != c_k0) { c_k0 = k1; continue; }; c_state_out_len = 3; BZ_GET_FAST_C(k1); c_nblock_used++; if (c_nblock_used == s_save_nblockPP) continue; if (k1 != c_k0) { c_k0 = k1; continue; }; BZ_GET_FAST_C(k1); c_nblock_used++; c_state_out_len = ((Int32)k1) + 4; BZ_GET_FAST_C(c_k0); c_nblock_used++; } return_notr: total_out_lo32_old = s->strm->total_out_lo32; s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out); if (s->strm->total_out_lo32 < total_out_lo32_old) s->strm->total_out_hi32++; /* save */ s->calculatedBlockCRC = c_calculatedBlockCRC; s->state_out_ch = c_state_out_ch; s->state_out_len = c_state_out_len; s->nblock_used = c_nblock_used; s->k0 = c_k0; s->tt = c_tt; s->tPos = c_tPos; s->strm->next_out = cs_next_out; s->strm->avail_out = cs_avail_out; /* end save */ } return False; } /*---------------------------------------------------*/ __inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab ) { Int32 nb, na, mid; nb = 0; na = 256; do { mid = (nb + na) >> 1; if (indx >= cftab[mid]) nb = mid; else na = mid; } while (na - nb != 1); return nb; } /*---------------------------------------------------*/ /* Return True iff data corruption is discovered. Returns False if there is no problem. */ static Bool unRLE_obuf_to_output_SMALL ( DState* s ) { UChar k1; if (s->blockRandomised) { while (True) { /* try to finish existing run */ while (True) { if (s->strm->avail_out == 0) return False; if (s->state_out_len == 0) break; *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); s->state_out_len--; s->strm->next_out++; s->strm->avail_out--; s->strm->total_out_lo32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; } /* can a new run be started? */ if (s->nblock_used == s->save_nblock+1) return False; /* Only caused by corrupt data stream? */ if (s->nblock_used > s->save_nblock+1) return True; s->state_out_len = 1; s->state_out_ch = s->k0; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 2; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 3; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; k1 ^= BZ_RAND_MASK; s->nblock_used++; s->state_out_len = ((Int32)k1) + 4; BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; s->nblock_used++; } } else { while (True) { /* try to finish existing run */ while (True) { if (s->strm->avail_out == 0) return False; if (s->state_out_len == 0) break; *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); s->state_out_len--; s->strm->next_out++; s->strm->avail_out--; s->strm->total_out_lo32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; } /* can a new run be started? */ if (s->nblock_used == s->save_nblock+1) return False; /* Only caused by corrupt data stream? */ if (s->nblock_used > s->save_nblock+1) return True; s->state_out_len = 1; s->state_out_ch = s->k0; BZ_GET_SMALL(k1); s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 2; BZ_GET_SMALL(k1); s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; s->state_out_len = 3; BZ_GET_SMALL(k1); s->nblock_used++; if (s->nblock_used == s->save_nblock+1) continue; if (k1 != s->k0) { s->k0 = k1; continue; }; BZ_GET_SMALL(k1); s->nblock_used++; s->state_out_len = ((Int32)k1) + 4; BZ_GET_SMALL(s->k0); s->nblock_used++; } } } /*---------------------------------------------------*/ int BZ_API(BZ2_bzDecompress) ( bz_stream *strm ) { Bool corrupt; DState* s; if (strm == NULL) return BZ_PARAM_ERROR; s = strm->state; if (s == NULL) return BZ_PARAM_ERROR; if (s->strm != strm) return BZ_PARAM_ERROR; while (True) { if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR; if (s->state == BZ_X_OUTPUT) { if (s->smallDecompress) corrupt = unRLE_obuf_to_output_SMALL ( s ); else corrupt = unRLE_obuf_to_output_FAST ( s ); if (corrupt) return BZ_DATA_ERROR; if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { BZ_FINALISE_CRC ( s->calculatedBlockCRC ); if (s->verbosity >= 3) VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC, s->calculatedBlockCRC ); if (s->verbosity >= 2) VPrintf0 ( "]" ); if (s->calculatedBlockCRC != s->storedBlockCRC) return BZ_DATA_ERROR; s->calculatedCombinedCRC = (s->calculatedCombinedCRC << 1) | (s->calculatedCombinedCRC >> 31); s->calculatedCombinedCRC ^= s->calculatedBlockCRC; s->state = BZ_X_BLKHDR_1; } else { return BZ_OK; } } if (s->state >= BZ_X_MAGIC_1) { Int32 r = BZ2_decompress ( s ); if (r == BZ_STREAM_END) { if (s->verbosity >= 3) VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x", s->storedCombinedCRC, s->calculatedCombinedCRC ); if (s->calculatedCombinedCRC != s->storedCombinedCRC) return BZ_DATA_ERROR; return r; } if (s->state != BZ_X_OUTPUT) return r; } } AssertH ( 0, 6001 ); return 0; /*NOTREACHED*/ } /*---------------------------------------------------*/ int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ) { DState* s; if (strm == NULL) return BZ_PARAM_ERROR; s = strm->state; if (s == NULL) return BZ_PARAM_ERROR; if (s->strm != strm) return BZ_PARAM_ERROR; if (s->tt != NULL) BZFREE(s->tt); if (s->ll16 != NULL) BZFREE(s->ll16); if (s->ll4 != NULL) BZFREE(s->ll4); BZFREE(strm->state); strm->state = NULL; return BZ_OK; } #ifndef BZ_NO_STDIO /*---------------------------------------------------*/ /*--- File I/O stuff ---*/ /*---------------------------------------------------*/ #define BZ_SETERR(eee) \ { \ if (bzerror != NULL) *bzerror = eee; \ if (bzf != NULL) bzf->lastErr = eee; \ } typedef struct { FILE* handle; Char buf[BZ_MAX_UNUSED]; Int32 bufN; Bool writing; bz_stream strm; Int32 lastErr; Bool initialisedOk; } bzFile; /*---------------------------------------------*/ static Bool myfeof ( FILE* f ) { Int32 c = fgetc ( f ); if (c == EOF) return True; ungetc ( c, f ); return False; } /*---------------------------------------------------*/ BZFILE* BZ_API(BZ2_bzWriteOpen) ( int* bzerror, FILE* f, int blockSize100k, int verbosity, int workFactor ) { Int32 ret; bzFile* bzf = NULL; BZ_SETERR(BZ_OK); if (f == NULL || (blockSize100k < 1 || blockSize100k > 9) || (workFactor < 0 || workFactor > 250) || (verbosity < 0 || verbosity > 4)) { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; if (ferror(f)) { BZ_SETERR(BZ_IO_ERROR); return NULL; }; bzf = malloc ( sizeof(bzFile) ); if (bzf == NULL) { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; BZ_SETERR(BZ_OK); bzf->initialisedOk = False; bzf->bufN = 0; bzf->handle = f; bzf->writing = True; bzf->strm.bzalloc = NULL; bzf->strm.bzfree = NULL; bzf->strm.opaque = NULL; if (workFactor == 0) workFactor = 30; ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, verbosity, workFactor ); if (ret != BZ_OK) { BZ_SETERR(ret); free(bzf); return NULL; }; bzf->strm.avail_in = 0; bzf->initialisedOk = True; return bzf; } /*---------------------------------------------------*/ void BZ_API(BZ2_bzWrite) ( int* bzerror, BZFILE* b, void* buf, int len ) { Int32 n, n2, ret; bzFile* bzf = (bzFile*)b; BZ_SETERR(BZ_OK); if (bzf == NULL || buf == NULL || len < 0) { BZ_SETERR(BZ_PARAM_ERROR); return; }; if (!(bzf->writing)) { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; if (ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return; }; if (len == 0) { BZ_SETERR(BZ_OK); return; }; bzf->strm.avail_in = len; bzf->strm.next_in = buf; while (True) { bzf->strm.avail_out = BZ_MAX_UNUSED; bzf->strm.next_out = bzf->buf; ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN ); if (ret != BZ_RUN_OK) { BZ_SETERR(ret); return; }; if (bzf->strm.avail_out < BZ_MAX_UNUSED) { n = BZ_MAX_UNUSED - bzf->strm.avail_out; n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), n, bzf->handle ); if (n != n2 || ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return; }; } if (bzf->strm.avail_in == 0) { BZ_SETERR(BZ_OK); return; }; } } /*---------------------------------------------------*/ void BZ_API(BZ2_bzWriteClose) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in, unsigned int* nbytes_out ) { BZ2_bzWriteClose64 ( bzerror, b, abandon, nbytes_in, NULL, nbytes_out, NULL ); } void BZ_API(BZ2_bzWriteClose64) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in_lo32, unsigned int* nbytes_in_hi32, unsigned int* nbytes_out_lo32, unsigned int* nbytes_out_hi32 ) { Int32 n, n2, ret; bzFile* bzf = (bzFile*)b; if (bzf == NULL) { BZ_SETERR(BZ_OK); return; }; if (!(bzf->writing)) { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; if (ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return; }; if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0; if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0; if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0; if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0; if ((!abandon) && bzf->lastErr == BZ_OK) { while (True) { bzf->strm.avail_out = BZ_MAX_UNUSED; bzf->strm.next_out = bzf->buf; ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH ); if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) { BZ_SETERR(ret); return; }; if (bzf->strm.avail_out < BZ_MAX_UNUSED) { n = BZ_MAX_UNUSED - bzf->strm.avail_out; n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), n, bzf->handle ); if (n != n2 || ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return; }; } if (ret == BZ_STREAM_END) break; } } if ( !abandon && !ferror ( bzf->handle ) ) { fflush ( bzf->handle ); if (ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return; }; } if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = bzf->strm.total_in_lo32; if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = bzf->strm.total_in_hi32; if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = bzf->strm.total_out_lo32; if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = bzf->strm.total_out_hi32; BZ_SETERR(BZ_OK); BZ2_bzCompressEnd ( &(bzf->strm) ); free ( bzf ); } /*---------------------------------------------------*/ BZFILE* BZ_API(BZ2_bzReadOpen) ( int* bzerror, FILE* f, int verbosity, int small, void* unused, int nUnused ) { bzFile* bzf = NULL; int ret; BZ_SETERR(BZ_OK); if (f == NULL || (small != 0 && small != 1) || (verbosity < 0 || verbosity > 4) || (unused == NULL && nUnused != 0) || (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED))) { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; if (ferror(f)) { BZ_SETERR(BZ_IO_ERROR); return NULL; }; bzf = malloc ( sizeof(bzFile) ); if (bzf == NULL) { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; BZ_SETERR(BZ_OK); bzf->initialisedOk = False; bzf->handle = f; bzf->bufN = 0; bzf->writing = False; bzf->strm.bzalloc = NULL; bzf->strm.bzfree = NULL; bzf->strm.opaque = NULL; while (nUnused > 0) { bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; unused = ((void*)( 1 + ((UChar*)(unused)) )); nUnused--; } ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small ); if (ret != BZ_OK) { BZ_SETERR(ret); free(bzf); return NULL; }; bzf->strm.avail_in = bzf->bufN; bzf->strm.next_in = bzf->buf; bzf->initialisedOk = True; return bzf; } /*---------------------------------------------------*/ void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b ) { bzFile* bzf = (bzFile*)b; BZ_SETERR(BZ_OK); if (bzf == NULL) { BZ_SETERR(BZ_OK); return; }; if (bzf->writing) { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; if (bzf->initialisedOk) (void)BZ2_bzDecompressEnd ( &(bzf->strm) ); free ( bzf ); } /*---------------------------------------------------*/ int BZ_API(BZ2_bzRead) ( int* bzerror, BZFILE* b, void* buf, int len ) { Int32 n, ret; bzFile* bzf = (bzFile*)b; BZ_SETERR(BZ_OK); if (bzf == NULL || buf == NULL || len < 0) { BZ_SETERR(BZ_PARAM_ERROR); return 0; }; if (bzf->writing) { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; }; if (len == 0) { BZ_SETERR(BZ_OK); return 0; }; bzf->strm.avail_out = len; bzf->strm.next_out = buf; while (True) { if (ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return 0; }; if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { n = fread ( bzf->buf, sizeof(UChar), BZ_MAX_UNUSED, bzf->handle ); if (ferror(bzf->handle)) { BZ_SETERR(BZ_IO_ERROR); return 0; }; bzf->bufN = n; bzf->strm.avail_in = bzf->bufN; bzf->strm.next_in = bzf->buf; } ret = BZ2_bzDecompress ( &(bzf->strm) ); if (ret != BZ_OK && ret != BZ_STREAM_END) { BZ_SETERR(ret); return 0; }; if (ret == BZ_OK && myfeof(bzf->handle) && bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; if (ret == BZ_STREAM_END) { BZ_SETERR(BZ_STREAM_END); return len - bzf->strm.avail_out; }; if (bzf->strm.avail_out == 0) { BZ_SETERR(BZ_OK); return len; }; } return 0; /*not reached*/ } /*---------------------------------------------------*/ void BZ_API(BZ2_bzReadGetUnused) ( int* bzerror, BZFILE* b, void** unused, int* nUnused ) { bzFile* bzf = (bzFile*)b; if (bzf == NULL) { BZ_SETERR(BZ_PARAM_ERROR); return; }; if (bzf->lastErr != BZ_STREAM_END) { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; if (unused == NULL || nUnused == NULL) { BZ_SETERR(BZ_PARAM_ERROR); return; }; BZ_SETERR(BZ_OK); *nUnused = bzf->strm.avail_in; *unused = bzf->strm.next_in; } #endif /*---------------------------------------------------*/ /*--- Misc convenience stuff ---*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ int BZ_API(BZ2_bzBuffToBuffCompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int blockSize100k, int verbosity, int workFactor ) { bz_stream strm; int ret; if (dest == NULL || destLen == NULL || source == NULL || blockSize100k < 1 || blockSize100k > 9 || verbosity < 0 || verbosity > 4 || workFactor < 0 || workFactor > 250) return BZ_PARAM_ERROR; if (workFactor == 0) workFactor = 30; strm.bzalloc = NULL; strm.bzfree = NULL; strm.opaque = NULL; ret = BZ2_bzCompressInit ( &strm, blockSize100k, verbosity, workFactor ); if (ret != BZ_OK) return ret; strm.next_in = source; strm.next_out = dest; strm.avail_in = sourceLen; strm.avail_out = *destLen; ret = BZ2_bzCompress ( &strm, BZ_FINISH ); if (ret == BZ_FINISH_OK) goto output_overflow; if (ret != BZ_STREAM_END) goto errhandler; /* normal termination */ *destLen -= strm.avail_out; BZ2_bzCompressEnd ( &strm ); return BZ_OK; output_overflow: BZ2_bzCompressEnd ( &strm ); return BZ_OUTBUFF_FULL; errhandler: BZ2_bzCompressEnd ( &strm ); return ret; } /*---------------------------------------------------*/ int BZ_API(BZ2_bzBuffToBuffDecompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int small, int verbosity ) { bz_stream strm; int ret; if (dest == NULL || destLen == NULL || source == NULL || (small != 0 && small != 1) || verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; strm.bzalloc = NULL; strm.bzfree = NULL; strm.opaque = NULL; ret = BZ2_bzDecompressInit ( &strm, verbosity, small ); if (ret != BZ_OK) return ret; strm.next_in = source; strm.next_out = dest; strm.avail_in = sourceLen; strm.avail_out = *destLen; ret = BZ2_bzDecompress ( &strm ); if (ret == BZ_OK) goto output_overflow_or_eof; if (ret != BZ_STREAM_END) goto errhandler; /* normal termination */ *destLen -= strm.avail_out; BZ2_bzDecompressEnd ( &strm ); return BZ_OK; output_overflow_or_eof: if (strm.avail_out > 0) { BZ2_bzDecompressEnd ( &strm ); return BZ_UNEXPECTED_EOF; } else { BZ2_bzDecompressEnd ( &strm ); return BZ_OUTBUFF_FULL; }; errhandler: BZ2_bzDecompressEnd ( &strm ); return ret; } /*---------------------------------------------------*/ /*-- Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) to support better zlib compatibility. This code is not _officially_ part of libbzip2 (yet); I haven't tested it, documented it, or considered the threading-safeness of it. If this code breaks, please contact both Yoshioka and me. --*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ /*-- return version like "0.9.5d, 4-Sept-1999". --*/ const char * BZ_API(BZ2_bzlibVersion)(void) { return BZ_VERSION; } #ifndef BZ_NO_STDIO /*---------------------------------------------------*/ #if defined(_WIN32) || defined(OS2) || defined(MSDOS) # include # include # define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY) #else # define SET_BINARY_MODE(file) #endif static BZFILE * bzopen_or_bzdopen ( const char *path, /* no use when bzdopen */ int fd, /* no use when bzdopen */ const char *mode, int open_mode) /* bzopen: 0, bzdopen:1 */ { int bzerr; char unused[BZ_MAX_UNUSED]; int blockSize100k = 9; int writing = 0; char mode2[10] = ""; FILE *fp = NULL; BZFILE *bzfp = NULL; int verbosity = 0; int workFactor = 30; int smallMode = 0; int nUnused = 0; if (mode == NULL) return NULL; while (*mode) { switch (*mode) { case 'r': writing = 0; break; case 'w': writing = 1; break; case 's': smallMode = 1; break; default: if (isdigit((int)(*mode))) { blockSize100k = *mode-BZ_HDR_0; } } mode++; } strcat(mode2, writing ? "w" : "r" ); strcat(mode2,"b"); /* binary mode */ if (open_mode==0) { if (path==NULL || strcmp(path,"")==0) { fp = (writing ? stdout : stdin); SET_BINARY_MODE(fp); } else { fp = fopen(path,mode2); } } else { #ifdef BZ_STRICT_ANSI fp = NULL; #else fp = fdopen(fd,mode2); #endif } if (fp == NULL) return NULL; if (writing) { /* Guard against total chaos and anarchy -- JRS */ if (blockSize100k < 1) blockSize100k = 1; if (blockSize100k > 9) blockSize100k = 9; bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, verbosity,workFactor); } else { bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode, unused,nUnused); } if (bzfp == NULL) { if (fp != stdin && fp != stdout) fclose(fp); return NULL; } return bzfp; } /*---------------------------------------------------*/ /*-- open file for read or write. ex) bzopen("file","w9") case path="" or NULL => use stdin or stdout. --*/ BZFILE * BZ_API(BZ2_bzopen) ( const char *path, const char *mode ) { return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0); } /*---------------------------------------------------*/ BZFILE * BZ_API(BZ2_bzdopen) ( int fd, const char *mode ) { return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1); } /*---------------------------------------------------*/ int BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len ) { int bzerr, nread; if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0; nread = BZ2_bzRead(&bzerr,b,buf,len); if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) { return nread; } else { return -1; } } /*---------------------------------------------------*/ int BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len ) { int bzerr; BZ2_bzWrite(&bzerr,b,buf,len); if(bzerr == BZ_OK){ return len; }else{ return -1; } } /*---------------------------------------------------*/ int BZ_API(BZ2_bzflush) (BZFILE *b) { /* do nothing now... */ return 0; } /*---------------------------------------------------*/ void BZ_API(BZ2_bzclose) (BZFILE* b) { int bzerr; FILE *fp; if (b==NULL) {return;} fp = ((bzFile *)b)->handle; if(((bzFile*)b)->writing){ BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); if(bzerr != BZ_OK){ BZ2_bzWriteClose(NULL,b,1,NULL,NULL); } }else{ BZ2_bzReadClose(&bzerr,b); } if(fp!=stdin && fp!=stdout){ fclose(fp); } } /*---------------------------------------------------*/ /*-- return last error code --*/ static const char *bzerrorstrings[] = { "OK" ,"SEQUENCE_ERROR" ,"PARAM_ERROR" ,"MEM_ERROR" ,"DATA_ERROR" ,"DATA_ERROR_MAGIC" ,"IO_ERROR" ,"UNEXPECTED_EOF" ,"OUTBUFF_FULL" ,"CONFIG_ERROR" ,"???" /* for future */ ,"???" /* for future */ ,"???" /* for future */ ,"???" /* for future */ ,"???" /* for future */ ,"???" /* for future */ }; const char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum) { int err = ((bzFile *)b)->lastErr; if(err>0) err = 0; *errnum = err; return bzerrorstrings[err*-1]; } #endif /*-------------------------------------------------------------*/ /*--- end bzlib.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/bzlib.h000066400000000000000000000141451462133141200207660ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Public header file for the library. ---*/ /*--- bzlib.h ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #ifndef _BZLIB_H #define _BZLIB_H #ifdef __cplusplus extern "C" { #endif #define BZ_RUN 0 #define BZ_FLUSH 1 #define BZ_FINISH 2 #define BZ_OK 0 #define BZ_RUN_OK 1 #define BZ_FLUSH_OK 2 #define BZ_FINISH_OK 3 #define BZ_STREAM_END 4 #define BZ_SEQUENCE_ERROR (-1) #define BZ_PARAM_ERROR (-2) #define BZ_MEM_ERROR (-3) #define BZ_DATA_ERROR (-4) #define BZ_DATA_ERROR_MAGIC (-5) #define BZ_IO_ERROR (-6) #define BZ_UNEXPECTED_EOF (-7) #define BZ_OUTBUFF_FULL (-8) #define BZ_CONFIG_ERROR (-9) typedef struct { char *next_in; unsigned int avail_in; unsigned int total_in_lo32; unsigned int total_in_hi32; char *next_out; unsigned int avail_out; unsigned int total_out_lo32; unsigned int total_out_hi32; void *state; void *(*bzalloc)(void *,int,int); void (*bzfree)(void *,void *); void *opaque; } bz_stream; #ifndef BZ_IMPORT #define BZ_EXPORT #endif #ifndef BZ_NO_STDIO /* Need a definitition for FILE */ #include #endif #ifdef _WIN32 # include # ifdef small /* windows.h define small to char */ # undef small # endif # ifdef BZ_EXPORT # define BZ_API(func) WINAPI func # define BZ_EXTERN extern # else /* import windows dll dynamically */ # define BZ_API(func) (WINAPI * func) # define BZ_EXTERN # endif #else # define BZ_API(func) func # define BZ_EXTERN extern #endif /*-- Core (low-level) library functions --*/ BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( bz_stream* strm, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN int BZ_API(BZ2_bzCompress) ( bz_stream* strm, int action ); BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( bz_stream* strm ); BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( bz_stream *strm, int verbosity, int small ); BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( bz_stream* strm ); BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ); /*-- High(er) level library functions --*/ #ifndef BZ_NO_STDIO #define BZ_MAX_UNUSED 5000 typedef void BZFILE; BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( int* bzerror, FILE* f, int verbosity, int small, void* unused, int nUnused ); BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( int* bzerror, BZFILE* b ); BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( int* bzerror, BZFILE* b, void** unused, int* nUnused ); BZ_EXTERN int BZ_API(BZ2_bzRead) ( int* bzerror, BZFILE* b, void* buf, int len ); BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( int* bzerror, FILE* f, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN void BZ_API(BZ2_bzWrite) ( int* bzerror, BZFILE* b, void* buf, int len ); BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in, unsigned int* nbytes_out ); BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in_lo32, unsigned int* nbytes_in_hi32, unsigned int* nbytes_out_lo32, unsigned int* nbytes_out_hi32 ); #endif /*-- Utility functions --*/ BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int small, int verbosity ); /*-- Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) to support better zlib compatibility. This code is not _officially_ part of libbzip2 (yet); I haven't tested it, documented it, or considered the threading-safeness of it. If this code breaks, please contact both Yoshioka and me. --*/ BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( void ); #ifndef BZ_NO_STDIO BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( const char *path, const char *mode ); BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( int fd, const char *mode ); BZ_EXTERN int BZ_API(BZ2_bzread) ( BZFILE* b, void* buf, int len ); BZ_EXTERN int BZ_API(BZ2_bzwrite) ( BZFILE* b, void* buf, int len ); BZ_EXTERN int BZ_API(BZ2_bzflush) ( BZFILE* b ); BZ_EXTERN void BZ_API(BZ2_bzclose) ( BZFILE* b ); BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( BZFILE *b, int *errnum ); #endif #ifdef __cplusplus } #endif #endif /*-------------------------------------------------------------*/ /*--- end bzlib.h ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/bzlib_private.h000066400000000000000000000316741462133141200225260ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Private header file for the library. ---*/ /*--- bzlib_private.h ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #ifndef _BZLIB_PRIVATE_H #define _BZLIB_PRIVATE_H #include #ifndef BZ_NO_STDIO #include #include #include #endif #include "bzlib.h" /*-- General stuff. --*/ #define BZ_VERSION "1.0.6, 6-Sept-2010" typedef char Char; typedef unsigned char Bool; typedef unsigned char UChar; typedef int Int32; typedef unsigned int UInt32; typedef short Int16; typedef unsigned short UInt16; #define True ((Bool)1) #define False ((Bool)0) #ifndef __GNUC__ #define __inline__ /* */ #endif #ifndef BZ_NO_STDIO extern void BZ2_bz__AssertH__fail ( int errcode ); #define AssertH(cond,errcode) \ { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); } #if BZ_DEBUG #define AssertD(cond,msg) \ { if (!(cond)) { \ fprintf ( stderr, \ "\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\ exit(1); \ }} #else #define AssertD(cond,msg) /* */ #endif #define VPrintf0(zf) \ fprintf(stderr,zf) #define VPrintf1(zf,za1) \ fprintf(stderr,zf,za1) #define VPrintf2(zf,za1,za2) \ fprintf(stderr,zf,za1,za2) #define VPrintf3(zf,za1,za2,za3) \ fprintf(stderr,zf,za1,za2,za3) #define VPrintf4(zf,za1,za2,za3,za4) \ fprintf(stderr,zf,za1,za2,za3,za4) #define VPrintf5(zf,za1,za2,za3,za4,za5) \ fprintf(stderr,zf,za1,za2,za3,za4,za5) #else extern void bz_internal_error ( int errcode ); #define AssertH(cond,errcode) \ { if (!(cond)) bz_internal_error ( errcode ); } #define AssertD(cond,msg) do { } while (0) #define VPrintf0(zf) do { } while (0) #define VPrintf1(zf,za1) do { } while (0) #define VPrintf2(zf,za1,za2) do { } while (0) #define VPrintf3(zf,za1,za2,za3) do { } while (0) #define VPrintf4(zf,za1,za2,za3,za4) do { } while (0) #define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0) #endif #define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1) #define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp)) /*-- Header bytes. --*/ #define BZ_HDR_B 0x42 /* 'B' */ #define BZ_HDR_Z 0x5a /* 'Z' */ #define BZ_HDR_h 0x68 /* 'h' */ #define BZ_HDR_0 0x30 /* '0' */ /*-- Constants for the back end. --*/ #define BZ_MAX_ALPHA_SIZE 258 #define BZ_MAX_CODE_LEN 23 #define BZ_RUNA 0 #define BZ_RUNB 1 #define BZ_N_GROUPS 6 #define BZ_G_SIZE 50 #define BZ_N_ITERS 4 #define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE)) /*-- Stuff for randomising repetitive blocks. --*/ extern Int32 BZ2_rNums[512]; #define BZ_RAND_DECLS \ Int32 rNToGo; \ Int32 rTPos \ #define BZ_RAND_INIT_MASK \ s->rNToGo = 0; \ s->rTPos = 0 \ #define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0) #define BZ_RAND_UPD_MASK \ if (s->rNToGo == 0) { \ s->rNToGo = BZ2_rNums[s->rTPos]; \ s->rTPos++; \ if (s->rTPos == 512) s->rTPos = 0; \ } \ s->rNToGo--; /*-- Stuff for doing CRCs. --*/ extern UInt32 BZ2_crc32Table[256]; #define BZ_INITIALISE_CRC(crcVar) \ { \ crcVar = 0xffffffffL; \ } #define BZ_FINALISE_CRC(crcVar) \ { \ crcVar = ~(crcVar); \ } #define BZ_UPDATE_CRC(crcVar,cha) \ { \ crcVar = (crcVar << 8) ^ \ BZ2_crc32Table[(crcVar >> 24) ^ \ ((UChar)cha)]; \ } /*-- States and modes for compression. --*/ #define BZ_M_IDLE 1 #define BZ_M_RUNNING 2 #define BZ_M_FLUSHING 3 #define BZ_M_FINISHING 4 #define BZ_S_OUTPUT 1 #define BZ_S_INPUT 2 #define BZ_N_RADIX 2 #define BZ_N_QSORT 12 #define BZ_N_SHELL 18 #define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2) /*-- Structure holding all the compression-side stuff. --*/ typedef struct { /* pointer back to the struct bz_stream */ bz_stream* strm; /* mode this stream is in, and whether inputting */ /* or outputting data */ Int32 mode; Int32 state; /* remembers avail_in when flush/finish requested */ UInt32 avail_in_expect; /* for doing the block sorting */ UInt32* arr1; UInt32* arr2; UInt32* ftab; Int32 origPtr; /* aliases for arr1 and arr2 */ UInt32* ptr; UChar* block; UInt16* mtfv; UChar* zbits; /* for deciding when to use the fallback sorting algorithm */ Int32 workFactor; /* run-length-encoding of the input */ UInt32 state_in_ch; Int32 state_in_len; BZ_RAND_DECLS; /* input and output limits and current posns */ Int32 nblock; Int32 nblockMAX; Int32 numZ; Int32 state_out_pos; /* map of bytes used in block */ Int32 nInUse; Bool inUse[256]; UChar unseqToSeq[256]; /* the buffer for bit stream creation */ UInt32 bsBuff; Int32 bsLive; /* block and combined CRCs */ UInt32 blockCRC; UInt32 combinedCRC; /* misc administratium */ Int32 verbosity; Int32 blockNo; Int32 blockSize100k; /* stuff for coding the MTF values */ Int32 nMTF; Int32 mtfFreq [BZ_MAX_ALPHA_SIZE]; UChar selector [BZ_MAX_SELECTORS]; UChar selectorMtf[BZ_MAX_SELECTORS]; UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; /* second dimension: only 3 needed; 4 makes index calculations faster */ UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4]; } EState; /*-- externs for compression. --*/ extern void BZ2_blockSort ( EState* ); extern void BZ2_compressBlock ( EState*, Bool ); extern void BZ2_bsInitWrite ( EState* ); extern void BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); extern void BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); /*-- states for decompression. --*/ #define BZ_X_IDLE 1 #define BZ_X_OUTPUT 2 #define BZ_X_MAGIC_1 10 #define BZ_X_MAGIC_2 11 #define BZ_X_MAGIC_3 12 #define BZ_X_MAGIC_4 13 #define BZ_X_BLKHDR_1 14 #define BZ_X_BLKHDR_2 15 #define BZ_X_BLKHDR_3 16 #define BZ_X_BLKHDR_4 17 #define BZ_X_BLKHDR_5 18 #define BZ_X_BLKHDR_6 19 #define BZ_X_BCRC_1 20 #define BZ_X_BCRC_2 21 #define BZ_X_BCRC_3 22 #define BZ_X_BCRC_4 23 #define BZ_X_RANDBIT 24 #define BZ_X_ORIGPTR_1 25 #define BZ_X_ORIGPTR_2 26 #define BZ_X_ORIGPTR_3 27 #define BZ_X_MAPPING_1 28 #define BZ_X_MAPPING_2 29 #define BZ_X_SELECTOR_1 30 #define BZ_X_SELECTOR_2 31 #define BZ_X_SELECTOR_3 32 #define BZ_X_CODING_1 33 #define BZ_X_CODING_2 34 #define BZ_X_CODING_3 35 #define BZ_X_MTF_1 36 #define BZ_X_MTF_2 37 #define BZ_X_MTF_3 38 #define BZ_X_MTF_4 39 #define BZ_X_MTF_5 40 #define BZ_X_MTF_6 41 #define BZ_X_ENDHDR_2 42 #define BZ_X_ENDHDR_3 43 #define BZ_X_ENDHDR_4 44 #define BZ_X_ENDHDR_5 45 #define BZ_X_ENDHDR_6 46 #define BZ_X_CCRC_1 47 #define BZ_X_CCRC_2 48 #define BZ_X_CCRC_3 49 #define BZ_X_CCRC_4 50 /*-- Constants for the fast MTF decoder. --*/ #define MTFA_SIZE 4096 #define MTFL_SIZE 16 /*-- Structure holding all the decompression-side stuff. --*/ typedef struct { /* pointer back to the struct bz_stream */ bz_stream* strm; /* state indicator for this stream */ Int32 state; /* for doing the final run-length decoding */ UChar state_out_ch; Int32 state_out_len; Bool blockRandomised; BZ_RAND_DECLS; /* the buffer for bit stream reading */ UInt32 bsBuff; Int32 bsLive; /* misc administratium */ Int32 blockSize100k; Bool smallDecompress; Int32 currBlockNo; Int32 verbosity; /* for undoing the Burrows-Wheeler transform */ Int32 origPtr; UInt32 tPos; Int32 k0; Int32 unzftab[256]; Int32 nblock_used; Int32 cftab[257]; Int32 cftabCopy[257]; /* for undoing the Burrows-Wheeler transform (FAST) */ UInt32 *tt; /* for undoing the Burrows-Wheeler transform (SMALL) */ UInt16 *ll16; UChar *ll4; /* stored and calculated CRCs */ UInt32 storedBlockCRC; UInt32 storedCombinedCRC; UInt32 calculatedBlockCRC; UInt32 calculatedCombinedCRC; /* map of bytes used in block */ Int32 nInUse; Bool inUse[256]; Bool inUse16[16]; UChar seqToUnseq[256]; /* for decoding the MTF values */ UChar mtfa [MTFA_SIZE]; Int32 mtfbase[256 / MTFL_SIZE]; UChar selector [BZ_MAX_SELECTORS]; UChar selectorMtf[BZ_MAX_SELECTORS]; UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 minLens[BZ_N_GROUPS]; /* save area for scalars in the main decompress code */ Int32 save_i; Int32 save_j; Int32 save_t; Int32 save_alphaSize; Int32 save_nGroups; Int32 save_nSelectors; Int32 save_EOB; Int32 save_groupNo; Int32 save_groupPos; Int32 save_nextSym; Int32 save_nblockMAX; Int32 save_nblock; Int32 save_es; Int32 save_N; Int32 save_curr; Int32 save_zt; Int32 save_zn; Int32 save_zvec; Int32 save_zj; Int32 save_gSel; Int32 save_gMinlen; Int32* save_gLimit; Int32* save_gBase; Int32* save_gPerm; } DState; /*-- Macros for decompression. --*/ #define BZ_GET_FAST(cccc) \ /* c_tPos is unsigned, hence test < 0 is pointless. */ \ if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ s->tPos = s->tt[s->tPos]; \ cccc = (UChar)(s->tPos & 0xff); \ s->tPos >>= 8; #define BZ_GET_FAST_C(cccc) \ /* c_tPos is unsigned, hence test < 0 is pointless. */ \ if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \ c_tPos = c_tt[c_tPos]; \ cccc = (UChar)(c_tPos & 0xff); \ c_tPos >>= 8; #define SET_LL4(i,n) \ { if (((i) & 0x1) == 0) \ s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \ s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \ } #define GET_LL4(i) \ ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF) #define SET_LL(i,n) \ { s->ll16[i] = (UInt16)(n & 0x0000ffff); \ SET_LL4(i, n >> 16); \ } #define GET_LL(i) \ (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16)) #define BZ_GET_SMALL(cccc) \ /* c_tPos is unsigned, hence test < 0 is pointless. */ \ if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \ s->tPos = GET_LL(s->tPos); /*-- externs for decompression. --*/ extern Int32 BZ2_indexIntoF ( Int32, Int32* ); extern Int32 BZ2_decompress ( DState* ); extern void BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, Int32, Int32, Int32 ); #endif /*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/ #ifdef BZ_NO_STDIO #ifndef NULL #define NULL 0 #endif #endif /*-------------------------------------------------------------*/ /*--- end bzlib_private.h ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/compress.c000066400000000000000000000501211462133141200215040ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Compression machinery (not incl block sorting) ---*/ /*--- compress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ /* CHANGES 0.9.0 -- original version. 0.9.0a/b -- no changes in this file. 0.9.0c -- changed setting of nGroups in sendMTFValues() so as to do a bit better on small files */ #include "bzlib_private.h" /*---------------------------------------------------*/ /*--- Bit stream I/O ---*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ void BZ2_bsInitWrite ( EState* s ) { s->bsLive = 0; s->bsBuff = 0; } /*---------------------------------------------------*/ static void bsFinishWrite ( EState* s ) { while (s->bsLive > 0) { s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24); s->numZ++; s->bsBuff <<= 8; s->bsLive -= 8; } } /*---------------------------------------------------*/ #define bsNEEDW(nz) \ { \ while (s->bsLive >= 8) { \ s->zbits[s->numZ] \ = (UChar)(s->bsBuff >> 24); \ s->numZ++; \ s->bsBuff <<= 8; \ s->bsLive -= 8; \ } \ } /*---------------------------------------------------*/ static __inline__ void bsW ( EState* s, Int32 n, UInt32 v ) { bsNEEDW ( n ); s->bsBuff |= (v << (32 - s->bsLive - n)); s->bsLive += n; } /*---------------------------------------------------*/ static void bsPutUInt32 ( EState* s, UInt32 u ) { bsW ( s, 8, (u >> 24) & 0xffL ); bsW ( s, 8, (u >> 16) & 0xffL ); bsW ( s, 8, (u >> 8) & 0xffL ); bsW ( s, 8, u & 0xffL ); } /*---------------------------------------------------*/ static void bsPutUChar ( EState* s, UChar c ) { bsW( s, 8, (UInt32)c ); } /*---------------------------------------------------*/ /*--- The back end proper ---*/ /*---------------------------------------------------*/ /*---------------------------------------------------*/ static void makeMaps_e ( EState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->unseqToSeq[i] = s->nInUse; s->nInUse++; } } /*---------------------------------------------------*/ static void generateMTFValues ( EState* s ) { UChar yy[256]; Int32 i, j; Int32 zPend; Int32 wr; Int32 EOB; /* After sorting (eg, here), s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, and ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] holds the original block data. The first thing to do is generate the MTF values, and put them in ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ]. Because there are strictly fewer or equal MTF values than block values, ptr values in this area are overwritten with MTF values only when they are no longer needed. The final compressed bitstream is generated into the area starting at (UChar*) (&((UChar*)s->arr2)[s->nblock]) These storage aliases are set up in bzCompressInit(), except for the last one, which is arranged in compressBlock(). */ UInt32* ptr = s->ptr; UChar* block = s->block; UInt16* mtfv = s->mtfv; makeMaps_e ( s ); EOB = s->nInUse+1; for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0; wr = 0; zPend = 0; for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i; for (i = 0; i < s->nblock; i++) { UChar ll_i; AssertD ( wr <= i, "generateMTFValues(1)" ); j = ptr[i]-1; if (j < 0) j += s->nblock; ll_i = s->unseqToSeq[block[j]]; AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); if (yy[0] == ll_i) { zPend++; } else { if (zPend > 0) { zPend--; while (True) { if (zPend & 1) { mtfv[wr] = BZ_RUNB; wr++; s->mtfFreq[BZ_RUNB]++; } else { mtfv[wr] = BZ_RUNA; wr++; s->mtfFreq[BZ_RUNA]++; } if (zPend < 2) break; zPend = (zPend - 2) / 2; }; zPend = 0; } { register UChar rtmp; register UChar* ryy_j; register UChar rll_i; rtmp = yy[1]; yy[1] = yy[0]; ryy_j = &(yy[1]); rll_i = ll_i; while ( rll_i != rtmp ) { register UChar rtmp2; ryy_j++; rtmp2 = rtmp; rtmp = *ryy_j; *ryy_j = rtmp2; }; yy[0] = rtmp; j = ryy_j - &(yy[0]); mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++; } } } if (zPend > 0) { zPend--; while (True) { if (zPend & 1) { mtfv[wr] = BZ_RUNB; wr++; s->mtfFreq[BZ_RUNB]++; } else { mtfv[wr] = BZ_RUNA; wr++; s->mtfFreq[BZ_RUNA]++; } if (zPend < 2) break; zPend = (zPend - 2) / 2; }; zPend = 0; } mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++; s->nMTF = wr; } /*---------------------------------------------------*/ #define BZ_LESSER_ICOST 0 #define BZ_GREATER_ICOST 15 static void sendMTFValues ( EState* s ) { Int32 v, t, i, j, gs, ge, totc, bt, bc, iter; Int32 nSelectors, alphaSize, minLen, maxLen, selCtr; Int32 nGroups, nBytes; /*-- UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; is a global since the decoder also needs it. Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; are also globals only used in this proc. Made global to keep stack frame size small. --*/ UInt16 cost[BZ_N_GROUPS]; Int32 fave[BZ_N_GROUPS]; UInt16* mtfv = s->mtfv; if (s->verbosity >= 3) VPrintf3( " %d in block, %d after MTF & 1-2 coding, " "%d+2 syms in use\n", s->nblock, s->nMTF, s->nInUse ); alphaSize = s->nInUse+2; for (t = 0; t < BZ_N_GROUPS; t++) for (v = 0; v < alphaSize; v++) s->len[t][v] = BZ_GREATER_ICOST; /*--- Decide how many coding tables to use ---*/ AssertH ( s->nMTF > 0, 3001 ); if (s->nMTF < 200) nGroups = 2; else if (s->nMTF < 600) nGroups = 3; else if (s->nMTF < 1200) nGroups = 4; else if (s->nMTF < 2400) nGroups = 5; else nGroups = 6; /*--- Generate an initial set of coding tables ---*/ { Int32 nPart, remF, tFreq, aFreq; nPart = nGroups; remF = s->nMTF; gs = 0; while (nPart > 0) { tFreq = remF / nPart; ge = gs-1; aFreq = 0; while (aFreq < tFreq && ge < alphaSize-1) { ge++; aFreq += s->mtfFreq[ge]; } if (ge > gs && nPart != nGroups && nPart != 1 && ((nGroups-nPart) % 2 == 1)) { aFreq -= s->mtfFreq[ge]; ge--; } if (s->verbosity >= 3) VPrintf5( " initial group %d, [%d .. %d], " "has %d syms (%4.1f%%)\n", nPart, gs, ge, aFreq, (100.0 * (float)aFreq) / (float)(s->nMTF) ); for (v = 0; v < alphaSize; v++) if (v >= gs && v <= ge) s->len[nPart-1][v] = BZ_LESSER_ICOST; else s->len[nPart-1][v] = BZ_GREATER_ICOST; nPart--; gs = ge+1; remF -= aFreq; } } /*--- Iterate up to BZ_N_ITERS times to improve the tables. ---*/ for (iter = 0; iter < BZ_N_ITERS; iter++) { for (t = 0; t < nGroups; t++) fave[t] = 0; for (t = 0; t < nGroups; t++) for (v = 0; v < alphaSize; v++) s->rfreq[t][v] = 0; /*--- Set up an auxiliary length table which is used to fast-track the common case (nGroups == 6). ---*/ if (nGroups == 6) { for (v = 0; v < alphaSize; v++) { s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; } } nSelectors = 0; totc = 0; gs = 0; while (True) { /*--- Set group start & end marks. --*/ if (gs >= s->nMTF) break; ge = gs + BZ_G_SIZE - 1; if (ge >= s->nMTF) ge = s->nMTF-1; /*-- Calculate the cost of this group as coded by each of the coding tables. --*/ for (t = 0; t < nGroups; t++) cost[t] = 0; if (nGroups == 6 && 50 == ge-gs+1) { /*--- fast track the common case ---*/ register UInt32 cost01, cost23, cost45; register UInt16 icv; cost01 = cost23 = cost45 = 0; # define BZ_ITER(nn) \ icv = mtfv[gs+(nn)]; \ cost01 += s->len_pack[icv][0]; \ cost23 += s->len_pack[icv][1]; \ cost45 += s->len_pack[icv][2]; \ BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4); BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9); BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14); BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19); BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24); BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29); BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34); BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39); BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44); BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49); # undef BZ_ITER cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16; cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16; cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; } else { /*--- slow version which correctly handles all situations ---*/ for (i = gs; i <= ge; i++) { UInt16 icv = mtfv[i]; for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; } } /*-- Find the coding table which is best for this group, and record its identity in the selector table. --*/ bc = 999999999; bt = -1; for (t = 0; t < nGroups; t++) if (cost[t] < bc) { bc = cost[t]; bt = t; }; totc += bc; fave[bt]++; s->selector[nSelectors] = bt; nSelectors++; /*-- Increment the symbol frequencies for the selected table. --*/ if (nGroups == 6 && 50 == ge-gs+1) { /*--- fast track the common case ---*/ # define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++ BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4); BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9); BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14); BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19); BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24); BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29); BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34); BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39); BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44); BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49); # undef BZ_ITUR } else { /*--- slow version which correctly handles all situations ---*/ for (i = gs; i <= ge; i++) s->rfreq[bt][ mtfv[i] ]++; } gs = ge+1; } if (s->verbosity >= 3) { VPrintf2 ( " pass %d: size is %d, grp uses are ", iter+1, totc/8 ); for (t = 0; t < nGroups; t++) VPrintf1 ( "%d ", fave[t] ); VPrintf0 ( "\n" ); } /*-- Recompute the tables based on the accumulated frequencies. --*/ /* maxLen was changed from 20 to 17 in bzip2-1.0.3. See comment in huffman.c for details. */ for (t = 0; t < nGroups; t++) BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), alphaSize, 17 /*20*/ ); } AssertH( nGroups < 8, 3002 ); AssertH( nSelectors < 32768 && nSelectors <= (2 + (900000 / BZ_G_SIZE)), 3003 ); /*--- Compute MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp; for (i = 0; i < nGroups; i++) pos[i] = i; for (i = 0; i < nSelectors; i++) { ll_i = s->selector[i]; j = 0; tmp = pos[j]; while ( ll_i != tmp ) { j++; tmp2 = tmp; tmp = pos[j]; pos[j] = tmp2; }; pos[0] = tmp; s->selectorMtf[i] = j; } }; /*--- Assign actual codes for the tables. --*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } AssertH ( !(maxLen > 17 /*20*/ ), 3004 ); AssertH ( !(minLen < 1), 3005 ); BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); } /*--- Transmit the mapping table. ---*/ { Bool inUse16[16]; for (i = 0; i < 16; i++) { inUse16[i] = False; for (j = 0; j < 16; j++) if (s->inUse[i * 16 + j]) inUse16[i] = True; } nBytes = s->numZ; for (i = 0; i < 16; i++) if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); for (i = 0; i < 16; i++) if (inUse16[i]) for (j = 0; j < 16; j++) { if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); } if (s->verbosity >= 3) VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); } /*--- Now the selectors. ---*/ nBytes = s->numZ; bsW ( s, 3, nGroups ); bsW ( s, 15, nSelectors ); for (i = 0; i < nSelectors; i++) { for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); bsW(s,1,0); } if (s->verbosity >= 3) VPrintf1( "selectors %d, ", s->numZ-nBytes ); /*--- Now the coding tables. ---*/ nBytes = s->numZ; for (t = 0; t < nGroups; t++) { Int32 curr = s->len[t][0]; bsW ( s, 5, curr ); for (i = 0; i < alphaSize; i++) { while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ }; while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ }; bsW ( s, 1, 0 ); } } if (s->verbosity >= 3) VPrintf1 ( "code lengths %d, ", s->numZ-nBytes ); /*--- And finally, the block data proper ---*/ nBytes = s->numZ; selCtr = 0; gs = 0; while (True) { if (gs >= s->nMTF) break; ge = gs + BZ_G_SIZE - 1; if (ge >= s->nMTF) ge = s->nMTF-1; AssertH ( s->selector[selCtr] < nGroups, 3006 ); if (nGroups == 6 && 50 == ge-gs+1) { /*--- fast track the common case ---*/ UInt16 mtfv_i; UChar* s_len_sel_selCtr = &(s->len[s->selector[selCtr]][0]); Int32* s_code_sel_selCtr = &(s->code[s->selector[selCtr]][0]); # define BZ_ITAH(nn) \ mtfv_i = mtfv[gs+(nn)]; \ bsW ( s, \ s_len_sel_selCtr[mtfv_i], \ s_code_sel_selCtr[mtfv_i] ) BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4); BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9); BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14); BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19); BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24); BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29); BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34); BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39); BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44); BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49); # undef BZ_ITAH } else { /*--- slow version which correctly handles all situations ---*/ for (i = gs; i <= ge; i++) { bsW ( s, s->len [s->selector[selCtr]] [mtfv[i]], s->code [s->selector[selCtr]] [mtfv[i]] ); } } gs = ge+1; selCtr++; } AssertH( selCtr == nSelectors, 3007 ); if (s->verbosity >= 3) VPrintf1( "codes %d\n", s->numZ-nBytes ); } /*---------------------------------------------------*/ void BZ2_compressBlock ( EState* s, Bool is_last_block ) { if (s->nblock > 0) { BZ_FINALISE_CRC ( s->blockCRC ); s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31); s->combinedCRC ^= s->blockCRC; if (s->blockNo > 1) s->numZ = 0; if (s->verbosity >= 2) VPrintf4( " block %d: crc = 0x%08x, " "combined CRC = 0x%08x, size = %d\n", s->blockNo, s->blockCRC, s->combinedCRC, s->nblock ); BZ2_blockSort ( s ); } s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]); /*-- If this is the first block, create the stream header. --*/ if (s->blockNo == 1) { BZ2_bsInitWrite ( s ); bsPutUChar ( s, BZ_HDR_B ); bsPutUChar ( s, BZ_HDR_Z ); bsPutUChar ( s, BZ_HDR_h ); bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) ); } if (s->nblock > 0) { bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 ); bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 ); bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 ); /*-- Now the block's CRC, so it is in a known place. --*/ bsPutUInt32 ( s, s->blockCRC ); /*-- Now a single bit indicating (non-)randomisation. As of version 0.9.5, we use a better sorting algorithm which makes randomisation unnecessary. So always set the randomised bit to 'no'. Of course, the decoder still needs to be able to handle randomised blocks so as to maintain backwards compatibility with older versions of bzip2. --*/ bsW(s,1,0); bsW ( s, 24, s->origPtr ); generateMTFValues ( s ); sendMTFValues ( s ); } /*-- If this is the last block, add the stream trailer. --*/ if (is_last_block) { bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 ); bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 ); bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 ); bsPutUInt32 ( s, s->combinedCRC ); if (s->verbosity >= 2) VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC ); bsFinishWrite ( s ); } } /*-------------------------------------------------------------*/ /*--- end compress.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/crctable.c000066400000000000000000000113221462133141200214300ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Table for doing CRCs ---*/ /*--- crctable.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*-- I think this is an implementation of the AUTODIN-II, Ethernet & FDDI 32-bit CRC standard. Vaguely derived from code by Rob Warnock, in Section 51 of the comp.compression FAQ. --*/ UInt32 BZ2_crc32Table[256] = { /*-- Ugly, innit? --*/ 0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L, 0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L, 0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L, 0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL, 0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L, 0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L, 0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L, 0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL, 0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L, 0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L, 0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L, 0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL, 0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L, 0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L, 0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L, 0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL, 0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL, 0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L, 0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L, 0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL, 0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL, 0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L, 0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L, 0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL, 0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL, 0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L, 0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L, 0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL, 0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL, 0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L, 0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L, 0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL, 0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L, 0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL, 0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL, 0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L, 0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L, 0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL, 0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL, 0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L, 0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L, 0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL, 0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL, 0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L, 0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L, 0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL, 0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL, 0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L, 0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L, 0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL, 0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L, 0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L, 0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L, 0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL, 0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L, 0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L, 0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L, 0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL, 0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L, 0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L, 0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L, 0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL, 0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L, 0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L }; /*-------------------------------------------------------------*/ /*--- end crctable.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/decompress.c000066400000000000000000000506671462133141200220340ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/huffman.c000066400000000000000000000155171462133141200213070ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Huffman coding low-level stuff ---*/ /*--- huffman.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ #define WEIGHTOF(zz0) ((zz0) & 0xffffff00) #define DEPTHOF(zz1) ((zz1) & 0x000000ff) #define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3)) #define ADDWEIGHTS(zw1,zw2) \ (WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \ (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2))) #define UPHEAP(z) \ { \ Int32 zz, tmp; \ zz = z; tmp = heap[zz]; \ while (weight[tmp] < weight[heap[zz >> 1]]) { \ heap[zz] = heap[zz >> 1]; \ zz >>= 1; \ } \ heap[zz] = tmp; \ } #define DOWNHEAP(z) \ { \ Int32 zz, yy, tmp; \ zz = z; tmp = heap[zz]; \ while (True) { \ yy = zz << 1; \ if (yy > nHeap) break; \ if (yy < nHeap && \ weight[heap[yy+1]] < weight[heap[yy]]) \ yy++; \ if (weight[tmp] < weight[heap[yy]]) break; \ heap[zz] = heap[yy]; \ zz = yy; \ } \ heap[zz] = tmp; \ } /*---------------------------------------------------*/ void BZ2_hbMakeCodeLengths ( UChar *len, Int32 *freq, Int32 alphaSize, Int32 maxLen ) { /*-- Nodes and heap entries run from 1. Entry 0 for both the heap and nodes is a sentinel. --*/ Int32 nNodes, nHeap, n1, n2, i, j, k; Bool tooLong; Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; for (i = 0; i < alphaSize; i++) weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; while (True) { nNodes = alphaSize; nHeap = 0; heap[0] = 0; weight[0] = 0; parent[0] = -2; for (i = 1; i <= alphaSize; i++) { parent[i] = -1; nHeap++; heap[nHeap] = i; UPHEAP(nHeap); } AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); while (nHeap > 1) { n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); nNodes++; parent[n1] = parent[n2] = nNodes; weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]); parent[nNodes] = -1; nHeap++; heap[nHeap] = nNodes; UPHEAP(nHeap); } AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 ); tooLong = False; for (i = 1; i <= alphaSize; i++) { j = 0; k = i; while (parent[k] >= 0) { k = parent[k]; j++; } len[i-1] = j; if (j > maxLen) tooLong = True; } if (! tooLong) break; /* 17 Oct 04: keep-going condition for the following loop used to be 'i < alphaSize', which missed the last element, theoretically leading to the possibility of the compressor looping. However, this count-scaling step is only needed if one of the generated Huffman code words is longer than maxLen, which up to and including version 1.0.2 was 20 bits, which is extremely unlikely. In version 1.0.3 maxLen was changed to 17 bits, which has minimal effect on compression ratio, but does mean this scaling step is used from time to time, enough to verify that it works. This means that bzip2-1.0.3 and later will only produce Huffman codes with a maximum length of 17 bits. However, in order to preserve backwards compatibility with bitstreams produced by versions pre-1.0.3, the decompressor must still handle lengths of up to 20. */ for (i = 1; i <= alphaSize; i++) { j = weight[i] >> 8; j = 1 + (j / 2); weight[i] = j << 8; } } } /*---------------------------------------------------*/ void BZ2_hbAssignCodes ( Int32 *code, UChar *length, Int32 minLen, Int32 maxLen, Int32 alphaSize ) { Int32 n, vec, i; vec = 0; for (n = minLen; n <= maxLen; n++) { for (i = 0; i < alphaSize; i++) if (length[i] == n) { code[i] = vec; vec++; }; vec <<= 1; } } /*---------------------------------------------------*/ void BZ2_hbCreateDecodeTables ( Int32 *limit, Int32 *base, Int32 *perm, UChar *length, Int32 minLen, Int32 maxLen, Int32 alphaSize ) { Int32 pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) for (j = 0; j < alphaSize; j++) if (length[j] == i) { perm[pp] = j; pp++; }; for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; for (i = 0; i < alphaSize; i++) base[length[i]+1]++; for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (base[i+1] - base[i]); limit[i] = vec-1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) base[i] = ((limit[i-1] + 1) << 1) - base[i]; } /*-------------------------------------------------------------*/ /*--- end huffman.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/bzip2/libbz2.def000066400000000000000000000007521462133141200213560ustar00rootroot00000000000000LIBRARY LIBBZ2 DESCRIPTION "libbzip2: library for data compression" EXPORTS BZ2_bzCompressInit BZ2_bzCompress BZ2_bzCompressEnd BZ2_bzDecompressInit BZ2_bzDecompress BZ2_bzDecompressEnd BZ2_bzReadOpen BZ2_bzReadClose BZ2_bzReadGetUnused BZ2_bzRead BZ2_bzWriteOpen BZ2_bzWrite BZ2_bzWriteClose BZ2_bzWriteClose64 BZ2_bzBuffToBuffCompress BZ2_bzBuffToBuffDecompress BZ2_bzlibVersion BZ2_bzopen BZ2_bzdopen BZ2_bzread BZ2_bzwrite BZ2_bzflush BZ2_bzclose BZ2_bzerror bcmatroska2-5.3.101/libmatroska2/bzip2/randtable.c000066400000000000000000000074241462133141200216150ustar00rootroot00000000000000 /*-------------------------------------------------------------*/ /*--- Table for randomising repetitive blocks ---*/ /*--- randtable.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------*/ Int32 BZ2_rNums[512] = { 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, 936, 638 }; /*-------------------------------------------------------------*/ /*--- end randtable.c ---*/ /*-------------------------------------------------------------*/ bcmatroska2-5.3.101/libmatroska2/libmatroska2.proj000066400000000000000000000016261462133141200217530ustar00rootroot00000000000000#include "*/*.proj" PROJECT matroska2 { PROJECT_NAME "libmatroska2" PROJECT_VERSION 0.22.1 PROJECT_VENDOR "Matroska" } GROUP matroska2_group { USE ebml2 EXPDEFINE HAS_MATROSKA2 USE(CONFIG_CODEC_HELPER) tremor USE zlib_deflate USE minilzo USE bzlib DEFINE(CONFIG_MATROSKA2_NOGLOBAL) NO_MATROSKA2_GLOBAL EXPDEFINE(CONFIG_MATROSKA2_NOGLOBAL) NO_MATROSKA2_GLOBAL INCLUDE . EXPINCLUDE . SOURCE matroskamain.c {class Matroska_Class} SOURCE matroskablock.c SOURCE matroska_sem.c HEADER matroska/matroska.h HEADER matroska/matroska_sem.h HEADER matroska/matroska_internal.h } DLL matroska2 { DEFINE MATROSKA_LIBRARY USE matroska2_group } GROUP matroska2_haali { USE(COREMAKE_STATIC) matroska2_group USE(!COREMAKE_STATIC) matroska2 INCLUDE MatroskaParser SOURCE MatroskaParser/MatroskaParser.c {class HaaliStream_Class} HEADER MatroskaParser/MatroskaParser.h } bcmatroska2-5.3.101/libmatroska2/matroska/000077500000000000000000000000001462133141200203015ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/matroska/matroska.h000066400000000000000000000240241462133141200222750ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MATROSKA_MATROSKA_H #define MATROSKA_MATROSKA_H #include "ebml/ebml.h" #if defined(MATROSKA2_EXPORTS) #define MATROSKA_DLL DLLEXPORT #elif defined(MATROSKA2_IMPORTS) #define MATROSKA_DLL DLLIMPORT #else #define MATROSKA_DLL #endif #define CONTEXT_LIBMATROSKA_VERSION 0x00402 // if a profile is set in ebml_semantic.DisabledProfile that means the element is not available for that profile #define PROFILE_MATROSKA_V1 1 #define PROFILE_MATROSKA_V2 2 #define PROFILE_MATROSKA_V3 4 #define PROFILE_MATROSKA_V4 32 #define PROFILE_WEBM 8 #define PROFILE_DIVX 16 #define MATROSKA_VERSION 2 #define MATROSKA_BLOCK_COMPR_NONE -1 #define MATROSKA_BLOCK_COMPR_ZLIB 0 #define MATROSKA_BLOCK_COMPR_BZLIB 1 #define MATROSKA_BLOCK_COMPR_LZO1X 2 #define MATROSKA_BLOCK_COMPR_HEADER 3 #define MATROSKA_COMPR_SCOPE_BLOCK 1 #define MATROSKA_COMPR_SCOPE_PRIVATE 2 #define MATROSKA_COMPR_SCOPE_NEXT 4 #define MATROSKA_DISPLAY_UNIT_PIXEL 0 #define MATROSKA_DISPLAY_UNIT_CM 1 #define MATROSKA_DISPLAY_UNIT_INCHES 2 #define MATROSKA_DISPLAY_UNIT_DAR 3 EBML_DLL err_t MATROSKA_Init(nodecontext *p); EBML_DLL err_t MATROSKA_Done(nodecontext *p); #define INVALID_TIMECODE_T MAX_INT64 typedef int64_t timecode_t; // in nanoseconds #define TRACK_TYPE_VIDEO 1 #define TRACK_TYPE_AUDIO 2 #define TRACK_TYPE_COMPLEX 3 #define TRACK_TYPE_SUBTITLE 17 #define TRACK_TYPE_LOGO 16 #define TRACK_TYPE_BUTTONS 18 #define TRACK_TYPE_CONTROL 32 #define TRACK_STEREO_MODE_MONO 0 #define TRACK_STEREO_MODE_SIDEBYSIDE_L 1 #define TRACK_STEREO_MODE_TOPBOTTOM_R 2 #define TRACK_STEREO_MODE_TOPBOTTOM_L 3 #define TRACK_STEREO_MODE_CHECKBOARD_R 4 #define TRACK_STEREO_MODE_CHECKBOARD_L 5 #define TRACK_STEREO_MODE_INTERLEAVED_R 6 #define TRACK_STEREO_MODE_INTERLEAVED_L 7 #define TRACK_STEREO_MODE_COL_INTERLEAVED_L 8 #define TRACK_STEREO_MODE_COL_INTERLEAVED_R 9 #define TRACK_STEREO_MODE_ANAGLYPH_CYAN_RED 10 #define TRACK_STEREO_MODE_SIDEBYSIDE_R 11 #define TRACK_STEREO_MODE_ANAGLYPH_GREEN_MAG 12 #define TRACK_STEREO_MODE_ALTERNATE_PACKED_L 13 #define TRACK_STEREO_MODE_ALTERNATE_PACKED_R 14 #define TRACK_PLANE_LEFT 0 #define TRACK_PLANE_RIGHT 1 #define TRACK_PLANE_BACKGROUND 2 #define TRACK_OLD_STEREOMODE_MONO 0 #define TRACK_OLD_STEREOMODE_RIGHT 1 #define TRACK_OLD_STEREOMODE_LEFT 2 #define TRACK_OLD_STEREOMODE_BOTH 3 typedef struct matroska_block matroska_block; typedef struct matroska_cuepoint matroska_cuepoint; typedef struct matroska_cluster matroska_cluster; typedef struct matroska_seekpoint matroska_seekpoint; typedef struct matroska_trackentry matroska_trackentry; typedef struct matroska_frame { uint8_t *Data; uint32_t Size; timecode_t Timecode; timecode_t Duration; } matroska_frame; EBML_DLL err_t MATROSKA_LinkMetaSeekElement(matroska_seekpoint *MetaSeek, ebml_element *Link); EBML_DLL err_t MATROSKA_MetaSeekUpdate(matroska_seekpoint *MetaSeek); EBML_DLL err_t MATROSKA_LinkClusterReadSegmentInfo(matroska_cluster *Cluster, ebml_master *SegmentInfo, bool_t UseForWriteToo); EBML_DLL err_t MATROSKA_LinkBlockWithReadTracks(matroska_block *Block, ebml_master *Tracks, bool_t UseForWriteToo); EBML_DLL err_t MATROSKA_LinkBlockReadTrack(matroska_block *Block, ebml_master *Track, bool_t UseForWriteToo); EBML_DLL err_t MATROSKA_LinkBlockReadSegmentInfo(matroska_block *Block, ebml_master *SegmentInfo, bool_t UseForWriteToo); #if defined(CONFIG_EBML_WRITING) EBML_DLL err_t MATROSKA_LinkClusterWriteSegmentInfo(matroska_cluster *Cluster, ebml_master *SegmentInfo); EBML_DLL err_t MATROSKA_LinkBlockWithWriteTracks(matroska_block *Block, ebml_master *Tracks); EBML_DLL err_t MATROSKA_LinkBlockWriteTrack(matroska_block *Block, ebml_master *Track); EBML_DLL err_t MATROSKA_LinkBlockWriteSegmentInfo(matroska_block *Block, ebml_master *SegmentInfo); #endif //EBML_DLL err_t MATROSKA_LinkCueTrack(const ebml_element *Cue, ebml_element *Tracks); EBML_DLL err_t MATROSKA_LinkCueSegmentInfo(matroska_cuepoint *Cue, ebml_master *SegmentInfo); EBML_DLL err_t MATROSKA_LinkCuePointBlock(matroska_cuepoint *Cue, matroska_block *Block); EBML_DLL err_t MATROSKA_CuePointUpdate(matroska_cuepoint *Cue, ebml_element *Segment); EBML_DLL double MATROSKA_TrackTimecodeScale(const ebml_master *Track); EBML_DLL timecode_t MATROSKA_SegmentInfoTimecodeScale(const ebml_master *SegmentInfo); EBML_DLL void MATROSKA_ClusterSetTimecode(matroska_cluster *Cluster, timecode_t Timecode); EBML_DLL err_t MATROSKA_BlockSetTimecode(matroska_block *Block, timecode_t Timecode, timecode_t ClusterTimecode); EBML_DLL timecode_t MATROSKA_ClusterTimecode(matroska_cluster *Cluster); EBML_DLL timecode_t MATROSKA_ClusterTimecodeScale(matroska_cluster *Cluster, bool_t Read); EBML_DLL timecode_t MATROSKA_BlockTimecode(matroska_block *Block); EBML_DLL timecode_t MATROSKA_CueTimecode(const matroska_cuepoint *Cue); EBML_DLL filepos_t MATROSKA_CuePosInSegment(const matroska_cuepoint *Cue); EBML_DLL int16_t MATROSKA_BlockTrackNum(const matroska_block *Block); EBML_DLL bool_t MATROSKA_BlockKeyframe(const matroska_block *Block); EBML_DLL bool_t MATROSKA_BlockDiscardable(const matroska_block *Block); EBML_DLL bool_t MATROSKA_BlockLaced(const matroska_block *Block); EBML_DLL err_t MATROSKA_BlockReadData(matroska_block *Block, stream *Input); EBML_DLL err_t MATROSKA_BlockReleaseData(matroska_block *Block, bool_t IncludingNotRead); EBML_DLL int16_t MATROSKA_CueTrackNum(const matroska_cuepoint *Cue); EBML_DLL void MATROSKA_CuesSort(ebml_master *Cues); EBML_DLL void MATROSKA_AttachmentSort(ebml_master *Attachments); EBML_DLL fourcc_t MATROSKA_MetaSeekID(const matroska_seekpoint *MetaSeek); EBML_DLL bool_t MATROSKA_MetaSeekIsClass(const matroska_seekpoint *MetaSeek, const ebml_context *Class); EBML_DLL filepos_t MATROSKA_MetaSeekPosInSegment(const matroska_seekpoint *MetaSeek); EBML_DLL filepos_t MATROSKA_MetaSeekAbsolutePos(const matroska_seekpoint *MetaSeek); EBML_DLL matroska_cuepoint *MATROSKA_CuesGetTimecodeStart(const ebml_element *Cues, timecode_t Timecode); #if defined(CONFIG_EBML_WRITING) EBML_DLL int MATROSKA_TrackGetBlockCompression(const matroska_trackentry *TrackEntry); EBML_DLL bool_t MATROSKA_TrackSetCompressionZlib(matroska_trackentry *TrackEntry, int Scope); EBML_DLL bool_t MATROSKA_TrackSetCompressionHeader(matroska_trackentry *TrackEntry, const uint8_t *Header, size_t HeaderSize); EBML_DLL bool_t MATROSKA_TrackSetCompressionNone(matroska_trackentry *TrackEntry); EBML_DLL err_t CompressFrameZLib(const uint8_t *Cursor, size_t CursorSize, uint8_t **OutBuf, size_t *OutSize); #endif EBML_DLL void MATROSKA_ClusterSort(matroska_cluster *Cluster); // not good with P frames!!! EBML_DLL ebml_element *MATROSKA_BlockReadTrack(const matroska_block *Block); EBML_DLL ebml_element *MATROSKA_BlockReadSegmentInfo(const matroska_block *Block); #if defined(CONFIG_EBML_WRITING) EBML_DLL ebml_element *MATROSKA_BlockWriteTrack(const matroska_block *Block); EBML_DLL ebml_element *MATROSKA_BlockWriteSegmentInfo(const matroska_block *Block); #endif EBML_DLL err_t MATROSKA_BlockSkipToFrame(const matroska_block *Block, stream *Input, size_t FrameNum); EBML_DLL void MATROSKA_BlockSetKeyframe(matroska_block *Block, bool_t Set); EBML_DLL void MATROSKA_BlockSetTrackNum(matroska_block *Block, int16_t TrackNum); EBML_DLL void MATROSKA_BlockSetDiscardable(matroska_block *Block, bool_t Set); EBML_DLL err_t MATROSKA_BlockProcessFrameDurations(matroska_block *Block, stream *Input); EBML_DLL size_t MATROSKA_BlockGetFrameCount(const matroska_block *Block); EBML_DLL timecode_t MATROSKA_BlockGetFrameDuration(const matroska_block *Block, size_t FrameNum); EBML_DLL timecode_t MATROSKA_BlockGetFrameStart(const matroska_block *Block, size_t FrameNum); EBML_DLL timecode_t MATROSKA_BlockGetFrameEnd(const matroska_block *Block, size_t FrameNum); EBML_DLL size_t MATROSKA_BlockGetLength(const matroska_block *Block, size_t FrameNum); EBML_DLL err_t MATROSKA_BlockGetFrame(const matroska_block *Block, size_t FrameNum, matroska_frame *Frame, bool_t WithData); EBML_DLL err_t MATROSKA_BlockAppendFrame(matroska_block *Block, const matroska_frame *Frame, timecode_t ClusterTimecode); EBML_DLL matroska_block *MATROSKA_GetBlockForTimecode(matroska_cluster *Cluster, timecode_t Timecode, int16_t Track); EBML_DLL void MATROSKA_LinkClusterBlocks(matroska_cluster *Cluster, ebml_master *RSegmentInfo, ebml_master *Tracks, bool_t KeepUnmatched); extern const ebml_context MATROSKA_ContextStream; #endif // MATROSKA_MATROSKA_H bcmatroska2-5.3.101/libmatroska2/matroska/matroska_internal.h000066400000000000000000000061161462133141200241730ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBMATROSKA2_INTERNAL_H #define LIBMATROSKA2_INTERNAL_H /* * ONLY INCLUDE THIS FILE IF YOU PLAN TO CREATE YOUR OWN MATROSKA-BASED CLASS */ #include "ebml/ebml_internal.h" #define MATROSKA_BLOCK_READ_TRACK 0x180 #define MATROSKA_BLOCK_READ_SEGMENTINFO 0x181 #if defined(CONFIG_EBML_WRITING) #define MATROSKA_BLOCK_WRITE_TRACK 0x182 #define MATROSKA_BLOCK_WRITE_SEGMENTINFO 0x183 #endif struct matroska_block { ebml_binary Base; timecode_t GlobalTimecode; filepos_t FirstFrameLocation; array SizeList; // int32_t array SizeListIn; // int32_t array Data; // uint8_t array Durations; // timecode_t ebml_master *ReadTrack; ebml_master *ReadSegInfo; #if defined(CONFIG_EBML_WRITING) ebml_master *WriteTrack; ebml_master *WriteSegInfo; #endif bool_t IsKeyframe; bool_t IsDiscardable; bool_t Invisible; bool_t LocalTimecodeUsed; int16_t LocalTimecode; uint16_t TrackNumber; char Lacing; }; #define MATROSKA_BLOCK_CLASS FOURCC('M','K','B','L') #define MATROSKA_BLOCKGROUP_CLASS FOURCC('M','K','B','G') #define MATROSKA_CUEPOINT_CLASS FOURCC('M','K','C','P') #define MATROSKA_CLUSTER_CLASS FOURCC('M','K','C','U') #define MATROSKA_SEEKPOINT_CLASS FOURCC('M','K','S','K') #define MATROSKA_SEGMENTUID_CLASS FOURCC('M','K','I','D') #define MATROSKA_BIGBINARY_CLASS FOURCC('M','K','B','B') #define MATROSKA_ATTACHMENT_CLASS FOURCC('M','K','A','T') #define MATROSKA_TRACKENTRY_CLASS FOURCC('M','K','T','E') #endif /* LIBMATROSKA2_INTERNAL_H */ bcmatroska2-5.3.101/libmatroska2/matroska/matroska_sem.h000066400000000000000000000323261462133141200231450ustar00rootroot00000000000000/* * DO NOT EDIT, GENERATED WITH DATA2LIB2 * * $Id$ * Copyright (c) 2008-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "matroska/matroska.h" #include "matroska/matroska_internal.h" #ifndef MATROSKA_SEMANTIC_H #define MATROSKA_SEMANTIC_H extern const ebml_context MATROSKA_ContextSeekID; extern const ebml_context MATROSKA_ContextSeekPosition; extern const ebml_context MATROSKA_ContextSeek; extern const ebml_context MATROSKA_ContextSeekHead; extern const ebml_context MATROSKA_ContextSegmentUID; extern const ebml_context MATROSKA_ContextSegmentFilename; extern const ebml_context MATROSKA_ContextPrevUID; extern const ebml_context MATROSKA_ContextPrevFilename; extern const ebml_context MATROSKA_ContextNextUID; extern const ebml_context MATROSKA_ContextNextFilename; extern const ebml_context MATROSKA_ContextSegmentFamily; extern const ebml_context MATROSKA_ContextChapterTranslateEditionUID; extern const ebml_context MATROSKA_ContextChapterTranslateCodec; extern const ebml_context MATROSKA_ContextChapterTranslateID; extern const ebml_context MATROSKA_ContextChapterTranslate; extern const ebml_context MATROSKA_ContextTimecodeScale; extern const ebml_context MATROSKA_ContextDuration; extern const ebml_context MATROSKA_ContextDateUTC; extern const ebml_context MATROSKA_ContextTitle; extern const ebml_context MATROSKA_ContextMuxingApp; extern const ebml_context MATROSKA_ContextWritingApp; extern const ebml_context MATROSKA_ContextInfo; extern const ebml_context MATROSKA_ContextTimecode; extern const ebml_context MATROSKA_ContextSilentTrackNumber; extern const ebml_context MATROSKA_ContextSilentTracks; extern const ebml_context MATROSKA_ContextPosition; extern const ebml_context MATROSKA_ContextPrevSize; extern const ebml_context MATROSKA_ContextSimpleBlock; extern const ebml_context MATROSKA_ContextBlock; extern const ebml_context MATROSKA_ContextBlockVirtual; extern const ebml_context MATROSKA_ContextBlockAddID; extern const ebml_context MATROSKA_ContextBlockAdditional; extern const ebml_context MATROSKA_ContextBlockMore; extern const ebml_context MATROSKA_ContextBlockAdditions; extern const ebml_context MATROSKA_ContextBlockDuration; extern const ebml_context MATROSKA_ContextReferencePriority; extern const ebml_context MATROSKA_ContextReferenceBlock; extern const ebml_context MATROSKA_ContextReferenceVirtual; extern const ebml_context MATROSKA_ContextCodecState; extern const ebml_context MATROSKA_ContextDiscardPadding; extern const ebml_context MATROSKA_ContextLaceNumber; extern const ebml_context MATROSKA_ContextFrameNumber; extern const ebml_context MATROSKA_ContextBlockAdditionID; extern const ebml_context MATROSKA_ContextDelay; extern const ebml_context MATROSKA_ContextSliceDuration; extern const ebml_context MATROSKA_ContextTimeSlice; extern const ebml_context MATROSKA_ContextSlices; extern const ebml_context MATROSKA_ContextReferenceOffset; extern const ebml_context MATROSKA_ContextReferenceTimeCode; extern const ebml_context MATROSKA_ContextReferenceFrame; extern const ebml_context MATROSKA_ContextBlockGroup; extern const ebml_context MATROSKA_ContextEncryptedBlock; extern const ebml_context MATROSKA_ContextCluster; extern const ebml_context MATROSKA_ContextTrackNumber; extern const ebml_context MATROSKA_ContextTrackUID; extern const ebml_context MATROSKA_ContextTrackType; extern const ebml_context MATROSKA_ContextFlagEnabled; extern const ebml_context MATROSKA_ContextFlagDefault; extern const ebml_context MATROSKA_ContextFlagForced; extern const ebml_context MATROSKA_ContextFlagLacing; extern const ebml_context MATROSKA_ContextMinCache; extern const ebml_context MATROSKA_ContextMaxCache; extern const ebml_context MATROSKA_ContextDefaultDuration; extern const ebml_context MATROSKA_ContextDefaultDecodedFieldDuration; extern const ebml_context MATROSKA_ContextTrackTimecodeScale; extern const ebml_context MATROSKA_ContextTrackOffset; extern const ebml_context MATROSKA_ContextMaxBlockAdditionID; extern const ebml_context MATROSKA_ContextName; extern const ebml_context MATROSKA_ContextLanguage; extern const ebml_context MATROSKA_ContextCodecID; extern const ebml_context MATROSKA_ContextCodecPrivate; extern const ebml_context MATROSKA_ContextCodecName; extern const ebml_context MATROSKA_ContextAttachmentLink; extern const ebml_context MATROSKA_ContextCodecSettings; extern const ebml_context MATROSKA_ContextCodecInfoURL; extern const ebml_context MATROSKA_ContextCodecDownloadURL; extern const ebml_context MATROSKA_ContextCodecDecodeAll; extern const ebml_context MATROSKA_ContextTrackOverlay; extern const ebml_context MATROSKA_ContextCodecDelay; extern const ebml_context MATROSKA_ContextSeekPreRoll; extern const ebml_context MATROSKA_ContextTrackTranslateEditionUID; extern const ebml_context MATROSKA_ContextTrackTranslateCodec; extern const ebml_context MATROSKA_ContextTrackTranslateTrackID; extern const ebml_context MATROSKA_ContextTrackTranslate; extern const ebml_context MATROSKA_ContextFlagInterlaced; extern const ebml_context MATROSKA_ContextStereoMode; extern const ebml_context MATROSKA_ContextAlphaMode; extern const ebml_context MATROSKA_ContextOldStereoMode; extern const ebml_context MATROSKA_ContextPixelWidth; extern const ebml_context MATROSKA_ContextPixelHeight; extern const ebml_context MATROSKA_ContextPixelCropBottom; extern const ebml_context MATROSKA_ContextPixelCropTop; extern const ebml_context MATROSKA_ContextPixelCropLeft; extern const ebml_context MATROSKA_ContextPixelCropRight; extern const ebml_context MATROSKA_ContextDisplayWidth; extern const ebml_context MATROSKA_ContextDisplayHeight; extern const ebml_context MATROSKA_ContextDisplayUnit; extern const ebml_context MATROSKA_ContextAspectRatioType; extern const ebml_context MATROSKA_ContextColourSpace; extern const ebml_context MATROSKA_ContextGammaValue; extern const ebml_context MATROSKA_ContextFrameRate; extern const ebml_context MATROSKA_ContextVideo; extern const ebml_context MATROSKA_ContextSamplingFrequency; extern const ebml_context MATROSKA_ContextOutputSamplingFrequency; extern const ebml_context MATROSKA_ContextChannels; extern const ebml_context MATROSKA_ContextChannelPositions; extern const ebml_context MATROSKA_ContextBitDepth; extern const ebml_context MATROSKA_ContextAudio; extern const ebml_context MATROSKA_ContextTrackPlaneUID; extern const ebml_context MATROSKA_ContextTrackPlaneType; extern const ebml_context MATROSKA_ContextTrackPlane; extern const ebml_context MATROSKA_ContextTrackCombinePlanes; extern const ebml_context MATROSKA_ContextTrackJoinUID; extern const ebml_context MATROSKA_ContextTrackJoinBlocks; extern const ebml_context MATROSKA_ContextTrackOperation; extern const ebml_context MATROSKA_ContextTrickTrackUID; extern const ebml_context MATROSKA_ContextTrickTrackSegmentUID; extern const ebml_context MATROSKA_ContextTrickTrackFlag; extern const ebml_context MATROSKA_ContextTrickMasterTrackUID; extern const ebml_context MATROSKA_ContextTrickMasterTrackSegmentUID; extern const ebml_context MATROSKA_ContextContentEncodingOrder; extern const ebml_context MATROSKA_ContextContentEncodingScope; extern const ebml_context MATROSKA_ContextContentEncodingType; extern const ebml_context MATROSKA_ContextContentCompAlgo; extern const ebml_context MATROSKA_ContextContentCompSettings; extern const ebml_context MATROSKA_ContextContentCompression; extern const ebml_context MATROSKA_ContextContentEncAlgo; extern const ebml_context MATROSKA_ContextContentEncKeyID; extern const ebml_context MATROSKA_ContextContentSignature; extern const ebml_context MATROSKA_ContextContentSigKeyID; extern const ebml_context MATROSKA_ContextContentSigAlgo; extern const ebml_context MATROSKA_ContextContentSigHashAlgo; extern const ebml_context MATROSKA_ContextContentEncryption; extern const ebml_context MATROSKA_ContextContentEncoding; extern const ebml_context MATROSKA_ContextContentEncodings; extern const ebml_context MATROSKA_ContextTrackEntry; extern const ebml_context MATROSKA_ContextTracks; extern const ebml_context MATROSKA_ContextCueTime; extern const ebml_context MATROSKA_ContextCueTrack; extern const ebml_context MATROSKA_ContextCueClusterPosition; extern const ebml_context MATROSKA_ContextCueRelativePosition; extern const ebml_context MATROSKA_ContextCueDuration; extern const ebml_context MATROSKA_ContextCueBlockNumber; extern const ebml_context MATROSKA_ContextCueCodecState; extern const ebml_context MATROSKA_ContextCueRefTime; extern const ebml_context MATROSKA_ContextCueRefCluster; extern const ebml_context MATROSKA_ContextCueRefNumber; extern const ebml_context MATROSKA_ContextCueRefCodecState; extern const ebml_context MATROSKA_ContextCueReference; extern const ebml_context MATROSKA_ContextCueTrackPositions; extern const ebml_context MATROSKA_ContextCuePoint; extern const ebml_context MATROSKA_ContextCues; extern const ebml_context MATROSKA_ContextFileDescription; extern const ebml_context MATROSKA_ContextFileName; extern const ebml_context MATROSKA_ContextFileMimeType; extern const ebml_context MATROSKA_ContextFileData; extern const ebml_context MATROSKA_ContextFileUID; extern const ebml_context MATROSKA_ContextFileReferral; extern const ebml_context MATROSKA_ContextFileUsedStartTime; extern const ebml_context MATROSKA_ContextFileUsedEndTime; extern const ebml_context MATROSKA_ContextAttachedFile; extern const ebml_context MATROSKA_ContextAttachments; extern const ebml_context MATROSKA_ContextEditionUID; extern const ebml_context MATROSKA_ContextEditionFlagHidden; extern const ebml_context MATROSKA_ContextEditionFlagDefault; extern const ebml_context MATROSKA_ContextEditionFlagOrdered; extern const ebml_context MATROSKA_ContextChapterUID; extern const ebml_context MATROSKA_ContextChapterStringUID; extern const ebml_context MATROSKA_ContextChapterTimeStart; extern const ebml_context MATROSKA_ContextChapterTimeEnd; extern const ebml_context MATROSKA_ContextChapterFlagHidden; extern const ebml_context MATROSKA_ContextChapterFlagEnabled; extern const ebml_context MATROSKA_ContextChapterSegmentUID; extern const ebml_context MATROSKA_ContextChapterSegmentEditionUID; extern const ebml_context MATROSKA_ContextChapterPhysicalEquiv; extern const ebml_context MATROSKA_ContextChapterTrackNumber; extern const ebml_context MATROSKA_ContextChapterTrack; extern const ebml_context MATROSKA_ContextChapString; extern const ebml_context MATROSKA_ContextChapLanguage; extern const ebml_context MATROSKA_ContextChapCountry; extern const ebml_context MATROSKA_ContextChapterDisplay; extern const ebml_context MATROSKA_ContextChapProcessCodecID; extern const ebml_context MATROSKA_ContextChapProcessPrivate; extern const ebml_context MATROSKA_ContextChapProcessTime; extern const ebml_context MATROSKA_ContextChapProcessData; extern const ebml_context MATROSKA_ContextChapProcessCommand; extern const ebml_context MATROSKA_ContextChapProcess; extern const ebml_context MATROSKA_ContextChapterAtom; extern const ebml_context MATROSKA_ContextEditionEntry; extern const ebml_context MATROSKA_ContextChapters; extern const ebml_context MATROSKA_ContextTargetTypeValue; extern const ebml_context MATROSKA_ContextTargetType; extern const ebml_context MATROSKA_ContextTagTrackUID; extern const ebml_context MATROSKA_ContextTagEditionUID; extern const ebml_context MATROSKA_ContextTagChapterUID; extern const ebml_context MATROSKA_ContextTagAttachmentUID; extern const ebml_context MATROSKA_ContextTargets; extern const ebml_context MATROSKA_ContextTagName; extern const ebml_context MATROSKA_ContextTagLanguage; extern const ebml_context MATROSKA_ContextTagDefault; extern const ebml_context MATROSKA_ContextTagString; extern const ebml_context MATROSKA_ContextTagBinary; extern const ebml_context MATROSKA_ContextSimpleTag; extern const ebml_context MATROSKA_ContextTag; extern const ebml_context MATROSKA_ContextTags; extern const ebml_context MATROSKA_ContextSegment; #endif // MATROSKA_SEMANTIC_H bcmatroska2-5.3.101/libmatroska2/matroska_sem.c000066400000000000000000001424221462133141200213160ustar00rootroot00000000000000/* * DO NOT EDIT, GENERATED WITH DATA2LIB2 * * $Id$ * Copyright (c) 2008-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "matroska/matroska.h" #include "matroska/matroska_sem.h" #include "matroska/matroska_internal.h" const ebml_context MATROSKA_ContextSeekID = {0x53AB, EBML_BINARY_CLASS, 0, 0, "SeekID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSeekPosition = {0x53AC, EBML_INTEGER_CLASS, 0, 0, "SeekPosition", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSeek[] = { {1, 1, &MATROSKA_ContextSeekID, 0}, {1, 1, &MATROSKA_ContextSeekPosition, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSeek = {0x4DBB, MATROSKA_SEEKPOINT_CLASS, 0, 0, "Seek", EBML_SemanticSeek, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSeekHead[] = { {1, 0, &MATROSKA_ContextSeek, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSeekHead = {0x114D9B74, EBML_MASTER_CLASS, 0, 0, "SeekHead", EBML_SemanticSeekHead, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSegmentUID = {0x73A4, MATROSKA_SEGMENTUID_CLASS, 0, 0, "SegmentUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSegmentFilename = {0x7384, EBML_UNISTRING_CLASS, 0, 0, "SegmentFilename", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPrevUID = {0x3CB923, MATROSKA_SEGMENTUID_CLASS, 0, 0, "PrevUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPrevFilename = {0x3C83AB, EBML_UNISTRING_CLASS, 0, 0, "PrevFilename", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextNextUID = {0x3EB923, MATROSKA_SEGMENTUID_CLASS, 0, 0, "NextUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextNextFilename = {0x3E83BB, EBML_UNISTRING_CLASS, 0, 0, "NextFilename", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSegmentFamily = {0x4444, EBML_BINARY_CLASS, 0, 0, "SegmentFamily", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTranslateEditionUID = {0x69FC, EBML_INTEGER_CLASS, 0, 0, "ChapterTranslateEditionUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTranslateCodec = {0x69BF, EBML_INTEGER_CLASS, 0, 0, "ChapterTranslateCodec", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTranslateID = {0x69A5, EBML_BINARY_CLASS, 0, 0, "ChapterTranslateID", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapterTranslate[] = { {0, 0, &MATROSKA_ContextChapterTranslateEditionUID, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextChapterTranslateCodec, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextChapterTranslateID, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapterTranslate = {0x6924, EBML_MASTER_CLASS, 0, 0, "ChapterTranslate", EBML_SemanticChapterTranslate, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTimecodeScale = {0x2AD7B1, EBML_INTEGER_CLASS, 1, (intptr_t)1000000, "TimecodeScale", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDuration = {0x4489, EBML_FLOAT_CLASS, 0, 0, "Duration", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDateUTC = {0x4461, EBML_DATE_CLASS, 0, 0, "DateUTC", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTitle = {0x7BA9, EBML_UNISTRING_CLASS, 0, 0, "Title", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextMuxingApp = {0x4D80, EBML_UNISTRING_CLASS, 0, 0, "MuxingApp", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextWritingApp = {0x5741, EBML_UNISTRING_CLASS, 0, 0, "WritingApp", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticInfo[] = { {0, 1, &MATROSKA_ContextSegmentUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextSegmentFilename, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextPrevUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextPrevFilename, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextNextUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextNextFilename, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextSegmentFamily, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextChapterTranslate, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTimecodeScale, 0}, {0, 1, &MATROSKA_ContextDuration, 0}, {0, 1, &MATROSKA_ContextDateUTC, 0}, {0, 1, &MATROSKA_ContextTitle, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextMuxingApp, 0}, {1, 1, &MATROSKA_ContextWritingApp, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextInfo = {0x1549A966, EBML_MASTER_CLASS, 0, 0, "Info", EBML_SemanticInfo, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTimecode = {0xE7, EBML_INTEGER_CLASS, 0, 0, "Timecode", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSilentTrackNumber = {0x58D7, EBML_INTEGER_CLASS, 0, 0, "SilentTrackNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSilentTracks[] = { {0, 0, &MATROSKA_ContextSilentTrackNumber, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSilentTracks = {0x5854, EBML_MASTER_CLASS, 0, 0, "SilentTracks", EBML_SemanticSilentTracks, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPosition = {0xA7, EBML_INTEGER_CLASS, 0, 0, "Position", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPrevSize = {0xAB, EBML_INTEGER_CLASS, 0, 0, "PrevSize", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSimpleBlock = {0xA3, MATROSKA_BLOCK_CLASS, 0, 0, "SimpleBlock", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlock = {0xA1, MATROSKA_BLOCK_CLASS, 0, 0, "Block", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlockVirtual = {0xA2, EBML_BINARY_CLASS, 0, 0, "BlockVirtual", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlockAddID = {0xEE, EBML_INTEGER_CLASS, 1, (intptr_t)1, "BlockAddID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlockAdditional = {0xA5, EBML_BINARY_CLASS, 0, 0, "BlockAdditional", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticBlockMore[] = { {1, 1, &MATROSKA_ContextBlockAddID, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextBlockAdditional, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextBlockMore = {0xA6, EBML_MASTER_CLASS, 0, 0, "BlockMore", EBML_SemanticBlockMore, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticBlockAdditions[] = { {1, 0, &MATROSKA_ContextBlockMore, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextBlockAdditions = {0x75A1, EBML_MASTER_CLASS, 0, 0, "BlockAdditions", EBML_SemanticBlockAdditions, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlockDuration = {0x9B, EBML_INTEGER_CLASS, 0, 0, "BlockDuration", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextReferencePriority = {0xFA, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ReferencePriority", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextReferenceBlock = {0xFB, EBML_SINTEGER_CLASS, 0, 0, "ReferenceBlock", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextReferenceVirtual = {0xFD, EBML_SINTEGER_CLASS, 0, 0, "ReferenceVirtual", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecState = {0xA4, EBML_BINARY_CLASS, 0, 0, "CodecState", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDiscardPadding = {0x75A2, EBML_SINTEGER_CLASS, 0, 0, "DiscardPadding", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextLaceNumber = {0xCC, EBML_INTEGER_CLASS, 1, (intptr_t)0, "LaceNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFrameNumber = {0xCD, EBML_INTEGER_CLASS, 1, (intptr_t)0, "FrameNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBlockAdditionID = {0xCB, EBML_INTEGER_CLASS, 1, (intptr_t)0, "BlockAdditionID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDelay = {0xCE, EBML_INTEGER_CLASS, 1, (intptr_t)0, "Delay", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSliceDuration = {0xCF, EBML_INTEGER_CLASS, 1, (intptr_t)0, "SliceDuration", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTimeSlice[] = { {0, 1, &MATROSKA_ContextLaceNumber, PROFILE_DIVX}, {0, 1, &MATROSKA_ContextFrameNumber, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextBlockAdditionID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextDelay, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextSliceDuration, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTimeSlice = {0xE8, EBML_MASTER_CLASS, 0, 0, "TimeSlice", EBML_SemanticTimeSlice, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSlices[] = { {0, 0, &MATROSKA_ContextTimeSlice, PROFILE_DIVX}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSlices = {0x8E, EBML_MASTER_CLASS, 0, 0, "Slices", EBML_SemanticSlices, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextReferenceOffset = {0xC9, EBML_INTEGER_CLASS, 0, 0, "ReferenceOffset", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextReferenceTimeCode = {0xCA, EBML_INTEGER_CLASS, 0, 0, "ReferenceTimeCode", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticReferenceFrame[] = { {1, 1, &MATROSKA_ContextReferenceOffset, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextReferenceTimeCode, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextReferenceFrame = {0xC8, EBML_MASTER_CLASS, 0, 0, "ReferenceFrame", EBML_SemanticReferenceFrame, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticBlockGroup[] = { {1, 1, &MATROSKA_ContextBlock, 0}, {0, 1, &MATROSKA_ContextBlockVirtual, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextBlockAdditions, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextBlockDuration, 0}, {1, 1, &MATROSKA_ContextReferencePriority, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextReferenceBlock, 0}, {0, 1, &MATROSKA_ContextReferenceVirtual, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCodecState, PROFILE_MATROSKA_V1|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextDiscardPadding, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX}, {0, 1, &MATROSKA_ContextSlices, PROFILE_DIVX}, {0, 1, &MATROSKA_ContextReferenceFrame, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextBlockGroup = {0xA0, MATROSKA_BLOCKGROUP_CLASS, 0, 0, "BlockGroup", EBML_SemanticBlockGroup, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextEncryptedBlock = {0xAF, EBML_BINARY_CLASS, 0, 0, "EncryptedBlock", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticCluster[] = { {1, 1, &MATROSKA_ContextTimecode, 0}, {0, 1, &MATROSKA_ContextSilentTracks, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextPosition, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextPrevSize, 0}, {0, 0, &MATROSKA_ContextSimpleBlock, PROFILE_MATROSKA_V1}, {0, 0, &MATROSKA_ContextBlockGroup, 0}, {0, 0, &MATROSKA_ContextEncryptedBlock, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextCluster = {0x1F43B675, MATROSKA_CLUSTER_CLASS, 0, 0, "Cluster", EBML_SemanticCluster, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackNumber = {0xD7, EBML_INTEGER_CLASS, 0, 0, "TrackNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackUID = {0x73C5, EBML_INTEGER_CLASS, 0, 0, "TrackUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackType = {0x83, EBML_INTEGER_CLASS, 0, 0, "TrackType", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFlagEnabled = {0xB9, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "FlagEnabled", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFlagDefault = {0x88, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "FlagDefault", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFlagForced = {0x55AA, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "FlagForced", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFlagLacing = {0x9C, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "FlagLacing", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextMinCache = {0x6DE7, EBML_INTEGER_CLASS, 1, (intptr_t)0, "MinCache", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextMaxCache = {0x6DF8, EBML_INTEGER_CLASS, 0, 0, "MaxCache", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDefaultDuration = {0x23E383, EBML_INTEGER_CLASS, 0, 0, "DefaultDuration", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDefaultDecodedFieldDuration = {0x234E7A, EBML_INTEGER_CLASS, 0, 0, "DefaultDecodedFieldDuration", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackTimecodeScale = {0x23314F, EBML_FLOAT_CLASS, 1, (intptr_t)1.0, "TrackTimecodeScale", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackOffset = {0x537F, EBML_SINTEGER_CLASS, 1, (intptr_t)0, "TrackOffset", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextMaxBlockAdditionID = {0x55EE, EBML_INTEGER_CLASS, 1, (intptr_t)0, "MaxBlockAdditionID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextName = {0x536E, EBML_UNISTRING_CLASS, 0, 0, "Name", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextLanguage = {0x22B59C, EBML_STRING_CLASS, 1, (intptr_t)"eng", "Language", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecID = {0x86, EBML_STRING_CLASS, 0, 0, "CodecID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecPrivate = {0x63A2, EBML_BINARY_CLASS, 0, 0, "CodecPrivate", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecName = {0x258688, EBML_UNISTRING_CLASS, 0, 0, "CodecName", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextAttachmentLink = {0x7446, EBML_INTEGER_CLASS, 0, 0, "AttachmentLink", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecSettings = {0x3A9697, EBML_UNISTRING_CLASS, 0, 0, "CodecSettings", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecInfoURL = {0x3B4040, EBML_STRING_CLASS, 0, 0, "CodecInfoURL", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecDownloadURL = {0x26B240, EBML_STRING_CLASS, 0, 0, "CodecDownloadURL", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecDecodeAll = {0xAA, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "CodecDecodeAll", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackOverlay = {0x6FAB, EBML_INTEGER_CLASS, 0, 0, "TrackOverlay", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCodecDelay = {0x56AA, EBML_INTEGER_CLASS, 1, (intptr_t)0, "CodecDelay", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSeekPreRoll = {0x56BB, EBML_INTEGER_CLASS, 1, (intptr_t)0, "SeekPreRoll", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackTranslateEditionUID = {0x66FC, EBML_INTEGER_CLASS, 0, 0, "TrackTranslateEditionUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackTranslateCodec = {0x66BF, EBML_INTEGER_CLASS, 0, 0, "TrackTranslateCodec", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackTranslateTrackID = {0x66A5, EBML_BINARY_CLASS, 0, 0, "TrackTranslateTrackID", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackTranslate[] = { {0, 0, &MATROSKA_ContextTrackTranslateEditionUID, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTrackTranslateCodec, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTrackTranslateTrackID, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackTranslate = {0x6624, EBML_MASTER_CLASS, 0, 0, "TrackTranslate", EBML_SemanticTrackTranslate, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFlagInterlaced = {0x9A, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "FlagInterlaced", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextStereoMode = {0x53B8, EBML_INTEGER_CLASS, 1, (intptr_t)0, "StereoMode", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextAlphaMode = {0x53C0, EBML_INTEGER_CLASS, 1, (intptr_t)0, "AlphaMode", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextOldStereoMode = {0x53B9, EBML_INTEGER_CLASS, 0, 0, "OldStereoMode", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelWidth = {0xB0, EBML_INTEGER_CLASS, 0, 0, "PixelWidth", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelHeight = {0xBA, EBML_INTEGER_CLASS, 0, 0, "PixelHeight", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelCropBottom = {0x54AA, EBML_INTEGER_CLASS, 1, (intptr_t)0, "PixelCropBottom", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelCropTop = {0x54BB, EBML_INTEGER_CLASS, 1, (intptr_t)0, "PixelCropTop", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelCropLeft = {0x54CC, EBML_INTEGER_CLASS, 1, (intptr_t)0, "PixelCropLeft", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextPixelCropRight = {0x54DD, EBML_INTEGER_CLASS, 1, (intptr_t)0, "PixelCropRight", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDisplayWidth = {0x54B0, EBML_INTEGER_CLASS, 0, 0, "DisplayWidth", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDisplayHeight = {0x54BA, EBML_INTEGER_CLASS, 0, 0, "DisplayHeight", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextDisplayUnit = {0x54B2, EBML_INTEGER_CLASS, 1, (intptr_t)0, "DisplayUnit", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextAspectRatioType = {0x54B3, EBML_INTEGER_CLASS, 1, (intptr_t)0, "AspectRatioType", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextColourSpace = {0x2EB524, EBML_BINARY_CLASS, 0, 0, "ColourSpace", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextGammaValue = {0x2FB523, EBML_FLOAT_CLASS, 0, 0, "GammaValue", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFrameRate = {0x2383E3, EBML_FLOAT_CLASS, 0, 0, "FrameRate", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticVideo[] = { {1, 1, &MATROSKA_ContextFlagInterlaced, PROFILE_MATROSKA_V1|PROFILE_DIVX}, {0, 1, &MATROSKA_ContextStereoMode, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX}, {0, 1, &MATROSKA_ContextAlphaMode, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX}, {0, 1, &MATROSKA_ContextOldStereoMode, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextPixelWidth, 0}, {1, 1, &MATROSKA_ContextPixelHeight, 0}, {0, 1, &MATROSKA_ContextPixelCropBottom, 0}, {0, 1, &MATROSKA_ContextPixelCropTop, 0}, {0, 1, &MATROSKA_ContextPixelCropLeft, 0}, {0, 1, &MATROSKA_ContextPixelCropRight, 0}, {0, 1, &MATROSKA_ContextDisplayWidth, 0}, {0, 1, &MATROSKA_ContextDisplayHeight, 0}, {0, 1, &MATROSKA_ContextDisplayUnit, 0}, {0, 1, &MATROSKA_ContextAspectRatioType, 0}, {0, 1, &MATROSKA_ContextColourSpace, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextGammaValue, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextFrameRate, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextVideo = {0xE0, EBML_MASTER_CLASS, 0, 0, "Video", EBML_SemanticVideo, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextSamplingFrequency = {0xB5, EBML_FLOAT_CLASS, 1, (intptr_t)8000.0, "SamplingFrequency", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextOutputSamplingFrequency = {0x78B5, EBML_FLOAT_CLASS, 0, 0, "OutputSamplingFrequency", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChannels = {0x9F, EBML_INTEGER_CLASS, 1, (intptr_t)1, "Channels", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChannelPositions = {0x7D7B, EBML_BINARY_CLASS, 0, 0, "ChannelPositions", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextBitDepth = {0x6264, EBML_INTEGER_CLASS, 0, 0, "BitDepth", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticAudio[] = { {1, 1, &MATROSKA_ContextSamplingFrequency, 0}, {0, 1, &MATROSKA_ContextOutputSamplingFrequency, 0}, {1, 1, &MATROSKA_ContextChannels, 0}, {0, 1, &MATROSKA_ContextChannelPositions, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextBitDepth, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextAudio = {0xE1, EBML_MASTER_CLASS, 0, 0, "Audio", EBML_SemanticAudio, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackPlaneUID = {0xE5, EBML_INTEGER_CLASS, 0, 0, "TrackPlaneUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackPlaneType = {0xE6, EBML_INTEGER_CLASS, 0, 0, "TrackPlaneType", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackPlane[] = { {1, 1, &MATROSKA_ContextTrackPlaneUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTrackPlaneType, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackPlane = {0xE4, EBML_MASTER_CLASS, 0, 0, "TrackPlane", EBML_SemanticTrackPlane, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackCombinePlanes[] = { {1, 0, &MATROSKA_ContextTrackPlane, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackCombinePlanes = {0xE3, EBML_MASTER_CLASS, 0, 0, "TrackCombinePlanes", EBML_SemanticTrackCombinePlanes, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrackJoinUID = {0xED, EBML_INTEGER_CLASS, 0, 0, "TrackJoinUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackJoinBlocks[] = { {1, 0, &MATROSKA_ContextTrackJoinUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackJoinBlocks = {0xE9, EBML_MASTER_CLASS, 0, 0, "TrackJoinBlocks", EBML_SemanticTrackJoinBlocks, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackOperation[] = { {0, 1, &MATROSKA_ContextTrackCombinePlanes, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrackJoinBlocks, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackOperation = {0xE2, EBML_MASTER_CLASS, 0, 0, "TrackOperation", EBML_SemanticTrackOperation, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrickTrackUID = {0xC0, EBML_INTEGER_CLASS, 0, 0, "TrickTrackUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrickTrackSegmentUID = {0xC1, EBML_BINARY_CLASS, 0, 0, "TrickTrackSegmentUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrickTrackFlag = {0xC6, EBML_INTEGER_CLASS, 1, (intptr_t)0, "TrickTrackFlag", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrickMasterTrackUID = {0xC7, EBML_INTEGER_CLASS, 0, 0, "TrickMasterTrackUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTrickMasterTrackSegmentUID = {0xC4, EBML_BINARY_CLASS, 0, 0, "TrickMasterTrackSegmentUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentEncodingOrder = {0x5031, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentEncodingOrder", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentEncodingScope = {0x5032, EBML_INTEGER_CLASS, 1, (intptr_t)1, "ContentEncodingScope", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentEncodingType = {0x5033, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentEncodingType", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentCompAlgo = {0x4254, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentCompAlgo", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentCompSettings = {0x4255, EBML_BINARY_CLASS, 0, 0, "ContentCompSettings", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticContentCompression[] = { {1, 1, &MATROSKA_ContextContentCompAlgo, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentCompSettings, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextContentCompression = {0x5034, EBML_MASTER_CLASS, 0, 0, "ContentCompression", EBML_SemanticContentCompression, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentEncAlgo = {0x47E1, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentEncAlgo", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentEncKeyID = {0x47E2, EBML_BINARY_CLASS, 0, 0, "ContentEncKeyID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentSignature = {0x47E3, EBML_BINARY_CLASS, 0, 0, "ContentSignature", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentSigKeyID = {0x47E4, EBML_BINARY_CLASS, 0, 0, "ContentSigKeyID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentSigAlgo = {0x47E5, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentSigAlgo", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextContentSigHashAlgo = {0x47E6, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ContentSigHashAlgo", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticContentEncryption[] = { {0, 1, &MATROSKA_ContextContentEncAlgo, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentEncKeyID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentSignature, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentSigKeyID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentSigAlgo, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentSigHashAlgo, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextContentEncryption = {0x5035, EBML_MASTER_CLASS, 0, 0, "ContentEncryption", EBML_SemanticContentEncryption, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticContentEncoding[] = { {1, 1, &MATROSKA_ContextContentEncodingOrder, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextContentEncodingScope, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextContentEncodingType, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentCompression, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentEncryption, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextContentEncoding = {0x6240, EBML_MASTER_CLASS, 0, 0, "ContentEncoding", EBML_SemanticContentEncoding, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticContentEncodings[] = { {1, 0, &MATROSKA_ContextContentEncoding, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextContentEncodings = {0x6D80, EBML_MASTER_CLASS, 0, 0, "ContentEncodings", EBML_SemanticContentEncodings, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTrackEntry[] = { {1, 1, &MATROSKA_ContextTrackNumber, 0}, {1, 1, &MATROSKA_ContextTrackUID, 0}, {1, 1, &MATROSKA_ContextTrackType, 0}, {1, 1, &MATROSKA_ContextFlagEnabled, PROFILE_MATROSKA_V1|PROFILE_DIVX}, {1, 1, &MATROSKA_ContextFlagDefault, 0}, {1, 1, &MATROSKA_ContextFlagForced, 0}, {1, 1, &MATROSKA_ContextFlagLacing, 0}, {1, 1, &MATROSKA_ContextMinCache, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextMaxCache, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextDefaultDuration, 0}, {0, 1, &MATROSKA_ContextDefaultDecodedFieldDuration, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTrackTimecodeScale, PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrackOffset, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextMaxBlockAdditionID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextName, 0}, {0, 1, &MATROSKA_ContextLanguage, 0}, {1, 1, &MATROSKA_ContextCodecID, 0}, {0, 1, &MATROSKA_ContextCodecPrivate, 0}, {0, 1, &MATROSKA_ContextCodecName, 0}, {0, 1, &MATROSKA_ContextAttachmentLink, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCodecSettings, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, &MATROSKA_ContextCodecInfoURL, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, &MATROSKA_ContextCodecDownloadURL, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextCodecDecodeAll, PROFILE_MATROSKA_V1|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, &MATROSKA_ContextTrackOverlay, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCodecDelay, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX}, {1, 1, &MATROSKA_ContextSeekPreRoll, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX}, {0, 0, &MATROSKA_ContextTrackTranslate, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextVideo, 0}, {0, 1, &MATROSKA_ContextAudio, 0}, {0, 1, &MATROSKA_ContextTrackOperation, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrickTrackUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrickTrackSegmentUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrickTrackFlag, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrickMasterTrackUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTrickMasterTrackSegmentUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextContentEncodings, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTrackEntry = {0xAE, MATROSKA_TRACKENTRY_CLASS, 0, 0, "TrackEntry", EBML_SemanticTrackEntry, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTracks[] = { {1, 0, &MATROSKA_ContextTrackEntry, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTracks = {0x1654AE6B, EBML_MASTER_CLASS, 0, 0, "Tracks", EBML_SemanticTracks, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueTime = {0xB3, EBML_INTEGER_CLASS, 0, 0, "CueTime", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueTrack = {0xF7, EBML_INTEGER_CLASS, 0, 0, "CueTrack", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueClusterPosition = {0xF1, EBML_INTEGER_CLASS, 0, 0, "CueClusterPosition", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueRelativePosition = {0xF0, EBML_INTEGER_CLASS, 0, 0, "CueRelativePosition", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueDuration = {0xB2, EBML_INTEGER_CLASS, 0, 0, "CueDuration", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueBlockNumber = {0x5378, EBML_INTEGER_CLASS, 1, (intptr_t)1, "CueBlockNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueCodecState = {0xEA, EBML_INTEGER_CLASS, 1, (intptr_t)0, "CueCodecState", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueRefTime = {0x96, EBML_INTEGER_CLASS, 0, 0, "CueRefTime", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueRefCluster = {0x97, EBML_INTEGER_CLASS, 0, 0, "CueRefCluster", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueRefNumber = {0x535F, EBML_INTEGER_CLASS, 1, (intptr_t)1, "CueRefNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextCueRefCodecState = {0xEB, EBML_INTEGER_CLASS, 1, (intptr_t)0, "CueRefCodecState", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticCueReference[] = { {1, 1, &MATROSKA_ContextCueRefTime, PROFILE_MATROSKA_V1|PROFILE_DIVX|PROFILE_WEBM}, {1, 1, &MATROSKA_ContextCueRefCluster, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCueRefNumber, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCueRefCodecState, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextCueReference = {0xDB, EBML_MASTER_CLASS, 0, 0, "CueReference", EBML_SemanticCueReference, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticCueTrackPositions[] = { {1, 1, &MATROSKA_ContextCueTrack, 0}, {1, 1, &MATROSKA_ContextCueClusterPosition, 0}, {0, 1, &MATROSKA_ContextCueRelativePosition, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCueDuration, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextCueBlockNumber, 0}, {0, 1, &MATROSKA_ContextCueCodecState, PROFILE_MATROSKA_V1|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, &MATROSKA_ContextCueReference, PROFILE_MATROSKA_V1|PROFILE_DIVX|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextCueTrackPositions = {0xB7, EBML_MASTER_CLASS, 0, 0, "CueTrackPositions", EBML_SemanticCueTrackPositions, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticCuePoint[] = { {1, 1, &MATROSKA_ContextCueTime, 0}, {1, 0, &MATROSKA_ContextCueTrackPositions, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextCuePoint = {0xBB, MATROSKA_CUEPOINT_CLASS, 0, 0, "CuePoint", EBML_SemanticCuePoint, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticCues[] = { {1, 0, &MATROSKA_ContextCuePoint, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextCues = {0x1C53BB6B, EBML_MASTER_CLASS, 0, 0, "Cues", EBML_SemanticCues, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileDescription = {0x467E, EBML_UNISTRING_CLASS, 0, 0, "FileDescription", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileName = {0x466E, EBML_UNISTRING_CLASS, 0, 0, "FileName", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileMimeType = {0x4660, EBML_STRING_CLASS, 0, 0, "FileMimeType", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileData = {0x465C, MATROSKA_BIGBINARY_CLASS, 0, 0, "FileData", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileUID = {0x46AE, EBML_INTEGER_CLASS, 0, 0, "FileUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileReferral = {0x4675, EBML_BINARY_CLASS, 0, 0, "FileReferral", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileUsedStartTime = {0x4661, EBML_INTEGER_CLASS, 0, 0, "FileUsedStartTime", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextFileUsedEndTime = {0x4662, EBML_INTEGER_CLASS, 0, 0, "FileUsedEndTime", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticAttachedFile[] = { {0, 1, &MATROSKA_ContextFileDescription, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextFileName, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextFileMimeType, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextFileData, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextFileUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextFileReferral, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_DIVX|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextFileUsedStartTime, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 1, &MATROSKA_ContextFileUsedEndTime, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_MATROSKA_V3|PROFILE_MATROSKA_V4|PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextAttachedFile = {0x61A7, MATROSKA_ATTACHMENT_CLASS, 0, 0, "AttachedFile", EBML_SemanticAttachedFile, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticAttachments[] = { {1, 0, &MATROSKA_ContextAttachedFile, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextAttachments = {0x1941A469, EBML_MASTER_CLASS, 0, 0, "Attachments", EBML_SemanticAttachments, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextEditionUID = {0x45BC, EBML_INTEGER_CLASS, 0, 0, "EditionUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextEditionFlagHidden = {0x45BD, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "EditionFlagHidden", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextEditionFlagDefault = {0x45DB, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "EditionFlagDefault", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextEditionFlagOrdered = {0x45DD, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "EditionFlagOrdered", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterUID = {0x73C4, EBML_INTEGER_CLASS, 0, 0, "ChapterUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterStringUID = {0x5654, EBML_UNISTRING_CLASS, 0, 0, "ChapterStringUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTimeStart = {0x91, EBML_INTEGER_CLASS, 0, 0, "ChapterTimeStart", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTimeEnd = {0x92, EBML_INTEGER_CLASS, 0, 0, "ChapterTimeEnd", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterFlagHidden = {0x98, EBML_BOOLEAN_CLASS, 1, (intptr_t)0, "ChapterFlagHidden", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterFlagEnabled = {0x4598, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "ChapterFlagEnabled", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterSegmentUID = {0x6E67, EBML_BINARY_CLASS, 0, 0, "ChapterSegmentUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterSegmentEditionUID = {0x6EBC, EBML_INTEGER_CLASS, 0, 0, "ChapterSegmentEditionUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterPhysicalEquiv = {0x63C3, EBML_INTEGER_CLASS, 0, 0, "ChapterPhysicalEquiv", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapterTrackNumber = {0x89, EBML_INTEGER_CLASS, 0, 0, "ChapterTrackNumber", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapterTrack[] = { {1, 0, &MATROSKA_ContextChapterTrackNumber, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapterTrack = {0x8F, EBML_MASTER_CLASS, 0, 0, "ChapterTrack", EBML_SemanticChapterTrack, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapString = {0x85, EBML_UNISTRING_CLASS, 0, 0, "ChapString", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapLanguage = {0x437C, EBML_STRING_CLASS, 1, (intptr_t)"eng", "ChapLanguage", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapCountry = {0x437E, EBML_STRING_CLASS, 0, 0, "ChapCountry", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapterDisplay[] = { {1, 1, &MATROSKA_ContextChapString, 0}, {1, 0, &MATROSKA_ContextChapLanguage, 0}, {0, 0, &MATROSKA_ContextChapCountry, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapterDisplay = {0x80, EBML_MASTER_CLASS, 0, 0, "ChapterDisplay", EBML_SemanticChapterDisplay, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapProcessCodecID = {0x6955, EBML_INTEGER_CLASS, 1, (intptr_t)0, "ChapProcessCodecID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapProcessPrivate = {0x450D, EBML_BINARY_CLASS, 0, 0, "ChapProcessPrivate", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapProcessTime = {0x6922, EBML_INTEGER_CLASS, 0, 0, "ChapProcessTime", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextChapProcessData = {0x6933, EBML_BINARY_CLASS, 0, 0, "ChapProcessData", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapProcessCommand[] = { {1, 1, &MATROSKA_ContextChapProcessTime, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextChapProcessData, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapProcessCommand = {0x6911, EBML_MASTER_CLASS, 0, 0, "ChapProcessCommand", EBML_SemanticChapProcessCommand, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapProcess[] = { {1, 1, &MATROSKA_ContextChapProcessCodecID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapProcessPrivate, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextChapProcessCommand, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapProcess = {0x6944, EBML_MASTER_CLASS, 0, 0, "ChapProcess", EBML_SemanticChapProcess, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapterAtom[] = { {0, 0, &MATROSKA_ContextChapterAtom, 0}, // recursive {1, 1, &MATROSKA_ContextChapterUID, 0}, {0, 1, &MATROSKA_ContextChapterStringUID, PROFILE_MATROSKA_V1|PROFILE_MATROSKA_V2|PROFILE_DIVX}, {1, 1, &MATROSKA_ContextChapterTimeStart, 0}, {0, 1, &MATROSKA_ContextChapterTimeEnd, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextChapterFlagHidden, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextChapterFlagEnabled, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapterSegmentUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapterSegmentEditionUID, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapterPhysicalEquiv, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapterTrack, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextChapterDisplay, 0}, {0, 0, &MATROSKA_ContextChapProcess, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapterAtom = {0xB6, EBML_MASTER_CLASS, 0, 0, "ChapterAtom", EBML_SemanticChapterAtom, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticEditionEntry[] = { {0, 1, &MATROSKA_ContextEditionUID, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextEditionFlagHidden, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextEditionFlagDefault, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextEditionFlagOrdered, PROFILE_WEBM}, {1, 0, &MATROSKA_ContextChapterAtom, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextEditionEntry = {0x45B9, EBML_MASTER_CLASS, 0, 0, "EditionEntry", EBML_SemanticEditionEntry, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticChapters[] = { {1, 0, &MATROSKA_ContextEditionEntry, 0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextChapters = {0x1043A770, EBML_MASTER_CLASS, 0, 0, "Chapters", EBML_SemanticChapters, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTargetTypeValue = {0x68CA, EBML_INTEGER_CLASS, 1, (intptr_t)50, "TargetTypeValue", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTargetType = {0x63CA, EBML_STRING_CLASS, 0, 0, "TargetType", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagTrackUID = {0x63C5, EBML_INTEGER_CLASS, 1, (intptr_t)0, "TagTrackUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagEditionUID = {0x63C9, EBML_INTEGER_CLASS, 1, (intptr_t)0, "TagEditionUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagChapterUID = {0x63C4, EBML_INTEGER_CLASS, 1, (intptr_t)0, "TagChapterUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagAttachmentUID = {0x63C6, EBML_INTEGER_CLASS, 1, (intptr_t)0, "TagAttachmentUID", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTargets[] = { {0, 1, &MATROSKA_ContextTargetTypeValue, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTargetType, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextTagTrackUID, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextTagEditionUID, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextTagChapterUID, PROFILE_WEBM}, {0, 0, &MATROSKA_ContextTagAttachmentUID, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTargets = {0x63C0, EBML_MASTER_CLASS, 0, 0, "Targets", EBML_SemanticTargets, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagName = {0x45A3, EBML_UNISTRING_CLASS, 0, 0, "TagName", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagLanguage = {0x447A, EBML_STRING_CLASS, 1, (intptr_t)"und", "TagLanguage", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagDefault = {0x4484, EBML_BOOLEAN_CLASS, 1, (intptr_t)1, "TagDefault", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagString = {0x4487, EBML_UNISTRING_CLASS, 0, 0, "TagString", NULL, EBML_SemanticGlobals, NULL}; const ebml_context MATROSKA_ContextTagBinary = {0x4485, EBML_BINARY_CLASS, 0, 0, "TagBinary", NULL, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSimpleTag[] = { {0, 0, &MATROSKA_ContextSimpleTag, PROFILE_WEBM}, // recursive {1, 1, &MATROSKA_ContextTagName, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTagLanguage, PROFILE_WEBM}, {1, 1, &MATROSKA_ContextTagDefault, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTagString, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextTagBinary, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSimpleTag = {0x67C8, EBML_MASTER_CLASS, 0, 0, "SimpleTag", EBML_SemanticSimpleTag, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTag[] = { {1, 1, &MATROSKA_ContextTargets, PROFILE_WEBM}, {1, 0, &MATROSKA_ContextSimpleTag, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTag = {0x7373, EBML_MASTER_CLASS, 0, 0, "Tag", EBML_SemanticTag, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticTags[] = { {1, 0, &MATROSKA_ContextTag, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextTags = {0x1254C367, EBML_MASTER_CLASS, 0, 0, "Tags", EBML_SemanticTags, EBML_SemanticGlobals, NULL}; const ebml_semantic EBML_SemanticSegment[] = { {0, 0, &MATROSKA_ContextSeekHead, 0}, {1, 0, &MATROSKA_ContextInfo, 0}, {0, 0, &MATROSKA_ContextCluster, 0}, {0, 0, &MATROSKA_ContextTracks, 0}, {0, 1, &MATROSKA_ContextCues, 0}, {0, 1, &MATROSKA_ContextAttachments, PROFILE_WEBM}, {0, 1, &MATROSKA_ContextChapters, 0}, {0, 0, &MATROSKA_ContextTags, PROFILE_WEBM}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextSegment = {0x18538067, EBML_MASTER_CLASS, 0, 0, "Segment", EBML_SemanticSegment, EBML_SemanticGlobals, NULL}; bcmatroska2-5.3.101/libmatroska2/matroskablock.c000066400000000000000000000404371462133141200214700ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "matroska/matroska.h" #include "matroska/matroska_sem.h" #include "matroska/matroska_internal.h" #if defined(CONFIG_CODEC_HELPER) #include "ivorbiscodec.h" #include "codec_internal.h" #include "misc.h" #endif static int A_MPEG_freq[4][4] = { // v2.5 * v2 v1 {11025, 0, 22050, 44100}, {12000, 0, 24000, 48000}, { 8000, 0, 16000, 32000}, { 0, 0, 0, 0} }; static int A_MPEG_samples[4][4] = { // v2.5 * v2 v1 { 0, 0, 0, 0}, // unknown layer { 576, 0, 576, 1152}, // layer III {1152, 0, 1152, 1152}, // layer II { 384, 0, 384, 384} // layer I }; static const int A_AC3_freq[3][4] = { {48000, 44100, 32000, 0}, // EEEE<=8 {24000, 22050, 16000, 0}, // EEEE=9 {12000, 11025, 8000, 0}, // EEEE=10 }; static const int A_EAC3_freq[6] = { 48000, 44100, 32000, 24000, 22050, 16000 }; static const int A_EAC3_samples[4] = { 256, 512, 768, 1536 }; static const int A_DTS_freq[16] = { 0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 0, 0 }; err_t MATROSKA_BlockProcessFrameDurations(matroska_block *Block, stream *Input) { ebml_master *Track=NULL; ebml_element *Elt; tchar_t CodecID[MAXPATH]; err_t Err; bool_t ReadData; uint8_t *Cursor; size_t Frame; int Version, Layer, SampleRate, Samples, fscod, fscod2; Err = Node_GET(Block,MATROSKA_BLOCK_READ_TRACK,&Track); if (Err==ERR_NONE) { assert(Track!=NULL); Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackType); if (!Elt || EBML_IntegerValue((ebml_integer*)Elt)!=TRACK_TYPE_AUDIO) // other track types not supported for now Err = ERR_INVALID_DATA; else { if (Block->FirstFrameLocation==0) Err = ERR_READ; else { Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextCodecID); if (!Elt) // missing codec ID Err = ERR_INVALID_DATA; else { EBML_StringGet((ebml_string*)Elt,CodecID,TSIZEOF(CodecID)); ReadData = 0; if (!ArraySize(&Block->Data)) { Err = MATROSKA_BlockReadData(Block,Input); if (Err!=ERR_NONE) goto exit; ReadData = 1; } if (tcsisame_ascii(CodecID,T("A_MPEG/L3")) || tcsisame_ascii(CodecID,T("A_MPEG/L2")) || tcsisame_ascii(CodecID,T("A_MPEG/L1"))) { Block->IsKeyframe = 1; // safety ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Cursor = ARRAYBEGIN(Block->Data,uint8_t); for (Frame=0;FrameSizeList,int32_t);++Frame) { Version = (Cursor[1] >> 3) & 3; Layer = (Cursor[1] >> 1) & 3; SampleRate = (Cursor[2] >> 2) & 3; Samples = A_MPEG_samples[Layer][Version]; SampleRate = A_MPEG_freq[SampleRate][Version]; if (SampleRate!=0 && Samples!=0) ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate); else { Err = ERR_INVALID_DATA; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T; //goto exit; } Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame]; } } else if (tcsisame_ascii(CodecID,T("A_AC3"))) { Block->IsKeyframe = 1; // safety ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Cursor = ARRAYBEGIN(Block->Data,uint8_t); for (Frame=0;FrameSizeList,int32_t);++Frame) { fscod = Cursor[5] >> 3; SampleRate = Cursor[4] >> 6; if (fscod > 10 || fscod < 8) { Err = ERR_INVALID_DATA; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T; //goto exit; } else { SampleRate = A_AC3_freq[fscod-8][SampleRate]; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,1536,SampleRate); } Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame]; } } else if (tcsisame_ascii(CodecID,T("A_EAC3"))) { Block->IsKeyframe = 1; // safety ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Cursor = ARRAYBEGIN(Block->Data,uint8_t); for (Frame=0;FrameSizeList,int32_t);++Frame) { fscod = Cursor[4] >> 6; fscod2 = (Cursor[4] >> 4) & 0x03; if ((0x03 == fscod) && (0x03 == fscod2)) { Err = ERR_INVALID_DATA; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T; //goto exit; } else { SampleRate = A_EAC3_freq[0x03 == fscod ? 3 + fscod2 : fscod]; Samples = (0x03 == fscod) ? 1536 : A_EAC3_samples[fscod2]; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate); } Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame]; } } else if (tcsisame_ascii(CodecID,T("A_DTS"))) { Block->IsKeyframe = 1; // safety ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Cursor = ARRAYBEGIN(Block->Data,uint8_t); for (Frame=0;FrameSizeList,int32_t);++Frame) { Samples = (((Cursor[4] & 1) << 7) + (Cursor[5] >> 2) + 1) * 32; // TODO: handle the frame termination SampleRate = A_DTS_freq[(Cursor[8] >> 2) & 0x0F]; if (Samples==0 || SampleRate==0) { Err = ERR_INVALID_DATA; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T; //goto exit; } else ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate); Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame]; } } else if (tcsisame_ascii(CodecID,T("A_AAC")) || tcsncmp(CodecID,T("A_AAC/"),6)==0) { Block->IsKeyframe = 1; // safety Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextAudio); if (Elt) { Elt = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextSamplingFrequency); if (Elt) { ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Samples = 1024; SampleRate = (int)((ebml_float*)Elt)->Value; for (Frame=0;FrameSizeList,int32_t);++Frame) ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate); } } } #if defined(CONFIG_CODEC_HELPER) else if (tcsisame_ascii(CodecID,T("A_VORBIS"))) { Block->IsKeyframe = 1; // safety Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextCodecPrivate); if (Elt) { vorbis_info vi; vorbis_comment vc; ogg_packet OggPacket; ogg_reference OggRef; ogg_buffer OggBuffer; int n,i,j; codec_setup_info *ci; vorbis_info_init(&vi); vorbis_comment_init(&vc); memset(&OggPacket,0,sizeof(ogg_packet)); OggBuffer.data = (uint8_t*)EBML_BinaryGetData((ebml_binary*)Elt); OggBuffer.size = (long)Elt->DataSize; OggBuffer.refcount = 1; memset(&OggRef,0,sizeof(OggRef)); OggRef.buffer = &OggBuffer; OggRef.next = NULL; OggPacket.packet = &OggRef; OggPacket.packetno = -1; n = OggBuffer.data[0]; i = 1+n; j = 1; while (OggPacket.packetno < 3 && n>=j) { OggRef.begin = i; OggRef.length = 0; do { OggRef.length += OggBuffer.data[j]; } while (OggBuffer.data[j++] == 255 && n>=j); i += OggRef.length; if (i > OggBuffer.size) return ERR_INVALID_DATA; ++OggPacket.packetno; OggPacket.b_o_s = OggPacket.packetno == 0; OggPacket.bytes = OggPacket.packet->length; if (!(vorbis_synthesis_headerin(&vi,&vc,&OggPacket) >= 0) && OggPacket.packetno==0) return ERR_INVALID_DATA; } if (OggPacket.packetno < 3) { OggRef.begin = i; OggRef.length = OggBuffer.size - i; ++OggPacket.packetno; OggPacket.b_o_s = OggPacket.packetno == 0; OggPacket.bytes = OggPacket.packet->length; if (!(vorbis_synthesis_headerin(&vi,&vc,&OggPacket) >= 0) && OggPacket.packetno==0) return ERR_INVALID_DATA; } SampleRate = vi.rate; ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0); Cursor = ARRAYBEGIN(Block->Data,uint8_t); ci = vi.codec_setup; for (Frame=0;FrameSizeList,int32_t);++Frame) { fscod = _ilog(ci->modes-1); fscod = (Cursor[0] & 0x7F) >> (7-fscod); if (fscod > ci->modes) { Err = ERR_INVALID_DATA; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T; //goto exit; } else { Samples = ci->blocksizes[ci->mode_param[fscod]->blockflag]; ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate); } Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame]; } vorbis_comment_clear(&vc); vorbis_info_clear(&vi); } } #endif if (ReadData) { ArrayClear(&Block->Data); Block->Base.Base.bValueIsSet = 0; } } } } } exit: return Err; } size_t MATROSKA_BlockGetFrameCount(const matroska_block *Block) { return ARRAYCOUNT(Block->SizeList,int32_t); } size_t MATROSKA_BlockGetLength(const matroska_block *Block, size_t FrameNum) { if (FrameNum >= ARRAYCOUNT(Block->SizeList,int32_t)) return 0; return ARRAYBEGIN(Block->SizeList,int32_t)[FrameNum]; } timecode_t MATROSKA_BlockGetFrameDuration(const matroska_block *Block, size_t FrameNum) { if (FrameNum >= ARRAYCOUNT(Block->Durations,timecode_t)) return INVALID_TIMECODE_T; return ARRAYBEGIN(Block->Durations,timecode_t)[FrameNum]; } timecode_t MATROSKA_BlockGetFrameStart(const matroska_block *Block, size_t FrameNum) { if (FrameNum >= ARRAYCOUNT(Block->Durations,timecode_t)) return INVALID_TIMECODE_T; else { size_t i; timecode_t Start = MATROSKA_BlockTimecode((matroska_block*)Block); if (Start!=INVALID_TIMECODE_T) { for (i=0;iDurations,timecode_t)[i]==INVALID_TIMECODE_T) return INVALID_TIMECODE_T; Start += ARRAYBEGIN(Block->Durations,timecode_t)[i]; } } return Start; } } timecode_t MATROSKA_BlockGetFrameEnd(const matroska_block *Block, size_t FrameNum) { timecode_t Result = MATROSKA_BlockGetFrameStart(Block,FrameNum), a; if (Result==INVALID_TIMECODE_T) return INVALID_TIMECODE_T; a = MATROSKA_BlockGetFrameDuration(Block,FrameNum); if (a==INVALID_TIMECODE_T) return INVALID_TIMECODE_T; return Result + a; } bcmatroska2-5.3.101/libmatroska2/matroskamain.c000066400000000000000000002775271462133141200213360ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "matroska/matroska.h" #include "matroska/matroska_sem.h" #include "matroska/matroska_internal.h" #if defined(HAVE_ZLIB) #include "zlib/zlib.h" #elif defined(CONFIG_ZLIB) #include "zlib.h" #endif #if defined(CONFIG_BZLIB) #include #endif #if defined(CONFIG_LZO1X) #include "minilzo.h" #endif #if defined(MATROSKA_LIBRARY) #include "matroska2_project.h" #endif const ebml_semantic EBML_SemanticMatroska[] = { {1, 0, &EBML_ContextHead ,0}, {1, 0, &MATROSKA_ContextSegment ,0}, {0, 0, NULL ,0} // end of the table }; const ebml_context MATROSKA_ContextStream = {FOURCC('M','K','X','_'), EBML_MASTER_CLASS, 0, 0, "Matroska Stream", EBML_SemanticMatroska, EBML_SemanticGlobals, NULL}; err_t MATROSKA_Init(nodecontext *p) { #if defined(MATROSKA_LIBRARY) tchar_t LibName[MAXPATH]; #endif err_t Err = EBML_Init(p); if (Err == ERR_NONE) { #if defined(MATROSKA_LIBRARY) tcscpy_s(LibName,TSIZEOF(LibName),PROJECT_NAME T(" v") PROJECT_VERSION); Node_SetData(p,CONTEXT_LIBMATROSKA_VERSION,TYPE_STRING,LibName); #endif } return Err; } err_t MATROSKA_Done(nodecontext *p) { return EBML_Done(p); } #define MATROSKA_CUE_SEGMENTINFO 0x100 #define MATROSKA_CUE_BLOCK 0x101 #define MATROSKA_CLUSTER_READ_SEGMENTINFO 0x100 #define MATROSKA_CLUSTER_WRITE_SEGMENTINFO 0x101 #define MATROSKA_SEEKPOINT_ELEMENT 0x100 #define LACING_NONE 0 #define LACING_XIPH 1 #define LACING_FIXED 2 #define LACING_EBML 3 #define LACING_AUTO 4 struct matroska_cuepoint { ebml_master Base; ebml_master *SegInfo; matroska_block *Block; }; struct matroska_cluster { ebml_master Base; ebml_master *ReadSegInfo; ebml_master *WriteSegInfo; timecode_t GlobalTimecode; }; struct matroska_seekpoint { ebml_master Base; ebml_element *Link; }; struct matroska_trackentry { ebml_master Base; bool_t CodecPrivateCompressed; }; static err_t BlockTrackChanged(matroska_block *Block) { Block->Base.Base.bNeedDataSizeUpdate = 1; return ERR_NONE; } static err_t ClusterTimeChanged(matroska_cluster *Cluster) { timecode_t ClusterTimecode; #if defined(CONFIG_EBML_WRITING) timecode_t BlockTimecode; ebml_element *Elt, *GBlock; #endif Cluster->Base.Base.bNeedDataSizeUpdate = 1; ClusterTimecode = MATROSKA_ClusterTimecode(Cluster); MATROSKA_ClusterSetTimecode(Cluster, ClusterTimecode); #if defined(CONFIG_EBML_WRITING) for (Elt = EBML_MasterChildren(Cluster); Elt; Elt = EBML_MasterNext(Elt)) { if (EBML_ElementIsType(Elt, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Elt);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { BlockTimecode = MATROSKA_BlockTimecode((matroska_block*)GBlock); if (BlockTimecode!=INVALID_TIMECODE_T) MATROSKA_BlockSetTimecode((matroska_block*)GBlock, BlockTimecode, ClusterTimecode); break; } } } else if (EBML_ElementIsType(Elt, &MATROSKA_ContextSimpleBlock)) { BlockTimecode = MATROSKA_BlockTimecode((matroska_block*)Elt); if (BlockTimecode!=INVALID_TIMECODE_T) MATROSKA_BlockSetTimecode((matroska_block*)Elt, BlockTimecode, ClusterTimecode); } } #endif return ERR_NONE; } static err_t CheckCompression(matroska_block *Block) { ebml_master *Elt, *Header; assert(Block->ReadTrack!=NULL); Elt = (ebml_master*)EBML_MasterFindChild(Block->ReadTrack, &MATROSKA_ContextContentEncodings); if (Elt) { if (ARRAYCOUNT(Block->Data,uint8_t)) return ERR_INVALID_PARAM; // we cannot adjust sizes if the data are already read Elt = (ebml_master*)EBML_MasterFindChild(Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return ERR_INVALID_DATA; // TODO support cascaded compression/encryption Elt = (ebml_master*)EBML_MasterFindChild(Elt, &MATROSKA_ContextContentCompression); if (!Elt) return ERR_INVALID_DATA; // TODO: support encryption Header = (ebml_master*)EBML_MasterGetChild(Elt, &MATROSKA_ContextContentCompAlgo); #if defined(CONFIG_ZLIB) || defined(CONFIG_LZO1X) || defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_ZLIB) #endif #if defined(CONFIG_LZO1X) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_LZO1X) #endif #if defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_BZLIB) #endif #else if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #endif return ERR_INVALID_DATA; if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_HEADER) { Header = (ebml_master*)EBML_MasterFindChild(Elt, &MATROSKA_ContextContentCompSettings); if (Header) { uint32_t *i; for (i=ARRAYBEGIN(Block->SizeList,uint32_t);i!=ARRAYEND(Block->SizeList,uint32_t);++i) *i += (uint32_t)Header->Base.DataSize; } } } } return ERR_NONE; } err_t MATROSKA_LinkBlockWithReadTracks(matroska_block *Block, ebml_master *Tracks, bool_t UseForWriteToo) { ebml_element *Track; ebml_integer *TrackNum; bool_t WasLinked = Block->ReadTrack!=NULL; assert(EBML_ElementIsType((ebml_element*)Tracks, &MATROSKA_ContextTracks)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); for (Track=EBML_MasterChildren(Tracks);Track;Track=EBML_MasterNext(Track)) { TrackNum = (ebml_integer*)EBML_MasterFindChild((ebml_master*)Track,&MATROSKA_ContextTrackNumber); if (TrackNum && ((ebml_element*)TrackNum)->bValueIsSet && EBML_IntegerValue(TrackNum)==Block->TrackNumber) { Node_SET(Block,MATROSKA_BLOCK_READ_TRACK,&Track); #if defined(CONFIG_EBML_WRITING) if (UseForWriteToo) Node_SET(Block,MATROSKA_BLOCK_WRITE_TRACK,&Track); #endif if (WasLinked) return ERR_NONE; return CheckCompression(Block); } } return ERR_INVALID_DATA; } err_t MATROSKA_LinkBlockReadTrack(matroska_block *Block, ebml_master *Track, bool_t UseForWriteToo) { ebml_integer *TrackNum; bool_t WasLinked = Block->ReadTrack!=NULL; assert(EBML_ElementIsType((ebml_element*)Track, &MATROSKA_ContextTrackEntry)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); TrackNum = (ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); if (TrackNum && ((ebml_element*)TrackNum)->bValueIsSet) { Block->TrackNumber = (uint16_t)EBML_IntegerValue(TrackNum); Node_SET(Block,MATROSKA_BLOCK_READ_TRACK,&Track); #if defined(CONFIG_EBML_WRITING) if (UseForWriteToo) Node_SET(Block,MATROSKA_BLOCK_WRITE_TRACK,&Track); #endif if (WasLinked) return ERR_NONE; return CheckCompression(Block); } return ERR_INVALID_DATA; } #if defined(CONFIG_EBML_WRITING) err_t MATROSKA_LinkBlockWithWriteTracks(matroska_block *Block, ebml_master *Tracks) { ebml_master *Track; ebml_integer *TrackNum; bool_t WasLinked = Block->WriteTrack!=NULL; assert(EBML_ElementIsType((ebml_element*)Tracks, &MATROSKA_ContextTracks)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); for (Track=(ebml_master*)EBML_MasterChildren(Tracks);Track;Track=(ebml_master*)EBML_MasterNext(Track)) { TrackNum = (ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); if (TrackNum && ((ebml_element*)TrackNum)->bValueIsSet && EBML_IntegerValue(TrackNum)==Block->TrackNumber) { Node_SET(Block,MATROSKA_BLOCK_WRITE_TRACK,&Track); if (WasLinked) return ERR_NONE; return CheckCompression(Block); } } return ERR_INVALID_DATA; } err_t MATROSKA_LinkBlockWriteTrack(matroska_block *Block, ebml_master *Track) { ebml_integer *TrackNum; bool_t WasLinked = Block->WriteTrack!=NULL; assert(EBML_ElementIsType((ebml_element*)Track, &MATROSKA_ContextTrackEntry)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); TrackNum = (ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); if (TrackNum && ((ebml_element*)TrackNum)->bValueIsSet) { Block->TrackNumber = (uint16_t)EBML_IntegerValue(TrackNum); Node_SET(Block,MATROSKA_BLOCK_WRITE_TRACK,&Track); if (WasLinked) return ERR_NONE; return CheckCompression(Block); } return ERR_INVALID_DATA; } #endif ebml_element *MATROSKA_BlockReadTrack(const matroska_block *Block) { ebml_element *Track; if (Node_GET((node*)Block,MATROSKA_BLOCK_READ_TRACK,&Track)!=ERR_NONE) return NULL; return Track; } #if defined(CONFIG_EBML_WRITING) ebml_element *MATROSKA_BlockWriteTrack(const matroska_block *Block) { ebml_element *Track; if (Node_GET((node*)Block,MATROSKA_BLOCK_WRITE_TRACK,&Track)!=ERR_NONE) return NULL; return Track; } #endif err_t MATROSKA_LinkMetaSeekElement(matroska_seekpoint *MetaSeek, ebml_element *Link) { assert(EBML_ElementIsType((ebml_element*)MetaSeek, &MATROSKA_ContextSeek)); Node_SET(MetaSeek,MATROSKA_SEEKPOINT_ELEMENT,&Link); return ERR_NONE; } fourcc_t MATROSKA_MetaSeekID(const matroska_seekpoint *MetaSeek) { ebml_element *SeekID; assert(EBML_ElementIsType((ebml_element*)MetaSeek, &MATROSKA_ContextSeek)); SeekID = EBML_MasterFindChild((ebml_master*)MetaSeek, &MATROSKA_ContextSeekID); if (!SeekID) return 0; return EBML_BufferToID(EBML_BinaryGetData((ebml_binary*)SeekID)); } bool_t MATROSKA_MetaSeekIsClass(const matroska_seekpoint *MetaSeek, const ebml_context *Class) { return MATROSKA_MetaSeekID(MetaSeek) == Class->Id; } filepos_t MATROSKA_MetaSeekPosInSegment(const matroska_seekpoint *MetaSeek) { ebml_integer *SeekPos; assert(EBML_ElementIsType((ebml_element*)MetaSeek, &MATROSKA_ContextSeek)); SeekPos = (ebml_integer*)EBML_MasterFindChild((ebml_master*)MetaSeek, &MATROSKA_ContextSeekPosition); if (!SeekPos) return INVALID_FILEPOS_T; return EBML_IntegerValue(SeekPos); } filepos_t MATROSKA_MetaSeekAbsolutePos(const matroska_seekpoint *MetaSeek) { filepos_t RelPos = MATROSKA_MetaSeekPosInSegment(MetaSeek); ebml_element *RSegment; if (RelPos==INVALID_FILEPOS_T) return INVALID_FILEPOS_T; RSegment = EBML_ElementParent(MetaSeek); while (RSegment && !EBML_ElementIsType(RSegment, &MATROSKA_ContextSegment)) RSegment = EBML_ElementParent(RSegment); if (!RSegment) return INVALID_FILEPOS_T; return RelPos + EBML_ElementPositionData(RSegment); } err_t MATROSKA_MetaSeekUpdate(matroska_seekpoint *MetaSeek) { ebml_element *WSeekID, *WSeekPosSegmentInfo, *RSegment, *Link = NULL; size_t IdSize; err_t Err; uint8_t IdBuffer[4]; if (Node_IsPartOf(MetaSeek,EBML_VOID_CLASS)) return ERR_NONE; assert(EBML_ElementIsType((ebml_element*)MetaSeek, &MATROSKA_ContextSeek)); RSegment = EBML_ElementParent(MetaSeek); while (RSegment && !EBML_ElementIsType(RSegment, &MATROSKA_ContextSegment)) RSegment = EBML_ElementParent(RSegment); if (!RSegment) return ERR_INVALID_DATA; Err = Node_GET(MetaSeek,MATROSKA_SEEKPOINT_ELEMENT,&Link); if (Err != ERR_NONE) return Err; if (Link==NULL) return ERR_INVALID_DATA; WSeekID = EBML_MasterFindFirstElt((ebml_master*)MetaSeek,&MATROSKA_ContextSeekID,1,0); IdSize = EBML_FillBufferID(IdBuffer,sizeof(IdBuffer),Link->Context->Id); EBML_BinarySetData((ebml_binary*)WSeekID,IdBuffer,IdSize); WSeekPosSegmentInfo = EBML_MasterFindFirstElt((ebml_master*)MetaSeek,&MATROSKA_ContextSeekPosition,1,0); EBML_IntegerSetValue((ebml_integer*)WSeekPosSegmentInfo, Link->ElementPosition - EBML_ElementPositionData(RSegment)); return Err; } err_t MATROSKA_LinkClusterReadSegmentInfo(matroska_cluster *Cluster, ebml_master *SegmentInfo, bool_t UseForWriteToo) { assert(EBML_ElementIsType((ebml_element*)Cluster, &MATROSKA_ContextCluster)); assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); Node_SET(Cluster,MATROSKA_CLUSTER_READ_SEGMENTINFO,&SegmentInfo); if (UseForWriteToo) Node_SET(Cluster,MATROSKA_CLUSTER_WRITE_SEGMENTINFO,&SegmentInfo); return ERR_NONE; } #if defined(CONFIG_EBML_WRITING) err_t MATROSKA_LinkClusterWriteSegmentInfo(matroska_cluster *Cluster, ebml_master *SegmentInfo) { assert(EBML_ElementIsType((ebml_element*)Cluster, &MATROSKA_ContextCluster)); assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); Node_SET(Cluster,MATROSKA_CLUSTER_WRITE_SEGMENTINFO,&SegmentInfo); return ERR_NONE; } #endif err_t MATROSKA_LinkBlockReadSegmentInfo(matroska_block *Block, ebml_master *SegmentInfo, bool_t UseForWriteToo) { assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); Node_SET(Block,MATROSKA_BLOCK_READ_SEGMENTINFO,&SegmentInfo); #if defined(CONFIG_EBML_WRITING) if (UseForWriteToo) Node_SET(Block,MATROSKA_BLOCK_WRITE_SEGMENTINFO,&SegmentInfo); #endif return ERR_NONE; } #if defined(CONFIG_EBML_WRITING) err_t MATROSKA_LinkBlockWriteSegmentInfo(matroska_block *Block, ebml_master *SegmentInfo) { assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); Node_SET(Block,MATROSKA_BLOCK_WRITE_SEGMENTINFO,&SegmentInfo); return ERR_NONE; } #endif ebml_element *MATROSKA_BlockReadSegmentInfo(const matroska_block *Block) { ebml_element *SegmentInfo; if (Node_GET((node*)Block,MATROSKA_BLOCK_READ_SEGMENTINFO,&SegmentInfo)!=ERR_NONE) return NULL; return SegmentInfo; } #if defined(CONFIG_EBML_WRITING) ebml_element *MATROSKA_BlockWriteSegmentInfo(const matroska_block *Block) { ebml_element *SegmentInfo; if (Node_GET((node*)Block,MATROSKA_BLOCK_WRITE_SEGMENTINFO,&SegmentInfo)!=ERR_NONE) return NULL; return SegmentInfo; } #endif err_t MATROSKA_LinkCueSegmentInfo(matroska_cuepoint *Cue, ebml_master *SegmentInfo) { assert(EBML_ElementIsType((ebml_element*)Cue, &MATROSKA_ContextCuePoint)); assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); Node_SET(Cue,MATROSKA_CUE_SEGMENTINFO,&SegmentInfo); return ERR_NONE; } err_t MATROSKA_LinkCuePointBlock(matroska_cuepoint *CuePoint, matroska_block *Block) { assert(EBML_ElementIsType((ebml_element*)CuePoint, &MATROSKA_ContextCuePoint)); assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); Node_SET(CuePoint,MATROSKA_CUE_BLOCK,&Block); return ERR_NONE; } static int MATROSKA_BlockCmp(const matroska_block *BlockA, const matroska_block *BlockB) { timecode_t TimeA = MATROSKA_BlockTimecode((matroska_block*)BlockA); timecode_t TimeB = MATROSKA_BlockTimecode((matroska_block*)BlockB); if (TimeA != TimeB) return (int)((TimeA - TimeB)/100000); return MATROSKA_BlockTrackNum(BlockB) - MATROSKA_BlockTrackNum(BlockA); // usually the first track is video, so put audio/subs first } static int ClusterEltCmp(const matroska_cluster* Cluster, const ebml_element** a,const ebml_element** b) { const matroska_block *BlockA = NULL,*BlockB = NULL; if (EBML_ElementIsType(*a, &MATROSKA_ContextTimecode)) return -1; if (EBML_ElementIsType(*b, &MATROSKA_ContextTimecode)) return 1; if (EBML_ElementIsType(*a, &MATROSKA_ContextSimpleBlock)) BlockA = (const matroska_block *)*a; else if (EBML_ElementIsType(*a, &MATROSKA_ContextBlockGroup)) BlockA = (const matroska_block *)EBML_MasterFindChild((ebml_master*)*a,&MATROSKA_ContextBlock); if (EBML_ElementIsType(*b, &MATROSKA_ContextSimpleBlock)) BlockB = (const matroska_block *)*b; else if (EBML_ElementIsType(*a, &MATROSKA_ContextBlockGroup)) BlockB = (const matroska_block *)EBML_MasterFindChild((ebml_master*)*b,&MATROSKA_ContextBlock); if (BlockA != NULL && BlockB != NULL) return MATROSKA_BlockCmp(BlockA,BlockB); assert(0); // unsupported comparison return 0; } void MATROSKA_ClusterSort(matroska_cluster *Cluster) { EBML_MasterSort((ebml_master*)Cluster,(arraycmp)ClusterEltCmp,Cluster); } void MATROSKA_ClusterSetTimecode(matroska_cluster *Cluster, timecode_t Timecode) { ebml_integer *TimecodeElt; #if defined(CONFIG_EBML_WRITING) ebml_element *Elt, *GBlock; timecode_t BlockTimeCode; #endif assert(EBML_ElementIsType((ebml_element*)Cluster, &MATROSKA_ContextCluster)); Cluster->GlobalTimecode = Timecode; TimecodeElt = (ebml_integer*)EBML_MasterGetChild((ebml_master*)Cluster,&MATROSKA_ContextTimecode); #if defined(CONFIG_EBML_WRITING) assert(Cluster->WriteSegInfo); EBML_IntegerSetValue(TimecodeElt, Scale64(Timecode,1,MATROSKA_SegmentInfoTimecodeScale(Cluster->WriteSegInfo))); // update all the blocks LocalTimecode for (Elt = EBML_MasterChildren(Cluster); Elt; Elt = EBML_MasterNext(Elt)) { if (EBML_ElementIsType(Elt, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Elt);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { BlockTimeCode = MATROSKA_BlockTimecode((matroska_block*)GBlock); if (BlockTimeCode!=INVALID_TIMECODE_T) MATROSKA_BlockSetTimecode((matroska_block*)GBlock, BlockTimeCode, Timecode); break; } } } else if (EBML_ElementIsType(Elt, &MATROSKA_ContextSimpleBlock)) { BlockTimeCode = MATROSKA_BlockTimecode((matroska_block*)Elt); if (BlockTimeCode!=INVALID_TIMECODE_T) MATROSKA_BlockSetTimecode((matroska_block*)Elt, BlockTimeCode, Timecode); } } #else assert(Cluster->ReadSegInfo); EBML_IntegerSetValue(TimecodeElt, Scale64(Timecode,1,MATROSKA_SegmentInfoTimecodeScale(Cluster->ReadSegInfo))); #endif } timecode_t MATROSKA_ClusterTimecode(matroska_cluster *Cluster) { assert(EBML_ElementIsType((ebml_element*)Cluster, &MATROSKA_ContextCluster)); if (Cluster->GlobalTimecode == INVALID_TIMECODE_T) { ebml_integer *Timecode = (ebml_integer*)EBML_MasterFindChild((ebml_master*)Cluster,&MATROSKA_ContextTimecode); if (Timecode) Cluster->GlobalTimecode = EBML_IntegerValue(Timecode) * MATROSKA_SegmentInfoTimecodeScale(Cluster->ReadSegInfo); } return Cluster->GlobalTimecode; } timecode_t MATROSKA_ClusterTimecodeScale(matroska_cluster *Cluster, bool_t Read) { #if defined(CONFIG_EBML_WRITING) if (!Read) return MATROSKA_SegmentInfoTimecodeScale(Cluster->WriteSegInfo); #endif return MATROSKA_SegmentInfoTimecodeScale(Cluster->ReadSegInfo); } err_t MATROSKA_BlockSetTimecode(matroska_block *Block, timecode_t Timecode, timecode_t ClusterTimecode) { int64_t InternalTimecode = 32767; assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); assert(Timecode!=INVALID_TIMECODE_T); #if defined(CONFIG_EBML_WRITING) if( Block->WriteSegInfo && Block->WriteTrack) InternalTimecode = Scale64(Timecode - ClusterTimecode,1,(int64_t)(MATROSKA_SegmentInfoTimecodeScale(Block->WriteSegInfo) * MATROSKA_TrackTimecodeScale(Block->WriteTrack))); #else if( Block->ReadSegInfo && Block->ReadTrack) InternalTimecode = Scale64(Timecode - ClusterTimecode,1,(int64_t)(MATROSKA_SegmentInfoTimecodeScale(Block->ReadSegInfo) * MATROSKA_TrackTimecodeScale(Block->ReadTrack))); #endif if (InternalTimecode > 32767 || InternalTimecode < -32768) return ERR_INVALID_DATA; Block->LocalTimecode = (int16_t)InternalTimecode; Block->LocalTimecodeUsed = 1; return ERR_NONE; } timecode_t MATROSKA_BlockTimecode(matroska_block *Block) { ebml_element *Cluster; assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); if (Block->GlobalTimecode!=INVALID_TIMECODE_T) return Block->GlobalTimecode; if (Block->ReadTrack==NULL) return INVALID_TIMECODE_T; assert(Block->LocalTimecodeUsed); Cluster = EBML_ElementParent(Block); while (Cluster && !EBML_ElementIsType(Cluster, &MATROSKA_ContextCluster)) Cluster = EBML_ElementParent(Cluster); if (!Cluster) return INVALID_TIMECODE_T; Block->GlobalTimecode = MATROSKA_ClusterTimecode((matroska_cluster*)Cluster) + (timecode_t)(Block->LocalTimecode * MATROSKA_SegmentInfoTimecodeScale(Block->ReadSegInfo) * MATROSKA_TrackTimecodeScale(Block->ReadTrack)); MATROSKA_BlockSetTimecode(Block, Block->GlobalTimecode, MATROSKA_ClusterTimecode((matroska_cluster*)Cluster)); return Block->GlobalTimecode; } int16_t MATROSKA_BlockTrackNum(const matroska_block *Block) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); assert(Block->LocalTimecodeUsed); return Block->TrackNumber; } bool_t MATROSKA_BlockKeyframe(const matroska_block *Block) { ebml_master *BlockGroup; ebml_integer *Duration; assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); if (Block->IsKeyframe) return 1; if (!EBML_ElementIsType((const ebml_element*)Block, &MATROSKA_ContextBlock)) return 0; BlockGroup = (ebml_master*)EBML_ElementParent(Block); if (!BlockGroup || !Node_IsPartOf(BlockGroup,MATROSKA_BLOCKGROUP_CLASS)) return 0; if (EBML_MasterFindChild(BlockGroup,&MATROSKA_ContextReferenceBlock)) return 0; Duration = (ebml_integer*)EBML_MasterFindChild(BlockGroup,&MATROSKA_ContextBlockDuration); if (Duration!=NULL && EBML_IntegerValue(Duration)==0) return 0; return 1; } bool_t MATROSKA_BlockDiscardable(const matroska_block *Block) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); if (EBML_ElementIsType((const ebml_element*)Block, &MATROSKA_ContextBlock)) return 0; return Block->IsDiscardable; } void MATROSKA_BlockSetKeyframe(matroska_block *Block, bool_t Set) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); Block->IsKeyframe = Set; } void MATROSKA_BlockSetTrackNum(matroska_block *Block, int16_t TrackNum) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); Block->TrackNumber = TrackNum; } void MATROSKA_BlockSetDiscardable(matroska_block *Block, bool_t Set) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); if (EBML_ElementIsType((const ebml_element*)Block, &MATROSKA_ContextSimpleBlock)) Block->IsDiscardable = Set; } bool_t MATROSKA_BlockLaced(const matroska_block *Block) { assert(Node_IsPartOf(Block,MATROSKA_BLOCK_CLASS)); assert(Block->LocalTimecodeUsed); return Block->Lacing != LACING_NONE; } int16_t MATROSKA_CueTrackNum(const matroska_cuepoint *Cue) { ebml_master *Position; ebml_integer *CueTrack; assert(EBML_ElementIsType((ebml_element*)Cue, &MATROSKA_ContextCuePoint)); Position = (ebml_master*)EBML_MasterFindChild((ebml_master*)Cue,&MATROSKA_ContextCueTrackPositions); if (!Position) return -1; CueTrack = (ebml_integer*)EBML_MasterFindChild(Position,&MATROSKA_ContextCueTrack); if (!CueTrack) return -1; return (int16_t)EBML_IntegerValue(CueTrack); } void MATROSKA_CuesSort(ebml_master *Cues) { assert(EBML_ElementIsType((ebml_element*)Cues, &MATROSKA_ContextCues)); EBML_MasterSort(Cues,NULL,NULL); } void MATROSKA_AttachmentSort(ebml_master *Attachments) { assert(EBML_ElementIsType((ebml_element*)Attachments, &MATROSKA_ContextAttachments)); EBML_MasterSort(Attachments,NULL,NULL); } timecode_t MATROSKA_SegmentInfoTimecodeScale(const ebml_master *SegmentInfo) { ebml_integer *TimecodeScale = NULL; if (SegmentInfo) { assert(EBML_ElementIsType((ebml_element*)SegmentInfo, &MATROSKA_ContextInfo)); TimecodeScale = (ebml_integer*)EBML_MasterFindChild((ebml_master*)SegmentInfo,&MATROSKA_ContextTimecodeScale); } if (!TimecodeScale) return MATROSKA_ContextTimecodeScale.DefaultValue; return EBML_IntegerValue(TimecodeScale); } double MATROSKA_TrackTimecodeScale(const ebml_master *Track) { ebml_element *TimecodeScale; assert(EBML_ElementIsType((ebml_element*)Track, &MATROSKA_ContextTrackEntry)); TimecodeScale = EBML_MasterFindChild((ebml_master*)Track,&MATROSKA_ContextTrackTimecodeScale); if (!TimecodeScale) return MATROSKA_ContextTrackTimecodeScale.DefaultValue; return ((ebml_float*)TimecodeScale)->Value; } timecode_t MATROSKA_CueTimecode(const matroska_cuepoint *Cue) { ebml_integer *TimeCode; assert(EBML_ElementIsType((ebml_element*)Cue, &MATROSKA_ContextCuePoint)); TimeCode = (ebml_integer*) EBML_MasterFindChild((ebml_master*)Cue,&MATROSKA_ContextCueTime); if (!TimeCode) return INVALID_TIMECODE_T; return EBML_IntegerValue(TimeCode) * MATROSKA_SegmentInfoTimecodeScale(Cue->SegInfo); } filepos_t MATROSKA_CuePosInSegment(const matroska_cuepoint *Cue) { ebml_element *TimeCode; assert(EBML_ElementIsType((ebml_element*)Cue, &MATROSKA_ContextCuePoint)); TimeCode = EBML_MasterFindChild((ebml_master*)Cue,&MATROSKA_ContextCueTrackPositions); if (!TimeCode) return INVALID_TIMECODE_T; TimeCode = EBML_MasterFindChild((ebml_master*)TimeCode,&MATROSKA_ContextCueClusterPosition); if (!TimeCode) return INVALID_TIMECODE_T; return EBML_IntegerValue((ebml_integer*)TimeCode); } err_t MATROSKA_CuePointUpdate(matroska_cuepoint *Cue, ebml_element *Segment) { ebml_element *TimecodeElt, *Elt, *PosInCluster; ebml_integer *TrackNum; assert(EBML_ElementIsType((ebml_element*)Cue, &MATROSKA_ContextCuePoint)); assert(Cue->Block); assert(Cue->SegInfo); assert(Segment); // we need the segment location EBML_MasterErase((ebml_master*)Cue); EBML_MasterAddMandatory((ebml_master*)Cue,1); TimecodeElt = EBML_MasterGetChild((ebml_master*)Cue,&MATROSKA_ContextCueTime); if (!TimecodeElt) return ERR_OUT_OF_MEMORY; EBML_IntegerSetValue((ebml_integer*)TimecodeElt, Scale64(MATROSKA_BlockTimecode(Cue->Block),1,MATROSKA_SegmentInfoTimecodeScale(Cue->SegInfo))); Elt = EBML_MasterGetChild((ebml_master*)Cue,&MATROSKA_ContextCueTrackPositions); if (!Elt) return ERR_OUT_OF_MEMORY; TrackNum = (ebml_integer*)EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextCueTrack); if (!TrackNum) return ERR_OUT_OF_MEMORY; EBML_IntegerSetValue(TrackNum, MATROSKA_BlockTrackNum(Cue->Block)); PosInCluster = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextCueClusterPosition); if (!PosInCluster) return ERR_OUT_OF_MEMORY; Elt = EBML_ElementParent(Cue->Block); while (Elt && !EBML_ElementIsType(Elt, &MATROSKA_ContextCluster)) Elt = EBML_ElementParent(Elt); if (!Elt) return ERR_INVALID_DATA; assert(Elt->ElementPosition != INVALID_FILEPOS_T); EBML_IntegerSetValue((ebml_integer*)PosInCluster, Elt->ElementPosition - EBML_ElementPositionData(Segment)); return ERR_NONE; } matroska_block *MATROSKA_GetBlockForTimecode(matroska_cluster *Cluster, timecode_t Timecode, int16_t Track) { ebml_element *Block, *GBlock; for (Block = EBML_MasterChildren(Cluster);Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Block);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { if (MATROSKA_BlockTrackNum((matroska_block*)GBlock) == Track && MATROSKA_BlockTimecode((matroska_block*)GBlock) == Timecode) { return (matroska_block*)GBlock; } } } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { if (MATROSKA_BlockTrackNum((matroska_block*)Block) == Track && MATROSKA_BlockTimecode((matroska_block*)Block) == Timecode) { return (matroska_block*)Block; } } } return NULL; } void MATROSKA_LinkClusterBlocks(matroska_cluster *Cluster, ebml_master *RSegmentInfo, ebml_master *Tracks, bool_t KeepUnmatched) { ebml_element *Block, *GBlock,*NextBlock; assert(Node_IsPartOf(Cluster,MATROSKA_CLUSTER_CLASS)); assert(EBML_ElementIsType((ebml_element*)RSegmentInfo, &MATROSKA_ContextInfo)); assert(EBML_ElementIsType((ebml_element*)Tracks, &MATROSKA_ContextTracks)); // link each Block/SimpleBlock with its Track and SegmentInfo MATROSKA_LinkClusterReadSegmentInfo(Cluster,RSegmentInfo,1); for (Block = EBML_MasterChildren(Cluster);Block;Block=NextBlock) { NextBlock = EBML_MasterNext(Block); if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Block);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { if (MATROSKA_LinkBlockWithReadTracks((matroska_block*)GBlock,Tracks,1)!=ERR_NONE && !KeepUnmatched) NodeDelete((node*)Block); else MATROSKA_LinkBlockReadSegmentInfo((matroska_block*)GBlock,RSegmentInfo,1); break; } } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { if (MATROSKA_LinkBlockWithReadTracks((matroska_block*)Block,Tracks,1)!=ERR_NONE && !KeepUnmatched) NodeDelete((node*)Block); else MATROSKA_LinkBlockReadSegmentInfo((matroska_block*)Block,RSegmentInfo,1); } } } static size_t GetBlockHeadSize(const matroska_block *Element) { assert(Element->TrackNumber < 0x4000); if (Element->TrackNumber < 0x80) return 4; else return 5; } err_t MATROSKA_BlockReleaseData(matroska_block *Block, bool_t IncludingNotRead) { if (!IncludingNotRead && Block->GlobalTimecode==INVALID_TIMECODE_T) return ERR_NONE; ArrayClear(&Block->Data); Block->Base.Base.bValueIsSet = 0; if (ARRAYCOUNT(Block->SizeListIn,int32_t)) { // recover the size of each lace in SizeList for later reading int32_t *i,*o; assert(ARRAYCOUNT(Block->SizeListIn,int32_t) == ARRAYCOUNT(Block->SizeList,int32_t)); for (i=ARRAYBEGIN(Block->SizeListIn,int32_t),o=ARRAYBEGIN(Block->SizeList,int32_t);i!=ARRAYEND(Block->SizeListIn,int32_t);++i,++o) *o = *i; ArrayClear(&Block->SizeListIn); } return ERR_NONE; } err_t MATROSKA_BlockSkipToFrame(const matroska_block *Block, stream *Input, size_t FrameNum) { uint32_t *i; filepos_t SeekPos = EBML_ElementPositionData((ebml_element*)Block); if (FrameNum >= ARRAYCOUNT(Block->SizeList,uint32_t)) return ERR_INVALID_PARAM; if (Block->Lacing == LACING_NONE) SeekPos += GetBlockHeadSize(Block); else { SeekPos = Block->FirstFrameLocation; for (i=ARRAYBEGIN(Block->SizeList,uint32_t);FrameNum;--FrameNum,++i) SeekPos += *i; } if (Stream_Seek(Input,SeekPos,SEEK_SET) != SeekPos) return ERR_READ; return ERR_NONE; } // TODO: support zero copy reading (read the frames directly into a buffer with a callback per frame) // pass the Input stream and the amount to read per frame, give the timecode of the frame and get the end timecode in return, get an error code if reading failed err_t MATROSKA_BlockReadData(matroska_block *Element, stream *Input) { size_t Read,BufSize; size_t NumFrame; err_t Err = ERR_NONE; ebml_element *Elt, *Elt2, *Header = NULL; uint8_t *InBuf; int CompressionScope = MATROSKA_COMPR_SCOPE_BLOCK; if (!Element->Base.Base.bValueIsSet) { // find out if compressed headers are used assert(Element->ReadTrack!=NULL); Elt = EBML_MasterFindChild(Element->ReadTrack, &MATROSKA_ContextContentEncodings); if (Elt) { Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return ERR_NOT_SUPPORTED; // TODO support cascaded compression/encryption Elt2 = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncodingScope); if (Elt2) CompressionScope = (int)EBML_IntegerValue((ebml_integer*)Elt2); Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompression); if (!Elt) return ERR_NOT_SUPPORTED; // TODO: support encryption Header = EBML_MasterGetChild((ebml_master*)Elt, &MATROSKA_ContextContentCompAlgo); #if defined(CONFIG_ZLIB) || defined(CONFIG_LZO1X) || defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_ZLIB) #endif #if defined(CONFIG_LZO1X) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_LZO1X) #endif #if defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_BZLIB) #endif #else if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #endif return ERR_INVALID_DATA; if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_HEADER) Header = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompSettings); } } #if !defined(CONFIG_ZLIB) && !defined(CONFIG_LZO1X) && !defined(CONFIG_BZLIB) if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo) return ERR_NOT_SUPPORTED; #endif if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo && !(CompressionScope & MATROSKA_COMPR_SCOPE_BLOCK)) Header = NULL; Stream_Seek(Input,Element->FirstFrameLocation,SEEK_SET); if (Header) ArrayCopy(&Element->SizeListIn, &Element->SizeList); switch (Element->Lacing) { case LACING_NONE: #if defined(CONFIG_ZLIB) || defined(CONFIG_LZO1X) || defined(CONFIG_BZLIB) if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo) { // zlib handling, read the buffer in temp memory array TmpBuf; ArrayInit(&TmpBuf); if (!ArrayResize(&TmpBuf,(size_t)ARRAYBEGIN(Element->SizeList,int32_t)[0],0)) Err = ERR_OUT_OF_MEMORY; InBuf = ARRAYBEGIN(TmpBuf,uint8_t); Err = Stream_Read(Input,InBuf,(size_t)ARRAYBEGIN(Element->SizeList,int32_t)[0],&Read); if (Err==ERR_NONE) { if (Read!=(size_t)ARRAYBEGIN(Element->SizeList,int32_t)[0]) Err = ERR_READ; else { #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_ZLIB) { // get the ouput size, adjust the Element->SizeList value, write in Element->Data z_stream stream; int Res; memset(&stream,0,sizeof(stream)); Res = inflateInit(&stream); if (Res != Z_OK) Err = ERR_INVALID_DATA; else { size_t Count = 0; stream.next_in = InBuf; stream.avail_in = ARRAYBEGIN(Element->SizeList,int32_t)[0]; stream.next_out = ARRAYBEGIN(Element->Data,uint8_t); do { Count = stream.next_out - ARRAYBEGIN(Element->Data,uint8_t); stream.avail_out = 1024; if (!ArrayResize(&Element->Data, Count + stream.avail_out, 0)) { Res = Z_MEM_ERROR; break; } stream.next_out = ARRAYBEGIN(Element->Data,uint8_t) + Count; Res = inflate(&stream, Z_NO_FLUSH); if (Res!=Z_STREAM_END && Res!=Z_OK) break; } while (Res!=Z_STREAM_END && stream.avail_in && !stream.avail_out); ArrayResize(&Element->Data, stream.total_out, 0); ARRAYBEGIN(Element->SizeList,int32_t)[0] = stream.total_out; inflateEnd(&stream); if (Res != Z_STREAM_END) Err = ERR_INVALID_DATA; } } #endif #if defined(CONFIG_LZO1X) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_LZO1X) { if (lzo_init() != LZO_E_OK) Err = ERR_INVALID_DATA; else { lzo_uint outSize = max(2048, ARRAYBEGIN(Element->SizeList,int32_t)[0] << 2); if (!ArrayResize(&Element->Data, outSize, 0)) Err = ERR_OUT_OF_MEMORY; else { if (lzo1x_decompress_safe(InBuf, ARRAYBEGIN(Element->SizeList,int32_t)[0], ARRAYBEGIN(Element->Data,uint8_t), &outSize, NULL) != LZO_E_OK) Err = ERR_INVALID_DATA; else { ARRAYBEGIN(Element->SizeList,int32_t)[0] = outSize; ArrayResize(&Element->Data,outSize,0); } } } } #endif #if defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_BZLIB) { unsigned int outSize = ARRAYBEGIN(Element->SizeList,int32_t)[0] << 2; bz_stream strm; int Res; if (!ArrayResize(&Element->Data, outSize, 0)) Err = ERR_OUT_OF_MEMORY; else { strm.bzalloc = NULL; strm.bzfree = NULL; strm.opaque = NULL; if (BZ2_bzDecompressInit (&strm, 0, 1) != BZ_OK) Err = ERR_INVALID_DATA; else { size_t Count = 0; strm.next_in = (char*)InBuf; strm.avail_in = ARRAYBEGIN(Element->SizeList,int32_t)[0]; strm.next_out = ARRAYBEGIN(Element->Data,char); strm.avail_out = 0; do { Count = strm.next_out - ARRAYBEGIN(Element->Data,char); strm.avail_out = 1024; if (!ArrayResize(&Element->Data, Count + strm.avail_out, 0)) { Res = BZ_MEM_ERROR; break; } strm.next_out = ARRAYBEGIN(Element->Data,char) + Count; Res = BZ2_bzDecompress(&strm); if (Res!=BZ_STREAM_END && Res!=BZ_OK) break; } while (Res!=BZ_STREAM_END && strm.avail_in && !strm.avail_out); ArrayResize(&Element->Data, strm.total_out_lo32, 0); ARRAYBEGIN(Element->SizeList,int32_t)[0] = strm.total_out_lo32; BZ2_bzDecompressEnd(&strm); if (Res != BZ_STREAM_END) Err = ERR_INVALID_DATA; } } } #endif } } ArrayClear(&TmpBuf); } else #endif { if (!ArrayResize(&Element->Data,(size_t)ARRAYBEGIN(Element->SizeList,int32_t)[0],0)) { Err = ERR_OUT_OF_MEMORY; goto failed; } InBuf = ARRAYBEGIN(Element->Data,uint8_t); if (Header) { memcpy(InBuf,ARRAYBEGIN(((ebml_binary*)Header)->Data,uint8_t),(size_t)Header->DataSize); InBuf += (size_t)Header->DataSize; } Err = Stream_Read(Input,InBuf,(size_t)(ARRAYBEGIN(Element->SizeList,int32_t)[0] - (Header?Header->DataSize:0)),&Read); if (Err != ERR_NONE) goto failed; if (Read + (Header?Header->DataSize:0) != (size_t)ARRAYBEGIN(Element->SizeList,int32_t)[0]) { Err = ERR_READ; goto failed; } } break; case LACING_EBML: case LACING_XIPH: case LACING_FIXED: Read = 0; BufSize = 0; for (NumFrame=0;NumFrameSizeList,int32_t);++NumFrame) BufSize += ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame]; #if defined(CONFIG_ZLIB) || defined(CONFIG_LZO1X) || defined(CONFIG_BZLIB) if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo) { // zlib handling, read the buffer in temp memory // get the ouput size, adjust the Element->SizeList value, write in Element->Data array TmpBuf; int32_t FrameSize; size_t OutSize = 0; ArrayInit(&TmpBuf); if (!ArrayResize(&TmpBuf,BufSize,0)) { Err = ERR_OUT_OF_MEMORY; goto failed; } InBuf = ARRAYBEGIN(TmpBuf,uint8_t); Err = Stream_Read(Input,InBuf,BufSize,&Read); if (Err != ERR_NONE || Read!=BufSize) { if (Err==ERR_NONE) Err = ERR_READ; ArrayClear(&TmpBuf); goto failed; } for (NumFrame=0;Err==ERR_NONE && NumFrameSizeList,int32_t);++NumFrame) { #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_ZLIB) { z_stream stream; int Res; memset(&stream,0,sizeof(stream)); Res = inflateInit(&stream); if (Res != Z_OK) Err = ERR_INVALID_DATA; else { size_t Count; stream.next_in = InBuf; stream.avail_in = FrameSize = ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame]; stream.next_out = ARRAYBEGIN(Element->Data,uint8_t) + OutSize; do { Count = stream.next_out - ARRAYBEGIN(Element->Data,uint8_t); if (!ArrayResize(&Element->Data, Count + 1024, 0)) { Res = Z_MEM_ERROR; break; } stream.avail_out = ARRAYCOUNT(Element->Data,uint8_t) - Count; stream.next_out = ARRAYBEGIN(Element->Data,uint8_t) + Count; Res = inflate(&stream, Z_NO_FLUSH); if (Res!=Z_STREAM_END && Res!=Z_OK) break; } while (Res!=Z_STREAM_END && stream.avail_in && !stream.avail_out); ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame] = stream.total_out; OutSize += stream.total_out; inflateEnd(&stream); if (Res != Z_STREAM_END) Err = ERR_INVALID_DATA; } } #endif #if defined(CONFIG_LZO1X) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_LZO1X) { if (lzo_init() != LZO_E_OK) Err = ERR_INVALID_DATA; else { lzo_uint outSize = max(2048, ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame] << 2); FrameSize = ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame]; if (!ArrayResize(&Element->Data, OutSize + outSize, 0)) Err = ERR_OUT_OF_MEMORY; else { if (lzo1x_decompress_safe(InBuf, ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame], ARRAYBEGIN(Element->Data,uint8_t) + OutSize, &outSize, NULL) != LZO_E_OK) Err = ERR_INVALID_DATA; else { OutSize += outSize; ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame] = outSize; ArrayResize(&Element->Data,OutSize,0); } } } } #endif #if defined(CONFIG_BZLIB) if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_BZLIB) { bz_stream stream; int Res; memset(&stream,0,sizeof(stream)); Res = BZ2_bzDecompressInit (&stream, 0, 1); if (Res != BZ_OK) Err = ERR_INVALID_DATA; else { size_t Count; stream.next_in = (char*)InBuf; stream.avail_in = FrameSize = ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame]; stream.next_out = ARRAYBEGIN(Element->Data,char) + OutSize; do { Count = stream.next_out - ARRAYBEGIN(Element->Data,char); if (!ArrayResize(&Element->Data, Count + 1024, 0)) { Res = BZ_MEM_ERROR; break; } stream.avail_out = ARRAYCOUNT(Element->Data,uint8_t) - Count; stream.next_out = ARRAYBEGIN(Element->Data,char) + Count; Res = BZ2_bzDecompress(&stream); if (Res!=BZ_STREAM_END && Res!=BZ_OK) break; } while (Res!=BZ_STREAM_END && stream.avail_in && !stream.avail_out); ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame] = stream.total_out_lo32; OutSize += stream.total_out_lo32; BZ2_bzDecompressEnd(&stream); if (Res != BZ_STREAM_END) Err = ERR_INVALID_DATA; } } #endif InBuf += FrameSize; } ArrayResize(&Element->Data, OutSize, 0); // shrink the buffer ArrayClear(&TmpBuf); } else #endif { if (!ArrayResize(&Element->Data,BufSize,0)) { Err = ERR_OUT_OF_MEMORY; goto failed; } if (!Header) { //assert(BufSize + Element->FirstFrameLocation == Element->Base.Base.DataSize); Err = Stream_Read(Input,ARRAYBEGIN(Element->Data,uint8_t),BufSize,&BufSize); } else { InBuf = ARRAYBEGIN(Element->Data,uint8_t); for (NumFrame=0;NumFrameSizeList,int32_t);++NumFrame) { memcpy(InBuf,ARRAYBEGIN(((ebml_binary*)Header)->Data,uint8_t),(size_t)Header->DataSize); InBuf += (size_t)Header->DataSize; Read = ARRAYBEGIN(Element->SizeList,int32_t)[NumFrame] - (int32_t)Header->DataSize; BufSize = Read; assert(InBuf + Read <= ARRAYEND(Element->Data,uint8_t)); Err = Stream_Read(Input,InBuf,BufSize,&Read); if (Err != ERR_NONE || Read!=BufSize) goto failed; InBuf += Read; } } } if (Err != ERR_NONE) goto failed; break; default: assert(0); // we should support the other lacing modes Err = ERR_NOT_SUPPORTED; goto failed; } Element->Base.Base.bValueIsSet = 1; } #if defined(CONFIG_EBML_WRITING) if (Element->ReadTrack != Element->WriteTrack || Element->ReadSegInfo != Element->WriteSegInfo) // TODO: only if the track compression/timecode scale is different Element->Base.Base.bNeedDataSizeUpdate = 1; #endif failed: return Err; } static err_t SetBlockParent(matroska_block *Block, void* Parent, void* Before) { // update the timecode timecode_t AbsTimeCode; err_t Result = ERR_NONE; if (Block->LocalTimecodeUsed && Parent && NodeTree_Parent(Block)) { assert(Node_IsPartOf(Parent,MATROSKA_CLUSTER_CLASS)); AbsTimeCode = MATROSKA_BlockTimecode(Block); assert(AbsTimeCode != INVALID_TIMECODE_T); Result = MATROSKA_BlockSetTimecode(Block,AbsTimeCode,MATROSKA_ClusterTimecode((matroska_cluster*)Parent)); } if (Result==ERR_NONE) Result = INHERITED(Block,nodetree_vmt,MATROSKA_BLOCK_CLASS)->SetParent(Block, Parent, Before); return Result; } static err_t SetBlockGroupParent(ebml_master *Element, void* Parent, void* Before) { // update the timecode err_t Result = ERR_NONE; matroska_block *Block = (matroska_block*)EBML_MasterFindChild(Element, &MATROSKA_ContextBlock); timecode_t AbsTimeCode; if (Block && Block->LocalTimecodeUsed && Parent && NodeTree_Parent(Block) && NodeTree_Parent(NodeTree_Parent(Block))) { assert(Node_IsPartOf(Parent,MATROSKA_CLUSTER_CLASS)); AbsTimeCode = MATROSKA_BlockTimecode(Block); assert(AbsTimeCode != INVALID_TIMECODE_T); Result = MATROSKA_BlockSetTimecode(Block,AbsTimeCode,MATROSKA_ClusterTimecode((matroska_cluster*)Parent)); } if (Result==ERR_NONE) Result = INHERITED(Element,nodetree_vmt,MATROSKA_BLOCKGROUP_CLASS)->SetParent(Element, Parent, Before); return Result; } static err_t ReadBigBinaryData(ebml_binary *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { if (Scope == SCOPE_PARTIAL_DATA) { EBML_ElementSkipData((ebml_element*)Element,Input,ParserContext,NULL,AllowDummyElt); return ERR_NONE; } return INHERITED(Element,ebml_element_vmt,MATROSKA_BIGBINARY_CLASS)->ReadData(Element, Input, ParserContext, AllowDummyElt, Scope, DepthCheckCRC); } static err_t ReadBlockData(matroska_block *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope) { err_t Result; uint8_t _TempHead[5]; uint8_t *cursor = _TempHead; uint8_t *_tmpBuf; uint8_t BlockHeadSize = 4; // default when the TrackNumber is < 16 assert(!Element->Base.Base.bValueIsSet); Element->Base.Base.bValueIsSet = 0; if (Scope == SCOPE_NO_DATA) return ERR_NONE; if (Stream_Seek(Input,EBML_ElementPositionData((ebml_element*)Element),SEEK_SET)==INVALID_FILEPOS_T) { Result = ERR_READ; goto failed; } Result = Stream_Read(Input,_TempHead, 5, NULL); if (Result != ERR_NONE) goto failed; // update internal values Element->TrackNumber = *cursor++; if (Element->TrackNumber & 0x80) Element->TrackNumber &= 0x7F; else { // there is extra data if ((Element->TrackNumber & 0x40) == 0) { // We don't support track numbers that large ! Result = ERR_INVALID_DATA; goto failed; } Element->TrackNumber = (Element->TrackNumber & 0x3F) << 8; Element->TrackNumber += *cursor++; BlockHeadSize++; } Element->LocalTimecode = LOAD16BE(cursor); Element->LocalTimecodeUsed = 1; cursor += 2; if (EBML_ElementIsType((ebml_element*)Element, &MATROSKA_ContextSimpleBlock)) { Element->IsKeyframe = (*cursor & 0x80) != 0; Element->IsDiscardable = (*cursor & 0x01) != 0; } Element->Invisible = (*cursor & 0x08) >> 3; Element->Lacing = (*cursor++ & 0x06) >> 1; Element->FirstFrameLocation = EBML_ElementPositionData((ebml_element*)Element) + BlockHeadSize; if (cursor == &_TempHead[4]) _TempHead[0] = _TempHead[4]; else Result += Stream_Read(Input,_TempHead, 1, NULL); // put all Frames in the list if (Element->Lacing == LACING_NONE) { ArrayResize(&Element->SizeList,sizeof(int32_t),0); ARRAYBEGIN(Element->SizeList,int32_t)[0] = (size_t)Element->Base.Base.DataSize - BlockHeadSize; } else { // read the number of frames in the lace uint32_t LastBufferSize = (size_t)Element->Base.Base.DataSize - BlockHeadSize - 1; // 1 for number of frame uint8_t FrameNum = _TempHead[0]; // number of frames in the lace - 1 // read the list of frame sizes uint8_t Index; int32_t FrameSize; size_t SizeRead; filepos_t SizeUnknown; Element->FirstFrameLocation++; // for the number of frame ArrayResize(&Element->SizeList,sizeof(int32_t)*(FrameNum + 1),0); switch (Element->Lacing) { case LACING_XIPH: for (Index=0; IndexFirstFrameLocation++; } while (_TempHead[0] == 0xFF); ARRAYBEGIN(Element->SizeList,int32_t)[Index] = FrameSize; LastBufferSize -= FrameSize; } ARRAYBEGIN(Element->SizeList,int32_t)[Index] = LastBufferSize; break; case LACING_EBML: SizeRead = LastBufferSize; _tmpBuf = malloc(FrameNum*4); cursor = _tmpBuf; /// \warning assume the mean size will be coded in less than 4 bytes Result += Stream_Read(Input,cursor, FrameNum*4,NULL); FrameSize = (int32_t)EBML_ReadCodedSizeValue(cursor, &SizeRead, &SizeUnknown); ARRAYBEGIN(Element->SizeList,int32_t)[0] = FrameSize; cursor += SizeRead; LastBufferSize -= FrameSize + SizeRead; for (Index=1; IndexSizeList,int32_t)[Index] = FrameSize; cursor += SizeRead; LastBufferSize -= FrameSize + SizeRead; } Element->FirstFrameLocation += cursor - _tmpBuf; ARRAYBEGIN(Element->SizeList,int32_t)[Index] = LastBufferSize; free(_tmpBuf); break; case LACING_FIXED: for (Index=0; Index<=FrameNum; Index++) // get the size of the frame ARRAYBEGIN(Element->SizeList,int32_t)[Index] = LastBufferSize / (FrameNum + 1); break; default: // other lacing not supported assert(0); } } if (Scope == SCOPE_PARTIAL_DATA) { if (Stream_Seek(Input,Element->Lacing==LACING_NONE ? (EBML_ElementPositionData((ebml_element*)Element) + BlockHeadSize) : Element->FirstFrameLocation,SEEK_SET)==INVALID_FILEPOS_T) Result = ERR_READ; else Result = ERR_NONE; } else Result = MATROSKA_BlockReadData(Element, Input); failed: return Result; } err_t MATROSKA_BlockGetFrame(const matroska_block *Block, size_t FrameNum, matroska_frame *Frame, bool_t WithData) { size_t i; assert(!WithData || Block->Base.Base.bValueIsSet); if (WithData && !ARRAYCOUNT(Block->Data,uint8_t)) return ERR_READ; if (FrameNum >= ARRAYCOUNT(Block->SizeList,uint32_t)) return ERR_INVALID_PARAM; Frame->Data = WithData ? ARRAYBEGIN(Block->Data,uint8_t) : NULL; Frame->Timecode = MATROSKA_BlockTimecode((matroska_block*)Block); for (i=0;iData += ARRAYBEGIN(Block->SizeList,uint32_t)[i]; if (Frame->Timecode != INVALID_TIMECODE_T) { if (i < ARRAYCOUNT(Block->Durations,timecode_t) && ARRAYBEGIN(Block->Durations,timecode_t)[i] != INVALID_TIMECODE_T) Frame->Timecode += ARRAYBEGIN(Block->Durations,timecode_t)[i]; else Frame->Timecode = INVALID_TIMECODE_T; } } Frame->Size = ARRAYBEGIN(Block->SizeList,uint32_t)[i]; if (FrameNum < ARRAYCOUNT(Block->Durations,timecode_t)) Frame->Duration = ARRAYBEGIN(Block->Durations,timecode_t)[i]; else Frame->Duration = INVALID_TIMECODE_T; return ERR_NONE; } err_t MATROSKA_BlockAppendFrame(matroska_block *Block, const matroska_frame *Frame, timecode_t ClusterTimecode) { if (!Block->Base.Base.bValueIsSet && Frame->Timecode!=INVALID_TIMECODE_T) MATROSKA_BlockSetTimecode(Block,Frame->Timecode,ClusterTimecode); ArrayAppend(&Block->Data,Frame->Data,Frame->Size,0); ArrayAppend(&Block->Durations,&Frame->Duration,sizeof(Frame->Duration),0); ArrayAppend(&Block->SizeList,&Frame->Size,sizeof(Frame->Size),0); Block->Base.Base.bValueIsSet = 1; Block->Base.Base.bNeedDataSizeUpdate = 1; Block->Lacing = LACING_AUTO; return ERR_NONE; } #if defined(CONFIG_ZLIB) err_t UnCompressFrameZLib(const uint8_t *Cursor, size_t CursorSize, array *OutBuf, size_t *FrameSize, size_t *ArrayOffset) { z_stream stream; int Res; err_t Err = ERR_NONE; memset(&stream,0,sizeof(stream)); Res = inflateInit(&stream); if (Res != Z_OK) Err = ERR_INVALID_DATA; else { size_t Count; stream.next_in = Cursor; stream.avail_in = CursorSize; stream.next_out = ARRAYBEGIN(*OutBuf,uint8_t) + *ArrayOffset; do { Count = stream.next_out - ARRAYBEGIN(*OutBuf,uint8_t); if (!ArrayResize(OutBuf, Count + 1024, 0)) { Res = Z_MEM_ERROR; break; } stream.avail_out = ARRAYCOUNT(*OutBuf,uint8_t) - Count; stream.next_out = ARRAYBEGIN(*OutBuf,uint8_t) + Count; Res = inflate(&stream, Z_NO_FLUSH); if (Res!=Z_STREAM_END && Res!=Z_OK) break; } while (Res!=Z_STREAM_END && stream.avail_in && !stream.avail_out); *FrameSize = stream.total_out; *ArrayOffset = *ArrayOffset + stream.total_out; inflateEnd(&stream); if (Res != Z_STREAM_END) Err = ERR_INVALID_DATA; } return Err; } #if defined(CONFIG_EBML_WRITING) err_t CompressFrameZLib(const uint8_t *Cursor, size_t CursorSize, uint8_t **OutBuf, size_t *OutSize) { err_t Err = ERR_NONE; z_stream stream; size_t Count; array TmpBuf; int Res; memset(&stream,0,sizeof(stream)); if (deflateInit(&stream, 9)!=Z_OK) return ERR_INVALID_DATA; stream.next_in = (Bytef*)Cursor; stream.avail_in = CursorSize; Count = 0; ArrayInit(&TmpBuf); stream.next_out = ARRAYBEGIN(TmpBuf,uint8_t); do { Count = stream.next_out - ARRAYBEGIN(TmpBuf,uint8_t); if (!ArrayResize(&TmpBuf,CursorSize + Count,0)) { ArrayClear(&TmpBuf); Err = ERR_OUT_OF_MEMORY; break; } stream.avail_out = ARRAYCOUNT(TmpBuf,uint8_t) - Count; stream.next_out = ARRAYBEGIN(TmpBuf,uint8_t) + Count; Res = deflate(&stream, Z_FINISH); } while (stream.avail_out==0 && Res!=Z_STREAM_END); if (OutBuf && OutSize) // TODO: write directly in the output buffer memcpy(*OutBuf, ARRAYBEGIN(TmpBuf,uint8_t), min(*OutSize, stream.total_out)); ArrayClear(&TmpBuf); if (OutSize) *OutSize = stream.total_out; deflateEnd(&stream); return Err; } #endif // CONFIG_EBML_WRITING #endif // CONFIG_ZLIB static filepos_t GetBlockFrameSize(const matroska_block *Element, size_t Frame, const ebml_element *Header, int CompScope) { if (Frame >= ARRAYCOUNT(Element->SizeList,int32_t)) return 0; if (!Header || (CompScope & MATROSKA_COMPR_SCOPE_BLOCK)==0) return ARRAYBEGIN(Element->SizeList,int32_t)[Frame]; if (Header->Context==&MATROSKA_ContextContentCompAlgo) { // handle zlib size_t OutSize; const int32_t *Size = ARRAYBEGIN(Element->SizeList,int32_t); const uint8_t *Data = ARRAYBEGIN(Element->Data,uint8_t); while (Frame) { Data += *Size; ++Size; --Frame; } OutSize = *Size; assert(Element->Base.Base.bValueIsSet); #if defined(CONFIG_EBML_WRITING) && defined(CONFIG_ZLIB) if (!Element->Base.Base.bValueIsSet || CompressFrameZLib(Data,*Size,NULL,&OutSize)!=ERR_NONE) #else if (!Element->Base.Base.bValueIsSet) #endif return *Size; // we can't tell the final size without decoding the data return OutSize; } return ARRAYBEGIN(Element->SizeList,int32_t)[Frame] - Header->DataSize; // header stripping } #if defined(CONFIG_EBML_WRITING) static char GetBestLacingType(const matroska_block *Element) { int XiphLacingSize, EbmlLacingSize; size_t i; int32_t DataSize; ebml_element *Elt, *Elt2, *Header = NULL; int CompressionScope = MATROSKA_COMPR_SCOPE_BLOCK; if (ARRAYCOUNT(Element->SizeList,int32_t) <= 1) return LACING_NONE; DataSize = ARRAYBEGIN(Element->SizeList,int32_t)[0]; for (i=1;iSizeList,int32_t);++i) { if (ARRAYBEGIN(Element->SizeList,int32_t)[i]!=DataSize) break; } if (i==ARRAYCOUNT(Element->SizeList,int32_t)) return LACING_FIXED; // find out if compressed headers are used assert(Element->WriteTrack!=NULL); Elt = EBML_MasterFindChild(Element->WriteTrack, &MATROSKA_ContextContentEncodings); if (Elt) { Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return 0; // TODO support cascaded compression/encryption Elt2 = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncodingScope); if (Elt2) CompressionScope = EBML_IntegerValue((ebml_integer*)Elt2); Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompression); if (!Elt) return 0; // TODO: support encryption Header = EBML_MasterGetChild((ebml_master*)Elt, &MATROSKA_ContextContentCompAlgo); #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER && EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_ZLIB) #else if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #endif return 0; if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_HEADER) Header = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompSettings); } } XiphLacingSize = 0; for (i=0;iSizeList,int32_t)-1;++i) { DataSize = (int32_t)GetBlockFrameSize(Element, i, Header, CompressionScope); while (DataSize >= 0xFF) { XiphLacingSize++; DataSize -= 0xFF; } XiphLacingSize++; } EbmlLacingSize = EBML_CodedSizeLength(GetBlockFrameSize(Element, 0, Header, CompressionScope),0,1); for (i=1;iSizeList,int32_t)-1;++i) { DataSize = (int32_t)GetBlockFrameSize(Element, i, Header, CompressionScope) - DataSize; EbmlLacingSize += EBML_CodedSizeLengthSigned(DataSize,0); } if (XiphLacingSize < EbmlLacingSize) return LACING_XIPH; else return LACING_EBML; } static err_t RenderBlockData(matroska_block *Element, stream *Output, bool_t bForceWithoutMandatory, bool_t bWithDefault, filepos_t *Rendered) { err_t Err = ERR_NONE; uint8_t BlockHead[5], *Cursor; size_t ToWrite, Written, BlockHeadSize = 4; ebml_element *Elt, *Elt2, *Header = NULL; int32_t *i; int CompressionScope = MATROSKA_COMPR_SCOPE_BLOCK; assert(Element->Lacing != LACING_AUTO); if (Element->TrackNumber < 0x80) { BlockHead[0] = 0x80 | (Element->TrackNumber & 0xFF); Cursor = &BlockHead[1]; } else if (Element->TrackNumber < 0x4000) { BlockHead[0] = 0x40 | (Element->TrackNumber >> 8); BlockHead[1] = Element->TrackNumber & 0xFF; Cursor = &BlockHead[2]; BlockHeadSize = 5; } else return ERR_INVALID_DATA; STORE16BE(Cursor,Element->LocalTimecode); Cursor += 2; *Cursor = 0; if (Element->Invisible) *Cursor |= 0x08; *Cursor |= Element->Lacing << 1; if (EBML_ElementIsType((ebml_element*)Element, &MATROSKA_ContextSimpleBlock)) { if (Element->IsKeyframe) *Cursor |= 0x80; if (Element->IsDiscardable) *Cursor |= 0x01; } Err = Stream_Write(Output,BlockHead,BlockHeadSize,&Written); if (Err != ERR_NONE) goto failed; if (Written != BlockHeadSize) { Err = ERR_WRITE; goto failed; } if (Rendered) *Rendered = Written; assert(Element->WriteTrack!=NULL); Elt = EBML_MasterFindChild(Element->WriteTrack, &MATROSKA_ContextContentEncodings); if (Elt) { Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return ERR_INVALID_DATA; // TODO support cascaded compression/encryption Elt2 = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncodingScope); if (Elt2) CompressionScope = EBML_IntegerValue((ebml_integer*)Elt2); Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompression); if (!Elt) return ERR_INVALID_DATA; // TODO: support encryption Header = EBML_MasterGetChild((ebml_master*)Elt, &MATROSKA_ContextContentCompAlgo); #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER && EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_ZLIB) #else if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #endif { Err = ERR_NOT_SUPPORTED; goto failed; } if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_HEADER) Header = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompSettings); } } #if !defined(CONFIG_ZLIB) if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo) { Err = ERR_NOT_SUPPORTED; goto failed; } #endif if (Element->Lacing == LACING_AUTO) Element->Lacing = GetBestLacingType(Element); if (Element->Lacing != LACING_NONE) { uint8_t *LaceHead = malloc(1 + ARRAYCOUNT(Element->SizeList,int32_t)*4); size_t i,LaceSize = 1; int32_t DataSize, PrevSize; if (!LaceHead) { Err = ERR_OUT_OF_MEMORY; goto failed; } LaceHead[0] = (ARRAYCOUNT(Element->SizeList,int32_t)-1) & 0xFF; // number of elements in the lace if (Element->Lacing == LACING_EBML) { DataSize = (int32_t)GetBlockFrameSize(Element, 0, Header, CompressionScope); LaceSize += EBML_CodedValueLength(DataSize,EBML_CodedSizeLength(DataSize,0,1),LaceHead+LaceSize, 1); for (i=1;iSizeList,int32_t)-1;++i) { PrevSize = DataSize; DataSize = (int32_t)GetBlockFrameSize(Element, i, Header, CompressionScope); LaceSize += EBML_CodedValueLengthSigned(DataSize-PrevSize,EBML_CodedSizeLengthSigned(DataSize-PrevSize,0),LaceHead+LaceSize); } } else if (Element->Lacing == LACING_XIPH) { for (i=0;iSizeList,int32_t)-1;++i) { DataSize = (int32_t)GetBlockFrameSize(Element, i, Header, CompressionScope); while (DataSize >= 0xFF) { LaceHead[LaceSize++] = 0xFF; DataSize -= 0xFF; } LaceHead[LaceSize++] = (uint8_t)DataSize; } } else if (Element->Lacing == LACING_FIXED) { // nothing to write } assert(LaceSize <= (1 + ARRAYCOUNT(Element->SizeList,int32_t)*4)); Err = Stream_Write(Output,LaceHead,LaceSize,&Written); if (Err != ERR_NONE) goto failed; if (Rendered) *Rendered += Written; free(LaceHead); } Node_SET(Element,MATROSKA_BLOCK_READ_TRACK,&Element->WriteTrack); // now use the write track for consecutive read of the same element Cursor = ARRAYBEGIN(Element->Data,uint8_t); if (Header && (CompressionScope & MATROSKA_COMPR_SCOPE_BLOCK)) { if (Header && Header->Context==&MATROSKA_ContextContentCompAlgo) { #if defined(CONFIG_ZLIB) uint8_t *OutBuf; array TmpBuf; ArrayInit(&TmpBuf); for (i=ARRAYBEGIN(Element->SizeList,int32_t);i!=ARRAYEND(Element->SizeList,int32_t);++i) { if (!ArrayResize(&TmpBuf,*i + 100,0)) { ArrayClear(&TmpBuf); Err = ERR_OUT_OF_MEMORY; break; } OutBuf = ARRAYBEGIN(TmpBuf,uint8_t); ToWrite = ARRAYCOUNT(TmpBuf,uint8_t); if (CompressFrameZLib(Cursor, *i, &OutBuf, &ToWrite) != ERR_NONE) { ArrayClear(&TmpBuf); Err = ERR_OUT_OF_MEMORY; break; } Err = Stream_Write(Output,OutBuf,ToWrite,&Written); ArrayClear(&TmpBuf); if (Rendered) *Rendered += Written; Cursor += *i; if (Err!=ERR_NONE) break; } #endif } else { // header compression for (i=ARRAYBEGIN(Element->SizeList,int32_t);i!=ARRAYEND(Element->SizeList,int32_t);++i) { assert(memcmp(Cursor,ARRAYBEGIN(((ebml_binary*)Header)->Data,uint8_t),(size_t)Header->DataSize)==0); if (memcmp(Cursor,ARRAYBEGIN(((ebml_binary*)Header)->Data,uint8_t),(size_t)Header->DataSize)!=0) { Err = ERR_INVALID_DATA; goto failed; } Cursor += Header->DataSize; ToWrite = *i - (size_t)Header->DataSize; Err = Stream_Write(Output,Cursor,ToWrite,&Written); if (Rendered) *Rendered += Written; Cursor += Written; } } } else { ToWrite = ARRAYCOUNT(Element->Data,uint8_t); Err = Stream_Write(Output,Cursor,ToWrite,&Written); if (Rendered) *Rendered += Written; } failed: return Err; } #endif static matroska_block *CopyBlockInfo(const matroska_block *Element, const void *Cookie) { matroska_block *Result = (matroska_block*)INHERITED(Element,ebml_element_vmt,Node_ClassId(Element))->Copy(Element,Cookie); if (Result) { Result->TrackNumber = Element->TrackNumber; Result->IsKeyframe = Element->IsKeyframe; Result->IsDiscardable = Element->IsDiscardable; Result->Invisible = Element->Invisible; #if 0 // computed once blocks are added Result->LocalTimecode = Element->LocalTimecode; Result->LocalTimecodeUsed = Element->LocalTimecodeUsed; Result->GlobalTimecode = Element->GlobalTimecode; Result->Lacing = Element->Lacing; Result->FirstFrameLocation = Element->FirstFrameLocation; array SizeList = Element->; // int32_t array Data = Element->; // uint8_t array Durations = Element->; // timecode_t #else Result->Base.Base.bValueIsSet = 0; #endif Node_SET(Result,MATROSKA_BLOCK_READ_TRACK,&Element->ReadTrack); Node_SET(Result,MATROSKA_BLOCK_READ_SEGMENTINFO,&Element->ReadSegInfo); #if defined(CONFIG_EBML_WRITING) Node_SET(Result,MATROSKA_BLOCK_WRITE_TRACK,&Element->WriteTrack); Node_SET(Result,MATROSKA_BLOCK_WRITE_SEGMENTINFO,&Element->WriteSegInfo); #endif } return Result; } static filepos_t UpdateBlockSize(matroska_block *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { int CompressionScope = MATROSKA_COMPR_SCOPE_BLOCK; if (EBML_ElementNeedsDataSizeUpdate(Element, bWithDefault)) { ebml_element *Header = NULL; #if defined(CONFIG_EBML_WRITING) ebml_element *Elt, *Elt2; if (Element->Lacing == LACING_AUTO) Element->Lacing = GetBestLacingType(Element); assert(Element->WriteTrack!=NULL); Elt = EBML_MasterFindChild(Element->WriteTrack, &MATROSKA_ContextContentEncodings); if (Elt) { Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return ERR_INVALID_DATA; // TODO support cascaded compression/encryption Elt2 = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentEncodingScope); if (Elt2) CompressionScope = EBML_IntegerValue((ebml_integer*)Elt2); Elt = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompression); if (!Elt) return ERR_INVALID_DATA; // TODO: support encryption Header = EBML_MasterGetChild((ebml_master*)Elt, &MATROSKA_ContextContentCompAlgo); #if defined(CONFIG_ZLIB) if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER && EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_ZLIB) #else if (EBML_IntegerValue((ebml_integer*)Header)!=MATROSKA_BLOCK_COMPR_HEADER) #endif return ERR_INVALID_DATA; if (EBML_IntegerValue((ebml_integer*)Header)==MATROSKA_BLOCK_COMPR_HEADER) Header = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextContentCompSettings); } } #else assert(Element->Lacing!=LACING_AUTO); #endif if (Element->Lacing == LACING_NONE) { assert(ARRAYCOUNT(Element->SizeList,int32_t) == 1); Element->Base.Base.DataSize = GetBlockHeadSize(Element) + GetBlockFrameSize(Element,0,Header, CompressionScope); } else if (Element->Lacing == LACING_EBML) { size_t i; filepos_t PrevSize, Size; filepos_t Result = GetBlockHeadSize(Element) + 1; // 1 for the number of frames Size = GetBlockFrameSize(Element,0,Header, CompressionScope); Result += EBML_CodedSizeLength(Size,0,1) + Size; for (i=1;iSizeList,int32_t)-1;++i) { PrevSize = Size; Size = GetBlockFrameSize(Element,i,Header, CompressionScope); Result += Size + EBML_CodedSizeLengthSigned(Size - PrevSize,0); } Result += GetBlockFrameSize(Element,i,Header, CompressionScope); Element->Base.Base.DataSize = Result; } else if (Element->Lacing == LACING_XIPH) { size_t i; filepos_t Size; filepos_t Result = GetBlockHeadSize(Element) + 1; // 1 for the number of frames for (i=0;iSizeList,int32_t)-1;++i) { Size = GetBlockFrameSize(Element,i,Header, CompressionScope); Result += (Size / 0xFF + 1) + Size; } Result += GetBlockFrameSize(Element,i,Header, CompressionScope); Element->Base.Base.DataSize = Result; } else if (Element->Lacing == LACING_FIXED) { size_t i; filepos_t Result = GetBlockHeadSize(Element) + 1; // 1 for the number of frames for (i=0;iSizeList,int32_t);++i) Result += GetBlockFrameSize(Element,i,Header, CompressionScope); Element->Base.Base.DataSize = Result; } #ifdef TODO char LacingHere; // compute the final size of the data switch (ARRAYCOUNT(Element->SizeList,int32_t)) { case 0: Element->Base.Base.DataSize = 0; break; case 1: Element->Base.Base.DataSize = 4 + *ARRAYBEGIN(Element->SizeList,int32_t); break; default: Element->Base.Base.DataSize = 4 + 1; // 1 for the lacing head if (Element->Lacing == LACING_AUTO) LacingHere = GetBestLacingType(Element); else LacingHere = Element->Lacing; switch (LacingHere) { case LACING_XIPH: for (i=0; iDataSize() + (myBuffers[i]->DataSize() / 0xFF + 1)); } break; case LACING_EBML: SetSize_(GetSize() + myBuffers[0]->DataSize() + CodedSizeLength(myBuffers[0]->DataSize(), 0, IsFiniteSize())); for (i=1; iDataSize() + CodedSizeLengthSigned(int64(myBuffers[i]->DataSize()) - int64(myBuffers[i-1]->DataSize()), 0)); } break; case LACING_FIXED: for (i=0; iDataSize()); } break; default: assert(0); } // DataSize of the last frame (not in lace) SetSize_(GetSize() + myBuffers[i]->DataSize()); break; } if (Element->Base.Base.DataSize && Element->TrackNumber >= 0x80) ++Element->Base.Base.DataSize; // the size will be coded with one more octet #endif } // skip the EBML_BINARY_CLASS version as we have another internal buffer return INHERITED(Element,ebml_element_vmt,EBML_BINARY_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static int CmpCuePoint(const matroska_cuepoint* a,const matroska_cuepoint* b) { // returns a > b timecode_t TA = MATROSKA_CueTimecode(a); timecode_t TB = MATROSKA_CueTimecode(b); int NA,NB; if (TB < TA) return 1; if (TB > TA) return -1; NA = MATROSKA_CueTrackNum(a); NB = MATROSKA_CueTrackNum(b); if (NB < NA) return 1; if (NB > NA) return -1; return 0; } static int CmpAttachedFile(const ebml_master* a,const ebml_master* b) { // returns a > b // sort cover art names according to http://www.matroska.org/technical/cover_art/index.html tchar_t FilenameA[MAXPATH]; tchar_t FilenameB[MAXPATH]; bool_t CoverA=0,CoverB=0; bool_t LandCoverA=0,LandCoverB=0; bool_t SmallCoverA=0,SmallCoverB=0; ebml_element *NameA = EBML_MasterFindChild(a,&MATROSKA_ContextFileName); ebml_element *NameB = EBML_MasterFindChild(b,&MATROSKA_ContextFileName); if (NameB==NULL) return -1; if (NameA==NULL) return 1; EBML_StringGet((ebml_string*)NameA,FilenameA,TSIZEOF(FilenameA)); EBML_StringGet((ebml_string*)NameB,FilenameB,TSIZEOF(FilenameB)); if (tcsisame_ascii(FilenameA, T("cover.jpg")) || tcsisame_ascii(FilenameA, T("cover.png"))) CoverA = 1; else if (tcsisame_ascii(FilenameA, T("cover_land.jpg")) || tcsisame_ascii(FilenameA, T("cover_land.png"))) LandCoverA = 1; else if (tcsisame_ascii(FilenameA, T("small_cover.jpg")) || tcsisame_ascii(FilenameA, T("small_cover.png"))) { CoverA = 1; SmallCoverA = 1; } else if (tcsisame_ascii(FilenameA, T("small_cover_land.jpg")) || tcsisame_ascii(FilenameA, T("small_cover_land.png"))) { LandCoverA = 1; SmallCoverA = 1; } if (tcsisame_ascii(FilenameB, T("cover.jpg")) || tcsisame_ascii(FilenameB, T("cover.png"))) CoverB = 1; else if (tcsisame_ascii(FilenameB, T("cover_land.jpg")) || tcsisame_ascii(FilenameB, T("cover_land.png"))) LandCoverB = 1; else if (tcsisame_ascii(FilenameB, T("small_cover.jpg")) || tcsisame_ascii(FilenameB, T("small_cover.png"))) { CoverB = 1; SmallCoverB = 1; } else if (tcsisame_ascii(FilenameB, T("small_cover_land.jpg")) || tcsisame_ascii(FilenameB, T("small_cover_land.png"))) { LandCoverB = 1; SmallCoverB = 1; } if (!CoverA && !CoverB && !LandCoverA && !LandCoverB) return tcscmp(FilenameA,FilenameB); // cover.jpg comes first if (CoverA && !SmallCoverA) return -1; if (CoverB && !SmallCoverB) return 1; if (CoverA == CoverB || LandCoverA == LandCoverB) return SmallCoverA - SmallCoverB; if (CoverA || LandCoverA) { if (CoverB) return 1; return -1; } if (CoverA) return -1; return 1; } matroska_cuepoint *MATROSKA_CuesGetTimecodeStart(const ebml_element *Cues, timecode_t Timecode) { matroska_cuepoint *Elt,*Prev=NULL; assert(Cues!=NULL); assert(EBML_ElementIsType(Cues, &MATROSKA_ContextCues)); if (Timecode==INVALID_TIMECODE_T) return NULL; for (Elt=(matroska_cuepoint*)EBML_MasterChildren(Cues);Elt;Prev=Elt, Elt=(matroska_cuepoint*)EBML_MasterNext(Elt)) { if (MATROSKA_CueTimecode(Elt) > Timecode) break; } return Prev ? Prev : (matroska_cuepoint*)EBML_MasterChildren(Cues); } static bool_t ValidateSizeSegUID(const ebml_binary *p) { uint8_t test[16]; if (p->Base.DataSize != 16 || !EBML_ElementIsFiniteSize((const ebml_element *)p)) return 0; if (!p->Base.bValueIsSet) return 1; memset(test,0,sizeof(test)); return memcmp(ARRAYBEGIN(p->Data,uint8_t),test,16)!=0; // make sure the value is not 0 } static err_t CreateBlock(matroska_block *p) { p->GlobalTimecode = INVALID_TIMECODE_T; return ERR_NONE; } static err_t CreateCluster(matroska_cluster *p) { p->GlobalTimecode = INVALID_TIMECODE_T; return ERR_NONE; } static err_t ReadTrackEntry(matroska_trackentry *Element, stream *Input, const ebml_parser_context *ParserContext, bool_t AllowDummyElt, int Scope, size_t DepthCheckCRC) { err_t Result = INHERITED(Element,ebml_element_vmt,MATROSKA_TRACKENTRY_CLASS)->ReadData(Element, Input, ParserContext, AllowDummyElt, Scope, DepthCheckCRC); if (Result==ERR_NONE) { ebml_element *Encodings = EBML_MasterFindChild(Element,&MATROSKA_ContextContentEncodings); if (Encodings) { ebml_element *Elt2 = EBML_MasterFindChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); if (Elt2) { ebml_element *Elt = EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); if (Elt) { ebml_integer *Scope = (ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextContentEncodingScope); Element->CodecPrivateCompressed = Scope && (EBML_IntegerValue(Scope) & MATROSKA_COMPR_SCOPE_PRIVATE)!=0; } } } } return Result; } static filepos_t UpdateDataSizeTrackEntry(matroska_trackentry *Element, bool_t bWithDefault, bool_t bForceWithoutMandatory) { #if defined(CONFIG_ZLIB) bool_t CodecPrivateCompressed = 0; ebml_integer *Scope = NULL; ebml_element *Encodings = EBML_MasterFindChild(Element,&MATROSKA_ContextContentEncodings); if (Encodings) { ebml_element *Elt2 = EBML_MasterFindChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); if (Elt2) { ebml_element *Elt = EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); if (Elt) { Scope = (ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextContentEncodingScope); CodecPrivateCompressed = Scope && (EBML_IntegerValue(Scope) & MATROSKA_COMPR_SCOPE_PRIVATE)!=0; } } } if (CodecPrivateCompressed != Element->CodecPrivateCompressed) { ebml_binary *CodecPrivate = (ebml_binary*)EBML_MasterFindChild(Element,&MATROSKA_ContextCodecPrivate); if (!Element->CodecPrivateCompressed) { // compress the codec private if (CodecPrivate) { size_t CompressedSize = ARRAYCOUNT(CodecPrivate->Data,uint8_t); uint8_t *Compressed = malloc(CompressedSize); if (CompressFrameZLib(ARRAYBEGIN(CodecPrivate->Data,uint8_t), (size_t)CodecPrivate->Base.DataSize, &Compressed, &CompressedSize)==ERR_NONE) { if (EBML_BinarySetData(CodecPrivate, Compressed, CompressedSize)==ERR_NONE) Element->CodecPrivateCompressed = 1; } free(Compressed); } if (!Element->CodecPrivateCompressed) EBML_IntegerSetValue(Scope, EBML_IntegerValue(Scope) ^ MATROSKA_COMPR_SCOPE_PRIVATE); } else { if (CodecPrivate) { size_t CompressedSize = ARRAYCOUNT(CodecPrivate->Data,uint8_t); size_t Offset = 0; array Compressed; ArrayInit(&Compressed); if (UnCompressFrameZLib(ARRAYBEGIN(CodecPrivate->Data,uint8_t), (size_t)CodecPrivate->Base.DataSize, &Compressed, &CompressedSize, &Offset)==ERR_NONE) { if (EBML_BinarySetData(CodecPrivate, ARRAYBEGIN(Compressed,uint8_t), CompressedSize)==ERR_NONE) Element->CodecPrivateCompressed = 0; } ArrayClear(&Compressed); } else Element->CodecPrivateCompressed = 0; if (Element->CodecPrivateCompressed) { // TODO: add in the Compression header that the header is still compressed } } } #endif return INHERITED(Element,ebml_element_vmt,MATROSKA_TRACKENTRY_CLASS)->UpdateDataSize(Element, bWithDefault, bForceWithoutMandatory); } static matroska_trackentry *CopyTrackEntry(const matroska_trackentry *Element, const void *Cookie) { matroska_trackentry *Result = (matroska_trackentry*)INHERITED(Element,ebml_element_vmt,MATROSKA_TRACKENTRY_CLASS)->Copy(Element, Cookie); if (Result) Result->CodecPrivateCompressed = Element->CodecPrivateCompressed; return Result; } int MATROSKA_TrackGetBlockCompression(const matroska_trackentry *TrackEntry) { ebml_element *Encodings, *Elt, *Elt2; assert(Node_IsPartOf(TrackEntry, MATROSKA_TRACKENTRY_CLASS)); Encodings = EBML_MasterFindChild(TrackEntry,&MATROSKA_ContextContentEncodings); if (!Encodings) return MATROSKA_BLOCK_COMPR_NONE; Elt2 = EBML_MasterFindChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); if (!Elt2) return MATROSKA_BLOCK_COMPR_NONE; Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentEncodingScope); if (!(EBML_IntegerValue((ebml_integer*)Elt) & MATROSKA_COMPR_SCOPE_BLOCK)) return MATROSKA_BLOCK_COMPR_NONE; Elt = EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); if (!Elt) return MATROSKA_BLOCK_COMPR_NONE; Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentCompAlgo); return (int)EBML_IntegerValue((ebml_integer*)Elt2); } bool_t MATROSKA_TrackSetCompressionZlib(matroska_trackentry *TrackEntry, int Scope) { // force zlib compression bool_t HadEncoding; ebml_element *Encodings, *Elt, *Elt2; assert(Node_IsPartOf(TrackEntry, MATROSKA_TRACKENTRY_CLASS)); // remove the previous compression and the new optimized one Encodings = EBML_MasterFindChild(TrackEntry,&MATROSKA_ContextContentEncodings); HadEncoding = Encodings!=NULL; if (Encodings!=NULL) NodeDelete((node*)Encodings); if (Scope!=0) { Encodings = EBML_MasterGetChild((ebml_master*)TrackEntry,&MATROSKA_ContextContentEncodings); Elt2 = EBML_MasterGetChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentEncodingScope); EBML_IntegerSetValue((ebml_integer*)Elt, Scope); Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentCompAlgo); EBML_IntegerSetValue((ebml_integer*)Elt2, MATROSKA_BLOCK_COMPR_ZLIB); } return HadEncoding; } bool_t MATROSKA_TrackSetCompressionHeader(matroska_trackentry *TrackEntry, const uint8_t *Header, size_t HeaderSize) { bool_t HadEncoding; ebml_element *Encodings, *Elt, *Elt2; assert(Node_IsPartOf(TrackEntry, MATROSKA_TRACKENTRY_CLASS)); // remove the previous compression and the new optimized one Encodings = EBML_MasterFindChild(TrackEntry,&MATROSKA_ContextContentEncodings); HadEncoding = Encodings!=NULL; if (Encodings!=NULL) NodeDelete((node*)Encodings); if (Header && HeaderSize) { Encodings = EBML_MasterGetChild((ebml_master*)TrackEntry,&MATROSKA_ContextContentEncodings); Elt2 = EBML_MasterGetChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentCompAlgo); EBML_IntegerSetValue((ebml_integer*)Elt2, MATROSKA_BLOCK_COMPR_HEADER); Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentCompSettings); EBML_BinarySetData((ebml_binary*)Elt2, Header, HeaderSize); } return HadEncoding; } bool_t MATROSKA_TrackSetCompressionNone(matroska_trackentry *TrackEntry) { ebml_element *Encodings = EBML_MasterFindChild(TrackEntry,&MATROSKA_ContextContentEncodings); assert(Node_IsPartOf(TrackEntry, MATROSKA_TRACKENTRY_CLASS)); if (!Encodings) return 0; NodeDelete((node*)Encodings); return 1; } META_START(Matroska_Class,MATROSKA_BLOCK_CLASS) META_CLASS(SIZE,sizeof(matroska_block)) META_CLASS(CREATE,CreateBlock) META_VMT(TYPE_FUNC,nodetree_vmt,SetParent,SetBlockParent) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadBlockData) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateBlockSize) #if defined(CONFIG_EBML_WRITING) META_VMT(TYPE_FUNC,ebml_element_vmt,RenderData,RenderBlockData) #endif META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,CopyBlockInfo) META_DATA(TYPE_ARRAY,0,matroska_block,SizeList) META_DATA(TYPE_ARRAY,0,matroska_block,SizeListIn) META_DATA(TYPE_ARRAY,0,matroska_block,Data) META_DATA(TYPE_ARRAY,0,matroska_block,Durations) META_PARAM(TYPE,MATROSKA_BLOCK_READ_TRACK,TYPE_NODE) META_DATA_UPDATE_CMP(TYPE_NODE_REF,MATROSKA_BLOCK_READ_TRACK,matroska_block,ReadTrack,BlockTrackChanged) META_PARAM(TYPE,MATROSKA_BLOCK_READ_SEGMENTINFO,TYPE_NODE) META_DATA_UPDATE_CMP(TYPE_NODE_REF,MATROSKA_BLOCK_READ_SEGMENTINFO,matroska_block,ReadSegInfo,BlockTrackChanged) #if defined(CONFIG_EBML_WRITING) META_PARAM(TYPE,MATROSKA_BLOCK_WRITE_TRACK,TYPE_NODE) META_DATA_UPDATE_CMP(TYPE_NODE_REF,MATROSKA_BLOCK_WRITE_TRACK,matroska_block,WriteTrack,BlockTrackChanged) META_PARAM(TYPE,MATROSKA_BLOCK_WRITE_SEGMENTINFO,TYPE_NODE) META_DATA_UPDATE_CMP(TYPE_NODE_REF,MATROSKA_BLOCK_WRITE_SEGMENTINFO,matroska_block,WriteSegInfo,BlockTrackChanged) #endif META_END_CONTINUE(EBML_BINARY_CLASS) META_START_CONTINUE(MATROSKA_BLOCKGROUP_CLASS) META_VMT(TYPE_FUNC,nodetree_vmt,SetParent,SetBlockGroupParent) META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(MATROSKA_BIGBINARY_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadBigBinaryData) META_END_CONTINUE(EBML_BINARY_CLASS) META_START_CONTINUE(MATROSKA_CUEPOINT_CLASS) META_CLASS(SIZE,sizeof(matroska_cuepoint)) META_VMT(TYPE_FUNC,ebml_element_vmt,Cmp,CmpCuePoint) META_PARAM(TYPE,MATROSKA_CUE_SEGMENTINFO,TYPE_NODE) META_DATA(TYPE_NODE_REF,MATROSKA_CUE_SEGMENTINFO,matroska_cuepoint,SegInfo) META_PARAM(TYPE,MATROSKA_CUE_BLOCK,TYPE_NODE) META_DATA(TYPE_NODE_REF,MATROSKA_CUE_BLOCK,matroska_cuepoint,Block) META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(MATROSKA_CLUSTER_CLASS) META_CLASS(SIZE,sizeof(matroska_cluster)) META_CLASS(CREATE,CreateCluster) META_PARAM(TYPE,MATROSKA_CLUSTER_READ_SEGMENTINFO,TYPE_NODE) META_DATA(TYPE_NODE_REF,MATROSKA_CLUSTER_READ_SEGMENTINFO,matroska_cluster,ReadSegInfo) META_PARAM(TYPE,MATROSKA_CLUSTER_WRITE_SEGMENTINFO,TYPE_NODE) META_DATA_UPDATE_CMP(TYPE_NODE_REF,MATROSKA_CLUSTER_WRITE_SEGMENTINFO,matroska_cluster,WriteSegInfo,ClusterTimeChanged) META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(MATROSKA_SEEKPOINT_CLASS) META_CLASS(SIZE,sizeof(matroska_seekpoint)) META_PARAM(TYPE,MATROSKA_SEEKPOINT_ELEMENT,TYPE_NODE) META_DATA(TYPE_NODE_REF,MATROSKA_SEEKPOINT_ELEMENT,matroska_seekpoint,Link) META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(MATROSKA_TRACKENTRY_CLASS) META_CLASS(SIZE,sizeof(matroska_trackentry)) META_VMT(TYPE_FUNC,ebml_element_vmt,ReadData,ReadTrackEntry) META_VMT(TYPE_FUNC,ebml_element_vmt,UpdateDataSize,UpdateDataSizeTrackEntry) META_VMT(TYPE_FUNC,ebml_element_vmt,Copy,CopyTrackEntry) META_END_CONTINUE(EBML_MASTER_CLASS) META_START_CONTINUE(MATROSKA_SEGMENTUID_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,ValidateSize,ValidateSizeSegUID) META_END_CONTINUE(EBML_BINARY_CLASS) META_START_CONTINUE(MATROSKA_ATTACHMENT_CLASS) META_VMT(TYPE_FUNC,ebml_element_vmt,Cmp,CmpAttachedFile) META_END(EBML_MASTER_CLASS) bcmatroska2-5.3.101/libmatroska2/minilzo/000077500000000000000000000000001462133141200201415ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/minilzo/COPYING000066400000000000000000000432621462133141200212030ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. bcmatroska2-5.3.101/libmatroska2/minilzo/Makefile000066400000000000000000000043761462133141200216130ustar00rootroot00000000000000# # a very simple Makefile for miniLZO # # Copyright (C) 1996-2008 Markus F.X.J. Oberhumer # PROGRAM = testmini SOURCES = testmini.c minilzo.c default: @echo "Please choose one of the following targets:" @echo " gcc: gcc" @echo " unix: hpux hpux9" @echo " win32: win32-bc win32-cygwin win32-dm win32-lccwin32" @echo " win32-intelc win32-mingw win32-vc win32-watcomc" @echo " dos16: dos16-bc dos16-mc dos16-wc" @echo " dos32: dos32-djgpp2 dos32-wc" # Make sure that minilzo.h, lzoconf.h and lzodefs.h are in the # current dircectory. Otherwise you may want to adjust CPPFLAGS. ##CPPFLAGS = -I../include/lzo -I. GCC_CFLAGS = -s -Wall -O2 -fomit-frame-pointer # # gcc (generic) # gcc: gcc $(CPPFLAGS) $(GCC_CFLAGS) -o $(PROGRAM) $(SOURCES) cc: cc $(CPPFLAGS) -o $(PROGRAM) $(SOURCES) # # UNIX # hpux: cc -Ae $(CPPFLAGS) -o $(PROGRAM) $(SOURCES) hpux9: cc -Aa -D_HPUX_SOURCE $(CPPFLAGS) -o $(PROGRAM) $(SOURCES) # # Windows (32-bit) # win32-borlandc win32-bc: bcc32 -O2 -d -w -w-aus $(CPPFLAGS) $(SOURCES) win32-cygwin32 win32-cygwin: gcc -mcygwin $(CPPFLAGS) $(GCC_CFLAGS) -o $(PROGRAM).exe $(SOURCES) win32-digitalmars win32-dm: dmc -mn -o -w- $(CPPFLAGS) $(SOURCES) win32-intelc win32-ic: icl -nologo -MD -W3 -O2 -GF $(CPPFLAGS) $(SOURCES) win32-lccwin32: @echo "NOTE: need lcc 2002-07-25 or newer, older versions have bugs" lc -A -unused -O $(CPPFLAGS) $(SOURCES) win32-mingw32 win32-mingw: gcc -mno-cygwin $(CPPFLAGS) $(GCC_CFLAGS) -o $(PROGRAM).exe $(SOURCES) win32-visualc win32-vc: cl -nologo -MD -W3 -O2 -GF $(CPPFLAGS) $(SOURCES) win32-watcomc win32-wc: wcl386 -bt=nt -zq -mf -5r -zc -w5 -oneatx $(CPPFLAGS) $(SOURCES) # # DOS (16-bit) # dos16-borlandc dos16-bc: bcc -ml -w -d -O -4 $(CPPFLAGS) $(SOURCES) dos16-microsoftc dos16-msc dos16-mc: cl -nologo -f- -AL -O -G2 -W3 $(CPPFLAGS) $(SOURCES) dos16-watcomc dos16-wc: wcl -zq -ml -bt=dos -l=dos -ox -w5 $(CPPFLAGS) $(SOURCES) # # DOS (32-bit) # dos32-djgpp2 dos32-dj2: gcc $(CPPFLAGS) $(GCC_CFLAGS) -o $(PROGRAM).exe $(SOURCES) dos32-watcomc dos32-wc: wcl386 -zq -mf -bt=dos -l=dos4g -5r -ox -zc $(CPPFLAGS) $(SOURCES) # # other targets # clean: rm -f $(PROGRAM) $(PROGRAM).exe $(PROGRAM).map $(PROGRAM).tds rm -f *.err *.o *.obj .PHONY: default clean bcmatroska2-5.3.101/libmatroska2/minilzo/README.LZO000066400000000000000000000077251462133141200214770ustar00rootroot00000000000000 ============================================================================ miniLZO -- mini subset of the LZO real-time data compression library ============================================================================ Author : Markus Franz Xaver Johannes Oberhumer http://www.oberhumer.com/opensource/lzo/ Version : 2.03 Date : 30 Apr 2008 I've created miniLZO for projects where it is inconvenient to include (or require) the full LZO source code just because you want to add a little bit of data compression to your application. miniLZO implements the LZO1X-1 compressor and both the standard and safe LZO1X decompressor. Apart from fast compression it also useful for situations where you want to use pre-compressed data files (which must have been compressed with LZO1X-999). miniLZO consists of one C source file and three header files: minilzo.c minilzo.h, lzoconf.h, lzodefs.h To use miniLZO just copy these files into your source directory, add minilzo.c to your Makefile and #include minilzo.h from your program. Note: you also must distribute this file (`README.LZO') with your project. minilzo.o compiles to about 6 kB (using gcc or Visual C on a i386), and the sources are about 30 kB when packed with zip - so there's no more excuse that your application doesn't support data compression :-) For more information, documentation, example programs and other support files (like Makefiles and build scripts) please download the full LZO package from http://www.oberhumer.com/opensource/lzo/ Have fun, Markus P.S. minilzo.c is generated automatically from the LZO sources and therefore functionality is completely identical Appendix A: building miniLZO ---------------------------- miniLZO is written such a way that it should compile and run out-of-the-box on most machines. If you are running on a very unusual architecture and lzo_init() fails then you should first recompile with `-DLZO_DEBUG' to see what causes the failure. The most probable case is something like `sizeof(char *) != sizeof(long)'. After identifying the problem you can compile by adding some defines like `-DSIZEOF_CHAR_P=8' to your Makefile. The best solution is (of course) using Autoconf - if your project uses Autoconf anyway just add `-DMINILZO_HAVE_CONFIG_H' to your compiler flags when compiling minilzo.c. See the LZO distribution for an example how to set up configure.in. Appendix B: list of public functions available in miniLZO --------------------------------------------------------- Library initialization lzo_init() Compression lzo1x_1_compress() Decompression lzo1x_decompress() lzo1x_decompress_safe() Checksum functions lzo_adler32() Version functions lzo_version() lzo_version_string() lzo_version_date() Portable (but slow) string functions lzo_memcmp() lzo_memcpy() lzo_memmove() lzo_memset() Appendix C: suggested macros for `configure.in' when using Autoconf ------------------------------------------------------------------- Checks for typedefs and structures AC_CHECK_TYPE(ptrdiff_t,long) AC_TYPE_SIZE_T AC_CHECK_SIZEOF(short) AC_CHECK_SIZEOF(int) AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(long long) AC_CHECK_SIZEOF(__int64) AC_CHECK_SIZEOF(void *) AC_CHECK_SIZEOF(size_t) AC_CHECK_SIZEOF(ptrdiff_t) Checks for compiler characteristics AC_C_CONST Checks for library functions AC_CHECK_FUNCS(memcmp memcpy memmove memset) Appendix D: Copyright --------------------- LZO and miniLZO are Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Markus Franz Xaver Johannes Oberhumer LZO and miniLZO are distributed under the terms of the GNU General Public License (GPL). See the file COPYING. Special licenses for commercial and other applications which are not willing to accept the GNU General Public License are available by contacting the author. bcmatroska2-5.3.101/libmatroska2/minilzo/lzoconf.h000066400000000000000000000334121462133141200217670ustar00rootroot00000000000000/* lzoconf.h -- configuration for the LZO real-time data compression library This file is part of the LZO real-time data compression library. Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer http://www.oberhumer.com/opensource/lzo/ */ #ifndef __LZOCONF_H_INCLUDED #define __LZOCONF_H_INCLUDED #define LZO_VERSION 0x2030 #define LZO_VERSION_STRING "2.03" #define LZO_VERSION_DATE "Apr 30 2008" /* internal Autoconf configuration file - only used when building LZO */ #if defined(LZO_HAVE_CONFIG_H) # include #endif #include #include /*********************************************************************** // LZO requires a conforming ************************************************************************/ #if !defined(CHAR_BIT) || (CHAR_BIT != 8) # error "invalid CHAR_BIT" #endif #if !defined(UCHAR_MAX) || !defined(UINT_MAX) || !defined(ULONG_MAX) # error "check your compiler installation" #endif #if (USHRT_MAX < 1) || (UINT_MAX < 1) || (ULONG_MAX < 1) # error "your limits.h macros are broken" #endif /* get OS and architecture defines */ #ifndef __LZODEFS_H_INCLUDED #include "lzodefs.h" #endif #ifdef __cplusplus extern "C" { #endif /*********************************************************************** // some core defines ************************************************************************/ #if !defined(LZO_UINT32_C) # if (UINT_MAX < LZO_0xffffffffL) # define LZO_UINT32_C(c) c ## UL # else # define LZO_UINT32_C(c) ((c) + 0U) # endif #endif /* memory checkers */ #if !defined(__LZO_CHECKER) # if defined(__BOUNDS_CHECKING_ON) # define __LZO_CHECKER 1 # elif defined(__CHECKER__) # define __LZO_CHECKER 1 # elif defined(__INSURE__) # define __LZO_CHECKER 1 # elif defined(__PURIFY__) # define __LZO_CHECKER 1 # endif #endif /*********************************************************************** // integral and pointer types ************************************************************************/ /* lzo_uint should match size_t */ #if !defined(LZO_UINT_MAX) # if defined(LZO_ABI_LLP64) /* WIN64 */ # if defined(LZO_OS_WIN64) typedef unsigned __int64 lzo_uint; typedef __int64 lzo_int; # else typedef unsigned long long lzo_uint; typedef long long lzo_int; # endif # define LZO_UINT_MAX 0xffffffffffffffffull # define LZO_INT_MAX 9223372036854775807LL # define LZO_INT_MIN (-1LL - LZO_INT_MAX) # elif defined(LZO_ABI_IP32L64) /* MIPS R5900 */ typedef unsigned int lzo_uint; typedef int lzo_int; # define LZO_UINT_MAX UINT_MAX # define LZO_INT_MAX INT_MAX # define LZO_INT_MIN INT_MIN # elif (ULONG_MAX >= LZO_0xffffffffL) typedef unsigned long lzo_uint; typedef long lzo_int; # define LZO_UINT_MAX ULONG_MAX # define LZO_INT_MAX LONG_MAX # define LZO_INT_MIN LONG_MIN # else # error "lzo_uint" # endif #endif /* Integral types with 32 bits or more. */ #if !defined(LZO_UINT32_MAX) # if (UINT_MAX >= LZO_0xffffffffL) typedef unsigned int lzo_uint32; typedef int lzo_int32; # define LZO_UINT32_MAX UINT_MAX # define LZO_INT32_MAX INT_MAX # define LZO_INT32_MIN INT_MIN # elif (ULONG_MAX >= LZO_0xffffffffL) typedef unsigned long lzo_uint32; typedef long lzo_int32; # define LZO_UINT32_MAX ULONG_MAX # define LZO_INT32_MAX LONG_MAX # define LZO_INT32_MIN LONG_MIN # else # error "lzo_uint32" # endif #endif /* The larger type of lzo_uint and lzo_uint32. */ #if (LZO_UINT_MAX >= LZO_UINT32_MAX) # define lzo_xint lzo_uint #else # define lzo_xint lzo_uint32 #endif /* Memory model that allows to access memory at offsets of lzo_uint. */ #if !defined(__LZO_MMODEL) # if (LZO_UINT_MAX <= UINT_MAX) # define __LZO_MMODEL # elif defined(LZO_HAVE_MM_HUGE_PTR) # define __LZO_MMODEL_HUGE 1 # define __LZO_MMODEL __huge # else # define __LZO_MMODEL # endif #endif /* no typedef here because of const-pointer issues */ #define lzo_bytep unsigned char __LZO_MMODEL * #define lzo_charp char __LZO_MMODEL * #define lzo_voidp void __LZO_MMODEL * #define lzo_shortp short __LZO_MMODEL * #define lzo_ushortp unsigned short __LZO_MMODEL * #define lzo_uint32p lzo_uint32 __LZO_MMODEL * #define lzo_int32p lzo_int32 __LZO_MMODEL * #define lzo_uintp lzo_uint __LZO_MMODEL * #define lzo_intp lzo_int __LZO_MMODEL * #define lzo_xintp lzo_xint __LZO_MMODEL * #define lzo_voidpp lzo_voidp __LZO_MMODEL * #define lzo_bytepp lzo_bytep __LZO_MMODEL * /* deprecated - use `lzo_bytep' instead of `lzo_byte *' */ #define lzo_byte unsigned char __LZO_MMODEL typedef int lzo_bool; /*********************************************************************** // function types ************************************************************************/ /* name mangling */ #if !defined(__LZO_EXTERN_C) # ifdef __cplusplus # define __LZO_EXTERN_C extern "C" # else # define __LZO_EXTERN_C extern # endif #endif /* calling convention */ #if !defined(__LZO_CDECL) # define __LZO_CDECL __lzo_cdecl #endif /* DLL export information */ #if !defined(__LZO_EXPORT1) # define __LZO_EXPORT1 #endif #if !defined(__LZO_EXPORT2) # define __LZO_EXPORT2 #endif /* __cdecl calling convention for public C and assembly functions */ #if !defined(LZO_PUBLIC) # define LZO_PUBLIC(_rettype) __LZO_EXPORT1 _rettype __LZO_EXPORT2 __LZO_CDECL #endif #if !defined(LZO_EXTERN) # define LZO_EXTERN(_rettype) __LZO_EXTERN_C LZO_PUBLIC(_rettype) #endif #if !defined(LZO_PRIVATE) # define LZO_PRIVATE(_rettype) static _rettype __LZO_CDECL #endif /* function types */ typedef int (__LZO_CDECL *lzo_compress_t) ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem ); typedef int (__LZO_CDECL *lzo_decompress_t) ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem ); typedef int (__LZO_CDECL *lzo_optimize_t) ( lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem ); typedef int (__LZO_CDECL *lzo_compress_dict_t)(const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len ); typedef int (__LZO_CDECL *lzo_decompress_dict_t)(const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len ); /* Callback interface. Currently only the progress indicator ("nprogress") * is used, but this may change in a future release. */ struct lzo_callback_t; typedef struct lzo_callback_t lzo_callback_t; #define lzo_callback_p lzo_callback_t __LZO_MMODEL * /* malloc & free function types */ typedef lzo_voidp (__LZO_CDECL *lzo_alloc_func_t) (lzo_callback_p self, lzo_uint items, lzo_uint size); typedef void (__LZO_CDECL *lzo_free_func_t) (lzo_callback_p self, lzo_voidp ptr); /* a progress indicator callback function */ typedef void (__LZO_CDECL *lzo_progress_func_t) (lzo_callback_p, lzo_uint, lzo_uint, int); struct lzo_callback_t { /* custom allocators (set to 0 to disable) */ lzo_alloc_func_t nalloc; /* [not used right now] */ lzo_free_func_t nfree; /* [not used right now] */ /* a progress indicator callback function (set to 0 to disable) */ lzo_progress_func_t nprogress; /* NOTE: the first parameter "self" of the nalloc/nfree/nprogress * callbacks points back to this struct, so you are free to store * some extra info in the following variables. */ lzo_voidp user1; lzo_xint user2; lzo_xint user3; }; /*********************************************************************** // error codes and prototypes ************************************************************************/ /* Error codes for the compression/decompression functions. Negative * values are errors, positive values will be used for special but * normal events. */ #define LZO_E_OK 0 #define LZO_E_ERROR (-1) #define LZO_E_OUT_OF_MEMORY (-2) /* [not used right now] */ #define LZO_E_NOT_COMPRESSIBLE (-3) /* [not used right now] */ #define LZO_E_INPUT_OVERRUN (-4) #define LZO_E_OUTPUT_OVERRUN (-5) #define LZO_E_LOOKBEHIND_OVERRUN (-6) #define LZO_E_EOF_NOT_FOUND (-7) #define LZO_E_INPUT_NOT_CONSUMED (-8) #define LZO_E_NOT_YET_IMPLEMENTED (-9) /* [not used right now] */ #ifndef lzo_sizeof_dict_t # define lzo_sizeof_dict_t ((unsigned)sizeof(lzo_bytep)) #endif /* lzo_init() should be the first function you call. * Check the return code ! * * lzo_init() is a macro to allow checking that the library and the * compiler's view of various types are consistent. */ #define lzo_init() __lzo_init_v2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\ (int)sizeof(long),(int)sizeof(lzo_uint32),(int)sizeof(lzo_uint),\ (int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\ (int)sizeof(lzo_callback_t)) LZO_EXTERN(int) __lzo_init_v2(unsigned,int,int,int,int,int,int,int,int,int); /* version functions (useful for shared libraries) */ LZO_EXTERN(unsigned) lzo_version(void); LZO_EXTERN(const char *) lzo_version_string(void); LZO_EXTERN(const char *) lzo_version_date(void); LZO_EXTERN(const lzo_charp) _lzo_version_string(void); LZO_EXTERN(const lzo_charp) _lzo_version_date(void); /* string functions */ LZO_EXTERN(int) lzo_memcmp(const lzo_voidp _s1, const lzo_voidp _s2, lzo_uint _len); LZO_EXTERN(lzo_voidp) lzo_memcpy(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len); LZO_EXTERN(lzo_voidp) lzo_memmove(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len); LZO_EXTERN(lzo_voidp) lzo_memset(lzo_voidp _s, int _c, lzo_uint _len); /* checksum functions */ LZO_EXTERN(lzo_uint32) lzo_adler32(lzo_uint32 _adler, const lzo_bytep _buf, lzo_uint _len); LZO_EXTERN(lzo_uint32) lzo_crc32(lzo_uint32 _c, const lzo_bytep _buf, lzo_uint _len); LZO_EXTERN(const lzo_uint32p) lzo_get_crc32_table(void); /* misc. */ LZO_EXTERN(int) _lzo_config_check(void); typedef union { lzo_bytep p; lzo_uint u; } __lzo_pu_u; typedef union { lzo_bytep p; lzo_uint32 u32; } __lzo_pu32_u; typedef union { void *vp; lzo_bytep bp; lzo_uint32 u32; long l; } lzo_align_t; /* align a char pointer on a boundary that is a multiple of `size' */ LZO_EXTERN(unsigned) __lzo_align_gap(const lzo_voidp _ptr, lzo_uint _size); #define LZO_PTR_ALIGN_UP(_ptr,_size) \ ((_ptr) + (lzo_uint) __lzo_align_gap((const lzo_voidp)(_ptr),(lzo_uint)(_size))) /*********************************************************************** // deprecated macros - only for backward compatibility with LZO v1.xx ************************************************************************/ #if defined(LZO_CFG_COMPAT) #define __LZOCONF_H 1 #if defined(LZO_ARCH_I086) # define __LZO_i386 1 #elif defined(LZO_ARCH_I386) # define __LZO_i386 1 #endif #if defined(LZO_OS_DOS16) # define __LZO_DOS 1 # define __LZO_DOS16 1 #elif defined(LZO_OS_DOS32) # define __LZO_DOS 1 #elif defined(LZO_OS_WIN16) # define __LZO_WIN 1 # define __LZO_WIN16 1 #elif defined(LZO_OS_WIN32) # define __LZO_WIN 1 #endif #define __LZO_CMODEL #define __LZO_DMODEL #define __LZO_ENTRY __LZO_CDECL #define LZO_EXTERN_CDECL LZO_EXTERN #define LZO_ALIGN LZO_PTR_ALIGN_UP #define lzo_compress_asm_t lzo_compress_t #define lzo_decompress_asm_t lzo_decompress_t #endif /* LZO_CFG_COMPAT */ #ifdef __cplusplus } /* extern "C" */ #endif #endif /* already included */ /* vim:set ts=4 et: */ bcmatroska2-5.3.101/libmatroska2/minilzo/lzodefs.h000066400000000000000000002004421462133141200217620ustar00rootroot00000000000000/* lzodefs.h -- architecture, OS and compiler specific defines This file is part of the LZO real-time data compression library. Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer http://www.oberhumer.com/opensource/lzo/ */ #ifndef __LZODEFS_H_INCLUDED #define __LZODEFS_H_INCLUDED 1 #if defined(__CYGWIN32__) && !defined(__CYGWIN__) # define __CYGWIN__ __CYGWIN32__ #endif #if defined(__IBMCPP__) && !defined(__IBMC__) # define __IBMC__ __IBMCPP__ #endif #if defined(__ICL) && defined(_WIN32) && !defined(__INTEL_COMPILER) # define __INTEL_COMPILER __ICL #endif #if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) # define _ALL_SOURCE 1 #endif #if defined(__mips__) && defined(__R5900__) # if !defined(__LONG_MAX__) # define __LONG_MAX__ 9223372036854775807L # endif #endif #if defined(__INTEL_COMPILER) && defined(__linux__) # pragma warning(disable: 193) #endif #if defined(__KEIL__) && defined(__C166__) # pragma warning disable = 322 #elif 0 && defined(__C251__) # pragma warning disable = 322 #endif #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) # if (_MSC_VER >= 1300) # pragma warning(disable: 4668) # endif #endif #if 0 && defined(__WATCOMC__) # if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) # pragma warning 203 9 # endif #endif #if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) # pragma option -h #endif #if 0 #define LZO_0xffffL 0xfffful #define LZO_0xffffffffL 0xfffffffful #else #define LZO_0xffffL 65535ul #define LZO_0xffffffffL 4294967295ul #endif #if (LZO_0xffffL == LZO_0xffffffffL) # error "your preprocessor is broken 1" #endif #if (16ul * 16384ul != 262144ul) # error "your preprocessor is broken 2" #endif #if 0 #if (32767 >= 4294967295ul) # error "your preprocessor is broken 3" #endif #if (65535u >= 4294967295ul) # error "your preprocessor is broken 4" #endif #endif #if (UINT_MAX == LZO_0xffffL) #if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) # if !defined(MSDOS) # define MSDOS 1 # endif # if !defined(_MSDOS) # define _MSDOS 1 # endif #elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) # if (__VERSION == 520) && (MB_LEN_MAX == 1) # if !defined(__AZTEC_C__) # define __AZTEC_C__ __VERSION # endif # if !defined(__DOS__) # define __DOS__ 1 # endif # endif #endif #endif #if defined(_MSC_VER) && defined(M_I86HM) && (UINT_MAX == LZO_0xffffL) # define ptrdiff_t long # define _PTRDIFF_T_DEFINED #endif #if (UINT_MAX == LZO_0xffffL) # undef __LZO_RENAME_A # undef __LZO_RENAME_B # if defined(__AZTEC_C__) && defined(__DOS__) # define __LZO_RENAME_A 1 # elif defined(_MSC_VER) && defined(MSDOS) # if (_MSC_VER < 600) # define __LZO_RENAME_A 1 # elif (_MSC_VER < 700) # define __LZO_RENAME_B 1 # endif # elif defined(__TSC__) && defined(__OS2__) # define __LZO_RENAME_A 1 # elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) # define __LZO_RENAME_A 1 # elif defined(__PACIFIC__) && defined(DOS) # if !defined(__far) # define __far far # endif # if !defined(__near) # define __near near # endif # endif # if defined(__LZO_RENAME_A) # if !defined(__cdecl) # define __cdecl cdecl # endif # if !defined(__far) # define __far far # endif # if !defined(__huge) # define __huge huge # endif # if !defined(__near) # define __near near # endif # if !defined(__pascal) # define __pascal pascal # endif # if !defined(__huge) # define __huge huge # endif # elif defined(__LZO_RENAME_B) # if !defined(__cdecl) # define __cdecl _cdecl # endif # if !defined(__far) # define __far _far # endif # if !defined(__huge) # define __huge _huge # endif # if !defined(__near) # define __near _near # endif # if !defined(__pascal) # define __pascal _pascal # endif # elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) # if !defined(__cdecl) # define __cdecl cdecl # endif # if !defined(__pascal) # define __pascal pascal # endif # endif # undef __LZO_RENAME_A # undef __LZO_RENAME_B #endif #if (UINT_MAX == LZO_0xffffL) #if defined(__AZTEC_C__) && defined(__DOS__) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 #elif defined(_MSC_VER) && defined(MSDOS) # if (_MSC_VER < 600) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 # endif # if (_MSC_VER < 700) # define LZO_BROKEN_INTEGRAL_PROMOTION 1 # define LZO_BROKEN_SIZEOF 1 # endif #elif defined(__PACIFIC__) && defined(DOS) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 #elif defined(__TURBOC__) && defined(__MSDOS__) # if (__TURBOC__ < 0x0150) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 # define LZO_BROKEN_INTEGRAL_PROMOTION 1 # endif # if (__TURBOC__ < 0x0200) # define LZO_BROKEN_SIZEOF 1 # endif # if (__TURBOC__ < 0x0400) && defined(__cplusplus) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # endif #elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # define LZO_BROKEN_SIZEOF 1 #endif #endif #if defined(__WATCOMC__) && (__WATCOMC__ < 900) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 #endif #if defined(_CRAY) && defined(_CRAY1) # define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 #endif #define LZO_PP_STRINGIZE(x) #x #define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) #define LZO_PP_CONCAT2(a,b) a ## b #define LZO_PP_CONCAT3(a,b,c) a ## b ## c #define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d #define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e #define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) #define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) #define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) #define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) #if 1 #define LZO_CPP_STRINGIZE(x) #x #define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) #define LZO_CPP_CONCAT2(a,b) a ## b #define LZO_CPP_CONCAT3(a,b,c) a ## b ## c #define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d #define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e #define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) #define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) #define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) #define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) #endif #define __LZO_MASK_GEN(o,b) (((((o) << ((b)-1)) - (o)) << 1) + (o)) #if 1 && defined(__cplusplus) # if !defined(__STDC_CONSTANT_MACROS) # define __STDC_CONSTANT_MACROS 1 # endif # if !defined(__STDC_LIMIT_MACROS) # define __STDC_LIMIT_MACROS 1 # endif #endif #if defined(__cplusplus) # define LZO_EXTERN_C extern "C" #else # define LZO_EXTERN_C extern #endif #if !defined(__LZO_OS_OVERRIDE) #if defined(LZO_OS_FREESTANDING) # define LZO_INFO_OS "freestanding" #elif defined(LZO_OS_EMBEDDED) # define LZO_INFO_OS "embedded" #elif 1 && defined(__IAR_SYSTEMS_ICC__) # define LZO_OS_EMBEDDED 1 # define LZO_INFO_OS "embedded" #elif defined(__CYGWIN__) && defined(__GNUC__) # define LZO_OS_CYGWIN 1 # define LZO_INFO_OS "cygwin" #elif defined(__EMX__) && defined(__GNUC__) # define LZO_OS_EMX 1 # define LZO_INFO_OS "emx" #elif defined(__BEOS__) # define LZO_OS_BEOS 1 # define LZO_INFO_OS "beos" #elif defined(__Lynx__) # define LZO_OS_LYNXOS 1 # define LZO_INFO_OS "lynxos" #elif defined(__OS400__) # define LZO_OS_OS400 1 # define LZO_INFO_OS "os400" #elif defined(__QNX__) # define LZO_OS_QNX 1 # define LZO_INFO_OS "qnx" #elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" #elif defined(__BORLANDC__) && defined(__DPMI16__) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" #elif defined(__ZTC__) && defined(DOS386) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" #elif defined(__OS2__) || defined(__OS2V2__) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_OS216 1 # define LZO_INFO_OS "os216" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_OS2 1 # define LZO_INFO_OS "os2" # else # error "check your limits.h header" # endif #elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) # define LZO_OS_WIN64 1 # define LZO_INFO_OS "win64" #elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" #elif defined(__MWERKS__) && defined(__INTEL__) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" #elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_WIN16 1 # define LZO_INFO_OS "win16" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" # else # error "check your limits.h header" # endif #elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" # else # error "check your limits.h header" # endif #elif defined(__WATCOMC__) # if defined(__NT__) && (UINT_MAX == LZO_0xffffL) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" # elif defined(__NT__) && (__WATCOMC__ < 1100) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" # elif defined(__linux__) || defined(__LINUX__) # define LZO_OS_POSIX 1 # define LZO_INFO_OS "posix" # else # error "please specify a target using the -bt compiler option" # endif #elif defined(__palmos__) # define LZO_OS_PALMOS 1 # define LZO_INFO_OS "palmos" #elif defined(__TOS__) || defined(__atarist__) # define LZO_OS_TOS 1 # define LZO_INFO_OS "tos" #elif defined(macintosh) && !defined(__ppc__) # define LZO_OS_MACCLASSIC 1 # define LZO_INFO_OS "macclassic" #elif defined(__VMS) # define LZO_OS_VMS 1 # define LZO_INFO_OS "vms" #elif ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) # define LZO_OS_CONSOLE 1 # define LZO_OS_CONSOLE_PS2 1 # define LZO_INFO_OS "console" # define LZO_INFO_OS_CONSOLE "ps2" #elif (defined(__mips__) && defined(__psp__)) # define LZO_OS_CONSOLE 1 # define LZO_OS_CONSOLE_PSP 1 # define LZO_INFO_OS "console" # define LZO_INFO_OS_CONSOLE "psp" #else # define LZO_OS_POSIX 1 # define LZO_INFO_OS "posix" #endif #if (LZO_OS_POSIX) # if defined(_AIX) || defined(__AIX__) || defined(__aix__) # define LZO_OS_POSIX_AIX 1 # define LZO_INFO_OS_POSIX "aix" # elif defined(__FreeBSD__) # define LZO_OS_POSIX_FREEBSD 1 # define LZO_INFO_OS_POSIX "freebsd" # elif defined(__hpux__) || defined(__hpux) # define LZO_OS_POSIX_HPUX 1 # define LZO_INFO_OS_POSIX "hpux" # elif defined(__INTERIX) # define LZO_OS_POSIX_INTERIX 1 # define LZO_INFO_OS_POSIX "interix" # elif defined(__IRIX__) || defined(__irix__) # define LZO_OS_POSIX_IRIX 1 # define LZO_INFO_OS_POSIX "irix" # elif defined(__linux__) || defined(__linux) || defined(__LINUX__) # define LZO_OS_POSIX_LINUX 1 # define LZO_INFO_OS_POSIX "linux" # elif defined(__APPLE__) || defined(__MACOS__) # define LZO_OS_POSIX_MACOSX 1 # define LZO_INFO_OS_POSIX "macosx" # elif defined(__minix__) || defined(__minix) # define LZO_OS_POSIX_MINIX 1 # define LZO_INFO_OS_POSIX "minix" # elif defined(__NetBSD__) # define LZO_OS_POSIX_NETBSD 1 # define LZO_INFO_OS_POSIX "netbsd" # elif defined(__OpenBSD__) # define LZO_OS_POSIX_OPENBSD 1 # define LZO_INFO_OS_POSIX "openbsd" # elif defined(__osf__) # define LZO_OS_POSIX_OSF 1 # define LZO_INFO_OS_POSIX "osf" # elif defined(__solaris__) || defined(__sun) # if defined(__SVR4) || defined(__svr4__) # define LZO_OS_POSIX_SOLARIS 1 # define LZO_INFO_OS_POSIX "solaris" # else # define LZO_OS_POSIX_SUNOS 1 # define LZO_INFO_OS_POSIX "sunos" # endif # elif defined(__ultrix__) || defined(__ultrix) # define LZO_OS_POSIX_ULTRIX 1 # define LZO_INFO_OS_POSIX "ultrix" # elif defined(_UNICOS) # define LZO_OS_POSIX_UNICOS 1 # define LZO_INFO_OS_POSIX "unicos" # else # define LZO_OS_POSIX_UNKNOWN 1 # define LZO_INFO_OS_POSIX "unknown" # endif #endif #endif #if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) # if (UINT_MAX != LZO_0xffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) # if (UINT_MAX != LZO_0xffffffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) # define LZO_CC_CILLY 1 # define LZO_INFO_CC "Cilly" # if defined(__CILLY__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) # else # define LZO_INFO_CCVER "unknown" # endif #elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) # define LZO_CC_SDCC 1 # define LZO_INFO_CC "sdcc" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) #elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) # define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + __PATHCC_MINOR__ * 0x100 + __PATHCC_PATCHLEVEL__) # define LZO_INFO_CC "Pathscale C" # define LZO_INFO_CCVER __PATHSCALE__ #elif defined(__INTEL_COMPILER) # define LZO_CC_INTELC 1 # define LZO_INFO_CC "Intel C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) # if defined(_WIN32) || defined(_WIN64) # define LZO_CC_SYNTAX_MSC 1 # else # define LZO_CC_SYNTAX_GNUC 1 # endif #elif defined(__POCC__) && defined(_WIN32) # define LZO_CC_PELLESC 1 # define LZO_INFO_CC "Pelles C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) #elif defined(__llvm__) && defined(__GNUC__) && defined(__VERSION__) # if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) # define LZO_CC_LLVM (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100 + __GNUC_PATCHLEVEL__) # else # define LZO_CC_LLVM (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100) # endif # define LZO_INFO_CC "llvm-gcc" # define LZO_INFO_CCVER __VERSION__ #elif defined(__GNUC__) && defined(__VERSION__) # if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) # define LZO_CC_GNUC (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100 + __GNUC_PATCHLEVEL__) # elif defined(__GNUC_MINOR__) # define LZO_CC_GNUC (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100) # else # define LZO_CC_GNUC (__GNUC__ * 0x10000L) # endif # define LZO_INFO_CC "gcc" # define LZO_INFO_CCVER __VERSION__ #elif defined(__ACK__) && defined(_ACK) # define LZO_CC_ACK 1 # define LZO_INFO_CC "Amsterdam Compiler Kit C" # define LZO_INFO_CCVER "unknown" #elif defined(__AZTEC_C__) # define LZO_CC_AZTECC 1 # define LZO_INFO_CC "Aztec C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) #elif defined(__BORLANDC__) # define LZO_CC_BORLANDC 1 # define LZO_INFO_CC "Borland C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) #elif defined(_CRAYC) && defined(_RELEASE) # define LZO_CC_CRAYC 1 # define LZO_INFO_CC "Cray C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) #elif defined(__DMC__) && defined(__SC__) # define LZO_CC_DMC 1 # define LZO_INFO_CC "Digital Mars C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) #elif defined(__DECC) # define LZO_CC_DECC 1 # define LZO_INFO_CC "DEC C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) #elif defined(__HIGHC__) # define LZO_CC_HIGHC 1 # define LZO_INFO_CC "MetaWare High C" # define LZO_INFO_CCVER "unknown" #elif defined(__IAR_SYSTEMS_ICC__) # define LZO_CC_IARC 1 # define LZO_INFO_CC "IAR C" # if defined(__VER__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) # else # define LZO_INFO_CCVER "unknown" # endif #elif defined(__IBMC__) # define LZO_CC_IBMC 1 # define LZO_INFO_CC "IBM C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) #elif defined(__KEIL__) && defined(__C166__) # define LZO_CC_KEILC 1 # define LZO_INFO_CC "Keil C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) #elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) # define LZO_CC_LCCWIN32 1 # define LZO_INFO_CC "lcc-win32" # define LZO_INFO_CCVER "unknown" #elif defined(__LCC__) # define LZO_CC_LCC 1 # define LZO_INFO_CC "lcc" # if defined(__LCC_VERSION__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) # else # define LZO_INFO_CCVER "unknown" # endif #elif defined(_MSC_VER) # define LZO_CC_MSC 1 # define LZO_INFO_CC "Microsoft C" # if defined(_MSC_FULL_VER) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) # else # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) # endif #elif defined(__MWERKS__) # define LZO_CC_MWERKS 1 # define LZO_INFO_CC "Metrowerks C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) #elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) # define LZO_CC_NDPC 1 # define LZO_INFO_CC "Microway NDP C" # define LZO_INFO_CCVER "unknown" #elif defined(__PACIFIC__) # define LZO_CC_PACIFICC 1 # define LZO_INFO_CC "Pacific C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) #elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) # define LZO_CC_PGI 1 # define LZO_INFO_CC "Portland Group PGI C" # define LZO_INFO_CCVER "unknown" #elif defined(__PUREC__) && defined(__TOS__) # define LZO_CC_PUREC 1 # define LZO_INFO_CC "Pure C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) #elif defined(__SC__) && defined(__ZTC__) # define LZO_CC_SYMANTECC 1 # define LZO_INFO_CC "Symantec C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) #elif defined(__SUNPRO_C) # define LZO_INFO_CC "SunPro C" # if ((__SUNPRO_C)+0 > 0) # define LZO_CC_SUNPROC __SUNPRO_C # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) # else # define LZO_CC_SUNPROC 1 # define LZO_INFO_CCVER "unknown" # endif #elif defined(__SUNPRO_CC) # define LZO_INFO_CC "SunPro C" # if ((__SUNPRO_CC)+0 > 0) # define LZO_CC_SUNPROC __SUNPRO_CC # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) # else # define LZO_CC_SUNPROC 1 # define LZO_INFO_CCVER "unknown" # endif #elif defined(__TINYC__) # define LZO_CC_TINYC 1 # define LZO_INFO_CC "Tiny C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) #elif defined(__TSC__) # define LZO_CC_TOPSPEEDC 1 # define LZO_INFO_CC "TopSpeed C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) #elif defined(__WATCOMC__) # define LZO_CC_WATCOMC 1 # define LZO_INFO_CC "Watcom C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) #elif defined(__TURBOC__) # define LZO_CC_TURBOC 1 # define LZO_INFO_CC "Turbo C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) #elif defined(__ZTC__) # define LZO_CC_ZORTECHC 1 # define LZO_INFO_CC "Zortech C" # if (__ZTC__ == 0x310) # define LZO_INFO_CCVER "0x310" # else # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) # endif #else # define LZO_CC_UNKNOWN 1 # define LZO_INFO_CC "unknown" # define LZO_INFO_CCVER "unknown" #endif #if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) # error "LZO_CC_MSC: _MSC_FULL_VER is not defined" #endif #if !defined(__LZO_ARCH_OVERRIDE) && !defined(LZO_ARCH_GENERIC) && defined(_CRAY) # if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) # if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) # define LZO_ARCH_CRAY_MPP 1 # elif defined(_CRAY1) # define LZO_ARCH_CRAY_PVP 1 # endif # endif #endif #if !defined(__LZO_ARCH_OVERRIDE) #if defined(LZO_ARCH_GENERIC) # define LZO_INFO_ARCH "generic" #elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) # define LZO_ARCH_I086 1 # define LZO_ARCH_IA16 1 # define LZO_INFO_ARCH "i086" #elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) # define LZO_ARCH_ALPHA 1 # define LZO_INFO_ARCH "alpha" #elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) # define LZO_ARCH_ALPHA 1 # define LZO_INFO_ARCH "alpha" #elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) # define LZO_ARCH_AMD64 1 # define LZO_INFO_ARCH "amd64" #elif defined(__thumb__) || (defined(_M_ARM) && defined(_M_THUMB)) # define LZO_ARCH_ARM 1 # define LZO_ARCH_ARM_THUMB 1 # define LZO_INFO_ARCH "arm_thumb" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) # define LZO_ARCH_ARM 1 # if defined(__CPU_MODE__) && ((__CPU_MODE__)+0 == 1) # define LZO_ARCH_ARM_THUMB 1 # define LZO_INFO_ARCH "arm_thumb" # elif defined(__CPU_MODE__) && ((__CPU_MODE__)+0 == 2) # define LZO_INFO_ARCH "arm" # else # define LZO_INFO_ARCH "arm" # endif #elif defined(__arm__) || defined(_M_ARM) # define LZO_ARCH_ARM 1 # define LZO_INFO_ARCH "arm" #elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) # define LZO_ARCH_AVR 1 # define LZO_INFO_ARCH "avr" #elif defined(__bfin__) # define LZO_ARCH_BLACKFIN 1 # define LZO_INFO_ARCH "blackfin" #elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) # define LZO_ARCH_C166 1 # define LZO_INFO_ARCH "c166" #elif defined(__cris__) # define LZO_ARCH_CRIS 1 # define LZO_INFO_ARCH "cris" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) # define LZO_ARCH_EZ80 1 # define LZO_INFO_ARCH "ez80" #elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) # define LZO_ARCH_H8300 1 # define LZO_INFO_ARCH "h8300" #elif defined(__hppa__) || defined(__hppa) # define LZO_ARCH_HPPA 1 # define LZO_INFO_ARCH "hppa" #elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif (LZO_CC_ZORTECHC && defined(__I86__)) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) # define LZO_ARCH_IA64 1 # define LZO_INFO_ARCH "ia64" #elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) # define LZO_ARCH_M16C 1 # define LZO_INFO_ARCH "m16c" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) # define LZO_ARCH_M16C 1 # define LZO_INFO_ARCH "m16c" #elif defined(__m32r__) # define LZO_ARCH_M32R 1 # define LZO_INFO_ARCH "m32r" #elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) # define LZO_ARCH_M68K 1 # define LZO_INFO_ARCH "m68k" #elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) # define LZO_ARCH_MCS251 1 # define LZO_INFO_ARCH "mcs251" #elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) # define LZO_ARCH_MCS51 1 # define LZO_INFO_ARCH "mcs51" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) # define LZO_ARCH_MCS51 1 # define LZO_INFO_ARCH "mcs51" #elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) # define LZO_ARCH_MIPS 1 # define LZO_INFO_ARCH "mips" #elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) # define LZO_ARCH_MSP430 1 # define LZO_INFO_ARCH "msp430" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) # define LZO_ARCH_MSP430 1 # define LZO_INFO_ARCH "msp430" #elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) # define LZO_ARCH_POWERPC 1 # define LZO_INFO_ARCH "powerpc" #elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) # define LZO_ARCH_S390 1 # define LZO_INFO_ARCH "s390" #elif defined(__sh__) || defined(_M_SH) # define LZO_ARCH_SH 1 # define LZO_INFO_ARCH "sh" #elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) # define LZO_ARCH_SPARC 1 # define LZO_INFO_ARCH "sparc" #elif defined(__SPU__) # define LZO_ARCH_SPU 1 # define LZO_INFO_ARCH "spu" #elif (UINT_MAX == LZO_0xffffL) && defined(__z80) # define LZO_ARCH_Z80 1 # define LZO_INFO_ARCH "z80" #elif (LZO_ARCH_CRAY_PVP) # if defined(_CRAYSV1) # define LZO_ARCH_CRAY_SV1 1 # define LZO_INFO_ARCH "cray_sv1" # elif (_ADDR64) # define LZO_ARCH_CRAY_T90 1 # define LZO_INFO_ARCH "cray_t90" # elif (_ADDR32) # define LZO_ARCH_CRAY_YMP 1 # define LZO_INFO_ARCH "cray_ymp" # else # define LZO_ARCH_CRAY_XMP 1 # define LZO_INFO_ARCH "cray_xmp" # endif #else # define LZO_ARCH_UNKNOWN 1 # define LZO_INFO_ARCH "unknown" #endif #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) # error "FIXME - missing define for CPU architecture" #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) # error "FIXME - missing WIN32 define for CPU architecture" #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) # error "FIXME - missing WIN64 define for CPU architecture" #endif #if (LZO_OS_OS216 || LZO_OS_WIN16) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && defined(BLX286)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #endif #if defined(LZO_ARCH_ARM_THUMB) && !defined(LZO_ARCH_ARM) # error "this should not happen" #endif #if defined(LZO_ARCH_I086PM) && !defined(LZO_ARCH_I086) # error "this should not happen" #endif #if (LZO_ARCH_I086) # if (UINT_MAX != LZO_0xffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if (LZO_ARCH_I386) # if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) # error "this should not happen" # endif # if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if !defined(__LZO_MM_OVERRIDE) #if (LZO_ARCH_I086) #if (UINT_MAX != LZO_0xffffL) # error "this should not happen" #endif #if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) # define LZO_MM_TINY 1 #elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) # define LZO_MM_HUGE 1 #elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) # define LZO_MM_SMALL 1 #elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) # define LZO_MM_MEDIUM 1 #elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) # define LZO_MM_COMPACT 1 #elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) # define LZO_MM_LARGE 1 #elif (LZO_CC_AZTECC) # if defined(_LARGE_CODE) && defined(_LARGE_DATA) # define LZO_MM_LARGE 1 # elif defined(_LARGE_CODE) # define LZO_MM_MEDIUM 1 # elif defined(_LARGE_DATA) # define LZO_MM_COMPACT 1 # else # define LZO_MM_SMALL 1 # endif #elif (LZO_CC_ZORTECHC && defined(__VCM__)) # define LZO_MM_LARGE 1 #else # error "unknown memory model" #endif #if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) #define LZO_HAVE_MM_HUGE_PTR 1 #define LZO_HAVE_MM_HUGE_ARRAY 1 #if (LZO_MM_TINY) # undef LZO_HAVE_MM_HUGE_ARRAY #endif #if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) # undef LZO_HAVE_MM_HUGE_PTR # undef LZO_HAVE_MM_HUGE_ARRAY #elif (LZO_CC_DMC || LZO_CC_SYMANTECC) # undef LZO_HAVE_MM_HUGE_ARRAY #elif (LZO_CC_MSC && defined(_QC)) # undef LZO_HAVE_MM_HUGE_ARRAY # if (_MSC_VER < 600) # undef LZO_HAVE_MM_HUGE_PTR # endif #elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) # undef LZO_HAVE_MM_HUGE_ARRAY #endif #if (LZO_ARCH_I086PM) && !defined(LZO_HAVE_MM_HUGE_PTR) # if (LZO_OS_DOS16) # error "this should not happen" # elif (LZO_CC_ZORTECHC) # else # error "this should not happen" # endif #endif #ifdef __cplusplus extern "C" { #endif #if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) # define LZO_MM_AHSHIFT 12 #elif (LZO_CC_WATCOMC) extern unsigned char _HShift; # define LZO_MM_AHSHIFT ((unsigned) _HShift) #else # error "FIXME - implement LZO_MM_AHSHIFT" #endif #ifdef __cplusplus } #endif #endif #elif (LZO_ARCH_C166) #if !defined(__MODEL__) # error "FIXME - C166 __MODEL__" #elif ((__MODEL__) == 0) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 1) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - C166 __MODEL__" #endif #elif (LZO_ARCH_MCS251) #if !defined(__MODEL__) # error "FIXME - MCS251 __MODEL__" #elif ((__MODEL__) == 0) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - MCS251 __MODEL__" #endif #elif (LZO_ARCH_MCS51) #if !defined(__MODEL__) # error "FIXME - MCS51 __MODEL__" #elif ((__MODEL__) == 1) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - MCS51 __MODEL__" #endif #elif (LZO_ARCH_CRAY_PVP) # define LZO_MM_PVP 1 #else # define LZO_MM_FLAT 1 #endif #if (LZO_MM_COMPACT) # define LZO_INFO_MM "compact" #elif (LZO_MM_FLAT) # define LZO_INFO_MM "flat" #elif (LZO_MM_HUGE) # define LZO_INFO_MM "huge" #elif (LZO_MM_LARGE) # define LZO_INFO_MM "large" #elif (LZO_MM_MEDIUM) # define LZO_INFO_MM "medium" #elif (LZO_MM_PVP) # define LZO_INFO_MM "pvp" #elif (LZO_MM_SMALL) # define LZO_INFO_MM "small" #elif (LZO_MM_TINY) # define LZO_INFO_MM "tiny" #else # error "unknown memory model" #endif #endif #if defined(SIZEOF_SHORT) # define LZO_SIZEOF_SHORT (SIZEOF_SHORT) #endif #if defined(SIZEOF_INT) # define LZO_SIZEOF_INT (SIZEOF_INT) #endif #if defined(SIZEOF_LONG) # define LZO_SIZEOF_LONG (SIZEOF_LONG) #endif #if defined(SIZEOF_LONG_LONG) # define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) #endif #if defined(SIZEOF___INT16) # define LZO_SIZEOF___INT16 (SIZEOF___INT16) #endif #if defined(SIZEOF___INT32) # define LZO_SIZEOF___INT32 (SIZEOF___INT32) #endif #if defined(SIZEOF___INT64) # define LZO_SIZEOF___INT64 (SIZEOF___INT64) #endif #if defined(SIZEOF_VOID_P) # define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) #endif #if defined(SIZEOF_SIZE_T) # define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) #endif #if defined(SIZEOF_PTRDIFF_T) # define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) #endif #define __LZO_LSR(x,b) (((x)+0ul) >> (b)) #if !defined(LZO_SIZEOF_SHORT) # if (LZO_ARCH_CRAY_PVP) # define LZO_SIZEOF_SHORT 8 # elif (USHRT_MAX == LZO_0xffffL) # define LZO_SIZEOF_SHORT 2 # elif (__LZO_LSR(USHRT_MAX,7) == 1) # define LZO_SIZEOF_SHORT 1 # elif (__LZO_LSR(USHRT_MAX,15) == 1) # define LZO_SIZEOF_SHORT 2 # elif (__LZO_LSR(USHRT_MAX,31) == 1) # define LZO_SIZEOF_SHORT 4 # elif (__LZO_LSR(USHRT_MAX,63) == 1) # define LZO_SIZEOF_SHORT 8 # elif (__LZO_LSR(USHRT_MAX,127) == 1) # define LZO_SIZEOF_SHORT 16 # else # error "LZO_SIZEOF_SHORT" # endif #endif #if !defined(LZO_SIZEOF_INT) # if (LZO_ARCH_CRAY_PVP) # define LZO_SIZEOF_INT 8 # elif (UINT_MAX == LZO_0xffffL) # define LZO_SIZEOF_INT 2 # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_SIZEOF_INT 4 # elif (__LZO_LSR(UINT_MAX,7) == 1) # define LZO_SIZEOF_INT 1 # elif (__LZO_LSR(UINT_MAX,15) == 1) # define LZO_SIZEOF_INT 2 # elif (__LZO_LSR(UINT_MAX,31) == 1) # define LZO_SIZEOF_INT 4 # elif (__LZO_LSR(UINT_MAX,63) == 1) # define LZO_SIZEOF_INT 8 # elif (__LZO_LSR(UINT_MAX,127) == 1) # define LZO_SIZEOF_INT 16 # else # error "LZO_SIZEOF_INT" # endif #endif #if !defined(LZO_SIZEOF_LONG) # if (ULONG_MAX == LZO_0xffffffffL) # define LZO_SIZEOF_LONG 4 # elif (__LZO_LSR(ULONG_MAX,7) == 1) # define LZO_SIZEOF_LONG 1 # elif (__LZO_LSR(ULONG_MAX,15) == 1) # define LZO_SIZEOF_LONG 2 # elif (__LZO_LSR(ULONG_MAX,31) == 1) # define LZO_SIZEOF_LONG 4 # elif (__LZO_LSR(ULONG_MAX,63) == 1) # define LZO_SIZEOF_LONG 8 # elif (__LZO_LSR(ULONG_MAX,127) == 1) # define LZO_SIZEOF_LONG 16 # else # error "LZO_SIZEOF_LONG" # endif #endif #if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) #if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) # if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) # if (LZO_CC_GNUC >= 0x030300ul) # if ((__LONG_MAX__)+0 == (__LONG_LONG_MAX__)+0) # define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG # elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) # define LZO_SIZEOF_LONG_LONG 4 # endif # endif # endif #endif #endif #if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) #if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) #if (LZO_ARCH_I086 && LZO_CC_DMC) #elif (LZO_CC_CILLY) && defined(__GNUC__) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) # define LZO_SIZEOF_LONG_LONG 8 #elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_OS_WIN64 || defined(_WIN64)) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_DMC)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) # define LZO_SIZEOF___INT64 8 #elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) # define LZO_SIZEOF___INT64 8 #elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && (_INTEGRAL_MAX_BITS == 64)) # define LZO_SIZEOF___INT64 8 #elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) # define LZO_SIZEOF_LONG_LONG 8 #elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) #elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # define LZO_SIZEOF_LONG_LONG 8 #endif #endif #endif #if defined(__cplusplus) && defined(LZO_CC_GNUC) # if (LZO_CC_GNUC < 0x020800ul) # undef LZO_SIZEOF_LONG_LONG # endif #endif #if defined(LZO_CFG_NO_LONG_LONG) || defined(__NO_LONG_LONG) # undef LZO_SIZEOF_LONG_LONG #endif #if !defined(LZO_SIZEOF_VOID_P) #if (LZO_ARCH_I086) # define __LZO_WORDSIZE 2 # if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) # define LZO_SIZEOF_VOID_P 2 # elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) # define LZO_SIZEOF_VOID_P 4 # else # error "LZO_MM" # endif #elif (LZO_ARCH_AVR || LZO_ARCH_Z80) # define __LZO_WORDSIZE 1 # define LZO_SIZEOF_VOID_P 2 #elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) # define LZO_SIZEOF_VOID_P 2 #elif (LZO_ARCH_H8300) # if defined(__NORMAL_MODE__) # define __LZO_WORDSIZE 4 # define LZO_SIZEOF_VOID_P 2 # elif defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) # define __LZO_WORDSIZE 4 # define LZO_SIZEOF_VOID_P 4 # else # define __LZO_WORDSIZE 2 # define LZO_SIZEOF_VOID_P 2 # endif # if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT # endif #elif (LZO_ARCH_M16C) # define __LZO_WORDSIZE 2 # if defined(__m32c_cpu__) || defined(__m32cm_cpu__) # define LZO_SIZEOF_VOID_P 4 # else # define LZO_SIZEOF_VOID_P 2 # endif #elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) # define __LZO_WORDSIZE 8 # define LZO_SIZEOF_VOID_P 4 #elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) # define __LZO_WORDSIZE 8 # define LZO_SIZEOF_VOID_P 8 #elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) # define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (LZO_OS_OS400 || defined(__OS400__)) # define __LZO_WORDSIZE LZO_SIZEOF_LONG # define LZO_SIZEOF_VOID_P 16 # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) # define LZO_SIZEOF_VOID_P 8 # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (LZO_ARCH_SPU) # if 0 # define __LZO_WORDSIZE 16 # endif # define LZO_SIZEOF_VOID_P 4 #else # define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG #endif #endif #if !defined(LZO_WORDSIZE) # if defined(__LZO_WORDSIZE) # define LZO_WORDSIZE __LZO_WORDSIZE # else # define LZO_WORDSIZE LZO_SIZEOF_VOID_P # endif #endif #if !defined(LZO_SIZEOF_SIZE_T) #if (LZO_ARCH_I086 || LZO_ARCH_M16C) # define LZO_SIZEOF_SIZE_T 2 #else # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P #endif #endif #if !defined(LZO_SIZEOF_PTRDIFF_T) #if (LZO_ARCH_I086) # if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P # elif (LZO_MM_COMPACT || LZO_MM_LARGE) # if (LZO_CC_BORLANDC || LZO_CC_TURBOC) # define LZO_SIZEOF_PTRDIFF_T 4 # else # define LZO_SIZEOF_PTRDIFF_T 2 # endif # else # error "LZO_MM" # endif #else # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T #endif #endif #if defined(LZO_ABI_NEUTRAL_ENDIAN) # undef LZO_ABI_BIG_ENDIAN # undef LZO_ABI_LITTLE_ENDIAN #elif !defined(LZO_ABI_BIG_ENDIAN) && !defined(LZO_ABI_LITTLE_ENDIAN) #if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) # define LZO_ABI_BIG_ENDIAN 1 #elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430) # define LZO_ABI_LITTLE_ENDIAN 1 #elif (LZO_ARCH_M68K || LZO_ARCH_S390) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) # if (__LITTLE_ENDIAN__ == 1) # define LZO_ABI_LITTLE_ENDIAN 1 # else # define LZO_ABI_BIG_ENDIAN 1 # endif #elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) # define LZO_ABI_LITTLE_ENDIAN 1 #elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) # define LZO_ABI_LITTLE_ENDIAN 1 #elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) # define LZO_ABI_LITTLE_ENDIAN 1 #endif #endif #if defined(LZO_ABI_BIG_ENDIAN) && defined(LZO_ABI_LITTLE_ENDIAN) # error "this should not happen" #endif #if defined(LZO_ABI_BIG_ENDIAN) # define LZO_INFO_ABI_ENDIAN "be" #elif defined(LZO_ABI_LITTLE_ENDIAN) # define LZO_INFO_ABI_ENDIAN "le" #elif defined(LZO_ABI_NEUTRAL_ENDIAN) # define LZO_INFO_ABI_ENDIAN "neutral" #endif #if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) # define LZO_ABI_I8LP16 1 # define LZO_INFO_ABI_PM "i8lp16" #elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) # define LZO_ABI_ILP16 1 # define LZO_INFO_ABI_PM "ilp16" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) # define LZO_ABI_ILP32 1 # define LZO_INFO_ABI_PM "ilp32" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) # define LZO_ABI_LLP64 1 # define LZO_INFO_ABI_PM "llp64" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) # define LZO_ABI_LP64 1 # define LZO_INFO_ABI_PM "lp64" #elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) # define LZO_ABI_ILP64 1 # define LZO_INFO_ABI_PM "ilp64" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) # define LZO_ABI_IP32L64 1 # define LZO_INFO_ABI_PM "ip32l64" #endif #if !defined(__LZO_LIBC_OVERRIDE) #if defined(LZO_LIBC_NAKED) # define LZO_INFO_LIBC "naked" #elif defined(LZO_LIBC_FREESTANDING) # define LZO_INFO_LIBC "freestanding" #elif defined(LZO_LIBC_MOSTLY_FREESTANDING) # define LZO_INFO_LIBC "mfreestanding" #elif defined(LZO_LIBC_ISOC90) # define LZO_INFO_LIBC "isoc90" #elif defined(LZO_LIBC_ISOC99) # define LZO_INFO_LIBC "isoc99" #elif defined(__dietlibc__) # define LZO_LIBC_DIETLIBC 1 # define LZO_INFO_LIBC "dietlibc" #elif defined(_NEWLIB_VERSION) # define LZO_LIBC_NEWLIB 1 # define LZO_INFO_LIBC "newlib" #elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) # if defined(__UCLIBC_SUBLEVEL__) # define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + __UCLIBC_MINOR__ * 0x100 + __UCLIBC_SUBLEVEL__) # else # define LZO_LIBC_UCLIBC 0x00090bL # endif # define LZO_INFO_LIBC "uclibc" #elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) # define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + __GLIBC_MINOR__ * 0x100) # define LZO_INFO_LIBC "glibc" #elif (LZO_CC_MWERKS) && defined(__MSL__) # define LZO_LIBC_MSL __MSL__ # define LZO_INFO_LIBC "msl" #elif 1 && defined(__IAR_SYSTEMS_ICC__) # define LZO_LIBC_ISOC90 1 # define LZO_INFO_LIBC "isoc90" #else # define LZO_LIBC_DEFAULT 1 # define LZO_INFO_LIBC "default" #endif #endif #if !defined(__lzo_gnuc_extension__) #if (LZO_CC_GNUC >= 0x020800ul) # define __lzo_gnuc_extension__ __extension__ #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_gnuc_extension__ __extension__ #else # define __lzo_gnuc_extension__ #endif #endif #if !defined(__lzo_ua_volatile) # define __lzo_ua_volatile volatile #endif #if !defined(__lzo_alignof) #if (LZO_CC_CILLY || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) # define __lzo_alignof(e) __alignof__(e) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) # define __lzo_alignof(e) __alignof__(e) #elif (LZO_CC_MSC && (_MSC_VER >= 1300)) # define __lzo_alignof(e) __alignof(e) #endif #endif #if defined(__lzo_alignof) # define __lzo_HAVE_alignof 1 #endif #if !defined(__lzo_constructor) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_constructor __attribute__((__constructor__,__used__)) #elif (LZO_CC_GNUC >= 0x020700ul) # define __lzo_constructor __attribute__((__constructor__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_constructor __attribute__((__constructor__)) #endif #endif #if defined(__lzo_constructor) # define __lzo_HAVE_constructor 1 #endif #if !defined(__lzo_destructor) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_destructor __attribute__((__destructor__,__used__)) #elif (LZO_CC_GNUC >= 0x020700ul) # define __lzo_destructor __attribute__((__destructor__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_destructor __attribute__((__destructor__)) #endif #endif #if defined(__lzo_destructor) # define __lzo_HAVE_destructor 1 #endif #if defined(__lzo_HAVE_destructor) && !defined(__lzo_HAVE_constructor) # error "this should not happen" #endif #if !defined(__lzo_inline) #if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) #elif defined(__cplusplus) # define __lzo_inline inline #elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) # define __lzo_inline __inline #elif (LZO_CC_CILLY || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) # define __lzo_inline __inline__ #elif (LZO_CC_DMC) # define __lzo_inline __inline #elif (LZO_CC_INTELC) # define __lzo_inline __inline #elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) # define __lzo_inline __inline #elif (LZO_CC_MSC && (_MSC_VER >= 900)) # define __lzo_inline __inline #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # define __lzo_inline inline #endif #endif #if defined(__lzo_inline) # define __lzo_HAVE_inline 1 #else # define __lzo_inline #endif #if !defined(__lzo_forceinline) #if (LZO_CC_GNUC >= 0x030200ul) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) # define __lzo_forceinline __forceinline #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) # define __lzo_forceinline __forceinline #endif #endif #if defined(__lzo_forceinline) # define __lzo_HAVE_forceinline 1 #else # define __lzo_forceinline #endif #if !defined(__lzo_noinline) #if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) # define __lzo_noinline __attribute__((__noinline__,__used__)) #elif (LZO_CC_GNUC >= 0x030200ul) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_MSC) # define __lzo_noinline __declspec(noinline) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1300)) # define __lzo_noinline __declspec(noinline) #elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) # if defined(__cplusplus) # else # define __lzo_noinline __declspec(noinline) # endif #endif #endif #if defined(__lzo_noinline) # define __lzo_HAVE_noinline 1 #else # define __lzo_noinline #endif #if (defined(__lzo_HAVE_forceinline) || defined(__lzo_HAVE_noinline)) && !defined(__lzo_HAVE_inline) # error "this should not happen" #endif #if !defined(__lzo_noreturn) #if (LZO_CC_GNUC >= 0x020700ul) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) # define __lzo_noreturn __declspec(noreturn) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_GNUC) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) # define __lzo_noreturn __declspec(noreturn) #endif #endif #if defined(__lzo_noreturn) # define __lzo_HAVE_noreturn 1 #else # define __lzo_noreturn #endif #if !defined(__lzo_nothrow) #if (LZO_CC_GNUC >= 0x030300ul) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) && defined(__cplusplus) # define __lzo_nothrow __declspec(nothrow) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) # define __lzo_nothrow __declspec(nothrow) #endif #endif #if defined(__lzo_nothrow) # define __lzo_HAVE_nothrow 1 #else # define __lzo_nothrow #endif #if !defined(__lzo_restrict) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_restrict __restrict__ #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_GNUC) # define __lzo_restrict __restrict__ #elif (LZO_CC_LLVM) # define __lzo_restrict __restrict__ #elif (LZO_CC_MSC && (_MSC_VER >= 1400)) # define __lzo_restrict __restrict #endif #endif #if defined(__lzo_restrict) # define __lzo_HAVE_restrict 1 #else # define __lzo_restrict #endif #if !defined(__lzo_likely) && !defined(__lzo_unlikely) #if (LZO_CC_GNUC >= 0x030200ul) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #endif #endif #if defined(__lzo_likely) # define __lzo_HAVE_likely 1 #else # define __lzo_likely(e) (e) #endif #if defined(__lzo_unlikely) # define __lzo_HAVE_unlikely 1 #else # define __lzo_unlikely(e) (e) #endif #if !defined(LZO_UNUSED) # if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) # define LZO_UNUSED(var) ((void) &var) # elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) # define LZO_UNUSED(var) if (&var) ; else # elif (LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) # define LZO_UNUSED(var) ((void) var) # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_UNUSED(var) if (&var) ; else # elif (LZO_CC_KEILC) # define LZO_UNUSED(var) {extern int __lzo_unused[1-2*!(sizeof(var)>0)];} # elif (LZO_CC_PACIFICC) # define LZO_UNUSED(var) ((void) sizeof(var)) # elif (LZO_CC_WATCOMC) && defined(__cplusplus) # define LZO_UNUSED(var) ((void) var) # else # define LZO_UNUSED(var) ((void) &var) # endif #endif #if !defined(LZO_UNUSED_FUNC) # if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) # define LZO_UNUSED_FUNC(func) ((void) func) # elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) # define LZO_UNUSED_FUNC(func) if (func) ; else # elif (LZO_CC_LLVM) # define LZO_UNUSED_FUNC(func) ((void) &func) # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_UNUSED_FUNC(func) if (func) ; else # elif (LZO_CC_MSC) # define LZO_UNUSED_FUNC(func) ((void) &func) # elif (LZO_CC_KEILC || LZO_CC_PELLESC) # define LZO_UNUSED_FUNC(func) {extern int __lzo_unused[1-2*!(sizeof((int)func)>0)];} # else # define LZO_UNUSED_FUNC(func) ((void) func) # endif #endif #if !defined(LZO_UNUSED_LABEL) # if (LZO_CC_WATCOMC) && defined(__cplusplus) # define LZO_UNUSED_LABEL(l) switch(0) case 1:goto l # elif (LZO_CC_INTELC || LZO_CC_WATCOMC) # define LZO_UNUSED_LABEL(l) if (0) goto l # else # define LZO_UNUSED_LABEL(l) switch(0) case 1:goto l # endif #endif #if !defined(LZO_DEFINE_UNINITIALIZED_VAR) # if 0 # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var # elif 0 && (LZO_CC_GNUC) # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var # else # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init # endif #endif #if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) # if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-!(e)]; # elif (LZO_CC_DMC || LZO_CC_SYMANTECC) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1u-2*!(e)]; # elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-!(e)]; # else # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-2*!(e)]; # endif #endif #if !defined(LZO_COMPILE_TIME_ASSERT) # if (LZO_CC_AZTECC) # define LZO_COMPILE_TIME_ASSERT(e) {typedef int __lzo_cta_t[1-!(e)];} # elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # else # define LZO_COMPILE_TIME_ASSERT(e) {typedef int __lzo_cta_t[1-2*!(e)];} # endif #endif #if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) # if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) # elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) # define __lzo_cdecl __cdecl # define __lzo_cdecl_atexit # define __lzo_cdecl_main __cdecl # if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) # define __lzo_cdecl_qsort __pascal # elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) # define __lzo_cdecl_qsort _stdcall # else # define __lzo_cdecl_qsort __cdecl # endif # elif (LZO_CC_WATCOMC) # define __lzo_cdecl __cdecl # else # define __lzo_cdecl __cdecl # define __lzo_cdecl_atexit __cdecl # define __lzo_cdecl_main __cdecl # define __lzo_cdecl_qsort __cdecl # endif # if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) # elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) # define __lzo_cdecl_sighandler __pascal # elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) # define __lzo_cdecl_sighandler _stdcall # elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) # define __lzo_cdecl_sighandler __clrcall # elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) # if defined(_DLL) # define __lzo_cdecl_sighandler _far _cdecl _loadds # elif defined(_MT) # define __lzo_cdecl_sighandler _far _cdecl # else # define __lzo_cdecl_sighandler _cdecl # endif # else # define __lzo_cdecl_sighandler __cdecl # endif #elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) # define __lzo_cdecl __cdecl #elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) # define __lzo_cdecl cdecl #endif #if !defined(__lzo_cdecl) # define __lzo_cdecl #endif #if !defined(__lzo_cdecl_atexit) # define __lzo_cdecl_atexit #endif #if !defined(__lzo_cdecl_main) # define __lzo_cdecl_main #endif #if !defined(__lzo_cdecl_qsort) # define __lzo_cdecl_qsort #endif #if !defined(__lzo_cdecl_sighandler) # define __lzo_cdecl_sighandler #endif #if !defined(__lzo_cdecl_va) # define __lzo_cdecl_va __lzo_cdecl #endif #if !defined(LZO_CFG_NO_WINDOWS_H) #if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) # if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) # elif (LZO_OS_WIN32 && LZO_CC_GNUC) && defined(__PW32__) # elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) # else # define LZO_HAVE_WINDOWS_H 1 # endif #endif #endif #if (LZO_ARCH_ALPHA) # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_AVOID_SHORT 1 # define LZO_OPT_AVOID_USHORT 1 #elif (LZO_ARCH_AMD64) # define LZO_OPT_AVOID_INT_INDEX 1 # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # define LZO_OPT_UNALIGNED64 1 #elif (LZO_ARCH_ARM && LZO_ARCH_ARM_THUMB) #elif (LZO_ARCH_ARM) # define LZO_OPT_AVOID_SHORT 1 # define LZO_OPT_AVOID_USHORT 1 #elif (LZO_ARCH_CRIS) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 #elif (LZO_ARCH_I386) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 #elif (LZO_ARCH_IA64) # define LZO_OPT_AVOID_INT_INDEX 1 # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_PREFER_POSTINC 1 #elif (LZO_ARCH_M68K) # define LZO_OPT_PREFER_POSTINC 1 # define LZO_OPT_PREFER_PREDEC 1 # if defined(__mc68020__) && !defined(__mcoldfire__) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # endif #elif (LZO_ARCH_MIPS) # define LZO_OPT_AVOID_UINT_INDEX 1 #elif (LZO_ARCH_POWERPC) # define LZO_OPT_PREFER_PREINC 1 # define LZO_OPT_PREFER_PREDEC 1 # if defined(LZO_ABI_BIG_ENDIAN) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # endif #elif (LZO_ARCH_S390) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # if (LZO_SIZEOF_SIZE_T == 8) # define LZO_OPT_UNALIGNED64 1 # endif #elif (LZO_ARCH_SH) # define LZO_OPT_PREFER_POSTINC 1 # define LZO_OPT_PREFER_PREDEC 1 #endif #if !defined(LZO_CFG_NO_INLINE_ASM) #if defined(LZO_CC_LLVM) # define LZO_CFG_NO_INLINE_ASM 1 #endif #endif #if !defined(LZO_CFG_NO_UNALIGNED) #if defined(LZO_ABI_NEUTRAL_ENDIAN) || defined(LZO_ARCH_GENERIC) # define LZO_CFG_NO_UNALIGNED 1 #endif #endif #if defined(LZO_CFG_NO_UNALIGNED) # undef LZO_OPT_UNALIGNED16 # undef LZO_OPT_UNALIGNED32 # undef LZO_OPT_UNALIGNED64 #endif #if defined(LZO_CFG_NO_INLINE_ASM) #elif (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) # define LZO_ASM_SYNTAX_MSC 1 #elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) #elif (LZO_ARCH_I386 && (LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) # define LZO_ASM_SYNTAX_GNUC 1 #elif (LZO_ARCH_AMD64 && (LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) # define LZO_ASM_SYNTAX_GNUC 1 #endif #if (LZO_ASM_SYNTAX_GNUC) #if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) # define __LZO_ASM_CLOBBER "ax" #elif (LZO_CC_INTELC) # define __LZO_ASM_CLOBBER "memory" #else # define __LZO_ASM_CLOBBER "cc", "memory" #endif #endif #if defined(__LZO_INFOSTR_MM) #elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) # define __LZO_INFOSTR_MM "" #elif defined(LZO_INFO_MM) # define __LZO_INFOSTR_MM "." LZO_INFO_MM #else # define __LZO_INFOSTR_MM "" #endif #if defined(__LZO_INFOSTR_PM) #elif defined(LZO_INFO_ABI_PM) # define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM #else # define __LZO_INFOSTR_PM "" #endif #if defined(__LZO_INFOSTR_ENDIAN) #elif defined(LZO_INFO_ABI_ENDIAN) # define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN #else # define __LZO_INFOSTR_ENDIAN "" #endif #if defined(__LZO_INFOSTR_OSNAME) #elif defined(LZO_INFO_OS_CONSOLE) # define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE #elif defined(LZO_INFO_OS_POSIX) # define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX #else # define __LZO_INFOSTR_OSNAME LZO_INFO_OS #endif #if defined(__LZO_INFOSTR_LIBC) #elif defined(LZO_INFO_LIBC) # define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC #else # define __LZO_INFOSTR_LIBC "" #endif #if defined(__LZO_INFOSTR_CCVER) #elif defined(LZO_INFO_CCVER) # define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER #else # define __LZO_INFOSTR_CCVER "" #endif #define LZO_INFO_STRING \ LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER #endif /* already included */ /* vim:set ts=4 et: */ bcmatroska2-5.3.101/libmatroska2/minilzo/minilzo.c000066400000000000000000003640011462133141200217720ustar00rootroot00000000000000/* minilzo.c -- mini subset of the LZO real-time data compression library This file is part of the LZO real-time data compression library. Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer http://www.oberhumer.com/opensource/lzo/ */ /* * NOTE: * the full LZO package can be found at * http://www.oberhumer.com/opensource/lzo/ */ #define __LZO_IN_MINILZO #define LZO_BUILD #if defined(LZO_CFG_FREESTANDING) # undef MINILZO_HAVE_CONFIG_H # define LZO_LIBC_FREESTANDING 1 # define LZO_OS_FREESTANDING 1 #endif #ifdef MINILZO_HAVE_CONFIG_H # include #endif #include #include #if defined(MINILZO_CFG_USE_INTERNAL_LZODEFS) #ifndef __LZODEFS_H_INCLUDED #define __LZODEFS_H_INCLUDED 1 #if defined(__CYGWIN32__) && !defined(__CYGWIN__) # define __CYGWIN__ __CYGWIN32__ #endif #if defined(__IBMCPP__) && !defined(__IBMC__) # define __IBMC__ __IBMCPP__ #endif #if defined(__ICL) && defined(_WIN32) && !defined(__INTEL_COMPILER) # define __INTEL_COMPILER __ICL #endif #if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) # define _ALL_SOURCE 1 #endif #if defined(__mips__) && defined(__R5900__) # if !defined(__LONG_MAX__) # define __LONG_MAX__ 9223372036854775807L # endif #endif #if defined(__INTEL_COMPILER) && defined(__linux__) # pragma warning(disable: 193) #endif #if defined(__KEIL__) && defined(__C166__) # pragma warning disable = 322 #elif 0 && defined(__C251__) # pragma warning disable = 322 #endif #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) # if (_MSC_VER >= 1300) # pragma warning(disable: 4668) # endif #endif #if 0 && defined(__WATCOMC__) # if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) # pragma warning 203 9 # endif #endif #if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) # pragma option -h #endif #if 0 #define LZO_0xffffL 0xfffful #define LZO_0xffffffffL 0xfffffffful #else #define LZO_0xffffL 65535ul #define LZO_0xffffffffL 4294967295ul #endif #if (LZO_0xffffL == LZO_0xffffffffL) # error "your preprocessor is broken 1" #endif #if (16ul * 16384ul != 262144ul) # error "your preprocessor is broken 2" #endif #if 0 #if (32767 >= 4294967295ul) # error "your preprocessor is broken 3" #endif #if (65535u >= 4294967295ul) # error "your preprocessor is broken 4" #endif #endif #if (UINT_MAX == LZO_0xffffL) #if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) # if !defined(MSDOS) # define MSDOS 1 # endif # if !defined(_MSDOS) # define _MSDOS 1 # endif #elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) # if (__VERSION == 520) && (MB_LEN_MAX == 1) # if !defined(__AZTEC_C__) # define __AZTEC_C__ __VERSION # endif # if !defined(__DOS__) # define __DOS__ 1 # endif # endif #endif #endif #if defined(_MSC_VER) && defined(M_I86HM) && (UINT_MAX == LZO_0xffffL) # define ptrdiff_t long # define _PTRDIFF_T_DEFINED #endif #if (UINT_MAX == LZO_0xffffL) # undef __LZO_RENAME_A # undef __LZO_RENAME_B # if defined(__AZTEC_C__) && defined(__DOS__) # define __LZO_RENAME_A 1 # elif defined(_MSC_VER) && defined(MSDOS) # if (_MSC_VER < 600) # define __LZO_RENAME_A 1 # elif (_MSC_VER < 700) # define __LZO_RENAME_B 1 # endif # elif defined(__TSC__) && defined(__OS2__) # define __LZO_RENAME_A 1 # elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) # define __LZO_RENAME_A 1 # elif defined(__PACIFIC__) && defined(DOS) # if !defined(__far) # define __far far # endif # if !defined(__near) # define __near near # endif # endif # if defined(__LZO_RENAME_A) # if !defined(__cdecl) # define __cdecl cdecl # endif # if !defined(__far) # define __far far # endif # if !defined(__huge) # define __huge huge # endif # if !defined(__near) # define __near near # endif # if !defined(__pascal) # define __pascal pascal # endif # if !defined(__huge) # define __huge huge # endif # elif defined(__LZO_RENAME_B) # if !defined(__cdecl) # define __cdecl _cdecl # endif # if !defined(__far) # define __far _far # endif # if !defined(__huge) # define __huge _huge # endif # if !defined(__near) # define __near _near # endif # if !defined(__pascal) # define __pascal _pascal # endif # elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) # if !defined(__cdecl) # define __cdecl cdecl # endif # if !defined(__pascal) # define __pascal pascal # endif # endif # undef __LZO_RENAME_A # undef __LZO_RENAME_B #endif #if (UINT_MAX == LZO_0xffffL) #if defined(__AZTEC_C__) && defined(__DOS__) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 #elif defined(_MSC_VER) && defined(MSDOS) # if (_MSC_VER < 600) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 # endif # if (_MSC_VER < 700) # define LZO_BROKEN_INTEGRAL_PROMOTION 1 # define LZO_BROKEN_SIZEOF 1 # endif #elif defined(__PACIFIC__) && defined(DOS) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 #elif defined(__TURBOC__) && defined(__MSDOS__) # if (__TURBOC__ < 0x0150) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 # define LZO_BROKEN_INTEGRAL_PROMOTION 1 # endif # if (__TURBOC__ < 0x0200) # define LZO_BROKEN_SIZEOF 1 # endif # if (__TURBOC__ < 0x0400) && defined(__cplusplus) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # endif #elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) # define LZO_BROKEN_CDECL_ALT_SYNTAX 1 # define LZO_BROKEN_SIZEOF 1 #endif #endif #if defined(__WATCOMC__) && (__WATCOMC__ < 900) # define LZO_BROKEN_INTEGRAL_CONSTANTS 1 #endif #if defined(_CRAY) && defined(_CRAY1) # define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 #endif #define LZO_PP_STRINGIZE(x) #x #define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) #define LZO_PP_CONCAT2(a,b) a ## b #define LZO_PP_CONCAT3(a,b,c) a ## b ## c #define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d #define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e #define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) #define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) #define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) #define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) #if 1 #define LZO_CPP_STRINGIZE(x) #x #define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) #define LZO_CPP_CONCAT2(a,b) a ## b #define LZO_CPP_CONCAT3(a,b,c) a ## b ## c #define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d #define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e #define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) #define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) #define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) #define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) #endif #define __LZO_MASK_GEN(o,b) (((((o) << ((b)-1)) - (o)) << 1) + (o)) #if 1 && defined(__cplusplus) # if !defined(__STDC_CONSTANT_MACROS) # define __STDC_CONSTANT_MACROS 1 # endif # if !defined(__STDC_LIMIT_MACROS) # define __STDC_LIMIT_MACROS 1 # endif #endif #if defined(__cplusplus) # define LZO_EXTERN_C extern "C" #else # define LZO_EXTERN_C extern #endif #if !defined(__LZO_OS_OVERRIDE) #if defined(LZO_OS_FREESTANDING) # define LZO_INFO_OS "freestanding" #elif defined(LZO_OS_EMBEDDED) # define LZO_INFO_OS "embedded" #elif 1 && defined(__IAR_SYSTEMS_ICC__) # define LZO_OS_EMBEDDED 1 # define LZO_INFO_OS "embedded" #elif defined(__CYGWIN__) && defined(__GNUC__) # define LZO_OS_CYGWIN 1 # define LZO_INFO_OS "cygwin" #elif defined(__EMX__) && defined(__GNUC__) # define LZO_OS_EMX 1 # define LZO_INFO_OS "emx" #elif defined(__BEOS__) # define LZO_OS_BEOS 1 # define LZO_INFO_OS "beos" #elif defined(__Lynx__) # define LZO_OS_LYNXOS 1 # define LZO_INFO_OS "lynxos" #elif defined(__OS400__) # define LZO_OS_OS400 1 # define LZO_INFO_OS "os400" #elif defined(__QNX__) # define LZO_OS_QNX 1 # define LZO_INFO_OS "qnx" #elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" #elif defined(__BORLANDC__) && defined(__DPMI16__) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" #elif defined(__ZTC__) && defined(DOS386) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" #elif defined(__OS2__) || defined(__OS2V2__) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_OS216 1 # define LZO_INFO_OS "os216" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_OS2 1 # define LZO_INFO_OS "os2" # else # error "check your limits.h header" # endif #elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) # define LZO_OS_WIN64 1 # define LZO_INFO_OS "win64" #elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" #elif defined(__MWERKS__) && defined(__INTEL__) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" #elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_WIN16 1 # define LZO_INFO_OS "win16" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" # else # error "check your limits.h header" # endif #elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) # if (UINT_MAX == LZO_0xffffL) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_OS_DOS32 1 # define LZO_INFO_OS "dos32" # else # error "check your limits.h header" # endif #elif defined(__WATCOMC__) # if defined(__NT__) && (UINT_MAX == LZO_0xffffL) # define LZO_OS_DOS16 1 # define LZO_INFO_OS "dos16" # elif defined(__NT__) && (__WATCOMC__ < 1100) # define LZO_OS_WIN32 1 # define LZO_INFO_OS "win32" # elif defined(__linux__) || defined(__LINUX__) # define LZO_OS_POSIX 1 # define LZO_INFO_OS "posix" # else # error "please specify a target using the -bt compiler option" # endif #elif defined(__palmos__) # define LZO_OS_PALMOS 1 # define LZO_INFO_OS "palmos" #elif defined(__TOS__) || defined(__atarist__) # define LZO_OS_TOS 1 # define LZO_INFO_OS "tos" #elif defined(macintosh) && !defined(__ppc__) # define LZO_OS_MACCLASSIC 1 # define LZO_INFO_OS "macclassic" #elif defined(__VMS) # define LZO_OS_VMS 1 # define LZO_INFO_OS "vms" #elif ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) # define LZO_OS_CONSOLE 1 # define LZO_OS_CONSOLE_PS2 1 # define LZO_INFO_OS "console" # define LZO_INFO_OS_CONSOLE "ps2" #elif (defined(__mips__) && defined(__psp__)) # define LZO_OS_CONSOLE 1 # define LZO_OS_CONSOLE_PSP 1 # define LZO_INFO_OS "console" # define LZO_INFO_OS_CONSOLE "psp" #else # define LZO_OS_POSIX 1 # define LZO_INFO_OS "posix" #endif #if (LZO_OS_POSIX) # if defined(_AIX) || defined(__AIX__) || defined(__aix__) # define LZO_OS_POSIX_AIX 1 # define LZO_INFO_OS_POSIX "aix" # elif defined(__FreeBSD__) # define LZO_OS_POSIX_FREEBSD 1 # define LZO_INFO_OS_POSIX "freebsd" # elif defined(__hpux__) || defined(__hpux) # define LZO_OS_POSIX_HPUX 1 # define LZO_INFO_OS_POSIX "hpux" # elif defined(__INTERIX) # define LZO_OS_POSIX_INTERIX 1 # define LZO_INFO_OS_POSIX "interix" # elif defined(__IRIX__) || defined(__irix__) # define LZO_OS_POSIX_IRIX 1 # define LZO_INFO_OS_POSIX "irix" # elif defined(__linux__) || defined(__linux) || defined(__LINUX__) # define LZO_OS_POSIX_LINUX 1 # define LZO_INFO_OS_POSIX "linux" # elif defined(__APPLE__) || defined(__MACOS__) # define LZO_OS_POSIX_MACOSX 1 # define LZO_INFO_OS_POSIX "macosx" # elif defined(__minix__) || defined(__minix) # define LZO_OS_POSIX_MINIX 1 # define LZO_INFO_OS_POSIX "minix" # elif defined(__NetBSD__) # define LZO_OS_POSIX_NETBSD 1 # define LZO_INFO_OS_POSIX "netbsd" # elif defined(__OpenBSD__) # define LZO_OS_POSIX_OPENBSD 1 # define LZO_INFO_OS_POSIX "openbsd" # elif defined(__osf__) # define LZO_OS_POSIX_OSF 1 # define LZO_INFO_OS_POSIX "osf" # elif defined(__solaris__) || defined(__sun) # if defined(__SVR4) || defined(__svr4__) # define LZO_OS_POSIX_SOLARIS 1 # define LZO_INFO_OS_POSIX "solaris" # else # define LZO_OS_POSIX_SUNOS 1 # define LZO_INFO_OS_POSIX "sunos" # endif # elif defined(__ultrix__) || defined(__ultrix) # define LZO_OS_POSIX_ULTRIX 1 # define LZO_INFO_OS_POSIX "ultrix" # elif defined(_UNICOS) # define LZO_OS_POSIX_UNICOS 1 # define LZO_INFO_OS_POSIX "unicos" # else # define LZO_OS_POSIX_UNKNOWN 1 # define LZO_INFO_OS_POSIX "unknown" # endif #endif #endif #if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) # if (UINT_MAX != LZO_0xffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) # if (UINT_MAX != LZO_0xffffffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) # define LZO_CC_CILLY 1 # define LZO_INFO_CC "Cilly" # if defined(__CILLY__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) # else # define LZO_INFO_CCVER "unknown" # endif #elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) # define LZO_CC_SDCC 1 # define LZO_INFO_CC "sdcc" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) #elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) # define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + __PATHCC_MINOR__ * 0x100 + __PATHCC_PATCHLEVEL__) # define LZO_INFO_CC "Pathscale C" # define LZO_INFO_CCVER __PATHSCALE__ #elif defined(__INTEL_COMPILER) # define LZO_CC_INTELC 1 # define LZO_INFO_CC "Intel C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) # if defined(_WIN32) || defined(_WIN64) # define LZO_CC_SYNTAX_MSC 1 # else # define LZO_CC_SYNTAX_GNUC 1 # endif #elif defined(__POCC__) && defined(_WIN32) # define LZO_CC_PELLESC 1 # define LZO_INFO_CC "Pelles C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) #elif defined(__llvm__) && defined(__GNUC__) && defined(__VERSION__) # if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) # define LZO_CC_LLVM (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100 + __GNUC_PATCHLEVEL__) # else # define LZO_CC_LLVM (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100) # endif # define LZO_INFO_CC "llvm-gcc" # define LZO_INFO_CCVER __VERSION__ #elif defined(__GNUC__) && defined(__VERSION__) # if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) # define LZO_CC_GNUC (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100 + __GNUC_PATCHLEVEL__) # elif defined(__GNUC_MINOR__) # define LZO_CC_GNUC (__GNUC__ * 0x10000L + __GNUC_MINOR__ * 0x100) # else # define LZO_CC_GNUC (__GNUC__ * 0x10000L) # endif # define LZO_INFO_CC "gcc" # define LZO_INFO_CCVER __VERSION__ #elif defined(__ACK__) && defined(_ACK) # define LZO_CC_ACK 1 # define LZO_INFO_CC "Amsterdam Compiler Kit C" # define LZO_INFO_CCVER "unknown" #elif defined(__AZTEC_C__) # define LZO_CC_AZTECC 1 # define LZO_INFO_CC "Aztec C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) #elif defined(__BORLANDC__) # define LZO_CC_BORLANDC 1 # define LZO_INFO_CC "Borland C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) #elif defined(_CRAYC) && defined(_RELEASE) # define LZO_CC_CRAYC 1 # define LZO_INFO_CC "Cray C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) #elif defined(__DMC__) && defined(__SC__) # define LZO_CC_DMC 1 # define LZO_INFO_CC "Digital Mars C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) #elif defined(__DECC) # define LZO_CC_DECC 1 # define LZO_INFO_CC "DEC C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) #elif defined(__HIGHC__) # define LZO_CC_HIGHC 1 # define LZO_INFO_CC "MetaWare High C" # define LZO_INFO_CCVER "unknown" #elif defined(__IAR_SYSTEMS_ICC__) # define LZO_CC_IARC 1 # define LZO_INFO_CC "IAR C" # if defined(__VER__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) # else # define LZO_INFO_CCVER "unknown" # endif #elif defined(__IBMC__) # define LZO_CC_IBMC 1 # define LZO_INFO_CC "IBM C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) #elif defined(__KEIL__) && defined(__C166__) # define LZO_CC_KEILC 1 # define LZO_INFO_CC "Keil C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) #elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) # define LZO_CC_LCCWIN32 1 # define LZO_INFO_CC "lcc-win32" # define LZO_INFO_CCVER "unknown" #elif defined(__LCC__) # define LZO_CC_LCC 1 # define LZO_INFO_CC "lcc" # if defined(__LCC_VERSION__) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) # else # define LZO_INFO_CCVER "unknown" # endif #elif defined(_MSC_VER) # define LZO_CC_MSC 1 # define LZO_INFO_CC "Microsoft C" # if defined(_MSC_FULL_VER) # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) # else # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) # endif #elif defined(__MWERKS__) # define LZO_CC_MWERKS 1 # define LZO_INFO_CC "Metrowerks C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) #elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) # define LZO_CC_NDPC 1 # define LZO_INFO_CC "Microway NDP C" # define LZO_INFO_CCVER "unknown" #elif defined(__PACIFIC__) # define LZO_CC_PACIFICC 1 # define LZO_INFO_CC "Pacific C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) #elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) # define LZO_CC_PGI 1 # define LZO_INFO_CC "Portland Group PGI C" # define LZO_INFO_CCVER "unknown" #elif defined(__PUREC__) && defined(__TOS__) # define LZO_CC_PUREC 1 # define LZO_INFO_CC "Pure C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) #elif defined(__SC__) && defined(__ZTC__) # define LZO_CC_SYMANTECC 1 # define LZO_INFO_CC "Symantec C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) #elif defined(__SUNPRO_C) # define LZO_INFO_CC "SunPro C" # if ((__SUNPRO_C)+0 > 0) # define LZO_CC_SUNPROC __SUNPRO_C # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) # else # define LZO_CC_SUNPROC 1 # define LZO_INFO_CCVER "unknown" # endif #elif defined(__SUNPRO_CC) # define LZO_INFO_CC "SunPro C" # if ((__SUNPRO_CC)+0 > 0) # define LZO_CC_SUNPROC __SUNPRO_CC # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) # else # define LZO_CC_SUNPROC 1 # define LZO_INFO_CCVER "unknown" # endif #elif defined(__TINYC__) # define LZO_CC_TINYC 1 # define LZO_INFO_CC "Tiny C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) #elif defined(__TSC__) # define LZO_CC_TOPSPEEDC 1 # define LZO_INFO_CC "TopSpeed C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) #elif defined(__WATCOMC__) # define LZO_CC_WATCOMC 1 # define LZO_INFO_CC "Watcom C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) #elif defined(__TURBOC__) # define LZO_CC_TURBOC 1 # define LZO_INFO_CC "Turbo C" # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) #elif defined(__ZTC__) # define LZO_CC_ZORTECHC 1 # define LZO_INFO_CC "Zortech C" # if (__ZTC__ == 0x310) # define LZO_INFO_CCVER "0x310" # else # define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) # endif #else # define LZO_CC_UNKNOWN 1 # define LZO_INFO_CC "unknown" # define LZO_INFO_CCVER "unknown" #endif #if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) # error "LZO_CC_MSC: _MSC_FULL_VER is not defined" #endif #if !defined(__LZO_ARCH_OVERRIDE) && !defined(LZO_ARCH_GENERIC) && defined(_CRAY) # if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) # if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) # define LZO_ARCH_CRAY_MPP 1 # elif defined(_CRAY1) # define LZO_ARCH_CRAY_PVP 1 # endif # endif #endif #if !defined(__LZO_ARCH_OVERRIDE) #if defined(LZO_ARCH_GENERIC) # define LZO_INFO_ARCH "generic" #elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) # define LZO_ARCH_I086 1 # define LZO_ARCH_IA16 1 # define LZO_INFO_ARCH "i086" #elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) # define LZO_ARCH_ALPHA 1 # define LZO_INFO_ARCH "alpha" #elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) # define LZO_ARCH_ALPHA 1 # define LZO_INFO_ARCH "alpha" #elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) # define LZO_ARCH_AMD64 1 # define LZO_INFO_ARCH "amd64" #elif defined(__thumb__) || (defined(_M_ARM) && defined(_M_THUMB)) # define LZO_ARCH_ARM 1 # define LZO_ARCH_ARM_THUMB 1 # define LZO_INFO_ARCH "arm_thumb" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) # define LZO_ARCH_ARM 1 # if defined(__CPU_MODE__) && ((__CPU_MODE__)+0 == 1) # define LZO_ARCH_ARM_THUMB 1 # define LZO_INFO_ARCH "arm_thumb" # elif defined(__CPU_MODE__) && ((__CPU_MODE__)+0 == 2) # define LZO_INFO_ARCH "arm" # else # define LZO_INFO_ARCH "arm" # endif #elif defined(__arm__) || defined(_M_ARM) # define LZO_ARCH_ARM 1 # define LZO_INFO_ARCH "arm" #elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) # define LZO_ARCH_AVR 1 # define LZO_INFO_ARCH "avr" #elif defined(__bfin__) # define LZO_ARCH_BLACKFIN 1 # define LZO_INFO_ARCH "blackfin" #elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) # define LZO_ARCH_C166 1 # define LZO_INFO_ARCH "c166" #elif defined(__cris__) # define LZO_ARCH_CRIS 1 # define LZO_INFO_ARCH "cris" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) # define LZO_ARCH_EZ80 1 # define LZO_INFO_ARCH "ez80" #elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) # define LZO_ARCH_H8300 1 # define LZO_INFO_ARCH "h8300" #elif defined(__hppa__) || defined(__hppa) # define LZO_ARCH_HPPA 1 # define LZO_INFO_ARCH "hppa" #elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif (LZO_CC_ZORTECHC && defined(__I86__)) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) # define LZO_ARCH_I386 1 # define LZO_ARCH_IA32 1 # define LZO_INFO_ARCH "i386" #elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) # define LZO_ARCH_IA64 1 # define LZO_INFO_ARCH "ia64" #elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) # define LZO_ARCH_M16C 1 # define LZO_INFO_ARCH "m16c" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) # define LZO_ARCH_M16C 1 # define LZO_INFO_ARCH "m16c" #elif defined(__m32r__) # define LZO_ARCH_M32R 1 # define LZO_INFO_ARCH "m32r" #elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) # define LZO_ARCH_M68K 1 # define LZO_INFO_ARCH "m68k" #elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) # define LZO_ARCH_MCS251 1 # define LZO_INFO_ARCH "mcs251" #elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) # define LZO_ARCH_MCS51 1 # define LZO_INFO_ARCH "mcs51" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) # define LZO_ARCH_MCS51 1 # define LZO_INFO_ARCH "mcs51" #elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) # define LZO_ARCH_MIPS 1 # define LZO_INFO_ARCH "mips" #elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) # define LZO_ARCH_MSP430 1 # define LZO_INFO_ARCH "msp430" #elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) # define LZO_ARCH_MSP430 1 # define LZO_INFO_ARCH "msp430" #elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) # define LZO_ARCH_POWERPC 1 # define LZO_INFO_ARCH "powerpc" #elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) # define LZO_ARCH_S390 1 # define LZO_INFO_ARCH "s390" #elif defined(__sh__) || defined(_M_SH) # define LZO_ARCH_SH 1 # define LZO_INFO_ARCH "sh" #elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) # define LZO_ARCH_SPARC 1 # define LZO_INFO_ARCH "sparc" #elif defined(__SPU__) # define LZO_ARCH_SPU 1 # define LZO_INFO_ARCH "spu" #elif (UINT_MAX == LZO_0xffffL) && defined(__z80) # define LZO_ARCH_Z80 1 # define LZO_INFO_ARCH "z80" #elif (LZO_ARCH_CRAY_PVP) # if defined(_CRAYSV1) # define LZO_ARCH_CRAY_SV1 1 # define LZO_INFO_ARCH "cray_sv1" # elif (_ADDR64) # define LZO_ARCH_CRAY_T90 1 # define LZO_INFO_ARCH "cray_t90" # elif (_ADDR32) # define LZO_ARCH_CRAY_YMP 1 # define LZO_INFO_ARCH "cray_ymp" # else # define LZO_ARCH_CRAY_XMP 1 # define LZO_INFO_ARCH "cray_xmp" # endif #else # define LZO_ARCH_UNKNOWN 1 # define LZO_INFO_ARCH "unknown" #endif #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) # error "FIXME - missing define for CPU architecture" #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) # error "FIXME - missing WIN32 define for CPU architecture" #endif #if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) # error "FIXME - missing WIN64 define for CPU architecture" #endif #if (LZO_OS_OS216 || LZO_OS_WIN16) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && defined(BLX286)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) # define LZO_ARCH_I086PM 1 # define LZO_ARCH_IA16PM 1 #endif #if defined(LZO_ARCH_ARM_THUMB) && !defined(LZO_ARCH_ARM) # error "this should not happen" #endif #if defined(LZO_ARCH_I086PM) && !defined(LZO_ARCH_I086) # error "this should not happen" #endif #if (LZO_ARCH_I086) # if (UINT_MAX != LZO_0xffffL) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if (LZO_ARCH_I386) # if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) # error "this should not happen" # endif # if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) # error "this should not happen" # endif # if (ULONG_MAX != LZO_0xffffffffL) # error "this should not happen" # endif #endif #if !defined(__LZO_MM_OVERRIDE) #if (LZO_ARCH_I086) #if (UINT_MAX != LZO_0xffffL) # error "this should not happen" #endif #if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) # define LZO_MM_TINY 1 #elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) # define LZO_MM_HUGE 1 #elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) # define LZO_MM_SMALL 1 #elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) # define LZO_MM_MEDIUM 1 #elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) # define LZO_MM_COMPACT 1 #elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) # define LZO_MM_LARGE 1 #elif (LZO_CC_AZTECC) # if defined(_LARGE_CODE) && defined(_LARGE_DATA) # define LZO_MM_LARGE 1 # elif defined(_LARGE_CODE) # define LZO_MM_MEDIUM 1 # elif defined(_LARGE_DATA) # define LZO_MM_COMPACT 1 # else # define LZO_MM_SMALL 1 # endif #elif (LZO_CC_ZORTECHC && defined(__VCM__)) # define LZO_MM_LARGE 1 #else # error "unknown memory model" #endif #if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) #define LZO_HAVE_MM_HUGE_PTR 1 #define LZO_HAVE_MM_HUGE_ARRAY 1 #if (LZO_MM_TINY) # undef LZO_HAVE_MM_HUGE_ARRAY #endif #if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) # undef LZO_HAVE_MM_HUGE_PTR # undef LZO_HAVE_MM_HUGE_ARRAY #elif (LZO_CC_DMC || LZO_CC_SYMANTECC) # undef LZO_HAVE_MM_HUGE_ARRAY #elif (LZO_CC_MSC && defined(_QC)) # undef LZO_HAVE_MM_HUGE_ARRAY # if (_MSC_VER < 600) # undef LZO_HAVE_MM_HUGE_PTR # endif #elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) # undef LZO_HAVE_MM_HUGE_ARRAY #endif #if (LZO_ARCH_I086PM) && !defined(LZO_HAVE_MM_HUGE_PTR) # if (LZO_OS_DOS16) # error "this should not happen" # elif (LZO_CC_ZORTECHC) # else # error "this should not happen" # endif #endif #ifdef __cplusplus extern "C" { #endif #if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) extern void __near __cdecl _AHSHIFT(void); # define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) #elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) # define LZO_MM_AHSHIFT 12 #elif (LZO_CC_WATCOMC) extern unsigned char _HShift; # define LZO_MM_AHSHIFT ((unsigned) _HShift) #else # error "FIXME - implement LZO_MM_AHSHIFT" #endif #ifdef __cplusplus } #endif #endif #elif (LZO_ARCH_C166) #if !defined(__MODEL__) # error "FIXME - C166 __MODEL__" #elif ((__MODEL__) == 0) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 1) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - C166 __MODEL__" #endif #elif (LZO_ARCH_MCS251) #if !defined(__MODEL__) # error "FIXME - MCS251 __MODEL__" #elif ((__MODEL__) == 0) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - MCS251 __MODEL__" #endif #elif (LZO_ARCH_MCS51) #if !defined(__MODEL__) # error "FIXME - MCS51 __MODEL__" #elif ((__MODEL__) == 1) # define LZO_MM_SMALL 1 #elif ((__MODEL__) == 2) # define LZO_MM_LARGE 1 #elif ((__MODEL__) == 3) # define LZO_MM_TINY 1 #elif ((__MODEL__) == 4) # define LZO_MM_XTINY 1 #elif ((__MODEL__) == 5) # define LZO_MM_XSMALL 1 #else # error "FIXME - MCS51 __MODEL__" #endif #elif (LZO_ARCH_CRAY_PVP) # define LZO_MM_PVP 1 #else # define LZO_MM_FLAT 1 #endif #if (LZO_MM_COMPACT) # define LZO_INFO_MM "compact" #elif (LZO_MM_FLAT) # define LZO_INFO_MM "flat" #elif (LZO_MM_HUGE) # define LZO_INFO_MM "huge" #elif (LZO_MM_LARGE) # define LZO_INFO_MM "large" #elif (LZO_MM_MEDIUM) # define LZO_INFO_MM "medium" #elif (LZO_MM_PVP) # define LZO_INFO_MM "pvp" #elif (LZO_MM_SMALL) # define LZO_INFO_MM "small" #elif (LZO_MM_TINY) # define LZO_INFO_MM "tiny" #else # error "unknown memory model" #endif #endif #if defined(SIZEOF_SHORT) # define LZO_SIZEOF_SHORT (SIZEOF_SHORT) #endif #if defined(SIZEOF_INT) # define LZO_SIZEOF_INT (SIZEOF_INT) #endif #if defined(SIZEOF_LONG) # define LZO_SIZEOF_LONG (SIZEOF_LONG) #endif #if defined(SIZEOF_LONG_LONG) # define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) #endif #if defined(SIZEOF___INT16) # define LZO_SIZEOF___INT16 (SIZEOF___INT16) #endif #if defined(SIZEOF___INT32) # define LZO_SIZEOF___INT32 (SIZEOF___INT32) #endif #if defined(SIZEOF___INT64) # define LZO_SIZEOF___INT64 (SIZEOF___INT64) #endif #if defined(SIZEOF_VOID_P) # define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) #endif #if defined(SIZEOF_SIZE_T) # define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) #endif #if defined(SIZEOF_PTRDIFF_T) # define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) #endif #define __LZO_LSR(x,b) (((x)+0ul) >> (b)) #if !defined(LZO_SIZEOF_SHORT) # if (LZO_ARCH_CRAY_PVP) # define LZO_SIZEOF_SHORT 8 # elif (USHRT_MAX == LZO_0xffffL) # define LZO_SIZEOF_SHORT 2 # elif (__LZO_LSR(USHRT_MAX,7) == 1) # define LZO_SIZEOF_SHORT 1 # elif (__LZO_LSR(USHRT_MAX,15) == 1) # define LZO_SIZEOF_SHORT 2 # elif (__LZO_LSR(USHRT_MAX,31) == 1) # define LZO_SIZEOF_SHORT 4 # elif (__LZO_LSR(USHRT_MAX,63) == 1) # define LZO_SIZEOF_SHORT 8 # elif (__LZO_LSR(USHRT_MAX,127) == 1) # define LZO_SIZEOF_SHORT 16 # else # error "LZO_SIZEOF_SHORT" # endif #endif #if !defined(LZO_SIZEOF_INT) # if (LZO_ARCH_CRAY_PVP) # define LZO_SIZEOF_INT 8 # elif (UINT_MAX == LZO_0xffffL) # define LZO_SIZEOF_INT 2 # elif (UINT_MAX == LZO_0xffffffffL) # define LZO_SIZEOF_INT 4 # elif (__LZO_LSR(UINT_MAX,7) == 1) # define LZO_SIZEOF_INT 1 # elif (__LZO_LSR(UINT_MAX,15) == 1) # define LZO_SIZEOF_INT 2 # elif (__LZO_LSR(UINT_MAX,31) == 1) # define LZO_SIZEOF_INT 4 # elif (__LZO_LSR(UINT_MAX,63) == 1) # define LZO_SIZEOF_INT 8 # elif (__LZO_LSR(UINT_MAX,127) == 1) # define LZO_SIZEOF_INT 16 # else # error "LZO_SIZEOF_INT" # endif #endif #if !defined(LZO_SIZEOF_LONG) # if (ULONG_MAX == LZO_0xffffffffL) # define LZO_SIZEOF_LONG 4 # elif (__LZO_LSR(ULONG_MAX,7) == 1) # define LZO_SIZEOF_LONG 1 # elif (__LZO_LSR(ULONG_MAX,15) == 1) # define LZO_SIZEOF_LONG 2 # elif (__LZO_LSR(ULONG_MAX,31) == 1) # define LZO_SIZEOF_LONG 4 # elif (__LZO_LSR(ULONG_MAX,63) == 1) # define LZO_SIZEOF_LONG 8 # elif (__LZO_LSR(ULONG_MAX,127) == 1) # define LZO_SIZEOF_LONG 16 # else # error "LZO_SIZEOF_LONG" # endif #endif #if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) #if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) # if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) # if (LZO_CC_GNUC >= 0x030300ul) # if ((__LONG_MAX__)+0 == (__LONG_LONG_MAX__)+0) # define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG # elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) # define LZO_SIZEOF_LONG_LONG 4 # endif # endif # endif #endif #endif #if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) #if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) #if (LZO_ARCH_I086 && LZO_CC_DMC) #elif (LZO_CC_CILLY) && defined(__GNUC__) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) # define LZO_SIZEOF_LONG_LONG 8 #elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_OS_WIN64 || defined(_WIN64)) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_DMC)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) # define LZO_SIZEOF___INT64 8 #elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) # define LZO_SIZEOF___INT64 8 #elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) # define LZO_SIZEOF___INT64 8 #elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && (_INTEGRAL_MAX_BITS == 64)) # define LZO_SIZEOF___INT64 8 #elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) # define LZO_SIZEOF_LONG_LONG 8 #elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) # define LZO_SIZEOF_LONG_LONG 8 #elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) #elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # define LZO_SIZEOF_LONG_LONG 8 #endif #endif #endif #if defined(__cplusplus) && defined(LZO_CC_GNUC) # if (LZO_CC_GNUC < 0x020800ul) # undef LZO_SIZEOF_LONG_LONG # endif #endif #if defined(LZO_CFG_NO_LONG_LONG) || defined(__NO_LONG_LONG) # undef LZO_SIZEOF_LONG_LONG #endif #if !defined(LZO_SIZEOF_VOID_P) #if (LZO_ARCH_I086) # define __LZO_WORDSIZE 2 # if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) # define LZO_SIZEOF_VOID_P 2 # elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) # define LZO_SIZEOF_VOID_P 4 # else # error "LZO_MM" # endif #elif (LZO_ARCH_AVR || LZO_ARCH_Z80) # define __LZO_WORDSIZE 1 # define LZO_SIZEOF_VOID_P 2 #elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) # define LZO_SIZEOF_VOID_P 2 #elif (LZO_ARCH_H8300) # if defined(__NORMAL_MODE__) # define __LZO_WORDSIZE 4 # define LZO_SIZEOF_VOID_P 2 # elif defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) # define __LZO_WORDSIZE 4 # define LZO_SIZEOF_VOID_P 4 # else # define __LZO_WORDSIZE 2 # define LZO_SIZEOF_VOID_P 2 # endif # if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT # endif #elif (LZO_ARCH_M16C) # define __LZO_WORDSIZE 2 # if defined(__m32c_cpu__) || defined(__m32cm_cpu__) # define LZO_SIZEOF_VOID_P 4 # else # define LZO_SIZEOF_VOID_P 2 # endif #elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) # define __LZO_WORDSIZE 8 # define LZO_SIZEOF_VOID_P 4 #elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) # define __LZO_WORDSIZE 8 # define LZO_SIZEOF_VOID_P 8 #elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) # define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (LZO_OS_OS400 || defined(__OS400__)) # define __LZO_WORDSIZE LZO_SIZEOF_LONG # define LZO_SIZEOF_VOID_P 16 # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) # define LZO_SIZEOF_VOID_P 8 # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG #elif (LZO_ARCH_SPU) # if 0 # define __LZO_WORDSIZE 16 # endif # define LZO_SIZEOF_VOID_P 4 #else # define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG #endif #endif #if !defined(LZO_WORDSIZE) # if defined(__LZO_WORDSIZE) # define LZO_WORDSIZE __LZO_WORDSIZE # else # define LZO_WORDSIZE LZO_SIZEOF_VOID_P # endif #endif #if !defined(LZO_SIZEOF_SIZE_T) #if (LZO_ARCH_I086 || LZO_ARCH_M16C) # define LZO_SIZEOF_SIZE_T 2 #else # define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P #endif #endif #if !defined(LZO_SIZEOF_PTRDIFF_T) #if (LZO_ARCH_I086) # if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P # elif (LZO_MM_COMPACT || LZO_MM_LARGE) # if (LZO_CC_BORLANDC || LZO_CC_TURBOC) # define LZO_SIZEOF_PTRDIFF_T 4 # else # define LZO_SIZEOF_PTRDIFF_T 2 # endif # else # error "LZO_MM" # endif #else # define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T #endif #endif #if defined(LZO_ABI_NEUTRAL_ENDIAN) # undef LZO_ABI_BIG_ENDIAN # undef LZO_ABI_LITTLE_ENDIAN #elif !defined(LZO_ABI_BIG_ENDIAN) && !defined(LZO_ABI_LITTLE_ENDIAN) #if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) # define LZO_ABI_BIG_ENDIAN 1 #elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430) # define LZO_ABI_LITTLE_ENDIAN 1 #elif (LZO_ARCH_M68K || LZO_ARCH_S390) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) # if (__LITTLE_ENDIAN__ == 1) # define LZO_ABI_LITTLE_ENDIAN 1 # else # define LZO_ABI_BIG_ENDIAN 1 # endif #elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) # define LZO_ABI_LITTLE_ENDIAN 1 #elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) # define LZO_ABI_LITTLE_ENDIAN 1 #elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) # define LZO_ABI_BIG_ENDIAN 1 #elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) # define LZO_ABI_LITTLE_ENDIAN 1 #endif #endif #if defined(LZO_ABI_BIG_ENDIAN) && defined(LZO_ABI_LITTLE_ENDIAN) # error "this should not happen" #endif #if defined(LZO_ABI_BIG_ENDIAN) # define LZO_INFO_ABI_ENDIAN "be" #elif defined(LZO_ABI_LITTLE_ENDIAN) # define LZO_INFO_ABI_ENDIAN "le" #elif defined(LZO_ABI_NEUTRAL_ENDIAN) # define LZO_INFO_ABI_ENDIAN "neutral" #endif #if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) # define LZO_ABI_I8LP16 1 # define LZO_INFO_ABI_PM "i8lp16" #elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) # define LZO_ABI_ILP16 1 # define LZO_INFO_ABI_PM "ilp16" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) # define LZO_ABI_ILP32 1 # define LZO_INFO_ABI_PM "ilp32" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) # define LZO_ABI_LLP64 1 # define LZO_INFO_ABI_PM "llp64" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) # define LZO_ABI_LP64 1 # define LZO_INFO_ABI_PM "lp64" #elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) # define LZO_ABI_ILP64 1 # define LZO_INFO_ABI_PM "ilp64" #elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) # define LZO_ABI_IP32L64 1 # define LZO_INFO_ABI_PM "ip32l64" #endif #if !defined(__LZO_LIBC_OVERRIDE) #if defined(LZO_LIBC_NAKED) # define LZO_INFO_LIBC "naked" #elif defined(LZO_LIBC_FREESTANDING) # define LZO_INFO_LIBC "freestanding" #elif defined(LZO_LIBC_MOSTLY_FREESTANDING) # define LZO_INFO_LIBC "mfreestanding" #elif defined(LZO_LIBC_ISOC90) # define LZO_INFO_LIBC "isoc90" #elif defined(LZO_LIBC_ISOC99) # define LZO_INFO_LIBC "isoc99" #elif defined(__dietlibc__) # define LZO_LIBC_DIETLIBC 1 # define LZO_INFO_LIBC "dietlibc" #elif defined(_NEWLIB_VERSION) # define LZO_LIBC_NEWLIB 1 # define LZO_INFO_LIBC "newlib" #elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) # if defined(__UCLIBC_SUBLEVEL__) # define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + __UCLIBC_MINOR__ * 0x100 + __UCLIBC_SUBLEVEL__) # else # define LZO_LIBC_UCLIBC 0x00090bL # endif # define LZO_INFO_LIBC "uclibc" #elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) # define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + __GLIBC_MINOR__ * 0x100) # define LZO_INFO_LIBC "glibc" #elif (LZO_CC_MWERKS) && defined(__MSL__) # define LZO_LIBC_MSL __MSL__ # define LZO_INFO_LIBC "msl" #elif 1 && defined(__IAR_SYSTEMS_ICC__) # define LZO_LIBC_ISOC90 1 # define LZO_INFO_LIBC "isoc90" #else # define LZO_LIBC_DEFAULT 1 # define LZO_INFO_LIBC "default" #endif #endif #if !defined(__lzo_gnuc_extension__) #if (LZO_CC_GNUC >= 0x020800ul) # define __lzo_gnuc_extension__ __extension__ #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_gnuc_extension__ __extension__ #else # define __lzo_gnuc_extension__ #endif #endif #if !defined(__lzo_ua_volatile) # define __lzo_ua_volatile volatile #endif #if !defined(__lzo_alignof) #if (LZO_CC_CILLY || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) # define __lzo_alignof(e) __alignof__(e) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) # define __lzo_alignof(e) __alignof__(e) #elif (LZO_CC_MSC && (_MSC_VER >= 1300)) # define __lzo_alignof(e) __alignof(e) #endif #endif #if defined(__lzo_alignof) # define __lzo_HAVE_alignof 1 #endif #if !defined(__lzo_constructor) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_constructor __attribute__((__constructor__,__used__)) #elif (LZO_CC_GNUC >= 0x020700ul) # define __lzo_constructor __attribute__((__constructor__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_constructor __attribute__((__constructor__)) #endif #endif #if defined(__lzo_constructor) # define __lzo_HAVE_constructor 1 #endif #if !defined(__lzo_destructor) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_destructor __attribute__((__destructor__,__used__)) #elif (LZO_CC_GNUC >= 0x020700ul) # define __lzo_destructor __attribute__((__destructor__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_destructor __attribute__((__destructor__)) #endif #endif #if defined(__lzo_destructor) # define __lzo_HAVE_destructor 1 #endif #if defined(__lzo_HAVE_destructor) && !defined(__lzo_HAVE_constructor) # error "this should not happen" #endif #if !defined(__lzo_inline) #if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) #elif defined(__cplusplus) # define __lzo_inline inline #elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) # define __lzo_inline __inline #elif (LZO_CC_CILLY || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) # define __lzo_inline __inline__ #elif (LZO_CC_DMC) # define __lzo_inline __inline #elif (LZO_CC_INTELC) # define __lzo_inline __inline #elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) # define __lzo_inline __inline #elif (LZO_CC_MSC && (_MSC_VER >= 900)) # define __lzo_inline __inline #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # define __lzo_inline inline #endif #endif #if defined(__lzo_inline) # define __lzo_HAVE_inline 1 #else # define __lzo_inline #endif #if !defined(__lzo_forceinline) #if (LZO_CC_GNUC >= 0x030200ul) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) # define __lzo_forceinline __forceinline #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_forceinline __inline__ __attribute__((__always_inline__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) # define __lzo_forceinline __forceinline #endif #endif #if defined(__lzo_forceinline) # define __lzo_HAVE_forceinline 1 #else # define __lzo_forceinline #endif #if !defined(__lzo_noinline) #if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) # define __lzo_noinline __attribute__((__noinline__,__used__)) #elif (LZO_CC_GNUC >= 0x030200ul) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_MSC) # define __lzo_noinline __declspec(noinline) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_noinline __attribute__((__noinline__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1300)) # define __lzo_noinline __declspec(noinline) #elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) # if defined(__cplusplus) # else # define __lzo_noinline __declspec(noinline) # endif #endif #endif #if defined(__lzo_noinline) # define __lzo_HAVE_noinline 1 #else # define __lzo_noinline #endif #if (defined(__lzo_HAVE_forceinline) || defined(__lzo_HAVE_noinline)) && !defined(__lzo_HAVE_inline) # error "this should not happen" #endif #if !defined(__lzo_noreturn) #if (LZO_CC_GNUC >= 0x020700ul) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) # define __lzo_noreturn __declspec(noreturn) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_GNUC) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_noreturn __attribute__((__noreturn__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) # define __lzo_noreturn __declspec(noreturn) #endif #endif #if defined(__lzo_noreturn) # define __lzo_HAVE_noreturn 1 #else # define __lzo_noreturn #endif #if !defined(__lzo_nothrow) #if (LZO_CC_GNUC >= 0x030300ul) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 450) && LZO_CC_SYNTAX_MSC) && defined(__cplusplus) # define __lzo_nothrow __declspec(nothrow) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800) && LZO_CC_SYNTAX_GNUC) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_nothrow __attribute__((__nothrow__)) #elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) # define __lzo_nothrow __declspec(nothrow) #endif #endif #if defined(__lzo_nothrow) # define __lzo_HAVE_nothrow 1 #else # define __lzo_nothrow #endif #if !defined(__lzo_restrict) #if (LZO_CC_GNUC >= 0x030400ul) # define __lzo_restrict __restrict__ #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 600) && LZO_CC_SYNTAX_GNUC) # define __lzo_restrict __restrict__ #elif (LZO_CC_LLVM) # define __lzo_restrict __restrict__ #elif (LZO_CC_MSC && (_MSC_VER >= 1400)) # define __lzo_restrict __restrict #endif #endif #if defined(__lzo_restrict) # define __lzo_HAVE_restrict 1 #else # define __lzo_restrict #endif #if !defined(__lzo_likely) && !defined(__lzo_unlikely) #if (LZO_CC_GNUC >= 0x030200ul) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #elif (LZO_CC_LLVM || LZO_CC_PATHSCALE) # define __lzo_likely(e) (__builtin_expect(!!(e),1)) # define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) #endif #endif #if defined(__lzo_likely) # define __lzo_HAVE_likely 1 #else # define __lzo_likely(e) (e) #endif #if defined(__lzo_unlikely) # define __lzo_HAVE_unlikely 1 #else # define __lzo_unlikely(e) (e) #endif #if !defined(LZO_UNUSED) # if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) # define LZO_UNUSED(var) ((void) &var) # elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) # define LZO_UNUSED(var) if (&var) ; else # elif (LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) # define LZO_UNUSED(var) ((void) var) # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_UNUSED(var) if (&var) ; else # elif (LZO_CC_KEILC) # define LZO_UNUSED(var) {extern int __lzo_unused[1-2*!(sizeof(var)>0)];} # elif (LZO_CC_PACIFICC) # define LZO_UNUSED(var) ((void) sizeof(var)) # elif (LZO_CC_WATCOMC) && defined(__cplusplus) # define LZO_UNUSED(var) ((void) var) # else # define LZO_UNUSED(var) ((void) &var) # endif #endif #if !defined(LZO_UNUSED_FUNC) # if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) # define LZO_UNUSED_FUNC(func) ((void) func) # elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) # define LZO_UNUSED_FUNC(func) if (func) ; else # elif (LZO_CC_LLVM) # define LZO_UNUSED_FUNC(func) ((void) &func) # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_UNUSED_FUNC(func) if (func) ; else # elif (LZO_CC_MSC) # define LZO_UNUSED_FUNC(func) ((void) &func) # elif (LZO_CC_KEILC || LZO_CC_PELLESC) # define LZO_UNUSED_FUNC(func) {extern int __lzo_unused[1-2*!(sizeof((int)func)>0)];} # else # define LZO_UNUSED_FUNC(func) ((void) func) # endif #endif #if !defined(LZO_UNUSED_LABEL) # if (LZO_CC_WATCOMC) && defined(__cplusplus) # define LZO_UNUSED_LABEL(l) switch(0) case 1:goto l # elif (LZO_CC_INTELC || LZO_CC_WATCOMC) # define LZO_UNUSED_LABEL(l) if (0) goto l # else # define LZO_UNUSED_LABEL(l) switch(0) case 1:goto l # endif #endif #if !defined(LZO_DEFINE_UNINITIALIZED_VAR) # if 0 # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var # elif 0 && (LZO_CC_GNUC) # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var # else # define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init # endif #endif #if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) # if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-!(e)]; # elif (LZO_CC_DMC || LZO_CC_SYMANTECC) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1u-2*!(e)]; # elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-!(e)]; # else # define LZO_COMPILE_TIME_ASSERT_HEADER(e) extern int __lzo_cta[1-2*!(e)]; # endif #endif #if !defined(LZO_COMPILE_TIME_ASSERT) # if (LZO_CC_AZTECC) # define LZO_COMPILE_TIME_ASSERT(e) {typedef int __lzo_cta_t[1-!(e)];} # elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # elif (LZO_CC_MSC && (_MSC_VER < 900)) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) # define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; # else # define LZO_COMPILE_TIME_ASSERT(e) {typedef int __lzo_cta_t[1-2*!(e)];} # endif #endif #if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) # if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) # elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) # define __lzo_cdecl __cdecl # define __lzo_cdecl_atexit # define __lzo_cdecl_main __cdecl # if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) # define __lzo_cdecl_qsort __pascal # elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) # define __lzo_cdecl_qsort _stdcall # else # define __lzo_cdecl_qsort __cdecl # endif # elif (LZO_CC_WATCOMC) # define __lzo_cdecl __cdecl # else # define __lzo_cdecl __cdecl # define __lzo_cdecl_atexit __cdecl # define __lzo_cdecl_main __cdecl # define __lzo_cdecl_qsort __cdecl # endif # if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) # elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) # define __lzo_cdecl_sighandler __pascal # elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) # define __lzo_cdecl_sighandler _stdcall # elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) # define __lzo_cdecl_sighandler __clrcall # elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) # if defined(_DLL) # define __lzo_cdecl_sighandler _far _cdecl _loadds # elif defined(_MT) # define __lzo_cdecl_sighandler _far _cdecl # else # define __lzo_cdecl_sighandler _cdecl # endif # else # define __lzo_cdecl_sighandler __cdecl # endif #elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) # define __lzo_cdecl __cdecl #elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) # define __lzo_cdecl cdecl #endif #if !defined(__lzo_cdecl) # define __lzo_cdecl #endif #if !defined(__lzo_cdecl_atexit) # define __lzo_cdecl_atexit #endif #if !defined(__lzo_cdecl_main) # define __lzo_cdecl_main #endif #if !defined(__lzo_cdecl_qsort) # define __lzo_cdecl_qsort #endif #if !defined(__lzo_cdecl_sighandler) # define __lzo_cdecl_sighandler #endif #if !defined(__lzo_cdecl_va) # define __lzo_cdecl_va __lzo_cdecl #endif #if !defined(LZO_CFG_NO_WINDOWS_H) #if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) # if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) # elif (LZO_OS_WIN32 && LZO_CC_GNUC) && defined(__PW32__) # elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) # else # define LZO_HAVE_WINDOWS_H 1 # endif #endif #endif #if (LZO_ARCH_ALPHA) # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_AVOID_SHORT 1 # define LZO_OPT_AVOID_USHORT 1 #elif (LZO_ARCH_AMD64) # define LZO_OPT_AVOID_INT_INDEX 1 # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # define LZO_OPT_UNALIGNED64 1 #elif (LZO_ARCH_ARM && LZO_ARCH_ARM_THUMB) #elif (LZO_ARCH_ARM) # define LZO_OPT_AVOID_SHORT 1 # define LZO_OPT_AVOID_USHORT 1 #elif (LZO_ARCH_CRIS) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 #elif (LZO_ARCH_I386) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 #elif (LZO_ARCH_IA64) # define LZO_OPT_AVOID_INT_INDEX 1 # define LZO_OPT_AVOID_UINT_INDEX 1 # define LZO_OPT_PREFER_POSTINC 1 #elif (LZO_ARCH_M68K) # define LZO_OPT_PREFER_POSTINC 1 # define LZO_OPT_PREFER_PREDEC 1 # if defined(__mc68020__) && !defined(__mcoldfire__) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # endif #elif (LZO_ARCH_MIPS) # define LZO_OPT_AVOID_UINT_INDEX 1 #elif (LZO_ARCH_POWERPC) # define LZO_OPT_PREFER_PREINC 1 # define LZO_OPT_PREFER_PREDEC 1 # if defined(LZO_ABI_BIG_ENDIAN) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # endif #elif (LZO_ARCH_S390) # define LZO_OPT_UNALIGNED16 1 # define LZO_OPT_UNALIGNED32 1 # if (LZO_SIZEOF_SIZE_T == 8) # define LZO_OPT_UNALIGNED64 1 # endif #elif (LZO_ARCH_SH) # define LZO_OPT_PREFER_POSTINC 1 # define LZO_OPT_PREFER_PREDEC 1 #endif #if !defined(LZO_CFG_NO_INLINE_ASM) #if defined(LZO_CC_LLVM) # define LZO_CFG_NO_INLINE_ASM 1 #endif #endif #if !defined(LZO_CFG_NO_UNALIGNED) #if defined(LZO_ABI_NEUTRAL_ENDIAN) || defined(LZO_ARCH_GENERIC) # define LZO_CFG_NO_UNALIGNED 1 #endif #endif #if defined(LZO_CFG_NO_UNALIGNED) # undef LZO_OPT_UNALIGNED16 # undef LZO_OPT_UNALIGNED32 # undef LZO_OPT_UNALIGNED64 #endif #if defined(LZO_CFG_NO_INLINE_ASM) #elif (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) # define LZO_ASM_SYNTAX_MSC 1 #elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) #elif (LZO_ARCH_I386 && (LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) # define LZO_ASM_SYNTAX_GNUC 1 #elif (LZO_ARCH_AMD64 && (LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) # define LZO_ASM_SYNTAX_GNUC 1 #endif #if (LZO_ASM_SYNTAX_GNUC) #if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) # define __LZO_ASM_CLOBBER "ax" #elif (LZO_CC_INTELC) # define __LZO_ASM_CLOBBER "memory" #else # define __LZO_ASM_CLOBBER "cc", "memory" #endif #endif #if defined(__LZO_INFOSTR_MM) #elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) # define __LZO_INFOSTR_MM "" #elif defined(LZO_INFO_MM) # define __LZO_INFOSTR_MM "." LZO_INFO_MM #else # define __LZO_INFOSTR_MM "" #endif #if defined(__LZO_INFOSTR_PM) #elif defined(LZO_INFO_ABI_PM) # define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM #else # define __LZO_INFOSTR_PM "" #endif #if defined(__LZO_INFOSTR_ENDIAN) #elif defined(LZO_INFO_ABI_ENDIAN) # define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN #else # define __LZO_INFOSTR_ENDIAN "" #endif #if defined(__LZO_INFOSTR_OSNAME) #elif defined(LZO_INFO_OS_CONSOLE) # define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE #elif defined(LZO_INFO_OS_POSIX) # define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX #else # define __LZO_INFOSTR_OSNAME LZO_INFO_OS #endif #if defined(__LZO_INFOSTR_LIBC) #elif defined(LZO_INFO_LIBC) # define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC #else # define __LZO_INFOSTR_LIBC "" #endif #if defined(__LZO_INFOSTR_CCVER) #elif defined(LZO_INFO_CCVER) # define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER #else # define __LZO_INFOSTR_CCVER "" #endif #define LZO_INFO_STRING \ LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER #endif #endif #undef LZO_HAVE_CONFIG_H #include "minilzo.h" #if !defined(MINILZO_VERSION) || (MINILZO_VERSION != 0x2030) # error "version mismatch in miniLZO source files" #endif #ifdef MINILZO_HAVE_CONFIG_H # define LZO_HAVE_CONFIG_H #endif #ifndef __LZO_CONF_H #define __LZO_CONF_H #if !defined(__LZO_IN_MINILZO) #if defined(LZO_CFG_FREESTANDING) # define LZO_LIBC_FREESTANDING 1 # define LZO_OS_FREESTANDING 1 # define ACC_LIBC_FREESTANDING 1 # define ACC_OS_FREESTANDING 1 #endif #if defined(LZO_CFG_NO_UNALIGNED) # define ACC_CFG_NO_UNALIGNED 1 #endif #if defined(LZO_ARCH_GENERIC) # define ACC_ARCH_GENERIC 1 #endif #if defined(LZO_ABI_NEUTRAL_ENDIAN) # define ACC_ABI_NEUTRAL_ENDIAN 1 #endif #if defined(LZO_HAVE_CONFIG_H) # define ACC_CONFIG_NO_HEADER 1 #endif #if defined(LZO_CFG_EXTRA_CONFIG_HEADER) # include LZO_CFG_EXTRA_CONFIG_HEADER #endif #if defined(__LZOCONF_H) || defined(__LZOCONF_H_INCLUDED) # error "include this file first" #endif #include "lzo/lzoconf.h" #endif #if (LZO_VERSION < 0x02000) || !defined(__LZOCONF_H_INCLUDED) # error "version mismatch" #endif #if (LZO_CC_BORLANDC && LZO_ARCH_I086) # pragma option -h #endif #if (LZO_CC_MSC && (_MSC_VER >= 1000)) # pragma warning(disable: 4127 4701) #endif #if (LZO_CC_MSC && (_MSC_VER >= 1300)) # pragma warning(disable: 4820) # pragma warning(disable: 4514 4710 4711) #endif #if (LZO_CC_SUNPROC) # pragma error_messages(off,E_END_OF_LOOP_CODE_NOT_REACHED) # pragma error_messages(off,E_LOOP_NOT_ENTERED_AT_TOP) #endif #if defined(__LZO_MMODEL_HUGE) && (!LZO_HAVE_MM_HUGE_PTR) # error "this should not happen - check defines for __huge" #endif #if defined(__LZO_IN_MINILZO) || defined(LZO_CFG_FREESTANDING) #elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) # define ACC_WANT_ACC_INCD_H 1 # define ACC_WANT_ACC_INCE_H 1 # define ACC_WANT_ACC_INCI_H 1 #elif 1 # include #else # define ACC_WANT_ACC_INCD_H 1 #endif #if (LZO_ARCH_I086) # define ACC_MM_AHSHIFT LZO_MM_AHSHIFT # define ACC_PTR_FP_OFF(x) (((const unsigned __far*)&(x))[0]) # define ACC_PTR_FP_SEG(x) (((const unsigned __far*)&(x))[1]) # define ACC_PTR_MK_FP(s,o) ((void __far*)(((unsigned long)(s)<<16)+(unsigned)(o))) #endif #if !defined(lzo_uintptr_t) # if defined(__LZO_MMODEL_HUGE) # define lzo_uintptr_t unsigned long # elif 1 && defined(LZO_OS_OS400) && (LZO_SIZEOF_VOID_P == 16) # define __LZO_UINTPTR_T_IS_POINTER 1 typedef char* lzo_uintptr_t; # define lzo_uintptr_t lzo_uintptr_t # elif (LZO_SIZEOF_SIZE_T == LZO_SIZEOF_VOID_P) # define lzo_uintptr_t size_t # elif (LZO_SIZEOF_LONG == LZO_SIZEOF_VOID_P) # define lzo_uintptr_t unsigned long # elif (LZO_SIZEOF_INT == LZO_SIZEOF_VOID_P) # define lzo_uintptr_t unsigned int # elif (LZO_SIZEOF_LONG_LONG == LZO_SIZEOF_VOID_P) # define lzo_uintptr_t unsigned long long # else # define lzo_uintptr_t size_t # endif #endif LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uintptr_t) >= sizeof(lzo_voidp)) #if 1 && !defined(LZO_CFG_FREESTANDING) #if 1 && !defined(HAVE_STRING_H) #define HAVE_STRING_H 1 #endif #if 1 && !defined(HAVE_MEMCMP) #define HAVE_MEMCMP 1 #endif #if 1 && !defined(HAVE_MEMCPY) #define HAVE_MEMCPY 1 #endif #if 1 && !defined(HAVE_MEMMOVE) #define HAVE_MEMMOVE 1 #endif #if 1 && !defined(HAVE_MEMSET) #define HAVE_MEMSET 1 #endif #endif #if 1 && defined(HAVE_STRING_H) #include #endif #if defined(LZO_CFG_FREESTANDING) # undef HAVE_MEMCMP # undef HAVE_MEMCPY # undef HAVE_MEMMOVE # undef HAVE_MEMSET #endif #if !defined(HAVE_MEMCMP) # undef memcmp # define memcmp(a,b,c) lzo_memcmp(a,b,c) #elif !defined(__LZO_MMODEL_HUGE) # define lzo_memcmp(a,b,c) memcmp(a,b,c) #endif #if !defined(HAVE_MEMCPY) # undef memcpy # define memcpy(a,b,c) lzo_memcpy(a,b,c) #elif !defined(__LZO_MMODEL_HUGE) # define lzo_memcpy(a,b,c) memcpy(a,b,c) #endif #if !defined(HAVE_MEMMOVE) # undef memmove # define memmove(a,b,c) lzo_memmove(a,b,c) #elif !defined(__LZO_MMODEL_HUGE) # define lzo_memmove(a,b,c) memmove(a,b,c) #endif #if !defined(HAVE_MEMSET) # undef memset # define memset(a,b,c) lzo_memset(a,b,c) #elif !defined(__LZO_MMODEL_HUGE) # define lzo_memset(a,b,c) memset(a,b,c) #endif #undef NDEBUG #if defined(LZO_CFG_FREESTANDING) # undef LZO_DEBUG # define NDEBUG 1 # undef assert # define assert(e) ((void)0) #else # if !defined(LZO_DEBUG) # define NDEBUG 1 # endif # include #endif #if 0 && defined(__BOUNDS_CHECKING_ON) # include #else # define BOUNDS_CHECKING_OFF_DURING(stmt) stmt # define BOUNDS_CHECKING_OFF_IN_EXPR(expr) (expr) #endif #if !defined(__lzo_inline) # define __lzo_inline #endif #if !defined(__lzo_forceinline) # define __lzo_forceinline #endif #if !defined(__lzo_noinline) # define __lzo_noinline #endif #if 1 # define LZO_BYTE(x) ((unsigned char) (x)) #else # define LZO_BYTE(x) ((unsigned char) ((x) & 0xff)) #endif #define LZO_MAX(a,b) ((a) >= (b) ? (a) : (b)) #define LZO_MIN(a,b) ((a) <= (b) ? (a) : (b)) #define LZO_MAX3(a,b,c) ((a) >= (b) ? LZO_MAX(a,c) : LZO_MAX(b,c)) #define LZO_MIN3(a,b,c) ((a) <= (b) ? LZO_MIN(a,c) : LZO_MIN(b,c)) #define lzo_sizeof(type) ((lzo_uint) (sizeof(type))) #define LZO_HIGH(array) ((lzo_uint) (sizeof(array)/sizeof(*(array)))) #define LZO_SIZE(bits) (1u << (bits)) #define LZO_MASK(bits) (LZO_SIZE(bits) - 1) #define LZO_LSIZE(bits) (1ul << (bits)) #define LZO_LMASK(bits) (LZO_LSIZE(bits) - 1) #define LZO_USIZE(bits) ((lzo_uint) 1 << (bits)) #define LZO_UMASK(bits) (LZO_USIZE(bits) - 1) #if !defined(DMUL) #if 0 # define DMUL(a,b) ((lzo_xint) ((lzo_uint32)(a) * (lzo_uint32)(b))) #else # define DMUL(a,b) ((lzo_xint) ((a) * (b))) #endif #endif #if 1 && !defined(LZO_CFG_NO_UNALIGNED) #if 1 && (LZO_ARCH_AMD64 || LZO_ARCH_I386) # if (LZO_SIZEOF_SHORT == 2) # define LZO_UNALIGNED_OK_2 # endif # if (LZO_SIZEOF_INT == 4) # define LZO_UNALIGNED_OK_4 # endif #endif #endif #if defined(LZO_UNALIGNED_OK_2) LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(short) == 2) #endif #if defined(LZO_UNALIGNED_OK_4) LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint32) == 4) #elif defined(LZO_ALIGNED_OK_4) LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint32) == 4) #endif #define MEMCPY8_DS(dest,src,len) \ lzo_memcpy(dest,src,len); dest += len; src += len #define BZERO8_PTR(s,l,n) \ lzo_memset((lzo_voidp)(s),0,(lzo_uint)(l)*(n)) #define MEMCPY_DS(dest,src,len) \ do *dest++ = *src++; while (--len > 0) __LZO_EXTERN_C int __lzo_init_done; __LZO_EXTERN_C const char __lzo_copyright[]; LZO_EXTERN(const lzo_bytep) lzo_copyright(void); #ifndef __LZO_PTR_H #define __LZO_PTR_H #ifdef __cplusplus extern "C" { #endif #if !defined(lzo_uintptr_t) # if defined(__LZO_MMODEL_HUGE) # define lzo_uintptr_t unsigned long # else # define lzo_uintptr_t acc_uintptr_t # ifdef __ACC_INTPTR_T_IS_POINTER # define __LZO_UINTPTR_T_IS_POINTER 1 # endif # endif #endif #if (LZO_ARCH_I086) #define PTR(a) ((lzo_bytep) (a)) #define PTR_ALIGNED_4(a) ((ACC_PTR_FP_OFF(a) & 3) == 0) #define PTR_ALIGNED2_4(a,b) (((ACC_PTR_FP_OFF(a) | ACC_PTR_FP_OFF(b)) & 3) == 0) #elif (LZO_MM_PVP) #define PTR(a) ((lzo_bytep) (a)) #define PTR_ALIGNED_8(a) ((((lzo_uintptr_t)(a)) >> 61) == 0) #define PTR_ALIGNED2_8(a,b) ((((lzo_uintptr_t)(a)|(lzo_uintptr_t)(b)) >> 61) == 0) #else #define PTR(a) ((lzo_uintptr_t) (a)) #define PTR_LINEAR(a) PTR(a) #define PTR_ALIGNED_4(a) ((PTR_LINEAR(a) & 3) == 0) #define PTR_ALIGNED_8(a) ((PTR_LINEAR(a) & 7) == 0) #define PTR_ALIGNED2_4(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 3) == 0) #define PTR_ALIGNED2_8(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 7) == 0) #endif #define PTR_LT(a,b) (PTR(a) < PTR(b)) #define PTR_GE(a,b) (PTR(a) >= PTR(b)) #define PTR_DIFF(a,b) (PTR(a) - PTR(b)) #define pd(a,b) ((lzo_uint) ((a)-(b))) LZO_EXTERN(lzo_uintptr_t) __lzo_ptr_linear(const lzo_voidp ptr); typedef union { char a_char; unsigned char a_uchar; short a_short; unsigned short a_ushort; int a_int; unsigned int a_uint; long a_long; unsigned long a_ulong; lzo_int a_lzo_int; lzo_uint a_lzo_uint; lzo_int32 a_lzo_int32; lzo_uint32 a_lzo_uint32; ptrdiff_t a_ptrdiff_t; lzo_uintptr_t a_lzo_uintptr_t; lzo_voidp a_lzo_voidp; void * a_void_p; lzo_bytep a_lzo_bytep; lzo_bytepp a_lzo_bytepp; lzo_uintp a_lzo_uintp; lzo_uint * a_lzo_uint_p; lzo_uint32p a_lzo_uint32p; lzo_uint32 * a_lzo_uint32_p; unsigned char * a_uchar_p; char * a_char_p; } lzo_full_align_t; #ifdef __cplusplus } #endif #endif #define LZO_DETERMINISTIC #define LZO_DICT_USE_PTR #if 0 && (LZO_ARCH_I086) # undef LZO_DICT_USE_PTR #endif #if defined(LZO_DICT_USE_PTR) # define lzo_dict_t const lzo_bytep # define lzo_dict_p lzo_dict_t __LZO_MMODEL * #else # define lzo_dict_t lzo_uint # define lzo_dict_p lzo_dict_t __LZO_MMODEL * #endif #endif #if !defined(MINILZO_CFG_SKIP_LZO_PTR) LZO_PUBLIC(lzo_uintptr_t) __lzo_ptr_linear(const lzo_voidp ptr) { lzo_uintptr_t p; #if (LZO_ARCH_I086) p = (((lzo_uintptr_t)(ACC_PTR_FP_SEG(ptr))) << (16 - ACC_MM_AHSHIFT)) + (ACC_PTR_FP_OFF(ptr)); #elif (LZO_MM_PVP) p = (lzo_uintptr_t) (ptr); p = (p << 3) | (p >> 61); #else p = (lzo_uintptr_t) PTR_LINEAR(ptr); #endif return p; } LZO_PUBLIC(unsigned) __lzo_align_gap(const lzo_voidp ptr, lzo_uint size) { #if defined(__LZO_UINTPTR_T_IS_POINTER) size_t n = (size_t) ptr; n = (((n + size - 1) / size) * size) - n; #else lzo_uintptr_t p, n; p = __lzo_ptr_linear(ptr); n = (((p + size - 1) / size) * size) - p; #endif assert(size > 0); assert((long)n >= 0); assert(n <= size); return (unsigned)n; } #endif /* If you use the LZO library in a product, I would appreciate that you * keep this copyright string in the executable of your product. */ const char __lzo_copyright[] = #if !defined(__LZO_IN_MINLZO) LZO_VERSION_STRING; #else "\r\n\n" "LZO data compression library.\n" "$Copyright: LZO (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Markus Franz Xaver Johannes Oberhumer\n" "\n" "http://www.oberhumer.com $\n\n" "$Id: LZO version: v" LZO_VERSION_STRING ", " LZO_VERSION_DATE " $\n" "$Built: " __DATE__ " " __TIME__ " $\n" "$Info: " LZO_INFO_STRING " $\n"; #endif LZO_PUBLIC(const lzo_bytep) lzo_copyright(void) { #if (LZO_OS_DOS16 && LZO_CC_TURBOC) return (lzo_voidp) __lzo_copyright; #else return (const lzo_bytep) __lzo_copyright; #endif } LZO_PUBLIC(unsigned) lzo_version(void) { return LZO_VERSION; } LZO_PUBLIC(const char *) lzo_version_string(void) { return LZO_VERSION_STRING; } LZO_PUBLIC(const char *) lzo_version_date(void) { return LZO_VERSION_DATE; } LZO_PUBLIC(const lzo_charp) _lzo_version_string(void) { return LZO_VERSION_STRING; } LZO_PUBLIC(const lzo_charp) _lzo_version_date(void) { return LZO_VERSION_DATE; } #define LZO_BASE 65521u #define LZO_NMAX 5552 #define LZO_DO1(buf,i) s1 += buf[i]; s2 += s1 #define LZO_DO2(buf,i) LZO_DO1(buf,i); LZO_DO1(buf,i+1); #define LZO_DO4(buf,i) LZO_DO2(buf,i); LZO_DO2(buf,i+2); #define LZO_DO8(buf,i) LZO_DO4(buf,i); LZO_DO4(buf,i+4); #define LZO_DO16(buf,i) LZO_DO8(buf,i); LZO_DO8(buf,i+8); LZO_PUBLIC(lzo_uint32) lzo_adler32(lzo_uint32 adler, const lzo_bytep buf, lzo_uint len) { lzo_uint32 s1 = adler & 0xffff; lzo_uint32 s2 = (adler >> 16) & 0xffff; unsigned k; if (buf == NULL) return 1; while (len > 0) { k = len < LZO_NMAX ? (unsigned) len : LZO_NMAX; len -= k; if (k >= 16) do { LZO_DO16(buf,0); buf += 16; k -= 16; } while (k >= 16); if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k > 0); s1 %= LZO_BASE; s2 %= LZO_BASE; } return (s2 << 16) | s1; } #undef LZO_DO1 #undef LZO_DO2 #undef LZO_DO4 #undef LZO_DO8 #undef LZO_DO16 #if !defined(MINILZO_CFG_SKIP_LZO_STRING) #undef lzo_memcmp #undef lzo_memcpy #undef lzo_memmove #undef lzo_memset #if !defined(__LZO_MMODEL_HUGE) # undef LZO_HAVE_MM_HUGE_PTR #endif #define lzo_hsize_t lzo_uint #define lzo_hvoid_p lzo_voidp #define lzo_hbyte_p lzo_bytep #define LZOLIB_PUBLIC(r,f) LZO_PUBLIC(r) f #define lzo_hmemcmp lzo_memcmp #define lzo_hmemcpy lzo_memcpy #define lzo_hmemmove lzo_memmove #define lzo_hmemset lzo_memset #define __LZOLIB_HMEMCPY_CH_INCLUDED 1 #if !defined(LZOLIB_PUBLIC) # define LZOLIB_PUBLIC(r,f) r __LZOLIB_FUNCNAME(f) #endif LZOLIB_PUBLIC(int, lzo_hmemcmp) (const lzo_hvoid_p s1, const lzo_hvoid_p s2, lzo_hsize_t len) { #if (LZO_HAVE_MM_HUGE_PTR) || !defined(HAVE_MEMCMP) const lzo_hbyte_p p1 = (const lzo_hbyte_p) s1; const lzo_hbyte_p p2 = (const lzo_hbyte_p) s2; if __lzo_likely(len > 0) do { int d = *p1 - *p2; if (d != 0) return d; p1++; p2++; } while __lzo_likely(--len > 0); return 0; #else return memcmp(s1, s2, len); #endif } LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemcpy) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) { #if (LZO_HAVE_MM_HUGE_PTR) || !defined(HAVE_MEMCPY) lzo_hbyte_p p1 = (lzo_hbyte_p) dest; const lzo_hbyte_p p2 = (const lzo_hbyte_p) src; if (!(len > 0) || p1 == p2) return dest; do *p1++ = *p2++; while __lzo_likely(--len > 0); return dest; #else return memcpy(dest, src, len); #endif } LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemmove) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) { #if (LZO_HAVE_MM_HUGE_PTR) || !defined(HAVE_MEMMOVE) lzo_hbyte_p p1 = (lzo_hbyte_p) dest; const lzo_hbyte_p p2 = (const lzo_hbyte_p) src; if (!(len > 0) || p1 == p2) return dest; if (p1 < p2) { do *p1++ = *p2++; while __lzo_likely(--len > 0); } else { p1 += len; p2 += len; do *--p1 = *--p2; while __lzo_likely(--len > 0); } return dest; #else return memmove(dest, src, len); #endif } LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemset) (lzo_hvoid_p s, int c, lzo_hsize_t len) { #if (LZO_HAVE_MM_HUGE_PTR) || !defined(HAVE_MEMSET) lzo_hbyte_p p = (lzo_hbyte_p) s; if __lzo_likely(len > 0) do *p++ = (unsigned char) c; while __lzo_likely(--len > 0); return s; #else return memset(s, c, len); #endif } #undef LZOLIB_PUBLIC #endif #if !defined(__LZO_IN_MINILZO) #define ACC_WANT_ACC_CHK_CH 1 #undef ACCCHK_ASSERT ACCCHK_ASSERT_IS_SIGNED_T(lzo_int) ACCCHK_ASSERT_IS_UNSIGNED_T(lzo_uint) ACCCHK_ASSERT_IS_SIGNED_T(lzo_int32) ACCCHK_ASSERT_IS_UNSIGNED_T(lzo_uint32) ACCCHK_ASSERT((LZO_UINT32_C(1) << (int)(8*sizeof(LZO_UINT32_C(1))-1)) > 0) ACCCHK_ASSERT(sizeof(lzo_uint32) >= 4) #if !defined(__LZO_UINTPTR_T_IS_POINTER) ACCCHK_ASSERT_IS_UNSIGNED_T(lzo_uintptr_t) #endif ACCCHK_ASSERT(sizeof(lzo_uintptr_t) >= sizeof(lzo_voidp)) ACCCHK_ASSERT_IS_UNSIGNED_T(lzo_xint) ACCCHK_ASSERT(sizeof(lzo_xint) >= sizeof(lzo_uint32)) ACCCHK_ASSERT(sizeof(lzo_xint) >= sizeof(lzo_uint)) ACCCHK_ASSERT(sizeof(lzo_xint) == sizeof(lzo_uint32) || sizeof(lzo_xint) == sizeof(lzo_uint)) #endif #undef ACCCHK_ASSERT LZO_PUBLIC(int) _lzo_config_check(void) { lzo_bool r = 1; union { unsigned char c[2*sizeof(lzo_xint)]; lzo_xint l[2]; } u; lzo_uintptr_t p; #if !defined(LZO_CFG_NO_CONFIG_CHECK) #if defined(LZO_ABI_BIG_ENDIAN) u.l[0] = u.l[1] = 0; u.c[sizeof(lzo_xint) - 1] = 128; r &= (u.l[0] == 128); #endif #if defined(LZO_ABI_LITTLE_ENDIAN) u.l[0] = u.l[1] = 0; u.c[0] = 128; r &= (u.l[0] == 128); #endif #if defined(LZO_UNALIGNED_OK_2) p = (lzo_uintptr_t) (const lzo_voidp) &u.c[0]; u.l[0] = u.l[1] = 0; r &= ((* (const lzo_ushortp) (p+1)) == 0); #endif #if defined(LZO_UNALIGNED_OK_4) p = (lzo_uintptr_t) (const lzo_voidp) &u.c[0]; u.l[0] = u.l[1] = 0; r &= ((* (const lzo_uint32p) (p+1)) == 0); #endif #endif LZO_UNUSED(u); LZO_UNUSED(p); return r == 1 ? LZO_E_OK : LZO_E_ERROR; } int __lzo_init_done = 0; LZO_PUBLIC(int) __lzo_init_v2(unsigned v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9) { int r; #if defined(__LZO_IN_MINILZO) #elif (LZO_CC_MSC && ((_MSC_VER) < 700)) #else #define ACC_WANT_ACC_CHK_CH 1 #undef ACCCHK_ASSERT #define ACCCHK_ASSERT(expr) LZO_COMPILE_TIME_ASSERT(expr) #endif #undef ACCCHK_ASSERT __lzo_init_done = 1; if (v == 0) return LZO_E_ERROR; r = (s1 == -1 || s1 == (int) sizeof(short)) && (s2 == -1 || s2 == (int) sizeof(int)) && (s3 == -1 || s3 == (int) sizeof(long)) && (s4 == -1 || s4 == (int) sizeof(lzo_uint32)) && (s5 == -1 || s5 == (int) sizeof(lzo_uint)) && (s6 == -1 || s6 == (int) lzo_sizeof_dict_t) && (s7 == -1 || s7 == (int) sizeof(char *)) && (s8 == -1 || s8 == (int) sizeof(lzo_voidp)) && (s9 == -1 || s9 == (int) sizeof(lzo_callback_t)); if (!r) return LZO_E_ERROR; r = _lzo_config_check(); if (r != LZO_E_OK) return r; return r; } #if !defined(__LZO_IN_MINILZO) #if (LZO_OS_WIN16 && LZO_CC_WATCOMC) && defined(__SW_BD) #if 0 BOOL FAR PASCAL LibMain ( HANDLE hInstance, WORD wDataSegment, WORD wHeapSize, LPSTR lpszCmdLine ) #else int __far __pascal LibMain ( int a, short b, short c, long d ) #endif { LZO_UNUSED(a); LZO_UNUSED(b); LZO_UNUSED(c); LZO_UNUSED(d); return 1; } #endif #endif #define do_compress _lzo1x_1_do_compress #if !defined(MINILZO_CFG_SKIP_LZO1X_1_COMPRESS) #define LZO_NEED_DICT_H #define D_BITS 14 #define D_INDEX1(d,p) d = DM(DMUL(0x21,DX3(p,5,5,6)) >> 5) #define D_INDEX2(d,p) d = (d & (D_MASK & 0x7ff)) ^ (D_HIGH | 0x1f) #ifndef __LZO_CONFIG1X_H #define __LZO_CONFIG1X_H #if !defined(LZO1X) && !defined(LZO1Y) && !defined(LZO1Z) # define LZO1X #endif #if !defined(__LZO_IN_MINILZO) #include "lzo/lzo1x.h" #endif #define LZO_EOF_CODE #undef LZO_DETERMINISTIC #define M1_MAX_OFFSET 0x0400 #ifndef M2_MAX_OFFSET #define M2_MAX_OFFSET 0x0800 #endif #define M3_MAX_OFFSET 0x4000 #define M4_MAX_OFFSET 0xbfff #define MX_MAX_OFFSET (M1_MAX_OFFSET + M2_MAX_OFFSET) #define M1_MIN_LEN 2 #define M1_MAX_LEN 2 #define M2_MIN_LEN 3 #ifndef M2_MAX_LEN #define M2_MAX_LEN 8 #endif #define M3_MIN_LEN 3 #define M3_MAX_LEN 33 #define M4_MIN_LEN 3 #define M4_MAX_LEN 9 #define M1_MARKER 0 #define M2_MARKER 64 #define M3_MARKER 32 #define M4_MARKER 16 #ifndef MIN_LOOKAHEAD #define MIN_LOOKAHEAD (M2_MAX_LEN + 1) #endif #if defined(LZO_NEED_DICT_H) #ifndef LZO_HASH #define LZO_HASH LZO_HASH_LZO_INCREMENTAL_B #endif #define DL_MIN_LEN M2_MIN_LEN #ifndef __LZO_DICT_H #define __LZO_DICT_H #ifdef __cplusplus extern "C" { #endif #if !defined(D_BITS) && defined(DBITS) # define D_BITS DBITS #endif #if !defined(D_BITS) # error "D_BITS is not defined" #endif #if (D_BITS < 16) # define D_SIZE LZO_SIZE(D_BITS) # define D_MASK LZO_MASK(D_BITS) #else # define D_SIZE LZO_USIZE(D_BITS) # define D_MASK LZO_UMASK(D_BITS) #endif #define D_HIGH ((D_MASK >> 1) + 1) #if !defined(DD_BITS) # define DD_BITS 0 #endif #define DD_SIZE LZO_SIZE(DD_BITS) #define DD_MASK LZO_MASK(DD_BITS) #if !defined(DL_BITS) # define DL_BITS (D_BITS - DD_BITS) #endif #if (DL_BITS < 16) # define DL_SIZE LZO_SIZE(DL_BITS) # define DL_MASK LZO_MASK(DL_BITS) #else # define DL_SIZE LZO_USIZE(DL_BITS) # define DL_MASK LZO_UMASK(DL_BITS) #endif #if (D_BITS != DL_BITS + DD_BITS) # error "D_BITS does not match" #endif #if (D_BITS < 8 || D_BITS > 18) # error "invalid D_BITS" #endif #if (DL_BITS < 8 || DL_BITS > 20) # error "invalid DL_BITS" #endif #if (DD_BITS < 0 || DD_BITS > 6) # error "invalid DD_BITS" #endif #if !defined(DL_MIN_LEN) # define DL_MIN_LEN 3 #endif #if !defined(DL_SHIFT) # define DL_SHIFT ((DL_BITS + (DL_MIN_LEN - 1)) / DL_MIN_LEN) #endif #define LZO_HASH_GZIP 1 #define LZO_HASH_GZIP_INCREMENTAL 2 #define LZO_HASH_LZO_INCREMENTAL_A 3 #define LZO_HASH_LZO_INCREMENTAL_B 4 #if !defined(LZO_HASH) # error "choose a hashing strategy" #endif #undef DM #undef DX #if (DL_MIN_LEN == 3) # define _DV2_A(p,shift1,shift2) \ (((( (lzo_xint)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2]) # define _DV2_B(p,shift1,shift2) \ (((( (lzo_xint)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0]) # define _DV3_B(p,shift1,shift2,shift3) \ ((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0]) #elif (DL_MIN_LEN == 2) # define _DV2_A(p,shift1,shift2) \ (( (lzo_xint)(p[0]) << shift1) ^ p[1]) # define _DV2_B(p,shift1,shift2) \ (( (lzo_xint)(p[1]) << shift1) ^ p[2]) #else # error "invalid DL_MIN_LEN" #endif #define _DV_A(p,shift) _DV2_A(p,shift,shift) #define _DV_B(p,shift) _DV2_B(p,shift,shift) #define DA2(p,s1,s2) \ (((((lzo_xint)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0]) #define DS2(p,s1,s2) \ (((((lzo_xint)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0]) #define DX2(p,s1,s2) \ (((((lzo_xint)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0]) #define DA3(p,s1,s2,s3) ((DA2((p)+1,s2,s3) << (s1)) + (p)[0]) #define DS3(p,s1,s2,s3) ((DS2((p)+1,s2,s3) << (s1)) - (p)[0]) #define DX3(p,s1,s2,s3) ((DX2((p)+1,s2,s3) << (s1)) ^ (p)[0]) #define DMS(v,s) ((lzo_uint) (((v) & (D_MASK >> (s))) << (s))) #define DM(v) DMS(v,0) #if (LZO_HASH == LZO_HASH_GZIP) # define _DINDEX(dv,p) (_DV_A((p),DL_SHIFT)) #elif (LZO_HASH == LZO_HASH_GZIP_INCREMENTAL) # define __LZO_HASH_INCREMENTAL # define DVAL_FIRST(dv,p) dv = _DV_A((p),DL_SHIFT) # define DVAL_NEXT(dv,p) dv = (((dv) << DL_SHIFT) ^ p[2]) # define _DINDEX(dv,p) (dv) # define DVAL_LOOKAHEAD DL_MIN_LEN #elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_A) # define __LZO_HASH_INCREMENTAL # define DVAL_FIRST(dv,p) dv = _DV_A((p),5) # define DVAL_NEXT(dv,p) \ dv ^= (lzo_xint)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2]) # define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) # define DVAL_LOOKAHEAD DL_MIN_LEN #elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_B) # define __LZO_HASH_INCREMENTAL # define DVAL_FIRST(dv,p) dv = _DV_B((p),5) # define DVAL_NEXT(dv,p) \ dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_xint)(p[2]) << (2*5))) # define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) # define DVAL_LOOKAHEAD DL_MIN_LEN #else # error "choose a hashing strategy" #endif #ifndef DINDEX #define DINDEX(dv,p) ((lzo_uint)((_DINDEX(dv,p)) & DL_MASK) << DD_BITS) #endif #if !defined(DINDEX1) && defined(D_INDEX1) #define DINDEX1 D_INDEX1 #endif #if !defined(DINDEX2) && defined(D_INDEX2) #define DINDEX2 D_INDEX2 #endif #if !defined(__LZO_HASH_INCREMENTAL) # define DVAL_FIRST(dv,p) ((void) 0) # define DVAL_NEXT(dv,p) ((void) 0) # define DVAL_LOOKAHEAD 0 #endif #if !defined(DVAL_ASSERT) #if defined(__LZO_HASH_INCREMENTAL) && !defined(NDEBUG) static void DVAL_ASSERT(lzo_xint dv, const lzo_bytep p) { lzo_xint df; DVAL_FIRST(df,(p)); assert(DINDEX(dv,p) == DINDEX(df,p)); } #else # define DVAL_ASSERT(dv,p) ((void) 0) #endif #endif #if defined(LZO_DICT_USE_PTR) # define DENTRY(p,in) (p) # define GINDEX(m_pos,m_off,dict,dindex,in) m_pos = dict[dindex] #else # define DENTRY(p,in) ((lzo_uint) ((p)-(in))) # define GINDEX(m_pos,m_off,dict,dindex,in) m_off = dict[dindex] #endif #if (DD_BITS == 0) # define UPDATE_D(dict,drun,dv,p,in) dict[ DINDEX(dv,p) ] = DENTRY(p,in) # define UPDATE_I(dict,drun,index,p,in) dict[index] = DENTRY(p,in) # define UPDATE_P(ptr,drun,p,in) (ptr)[0] = DENTRY(p,in) #else # define UPDATE_D(dict,drun,dv,p,in) \ dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK # define UPDATE_I(dict,drun,index,p,in) \ dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK # define UPDATE_P(ptr,drun,p,in) \ (ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK #endif #if defined(LZO_DICT_USE_PTR) #define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ (m_pos == NULL || (m_off = pd(ip, m_pos)) > max_offset) #define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ (BOUNDS_CHECKING_OFF_IN_EXPR(( \ m_pos = ip - (lzo_uint) PTR_DIFF(ip,m_pos), \ PTR_LT(m_pos,in) || \ (m_off = (lzo_uint) PTR_DIFF(ip,m_pos)) <= 0 || \ m_off > max_offset ))) #else #define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ (m_off == 0 || \ ((m_off = pd(ip, in) - m_off) > max_offset) || \ (m_pos = (ip) - (m_off), 0) ) #define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ (pd(ip, in) <= m_off || \ ((m_off = pd(ip, in) - m_off) > max_offset) || \ (m_pos = (ip) - (m_off), 0) ) #endif #if defined(LZO_DETERMINISTIC) # define LZO_CHECK_MPOS LZO_CHECK_MPOS_DET #else # define LZO_CHECK_MPOS LZO_CHECK_MPOS_NON_DET #endif #ifdef __cplusplus } #endif #endif #endif #endif #define DO_COMPRESS lzo1x_1_compress static __lzo_noinline lzo_uint do_compress ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { register const lzo_bytep ip; lzo_bytep op; const lzo_bytep const in_end = in + in_len; const lzo_bytep const ip_end = in + in_len - M2_MAX_LEN - 5; const lzo_bytep ii; lzo_dict_p const dict = (lzo_dict_p) wrkmem; op = out; ip = in; ii = ip; ip += 4; for (;;) { register const lzo_bytep m_pos; lzo_uint m_off; lzo_uint m_len; lzo_uint dindex; DINDEX1(dindex,ip); GINDEX(m_pos,m_off,dict,dindex,in); if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) goto literal; #if 1 if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) goto try_match; DINDEX2(dindex,ip); #endif GINDEX(m_pos,m_off,dict,dindex,in); if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) goto literal; if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) goto try_match; goto literal; try_match: #if 1 && defined(LZO_UNALIGNED_OK_2) if (* (const lzo_ushortp) m_pos != * (const lzo_ushortp) ip) #else if (m_pos[0] != ip[0] || m_pos[1] != ip[1]) #endif { } else { if __lzo_likely(m_pos[2] == ip[2]) { #if 0 if (m_off <= M2_MAX_OFFSET) goto match; if (lit <= 3) goto match; if (lit == 3) { assert(op - 2 > out); op[-2] |= LZO_BYTE(3); *op++ = *ii++; *op++ = *ii++; *op++ = *ii++; goto code_match; } if (m_pos[3] == ip[3]) #endif goto match; } else { #if 0 #if 0 if (m_off <= M1_MAX_OFFSET && lit > 0 && lit <= 3) #else if (m_off <= M1_MAX_OFFSET && lit == 3) #endif { register lzo_uint t; t = lit; assert(op - 2 > out); op[-2] |= LZO_BYTE(t); do *op++ = *ii++; while (--t > 0); assert(ii == ip); m_off -= 1; *op++ = LZO_BYTE(M1_MARKER | ((m_off & 3) << 2)); *op++ = LZO_BYTE(m_off >> 2); ip += 2; goto match_done; } #endif } } literal: UPDATE_I(dict,0,dindex,ip,in); ++ip; if __lzo_unlikely(ip >= ip_end) break; continue; match: UPDATE_I(dict,0,dindex,ip,in); if (pd(ip,ii) > 0) { register lzo_uint t = pd(ip,ii); if (t <= 3) { assert(op - 2 > out); op[-2] |= LZO_BYTE(t); } else if (t <= 18) *op++ = LZO_BYTE(t - 3); else { register lzo_uint tt = t - 18; *op++ = 0; while (tt > 255) { tt -= 255; *op++ = 0; } assert(tt > 0); *op++ = LZO_BYTE(tt); } do *op++ = *ii++; while (--t > 0); } assert(ii == ip); ip += 3; if (m_pos[3] != *ip++ || m_pos[4] != *ip++ || m_pos[5] != *ip++ || m_pos[6] != *ip++ || m_pos[7] != *ip++ || m_pos[8] != *ip++ #ifdef LZO1Y || m_pos[ 9] != *ip++ || m_pos[10] != *ip++ || m_pos[11] != *ip++ || m_pos[12] != *ip++ || m_pos[13] != *ip++ || m_pos[14] != *ip++ #endif ) { --ip; m_len = pd(ip, ii); assert(m_len >= 3); assert(m_len <= M2_MAX_LEN); if (m_off <= M2_MAX_OFFSET) { m_off -= 1; #if defined(LZO1X) *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); *op++ = LZO_BYTE(m_off >> 3); #elif defined(LZO1Y) *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); *op++ = LZO_BYTE(m_off >> 2); #endif } else if (m_off <= M3_MAX_OFFSET) { m_off -= 1; *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); goto m3_m4_offset; } else #if defined(LZO1X) { m_off -= 0x4000; assert(m_off > 0); assert(m_off <= 0x7fff); *op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11) | (m_len - 2)); goto m3_m4_offset; } #elif defined(LZO1Y) goto m4_match; #endif } else { { const lzo_bytep end = in_end; const lzo_bytep m = m_pos + M2_MAX_LEN + 1; while (ip < end && *m == *ip) m++, ip++; m_len = pd(ip, ii); } assert(m_len > M2_MAX_LEN); if (m_off <= M3_MAX_OFFSET) { m_off -= 1; if (m_len <= 33) *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); else { m_len -= 33; *op++ = M3_MARKER | 0; goto m3_m4_len; } } else { #if defined(LZO1Y) m4_match: #endif m_off -= 0x4000; assert(m_off > 0); assert(m_off <= 0x7fff); if (m_len <= M4_MAX_LEN) *op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11) | (m_len - 2)); else { m_len -= M4_MAX_LEN; *op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11)); m3_m4_len: while (m_len > 255) { m_len -= 255; *op++ = 0; } assert(m_len > 0); *op++ = LZO_BYTE(m_len); } } m3_m4_offset: *op++ = LZO_BYTE((m_off & 63) << 2); *op++ = LZO_BYTE(m_off >> 6); } #if 0 match_done: #endif ii = ip; if __lzo_unlikely(ip >= ip_end) break; } *out_len = pd(op, out); return pd(in_end,ii); } LZO_PUBLIC(int) DO_COMPRESS ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { lzo_bytep op = out; lzo_uint t; if __lzo_unlikely(in_len <= M2_MAX_LEN + 5) t = in_len; else { t = do_compress(in,in_len,op,out_len,wrkmem); op += *out_len; } if (t > 0) { const lzo_bytep ii = in + in_len - t; if (op == out && t <= 238) *op++ = LZO_BYTE(17 + t); else if (t <= 3) op[-2] |= LZO_BYTE(t); else if (t <= 18) *op++ = LZO_BYTE(t - 3); else { lzo_uint tt = t - 18; *op++ = 0; while (tt > 255) { tt -= 255; *op++ = 0; } assert(tt > 0); *op++ = LZO_BYTE(tt); } do *op++ = *ii++; while (--t > 0); } *op++ = M4_MARKER | 1; *op++ = 0; *op++ = 0; *out_len = pd(op, out); return LZO_E_OK; } #endif #undef do_compress #undef DO_COMPRESS #undef LZO_HASH #undef LZO_TEST_OVERRUN #undef DO_DECOMPRESS #define DO_DECOMPRESS lzo1x_decompress #if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS) #if defined(LZO_TEST_OVERRUN) # if !defined(LZO_TEST_OVERRUN_INPUT) # define LZO_TEST_OVERRUN_INPUT 2 # endif # if !defined(LZO_TEST_OVERRUN_OUTPUT) # define LZO_TEST_OVERRUN_OUTPUT 2 # endif # if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) # define LZO_TEST_OVERRUN_LOOKBEHIND # endif #endif #undef TEST_IP #undef TEST_OP #undef TEST_LB #undef TEST_LBO #undef NEED_IP #undef NEED_OP #undef HAVE_TEST_IP #undef HAVE_TEST_OP #undef HAVE_NEED_IP #undef HAVE_NEED_OP #undef HAVE_ANY_IP #undef HAVE_ANY_OP #if defined(LZO_TEST_OVERRUN_INPUT) # if (LZO_TEST_OVERRUN_INPUT >= 1) # define TEST_IP (ip < ip_end) # endif # if (LZO_TEST_OVERRUN_INPUT >= 2) # define NEED_IP(x) \ if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun # endif #endif #if defined(LZO_TEST_OVERRUN_OUTPUT) # if (LZO_TEST_OVERRUN_OUTPUT >= 1) # define TEST_OP (op <= op_end) # endif # if (LZO_TEST_OVERRUN_OUTPUT >= 2) # undef TEST_OP # define NEED_OP(x) \ if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun # endif #endif #if defined(LZO_TEST_OVERRUN_LOOKBEHIND) # define TEST_LB(m_pos) if (m_pos < out || m_pos >= op) goto lookbehind_overrun # define TEST_LBO(m_pos,o) if (m_pos < out || m_pos >= op - (o)) goto lookbehind_overrun #else # define TEST_LB(m_pos) ((void) 0) # define TEST_LBO(m_pos,o) ((void) 0) #endif #if !defined(LZO_EOF_CODE) && !defined(TEST_IP) # define TEST_IP (ip < ip_end) #endif #if defined(TEST_IP) # define HAVE_TEST_IP #else # define TEST_IP 1 #endif #if defined(TEST_OP) # define HAVE_TEST_OP #else # define TEST_OP 1 #endif #if defined(NEED_IP) # define HAVE_NEED_IP #else # define NEED_IP(x) ((void) 0) #endif #if defined(NEED_OP) # define HAVE_NEED_OP #else # define NEED_OP(x) ((void) 0) #endif #if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) # define HAVE_ANY_IP #endif #if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) # define HAVE_ANY_OP #endif #undef __COPY4 #define __COPY4(dst,src) * (lzo_uint32p)(dst) = * (const lzo_uint32p)(src) #undef COPY4 #if defined(LZO_UNALIGNED_OK_4) # define COPY4(dst,src) __COPY4(dst,src) #elif defined(LZO_ALIGNED_OK_4) # define COPY4(dst,src) __COPY4((lzo_uintptr_t)(dst),(lzo_uintptr_t)(src)) #endif #if defined(DO_DECOMPRESS) LZO_PUBLIC(int) DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) #endif { register lzo_bytep op; register const lzo_bytep ip; register lzo_uint t; #if defined(COPY_DICT) lzo_uint m_off; const lzo_bytep dict_end; #else register const lzo_bytep m_pos; #endif const lzo_bytep const ip_end = in + in_len; #if defined(HAVE_ANY_OP) lzo_bytep const op_end = out + *out_len; #endif #if defined(LZO1Z) lzo_uint last_m_off = 0; #endif LZO_UNUSED(wrkmem); #if defined(COPY_DICT) if (dict) { if (dict_len > M4_MAX_OFFSET) { dict += dict_len - M4_MAX_OFFSET; dict_len = M4_MAX_OFFSET; } dict_end = dict + dict_len; } else { dict_len = 0; dict_end = NULL; } #endif *out_len = 0; op = out; ip = in; if (*ip > 17) { t = *ip++ - 17; if (t < 4) goto match_next; assert(t > 0); NEED_OP(t); NEED_IP(t+1); do *op++ = *ip++; while (--t > 0); goto first_literal_run; } while (TEST_IP && TEST_OP) { t = *ip++; if (t >= 16) goto match; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 15 + *ip++; } assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) if (PTR_ALIGNED2_4(op,ip)) { #endif COPY4(op,ip); op += 4; ip += 4; if (--t > 0) { if (t >= 4) { do { COPY4(op,ip); op += 4; ip += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *ip++; while (--t > 0); } else do *op++ = *ip++; while (--t > 0); } #if !defined(LZO_UNALIGNED_OK_4) } else #endif #endif #if !defined(LZO_UNALIGNED_OK_4) { *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; do *op++ = *ip++; while (--t > 0); } #endif first_literal_run: t = *ip++; if (t >= 16) goto match; #if defined(COPY_DICT) #if defined(LZO1Z) m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); last_m_off = m_off; #else m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); #endif NEED_OP(3); t = 3; COPY_DICT(t,m_off) #else #if defined(LZO1Z) t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); m_pos = op - t; last_m_off = t; #else m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; #endif TEST_LB(m_pos); NEED_OP(3); *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; #endif goto match_done; do { match: if (t >= 64) { #if defined(COPY_DICT) #if defined(LZO1X) m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); t = (t >> 5) - 1; #elif defined(LZO1Y) m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); t = (t >> 4) - 3; #elif defined(LZO1Z) m_off = t & 0x1f; if (m_off >= 0x1c) m_off = last_m_off; else { m_off = 1 + (m_off << 6) + (*ip++ >> 2); last_m_off = m_off; } t = (t >> 5) - 1; #endif #else #if defined(LZO1X) m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1; #elif defined(LZO1Y) m_pos = op - 1; m_pos -= (t >> 2) & 3; m_pos -= *ip++ << 2; t = (t >> 4) - 3; #elif defined(LZO1Z) { lzo_uint off = t & 0x1f; m_pos = op; if (off >= 0x1c) { assert(last_m_off > 0); m_pos -= last_m_off; } else { off = 1 + (off << 6) + (*ip++ >> 2); m_pos -= off; last_m_off = off; } } t = (t >> 5) - 1; #endif TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); goto copy_match; #endif } else if (t >= 32) { t &= 31; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 31 + *ip++; } #if defined(COPY_DICT) #if defined(LZO1Z) m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); last_m_off = m_off; #else m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); #endif #else #if defined(LZO1Z) { lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); m_pos = op - off; last_m_off = off; } #elif defined(LZO_UNALIGNED_OK_2) && defined(LZO_ABI_LITTLE_ENDIAN) m_pos = op - 1; m_pos -= (* (const lzo_ushortp) ip) >> 2; #else m_pos = op - 1; m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif #endif ip += 2; } else if (t >= 16) { #if defined(COPY_DICT) m_off = (t & 8) << 11; #else m_pos = op; m_pos -= (t & 8) << 11; #endif t &= 7; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 7 + *ip++; } #if defined(COPY_DICT) #if defined(LZO1Z) m_off += (ip[0] << 6) + (ip[1] >> 2); #else m_off += (ip[0] >> 2) + (ip[1] << 6); #endif ip += 2; if (m_off == 0) goto eof_found; m_off += 0x4000; #if defined(LZO1Z) last_m_off = m_off; #endif #else #if defined(LZO1Z) m_pos -= (ip[0] << 6) + (ip[1] >> 2); #elif defined(LZO_UNALIGNED_OK_2) && defined(LZO_ABI_LITTLE_ENDIAN) m_pos -= (* (const lzo_ushortp) ip) >> 2; #else m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif ip += 2; if (m_pos == op) goto eof_found; m_pos -= 0x4000; #if defined(LZO1Z) last_m_off = pd((const lzo_bytep)op, m_pos); #endif #endif } else { #if defined(COPY_DICT) #if defined(LZO1Z) m_off = 1 + (t << 6) + (*ip++ >> 2); last_m_off = m_off; #else m_off = 1 + (t >> 2) + (*ip++ << 2); #endif NEED_OP(2); t = 2; COPY_DICT(t,m_off) #else #if defined(LZO1Z) t = 1 + (t << 6) + (*ip++ >> 2); m_pos = op - t; last_m_off = t; #else m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; #endif TEST_LB(m_pos); NEED_OP(2); *op++ = *m_pos++; *op++ = *m_pos; #endif goto match_done; } #if defined(COPY_DICT) NEED_OP(t+3-1); t += 3-1; COPY_DICT(t,m_off) #else TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) { assert((op - m_pos) >= 4); #else if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) { #endif COPY4(op,m_pos); op += 4; m_pos += 4; t -= 4 - (3 - 1); do { COPY4(op,m_pos); op += 4; m_pos += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *m_pos++; while (--t > 0); } else #endif { copy_match: *op++ = *m_pos++; *op++ = *m_pos++; do *op++ = *m_pos++; while (--t > 0); } #endif match_done: #if defined(LZO1Z) t = ip[-1] & 3; #else t = ip[-2] & 3; #endif if (t == 0) break; match_next: assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+1); #if 0 do *op++ = *ip++; while (--t > 0); #else *op++ = *ip++; if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } #endif t = *ip++; } while (TEST_IP && TEST_OP); } #if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP) *out_len = pd(op, out); return LZO_E_EOF_NOT_FOUND; #endif eof_found: assert(t == 1); *out_len = pd(op, out); return (ip == ip_end ? LZO_E_OK : (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); #if defined(HAVE_NEED_IP) input_overrun: *out_len = pd(op, out); return LZO_E_INPUT_OVERRUN; #endif #if defined(HAVE_NEED_OP) output_overrun: *out_len = pd(op, out); return LZO_E_OUTPUT_OVERRUN; #endif #if defined(LZO_TEST_OVERRUN_LOOKBEHIND) lookbehind_overrun: *out_len = pd(op, out); return LZO_E_LOOKBEHIND_OVERRUN; #endif } #endif #define LZO_TEST_OVERRUN #undef DO_DECOMPRESS #define DO_DECOMPRESS lzo1x_decompress_safe #if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS_SAFE) #if defined(LZO_TEST_OVERRUN) # if !defined(LZO_TEST_OVERRUN_INPUT) # define LZO_TEST_OVERRUN_INPUT 2 # endif # if !defined(LZO_TEST_OVERRUN_OUTPUT) # define LZO_TEST_OVERRUN_OUTPUT 2 # endif # if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) # define LZO_TEST_OVERRUN_LOOKBEHIND # endif #endif #undef TEST_IP #undef TEST_OP #undef TEST_LB #undef TEST_LBO #undef NEED_IP #undef NEED_OP #undef HAVE_TEST_IP #undef HAVE_TEST_OP #undef HAVE_NEED_IP #undef HAVE_NEED_OP #undef HAVE_ANY_IP #undef HAVE_ANY_OP #if defined(LZO_TEST_OVERRUN_INPUT) # if (LZO_TEST_OVERRUN_INPUT >= 1) # define TEST_IP (ip < ip_end) # endif # if (LZO_TEST_OVERRUN_INPUT >= 2) # define NEED_IP(x) \ if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun # endif #endif #if defined(LZO_TEST_OVERRUN_OUTPUT) # if (LZO_TEST_OVERRUN_OUTPUT >= 1) # define TEST_OP (op <= op_end) # endif # if (LZO_TEST_OVERRUN_OUTPUT >= 2) # undef TEST_OP # define NEED_OP(x) \ if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun # endif #endif #if defined(LZO_TEST_OVERRUN_LOOKBEHIND) # define TEST_LB(m_pos) if (m_pos < out || m_pos >= op) goto lookbehind_overrun # define TEST_LBO(m_pos,o) if (m_pos < out || m_pos >= op - (o)) goto lookbehind_overrun #else # define TEST_LB(m_pos) ((void) 0) # define TEST_LBO(m_pos,o) ((void) 0) #endif #if !defined(LZO_EOF_CODE) && !defined(TEST_IP) # define TEST_IP (ip < ip_end) #endif #if defined(TEST_IP) # define HAVE_TEST_IP #else # define TEST_IP 1 #endif #if defined(TEST_OP) # define HAVE_TEST_OP #else # define TEST_OP 1 #endif #if defined(NEED_IP) # define HAVE_NEED_IP #else # define NEED_IP(x) ((void) 0) #endif #if defined(NEED_OP) # define HAVE_NEED_OP #else # define NEED_OP(x) ((void) 0) #endif #if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) # define HAVE_ANY_IP #endif #if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) # define HAVE_ANY_OP #endif #undef __COPY4 #define __COPY4(dst,src) * (lzo_uint32p)(dst) = * (const lzo_uint32p)(src) #undef COPY4 #if defined(LZO_UNALIGNED_OK_4) # define COPY4(dst,src) __COPY4(dst,src) #elif defined(LZO_ALIGNED_OK_4) # define COPY4(dst,src) __COPY4((lzo_uintptr_t)(dst),(lzo_uintptr_t)(src)) #endif #if defined(DO_DECOMPRESS) LZO_PUBLIC(int) DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) #endif { register lzo_bytep op; register const lzo_bytep ip; register lzo_uint t; #if defined(COPY_DICT) lzo_uint m_off; const lzo_bytep dict_end; #else register const lzo_bytep m_pos; #endif const lzo_bytep const ip_end = in + in_len; #if defined(HAVE_ANY_OP) lzo_bytep const op_end = out + *out_len; #endif #if defined(LZO1Z) lzo_uint last_m_off = 0; #endif LZO_UNUSED(wrkmem); #if defined(COPY_DICT) if (dict) { if (dict_len > M4_MAX_OFFSET) { dict += dict_len - M4_MAX_OFFSET; dict_len = M4_MAX_OFFSET; } dict_end = dict + dict_len; } else { dict_len = 0; dict_end = NULL; } #endif *out_len = 0; op = out; ip = in; if (*ip > 17) { t = *ip++ - 17; if (t < 4) goto match_next; assert(t > 0); NEED_OP(t); NEED_IP(t+1); do *op++ = *ip++; while (--t > 0); goto first_literal_run; } while (TEST_IP && TEST_OP) { t = *ip++; if (t >= 16) goto match; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 15 + *ip++; } assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) if (PTR_ALIGNED2_4(op,ip)) { #endif COPY4(op,ip); op += 4; ip += 4; if (--t > 0) { if (t >= 4) { do { COPY4(op,ip); op += 4; ip += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *ip++; while (--t > 0); } else do *op++ = *ip++; while (--t > 0); } #if !defined(LZO_UNALIGNED_OK_4) } else #endif #endif #if !defined(LZO_UNALIGNED_OK_4) { *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; do *op++ = *ip++; while (--t > 0); } #endif first_literal_run: t = *ip++; if (t >= 16) goto match; #if defined(COPY_DICT) #if defined(LZO1Z) m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); last_m_off = m_off; #else m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); #endif NEED_OP(3); t = 3; COPY_DICT(t,m_off) #else #if defined(LZO1Z) t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); m_pos = op - t; last_m_off = t; #else m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; #endif TEST_LB(m_pos); NEED_OP(3); *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; #endif goto match_done; do { match: if (t >= 64) { #if defined(COPY_DICT) #if defined(LZO1X) m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); t = (t >> 5) - 1; #elif defined(LZO1Y) m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); t = (t >> 4) - 3; #elif defined(LZO1Z) m_off = t & 0x1f; if (m_off >= 0x1c) m_off = last_m_off; else { m_off = 1 + (m_off << 6) + (*ip++ >> 2); last_m_off = m_off; } t = (t >> 5) - 1; #endif #else #if defined(LZO1X) m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1; #elif defined(LZO1Y) m_pos = op - 1; m_pos -= (t >> 2) & 3; m_pos -= *ip++ << 2; t = (t >> 4) - 3; #elif defined(LZO1Z) { lzo_uint off = t & 0x1f; m_pos = op; if (off >= 0x1c) { assert(last_m_off > 0); m_pos -= last_m_off; } else { off = 1 + (off << 6) + (*ip++ >> 2); m_pos -= off; last_m_off = off; } } t = (t >> 5) - 1; #endif TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); goto copy_match; #endif } else if (t >= 32) { t &= 31; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 31 + *ip++; } #if defined(COPY_DICT) #if defined(LZO1Z) m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); last_m_off = m_off; #else m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); #endif #else #if defined(LZO1Z) { lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); m_pos = op - off; last_m_off = off; } #elif defined(LZO_UNALIGNED_OK_2) && defined(LZO_ABI_LITTLE_ENDIAN) m_pos = op - 1; m_pos -= (* (const lzo_ushortp) ip) >> 2; #else m_pos = op - 1; m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif #endif ip += 2; } else if (t >= 16) { #if defined(COPY_DICT) m_off = (t & 8) << 11; #else m_pos = op; m_pos -= (t & 8) << 11; #endif t &= 7; if (t == 0) { NEED_IP(1); while (*ip == 0) { t += 255; ip++; NEED_IP(1); } t += 7 + *ip++; } #if defined(COPY_DICT) #if defined(LZO1Z) m_off += (ip[0] << 6) + (ip[1] >> 2); #else m_off += (ip[0] >> 2) + (ip[1] << 6); #endif ip += 2; if (m_off == 0) goto eof_found; m_off += 0x4000; #if defined(LZO1Z) last_m_off = m_off; #endif #else #if defined(LZO1Z) m_pos -= (ip[0] << 6) + (ip[1] >> 2); #elif defined(LZO_UNALIGNED_OK_2) && defined(LZO_ABI_LITTLE_ENDIAN) m_pos -= (* (const lzo_ushortp) ip) >> 2; #else m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif ip += 2; if (m_pos == op) goto eof_found; m_pos -= 0x4000; #if defined(LZO1Z) last_m_off = pd((const lzo_bytep)op, m_pos); #endif #endif } else { #if defined(COPY_DICT) #if defined(LZO1Z) m_off = 1 + (t << 6) + (*ip++ >> 2); last_m_off = m_off; #else m_off = 1 + (t >> 2) + (*ip++ << 2); #endif NEED_OP(2); t = 2; COPY_DICT(t,m_off) #else #if defined(LZO1Z) t = 1 + (t << 6) + (*ip++ >> 2); m_pos = op - t; last_m_off = t; #else m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; #endif TEST_LB(m_pos); NEED_OP(2); *op++ = *m_pos++; *op++ = *m_pos; #endif goto match_done; } #if defined(COPY_DICT) NEED_OP(t+3-1); t += 3-1; COPY_DICT(t,m_off) #else TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) { assert((op - m_pos) >= 4); #else if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) { #endif COPY4(op,m_pos); op += 4; m_pos += 4; t -= 4 - (3 - 1); do { COPY4(op,m_pos); op += 4; m_pos += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *m_pos++; while (--t > 0); } else #endif { copy_match: *op++ = *m_pos++; *op++ = *m_pos++; do *op++ = *m_pos++; while (--t > 0); } #endif match_done: #if defined(LZO1Z) t = ip[-1] & 3; #else t = ip[-2] & 3; #endif if (t == 0) break; match_next: assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+1); #if 0 do *op++ = *ip++; while (--t > 0); #else *op++ = *ip++; if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } #endif t = *ip++; } while (TEST_IP && TEST_OP); } #if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP) *out_len = pd(op, out); return LZO_E_EOF_NOT_FOUND; #endif eof_found: assert(t == 1); *out_len = pd(op, out); return (ip == ip_end ? LZO_E_OK : (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); #if defined(HAVE_NEED_IP) input_overrun: *out_len = pd(op, out); return LZO_E_INPUT_OVERRUN; #endif #if defined(HAVE_NEED_OP) output_overrun: *out_len = pd(op, out); return LZO_E_OUTPUT_OVERRUN; #endif #if defined(LZO_TEST_OVERRUN_LOOKBEHIND) lookbehind_overrun: *out_len = pd(op, out); return LZO_E_LOOKBEHIND_OVERRUN; #endif } #endif /***** End of minilzo.c *****/ bcmatroska2-5.3.101/libmatroska2/minilzo/minilzo.h000066400000000000000000000066451462133141200220060ustar00rootroot00000000000000/* minilzo.h -- mini subset of the LZO real-time data compression library This file is part of the LZO real-time data compression library. Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer http://www.oberhumer.com/opensource/lzo/ */ /* * NOTE: * the full LZO package can be found at * http://www.oberhumer.com/opensource/lzo/ */ #ifndef __MINILZO_H #define __MINILZO_H #define MINILZO_VERSION 0x2030 #ifdef __LZOCONF_H # error "you cannot use both LZO and miniLZO" #endif #undef LZO_HAVE_CONFIG_H #include "lzoconf.h" #if !defined(LZO_VERSION) || (LZO_VERSION != MINILZO_VERSION) # error "version mismatch in header files" #endif #ifdef __cplusplus extern "C" { #endif /*********************************************************************** // ************************************************************************/ /* Memory required for the wrkmem parameter. * When the required size is 0, you can also pass a NULL pointer. */ #define LZO1X_MEM_COMPRESS LZO1X_1_MEM_COMPRESS #define LZO1X_1_MEM_COMPRESS ((lzo_uint32) (16384L * lzo_sizeof_dict_t)) #define LZO1X_MEM_DECOMPRESS (0) /* compression */ LZO_EXTERN(int) lzo1x_1_compress ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem ); /* decompression */ LZO_EXTERN(int) lzo1x_decompress ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem /* NOT USED */ ); /* safe decompression with overrun testing */ LZO_EXTERN(int) lzo1x_decompress_safe ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem /* NOT USED */ ); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* already included */ bcmatroska2-5.3.101/libmatroska2/minilzo/minilzo.proj000066400000000000000000000002471462133141200225210ustar00rootroot00000000000000IF CONFIG_LZO1X LIB minilzo { EXPINCLUDE . SOURCE minilzo.c HEADER minilzo.h HEADER lzoconf.h HEADER lzodefs.h } CON testmini { SOURCE testmini.c } ENDIF bcmatroska2-5.3.101/libmatroska2/minilzo/testmini.c000066400000000000000000000126551462133141200221520ustar00rootroot00000000000000/* testmini.c -- very simple test program for the miniLZO library This file is part of the LZO real-time data compression library. Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer http://www.oberhumer.com/opensource/lzo/ */ #include #include /************************************************************************* // This program shows the basic usage of the LZO library. // We will compress a block of data and decompress again. // // For more information, documentation, example programs and other support // files (like Makefiles and build scripts) please download the full LZO // package from // http://www.oberhumer.com/opensource/lzo/ **************************************************************************/ /* First let's include "minizo.h". */ #include "minilzo.h" /* We want to compress the data block at `in' with length `IN_LEN' to * the block at `out'. Because the input block may be incompressible, * we must provide a little more output space in case that compression * is not possible. */ #if defined(__LZO_STRICT_16BIT) #define IN_LEN (8*1024u) #elif defined(LZO_ARCH_I086) && !defined(LZO_HAVE_MM_HUGE_ARRAY) #define IN_LEN (60*1024u) #else #define IN_LEN (128*1024ul) #endif #define OUT_LEN (IN_LEN + IN_LEN / 16 + 64 + 3) static unsigned char __LZO_MMODEL in [ IN_LEN ]; static unsigned char __LZO_MMODEL out [ OUT_LEN ]; /* Work-memory needed for compression. Allocate memory in units * of `lzo_align_t' (instead of `char') to make sure it is properly aligned. */ #define HEAP_ALLOC(var,size) \ lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ] static HEAP_ALLOC(wrkmem,LZO1X_1_MEM_COMPRESS); /************************************************************************* // **************************************************************************/ int main(int argc, char *argv[]) { int r; lzo_uint in_len; lzo_uint out_len; lzo_uint new_len; if (argc < 0 && argv == NULL) /* avoid warning about unused args */ return 0; printf("\nLZO real-time data compression library (v%s, %s).\n", lzo_version_string(), lzo_version_date()); printf("Copyright (C) 1996-2008 Markus Franz Xaver Johannes Oberhumer\nAll Rights Reserved.\n\n"); /* * Step 1: initialize the LZO library */ if (lzo_init() != LZO_E_OK) { printf("internal error - lzo_init() failed !!!\n"); printf("(this usually indicates a compiler bug - try recompiling\nwithout optimizations, and enable `-DLZO_DEBUG' for diagnostics)\n"); return 3; } /* * Step 2: prepare the input block that will get compressed. * We just fill it with zeros in this example program, * but you would use your real-world data here. */ in_len = IN_LEN; lzo_memset(in,0,in_len); /* * Step 3: compress from `in' to `out' with LZO1X-1 */ r = lzo1x_1_compress(in,in_len,out,&out_len,wrkmem); if (r == LZO_E_OK) printf("compressed %lu bytes into %lu bytes\n", (unsigned long) in_len, (unsigned long) out_len); else { /* this should NEVER happen */ printf("internal error - compression failed: %d\n", r); return 2; } /* check for an incompressible block */ if (out_len >= in_len) { printf("This block contains incompressible data.\n"); return 0; } /* * Step 4: decompress again, now going from `out' to `in' */ new_len = in_len; r = lzo1x_decompress(out,out_len,in,&new_len,NULL); if (r == LZO_E_OK && new_len == in_len) printf("decompressed %lu bytes back into %lu bytes\n", (unsigned long) out_len, (unsigned long) in_len); else { /* this should NEVER happen */ printf("internal error - decompression failed: %d\n", r); return 1; } printf("\nminiLZO simple compression test passed.\n"); return 0; } /* vi:ts=4:et */ bcmatroska2-5.3.101/libmatroska2/test/000077500000000000000000000000001462133141200174375ustar00rootroot00000000000000bcmatroska2-5.3.101/libmatroska2/test/mkvtree.c000066400000000000000000000271531462133141200212700ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2008-2010, Matroska Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #define CONFIG_EBML_UNICODE #include "matroska/matroska.h" #include "mkvtree_stdafx.h" static int ShowPos = 0; #ifdef TARGET_WIN #include void DebugMessage(const tchar_t* Msg,...) { #if !defined(NDEBUG) || defined(LOGFILE) || defined(LOGTIME) va_list Args; tchar_t Buffer[1024],*s=Buffer; va_start(Args,Msg); vstprintf_s(Buffer,TSIZEOF(Buffer), Msg, Args); va_end(Args); tcscat_s(Buffer,TSIZEOF(Buffer),T("\r\n")); #endif #ifdef LOGTIME { tchar_t timed[1024]; SysTickToString(timed,TSIZEOF(timed),GetTimeTick(),1,1,0); stcatprintf_s(timed,TSIZEOF(timed),T(" %s"),s); s = timed; } #endif #if !defined(NDEBUG) OutputDebugString(s); #endif #if defined(LOGFILE) { static FILE* f=NULL; static char s8[1024]; size_t i; if (!f) #if defined(TARGET_WINCE) { tchar_t DocPath[MAXPATH]; char LogPath[MAXPATH]; charconv *ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); GetDocumentPath(NULL,DocPath,TSIZEOF(DocPath),FTYPE_LOG); // more visible via ActiveSync if (!DocPath[0]) tcscpy_s(DocPath,TSIZEOF(DocPath),T("\\My Documents")); if (!PathIsFolder(NULL,DocPath)) FolderCreate(NULL,DocPath); tcscat_s(DocPath,TSIZEOF(DocPath),T("\\corelog.txt")); CharConvST(ToStr,LogPath,sizeof(LogPath),DocPath); CharConvClose(ToStr); f=fopen(LogPath,"a+b"); if (!f) f=fopen("\\corelog.txt","a+b"); } #else f=fopen("\\corelog.txt","a+b"); #endif for (i=0;s[i];++i) s8[i]=(char)s[i]; s8[i]=0; fputs(s8,f); fflush(f); } #endif } #endif static void EndLine(ebml_element *Element) { if (ShowPos && EBML_ElementPosition(Element)!=INVALID_FILEPOS_T) fprintf(stdout," at %"PRId64"\r\n",EBML_ElementPosition(Element)); else fprintf(stdout,"\r\n"); } static ebml_element *OutputElement(ebml_element *Element, const ebml_parser_context *Context, stream *Input, int *Level) { int LevelPrint; for (LevelPrint=0;LevelPrint<*Level;++LevelPrint) fprintf(stdout,"+ "); fprintf(stdout,"%s: ", EBML_ElementGetClassName(Element)); if (Node_IsPartOf(Element,EBML_MASTER_CLASS)) { int UpperElement = 0; ebml_element *SubElement,*NewElement; ebml_parser_context SubContext; if (EBML_ElementDataSize(Element, 1) == INVALID_FILEPOS_T) fprintf(stdout,"(master)"); else if (!EBML_ElementIsFiniteSize(Element)) fprintf(stdout,"(master) [unknown size]",EBML_ElementDataSize(Element, 1)); else fprintf(stdout,"(master) [%"PRId64" bytes]",EBML_ElementDataSize(Element, 1)); EndLine(Element); SubContext.UpContext = Context; SubContext.Context = EBML_ElementContext(Element); SubContext.EndPosition = EBML_ElementPositionEnd(Element); SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, 1); while (SubElement != NULL && UpperElement<=0 && (!EBML_ElementIsFiniteSize(Element) || EBML_ElementPosition(SubElement) <= EBML_ElementPositionEnd(Element))) { // a sub element == not higher level and contained inside the current element (*Level)++; NewElement = OutputElement(SubElement, &SubContext, Input, Level); NodeDelete((node*)SubElement); if (NewElement) SubElement = NewElement; else SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, 1); (*Level)--; if (UpperElement < 0) *Level += UpperElement; else if (UpperElement != 0 && *Level>0) *Level -= UpperElement-1; } return SubElement; //EBML_ElementSkipData(Element, Input, Element->Context, NULL, 0); } else if (Node_IsPartOf(Element,EBML_STRING_CLASS) || Node_IsPartOf(Element,EBML_UNISTRING_CLASS)) { //tchar_t UnicodeString[MAXDATA]; //EBML_StringRead((ebml_string*)Element,Input,UnicodeString,TSIZEOF(UnicodeString)); if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA,0)==ERR_NONE) { tchar_t String[MAXDATA]; char cString[MAXDATA]; EBML_StringGet((ebml_string*)Element, String, TSIZEOF(String)); Node_ToUTF8(Element, cString, sizeof(cString), String); fprintf(stdout,"'%s'",cString); } else fprintf(stdout,""); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_DATE_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA,0)==ERR_NONE) { datepack_t Date; datetime_t DateTime = EBML_DateTime((ebml_date*)Element); GetDatePacked(DateTime,&Date,1); fprintf(stdout,"%04d-%02d-%02d %02d:%02d:%02d UTC",Date.Year,Date.Month,Date.Day,Date.Hour,Date.Minute,Date.Second); } else fprintf(stdout,""); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_INTEGER_CLASS) || Node_IsPartOf(Element,EBML_SINTEGER_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA,0)==ERR_NONE) { if (Node_IsPartOf(Element,EBML_SINTEGER_CLASS)) fprintf(stdout,"%"PRId64,EBML_IntegerValue((ebml_integer*)Element)); else fprintf(stdout,"%"PRIu64,EBML_IntegerValue((ebml_integer*)Element)); } else fprintf(stdout,""); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_FLOAT_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_ALL_DATA,0)==ERR_NONE) fprintf(stdout,"%f",EBML_FloatValue((ebml_float*)Element)); else fprintf(stdout,""); EndLine(Element); } else if (EBML_ElementIsDummy(Element)) { fprintf(stdout,"[%X] [%"PRId64" bytes]",EBML_ElementClassID(Element),EBML_ElementDataSize(Element, 1)); EBML_ElementSkipData(Element, Input, Context, NULL, 0); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_BINARY_CLASS)) { if (EBML_ElementReadData(Element,Input,NULL,0,SCOPE_PARTIAL_DATA,0)==ERR_NONE) { const uint8_t *Data = EBML_BinaryGetData((ebml_binary*)Element); if (EBML_ElementDataSize(Element, 1) != 0) { if (Data==NULL) fprintf(stdout,"[data too large] (%"PRId64")",EBML_ElementDataSize(Element, 1)); else if (EBML_ElementDataSize(Element, 1) == 1) fprintf(stdout,"%02X (%"PRId64")",Data[0],EBML_ElementDataSize(Element, 1)); else if (EBML_ElementDataSize(Element, 1) == 2) fprintf(stdout,"%02X %02X (%"PRId64")",Data[0],Data[1],EBML_ElementDataSize(Element, 1)); else if (EBML_ElementDataSize(Element, 1) == 3) fprintf(stdout,"%02X %02X %02X (%"PRId64")",Data[0],Data[1],Data[2],EBML_ElementDataSize(Element, 1)); else if (EBML_ElementDataSize(Element, 1) == 4) fprintf(stdout,"%02X %02X %02X %02X (%"PRId64")",Data[0],Data[1],Data[2],Data[3],EBML_ElementDataSize(Element, 1)); else fprintf(stdout,"%02X %02X %02X %02X.. (%"PRId64")",Data[0],Data[1],Data[2],Data[3],EBML_ElementDataSize(Element, 1)); } } else fprintf(stdout,""); EBML_ElementSkipData(Element, Input, Context, NULL, 0); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_VOID_CLASS)) { fprintf(stdout,"[%"PRId64" bytes]",EBML_ElementDataSize(Element, 1)); EBML_ElementSkipData(Element, Input, Context, NULL, 0); EndLine(Element); } else if (Node_IsPartOf(Element,EBML_CRC_CLASS)) { // TODO: handle crc32 fprintf(stdout,"[%"PRId64" bytes]",EBML_ElementDataSize(Element, 1)); EBML_ElementSkipData(Element, Input, Context, NULL, 0); EndLine(Element); } else { #ifdef IS_BIG_ENDIAN fprintf(stdout,"\r\n",Element->Context->Id); #else fourcc_t Id = EBML_ElementClassID(Element); fprintf(stdout,">= 8; } fprintf(stdout,">",EBML_ElementClassID(Element)); #endif EBML_ElementSkipData(Element, Input, Context, NULL, 0); EndLine(Element); } return NULL; } static void OutputTree(stream *Input) { ebml_element *Element = EBML_ElementCreate(Input,&MATROSKA_ContextStream,0,NULL); if (Element) { int Level = -1; EBML_ElementSetInfiniteSize(Element,1); OutputElement(Element, NULL, Input, &Level); NodeDelete((node*)Element); } } int main(int argc, const char *argv[]) { #if defined(CONFIG_EBML_UNICODE) parsercontext p; #else nodecontext p; #endif stream *Input; tchar_t Path[MAXPATHFULL]; if ((argc!=2 && argc!=3) || (argc==3 && strcmp(argv[1],"--pos"))) { fprintf(stderr, "Usage: mkvtree --pos [matroska_file]\r\n"); fprintf(stderr, "Options:\r\n"); fprintf(stderr, " --pos output the position of elements\r\n"); return 1; } if (argc==3) ShowPos = 1; // Core-C init phase #if defined(CONFIG_EBML_UNICODE) ParserContext_Init(&p,NULL,NULL,NULL); #else NodeContext_Init(&p,NULL,NULL,NULL); #endif StdAfx_Init((nodemodule*)&p); // EBML & Matroska Init MATROSKA_Init((nodecontext*)&p); // open the file to parse Node_FromStr(&p,Path,TSIZEOF(Path),argv[argc-1]); Input = StreamOpen(&p,Path,SFLAG_RDONLY/*|SFLAG_BUFFERED*/); if (Input == NULL) fprintf(stderr, "error: mkvtree cannot open file \"%s\"\r\n",argv[1]); else { OutputTree(Input); StreamClose(Input); } // EBML & Matroska ending MATROSKA_Done((nodecontext*)&p); // Core-C ending StdAfx_Done((nodemodule*)&p); #if defined(CONFIG_EBML_UNICODE) ParserContext_Done(&p); #else NodeContext_Done(&p); #endif return 0; } bcmatroska2-5.3.101/libmatroska2/test/test.proj000066400000000000000000000001251462133141200213100ustar00rootroot00000000000000CON mkvtree { USE matroska2 SOURCE mkvtree.c } GROUP mkvtests { USE mkvtree } bcmatroska2-5.3.101/mkclean/000077500000000000000000000000001462133141200155005ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/ChangeLog.txt000066400000000000000000000252251462133141200200760ustar00rootroot000000000000002012-xx-xx version 0.8.8: - add support for Matroska v4 elements like CueDuration and CueRelativePosition 2012-08-26 version 0.8.7: - handle non-latin command-line characters on windows 2011-09-25 version 0.8.6: - correct DisplayUnit that appears to be in pixels but marked as Display Aspect Ratio (DAR) 2011-08-15 version 0.8.5: - fix the recompression of the CodecPrivate through successive mkclean calls 2011-07-10 version 0.8.4: - fix the keyframe detection for WebM alt-ref frames (0 duration = non keyframe) 2011-06-02 version 0.8.3: - fix the Segment duration when using --timecodescale - fix the progress display on segments with no size set (like live streams) - add -alt-3d to pack video frames by 2 when left/right eyes are coded sequentially in time (half duration frames) 2011-04-03 version 0.8.2: - add support for Codec Private zlib compression with --optimize (for Vorbis) - add support for zlib compression of A_PCM and V_UNCOMPRESS tracks when --optimize is set - fix a bogus aspect ratio fix - use the generated semantic for libmatroska2 (no more mismatch with the specs) 2011-03-13 version 0.8.1: - turn old StereoMode values into the Matroska v3 ones - remove the ClusterPosition field in WebM files as it's not supported 2011-03-06 version 0.8.0: - add support for Matroska v3 - fix some odd case where some file other than the bogus output file would be deleted after an error - add more padding after the SeekHead to make room for links to chapters/tags/attachments/others and/or editing - add a link to the first Cluster in the Seek Head 2010-12-19 version 0.7.3: - add --optimize_nv to use header stripping where possible except video tracks (for some hardware) 2010-12-12 version 0.7.2: - discard --optimize for WebM 2010-11-21 version 0.7.1: - fix the regression test check on large files - fix the cues when blocks could not be read and written in the output - fix the timecodes when --optimize and --timecodescale are used - fix in libebml2 not to read data too far in a bogus EBML master - the regression tests pass under Linux too - add a --quiet option for the regression tests to disable mkvalidator error display 2010-11-14 version 0.7.0: - fix an incorrect element size computing when invalid data was read - allow StereoMode for WebM - adjust the timecodescale automatically if it's too small - fix AC-3 duration detection issues when remuxing - better handling of default/mandatory values - internal code shuffling - make the regression test tool compile under UNIX 2010-11-01 version 0.6.1: - add a progress phase during the cue creation as it's sometimes slow - safer handling of broken files - fix EBML reading on big endian processors (PowerPC) - add a regression test tool (needs mkvalidator too) - fix a wrong warning on files with only 1 Cluster - fix some errors when the source mkv was truncated at the end 2010-09-26 version 0.6.0: - fix a size update issue with the new "smarter" system - don't delete the mkclean binary if it's run with no parameter - put the attachments before the Cue entries (index) - put cover.jpg/cover.png at the front of attachments - support bz2 and lzo1x track reading (transformed to zlib when writing) - make sure cluster timecodes are always incrementing - add --regression to output files that can used for comparison in regression tests - fix OS X building (gcc_osx_x86 and xcode_x86) - fix float handling on some systems (thanks Monty) 2010-09-14 version 0.5.7: - fix a problem with attachments in safe mode (--unsafe not set) - put the attachments at the front as it usually makes more sense (fonts or cover art) 2010-09-02 version 0.5.6: - fix a major memory leak that could result in unexpected errors with large file - fix the UNIX source package 2010-08-22 version 0.5.5: - fix a timecode bug when --timecodescale was specified on input - improve the recovery of damaged files - fix command line errors when --doctype x was used as the last param - delete the output file in case the output file didn't finish correctly - add a timecode offset to files created with --live as live streams usually don't start at 0 - write some junk before the first cluster in --live mode, like a dumb server would do - fix the PrevSize computing in the --live mode - fix cleaning of files that had infinite sizes (live streams) 2010-08-17 version 0.5.4: - fix a potential use of free'd memory when using the --optimize mode with --remux 2010-08-16 version 0.5.3: - write CRC-32 elements on key parts for better file safety (not in unsafe mode) - don't write a Cue if there is only one Cluster 2010-08-08 version 0.5.2: - fix the use of file use in the command line - don't allow source video tracks with 0 pixel values - fix a bug/crash when moving a whole Block to the next Cluster - fix a crash when handling files with CRC (like AviMux GUI files) 2010-08-02 version 0.5.1: - fix an issue when fixing aspect ratio that only had one value (width or height) set 2010-08-02 version 0.5.0: - prepend the output filename with "clean." if no output filename is specified - fix a bug when header compression was used but not lacing - add a --no-optimize option to forbid track compression - add a mkWDclean tool to remove the track compression from the output files 2010-08-01 version 0.4.6: - remove bad cropping values - fix some potential issues when EBML lacing and header stripping was combined - support zlib compressed input and output tracks - don't try to strip headers of track with zlib compression or encryption - force zlib compression for a set of codecs (S_USF, S_VOBSUB, S_HDMV/PGS, B_VOBBTN) in --optimize mode 2010-07-25 version 0.4.5: - fix --remux when BlockGroup was encountered (rather than SimpleBlock) - fix --optimize on video tracks 2010-07-25 version 0.4.4: - fix a possible infinite loop when only --optimize was used - fix a potential timecode issue at the cluster boundaries 2010-07-19 version 0.4.3: - fix a bug in the segment size when a placeholder was added for later tag reference - reject files that don't have an EBML header - add --help and --version CLI options - put the timecodescale first in the segment info, put the duration just after - fix the amount of phases displayed 2010-07-17 version 0.4.2: - use DAR aspect ratio when pixels are not accurate enough - bootstrap.sh should now call the correct coremake config depending on the host platform - rename boostrap.sh to configure - avoid crashing with files that have no TrackInfo - read and skip custome elements rather than discarding (could result in corruption) - avoid a possible output corruption when the Segment size is much smaller than the original - fix the AppWriting string when there was no library in the source file - don't keep elements that are not valid for the output profile - check that track attachment links point to valid attachments and remove the invalid ones 2010-07-04 version 0.4.1: - fix a possible data corruption when optimizing blocks - add a --quiet option to only output errors - keep the discardable flag as-is when reclustering - fix the --timecodescale handling 2010-07-03 version 0.4.0: - allow using compressed headers (with --optimize) automatically picking the best size - delete CRC-32 elements until we can update them correctly - display the 64 bits integers correctly on all platforms - write the Cluster PrevSize and position in the Segment by default (can be disabled with --unsafe) - reserve a place after the SeekHead for a reference to Tags when they are not there (for easy editing) - make sure audio/subtitles frames are all keyframes (no known codec so far are not) - make sure the lacing flag in the track info matches what is used in the file - clean Haali's style aspect ratio (16/9 instead of the pixel values) - remove values that are the same as their (indirect) default values (like DisplayWidth/DisplayHeight and OutputSamplingFreq) - put the TrackNumber, TrackType and CodecId at the front of the Track elements 2010-06-11 version 0.3.1: - output an error when the remuxing is not possible due to a low TimecodeScale (thanks to Ben Danper) - add a --timecodescale option to force the global timecodescale 2010-06-09 version 0.3.0: - always put the matching audio frames before the video frames - do a "relacing" when remuxing to put audio frames close to the corresponding video keyframes (not all audio codecs are supported) for Vorbis (via Tremor), MP3, AC3, E-AC3, AAC, DTS 2010-05-27 version 0.2.5: - make sure only V_VP8 and A_VORBIS tracks are kept for webm - disable writing webm v1 (--doctype 3) - fix some default values in chapters - fix reading of elements with unknown/infinite sizes 2010-05-22 version 0.2.4: - in --live mode the Cluster also have an infinite/unknown size - remove the Cluster duration from the --live mode 2010-05-21 version 0.2.3: - add a --live option to create ouptut files that look like a live stream (not seekable) - do not write ClusterPosition and PrevSize (until we support it) - do not silently force a doctype change, but tell the user the CLI to use 2010-05-20 version 0.2.2: - unobfuscate the 'webm' and 'V_VP8' strings - fix a crash when reading Sorenson Squeeze files (Ebml Void in the header) 2010-05-18 version 0.2.1: - add an option to change the DocType name/version (no validity check) - put the (re)muxing date in the file (or if there was no date) 2010-05-17 version 0.2.0: - add an option to remux files with better Cluster boundaries - enforce mandatory elements are always (virtually) there - remove Master elements that are missing mandatory elements and are not unique in the context 2010-05-13 version 0.1.5: - create Cues from scratch - add a "--keep-cues" option to keep the original Cues instead of creating from scratch 2010-05-10 version 0.1.4: - Allow files with no Track/Clusters (a file with only "logical" chapters is possible) 2010-05-05 version 0.1.3: - By default build with support for large files (>4GB) - Sort the Cue entries - Optimize the Cue/Block linking speed by starting from, the previous matching Cluster found 2010-05-04 version 0.1.2: - Fix the wrong EBML header in release builds (doh!) version 0.1.1: - Fix the Seek Head computing mismatch for large files - Add a progress info during the cleaning (in 3 phases) 2010-05-04 version 0.1.0: - Initial public release bcmatroska2-5.3.101/mkclean/ReadMe.txt000066400000000000000000000030441462133141200173770ustar00rootroot00000000000000mkclean is a command line tool to clean and optimize Matroska files that have already been muxed. It currently reorders elements in an optimum way for local and web use. It also removes elements not found in the Matroska specs and the extra Meta Seek list of Clusters that some program add to their file. ** LICENSE ** The program is licensed with the BSD license. So you can modify it in any way you want. However we ask that you generously give back your enhancements to the community if you think it can help. Contact: slhomme@matroska.org mkclean depends on libebml2 (BSD) and libmatroska2 (BSD) that themselves rely on Core-C (BSD) which adds an object API on top of the C language. ** BUILDING ** To build mkclean you have to build coremake first: You can either run ./configure on Linux/OS X or - Just compile /corec/tools/coremake/coremake.c with your C compiler. - run coremake from the root of the source : * "coremake.exe vs9_win32" to generate the project files for Visual Studio 2008 * "coremake gcc_linux" to generate the project files for GNU make building with gcc * "coremake gcc_linux_x64" for GNU make building with gcc on Linux 64 bits * "coremake xcode_uni" to generate the project files for XCode for a universal OS X binary * look in the coremake folder for all the platforms supported The Makefile/mkclean.sln will end up in the mkclean folder. You just have to build from there and it will create mkclean(.exe) under /release/ To delete all the project files run "coremake(.exe) clean" from the root of the sources. bcmatroska2-5.3.101/mkclean/configure000066400000000000000000000004561462133141200174110ustar00rootroot00000000000000#!/bin/sh %%BEGIN SCRIPT %%END make -s -C corec/tools/coremake mv -f corec/tools/coremake/coremake . coremake_param=`corec/tools/coremake/system_output.sh` echo "Running ./coremake" $coremake_param ./coremake $coremake_param echo "Now you can run make -C %(PROJECT_NAME) or gmake -C %(PROJECT_NAME)"bcmatroska2-5.3.101/mkclean/default_config.h000066400000000000000000000006601462133141200206240ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE #define CONFIG_EBML_WRITING #undef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #define HAVE_EBML2 #define CONFIG_MATROSKA2 #define CONFIG_ZLIB #define CONFIG_LZO1X #define CONFIG_BZLIB #define USE_PRECOMPILED_HEADERS #define CONFIG_DEBUGCHECKS #define CONFIG_STDIO #define CONFIG_FILEPOS_64 #define CONFIG_CODEC_HELPER #define COREMAKE_CONFIG_HELPER //#define CONFIG_DEBUG_LEAKS bcmatroska2-5.3.101/mkclean/mkclean.c000066400000000000000000003746041462133141200172740ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010-2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mkclean_stdafx.h" #include "mkclean_project.h" #ifndef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #endif #include "matroska/matroska.h" #include "matroska/matroska_sem.h" /*! * \todo write the CRC-32 on Clusters too (make it faster in libebml2) * \todo discards tracks that has the same UID * \todo remuxing: turn a BlockGroup into a SimpleBlock in v2 profiles and when it makes sense (duration = default track duration) (optimize mode) * \todo error when an unknown codec (for the profile) is found (option to turn into a warning) (loose mode) * \todo compute the segment duration based on audio (when it's not set) * \todo remuxing: repack audio frames using lacing (no longer than the matching video frame ?) (optimize mode) * \todo compute the track default duration (when it's not set or not optimal) (optimize mode) * \todo add a batch mode to treat more than one file at once * \todo get the file name/list to treat from stdin too * \todo add an option to remove the original file * \todo add an option to rename the output to the original file * \todo add an option to show the size gained/added compared to the original * \todo support the japanese translation * * less important: * \todo (optionally) change the Segment UID (when key parts are altered/added) * \todo force keeping some forbidden elements in a profile (chapters/tags in 'webm') (loose mode) * \todo add an option to cut short a file with a start/end * \todo allow creating/replacing Tags * \todo allow creating/replacing Chapters * \todo allow creating/replacing Attachments */ #ifdef TARGET_WIN #include void DebugMessage(const tchar_t* Msg,...) { #if !defined(NDEBUG) || defined(LOGFILE) || defined(LOGTIME) va_list Args; tchar_t Buffer[1024],*s=Buffer; va_start(Args,Msg); vstprintf_s(Buffer,TSIZEOF(Buffer), Msg, Args); va_end(Args); tcscat_s(Buffer,TSIZEOF(Buffer),T("\r\n")); #endif #ifdef LOGTIME { tchar_t timed[1024]; SysTickToString(timed,TSIZEOF(timed),GetTimeTick(),1,1,0); stcatprintf_s(timed,TSIZEOF(timed),T(" %s"),s); s = timed; } #endif #if !defined(NDEBUG) OutputDebugString(s); #endif #if defined(LOGFILE) { static FILE* f=NULL; static char s8[1024]; size_t i; if (!f) #if defined(TARGET_WINCE) { tchar_t DocPath[MAXPATH]; char LogPath[MAXPATH]; charconv *ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); GetDocumentPath(NULL,DocPath,TSIZEOF(DocPath),FTYPE_LOG); // more visible via ActiveSync if (!DocPath[0]) tcscpy_s(DocPath,TSIZEOF(DocPath),T("\\My Documents")); if (!PathIsFolder(NULL,DocPath)) FolderCreate(NULL,DocPath); tcscat_s(DocPath,TSIZEOF(DocPath),T("\\corelog.txt")); CharConvST(ToStr,LogPath,sizeof(LogPath),DocPath); CharConvClose(ToStr); f=fopen(LogPath,"a+b"); if (!f) f=fopen("\\corelog.txt","a+b"); } #else f=fopen("\\corelog.txt","a+b"); #endif for (i=0;s[i];++i) s8[i]=(char)s[i]; s8[i]=0; fputs(s8,f); fflush(f); } #endif } #endif #define EXTRA_SEEK_SPACE 22 #define MARKER3D (block_info*)1 typedef struct block_info { matroska_block *Block; timecode_t DecodeTime; size_t FrameStartIndex; } block_info; #define TABLE_MARKER (uint8_t*)1 typedef struct track_info { bool_t IsLaced; // bool_t NeedsReading; } track_info; static const tchar_t *GetProfileName(size_t ProfileNum) { static const tchar_t *Profile[7] = {T("unknown"), T("matroska v1"), T("matroska v2"), T("matroska v3"), T("webm"), T("matroska+DivX"), T("matroska v4")}; switch (ProfileNum) { default: return Profile[0]; case PROFILE_MATROSKA_V1: return Profile[1]; case PROFILE_MATROSKA_V2: return Profile[2]; case PROFILE_MATROSKA_V3: return Profile[3]; case PROFILE_WEBM: return Profile[4]; case PROFILE_DIVX: return Profile[5]; case PROFILE_MATROSKA_V4: return Profile[6]; } } static int GetProfileId(int Profile) { switch (Profile) { default: return 0; case PROFILE_MATROSKA_V1: return 1; case PROFILE_MATROSKA_V2: return 2; case PROFILE_MATROSKA_V3: return 3; case PROFILE_WEBM: return 4; case PROFILE_DIVX: return 5; case PROFILE_MATROSKA_V4: return 6; } } static int DocVersion = 1; static int SrcProfile = 0, DstProfile = 0; static textwriter *StdErr = NULL; static size_t ExtraSizeDiff = 0; static bool_t Quiet = 0; static bool_t Unsafe = 0; static bool_t Live = 0; static int TotalPhases = 2; static int CurrentPhase = 1; static bool_t MasterError(void *cookie, int type, const tchar_t *ClassName, const ebml_element *i) { tchar_t IdString[MAXPATH]; if (type==MASTER_CHECK_PROFILE_INVALID) { EBML_ElementGetName(i,IdString,TSIZEOF(IdString)); TextPrintf(StdErr,T("The %s element at %") TPRId64 T(" is not part of profile '%s', skipping\r\n"),IdString,EBML_ElementPosition(i),GetProfileName(DstProfile)); } else if (type==MASTER_CHECK_MULTIPLE_UNIQUE) { EBML_ElementGetName(i,IdString,TSIZEOF(IdString)); TextPrintf(StdErr,T("The %s element at %") TPRId64 T(" has multiple versions of the unique element %s, skipping\r\n"),IdString,EBML_ElementPosition(i),ClassName); } else if (type==MASTER_CHECK_MISSING_MANDATORY) { EBML_ElementGetName(cookie,IdString,TSIZEOF(IdString)); TextPrintf(StdErr,T("The %s element at %") TPRId64 T(" is missing mandatory element %s\r\n"),IdString,EBML_ElementPosition(cookie),ClassName); } return 1; } static void ReduceSize(ebml_element *Element) { EBML_ElementSetSizeLength(Element, 0); // reset if (Node_IsPartOf(Element,EBML_MASTER_CLASS)) { ebml_element *i, *j; if (Unsafe) EBML_MasterUseChecksum((ebml_master*)Element,0); if (EBML_ElementIsType(Element, &MATROSKA_ContextBlockGroup) && !EBML_MasterCheckMandatory((ebml_master*)Element, 0)) { NodeDelete((node*)Element); return; } for (i=EBML_MasterChildren(Element);i;i=j) { j = EBML_MasterNext(i); if (Node_IsPartOf(i, EBML_VOID_CLASS)) { NodeDelete((node*)i); continue; } else if (Node_IsPartOf(i, EBML_DUMMY_ID)) { NodeDelete((node*)i); continue; } else if (EBML_ElementIsType(i, &EBML_ContextEbmlCrc32)) { NodeDelete((node*)i); continue; } ReduceSize(i); } if (!EBML_MasterChildren(Element) && !EBML_MasterCheckMandatory((ebml_master*)Element, 0)) { NodeDelete((node*)Element); return; } EBML_MasterAddMandatory((ebml_master*)Element,1); EBML_MasterCheckContext((ebml_master*)Element, DstProfile, MasterError, Element); } } static bool_t ReadClusterData(ebml_master *Cluster, stream *Input) { bool_t Changed = 0; err_t Result = ERR_NONE; ebml_element *Block, *GBlock, *NextBlock; // read all the Block/SimpleBlock data for (Block = EBML_MasterChildren(Cluster);Block;Block=NextBlock) { NextBlock = EBML_MasterNext(Block); if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Block);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { if ((Result = MATROSKA_BlockReadData((matroska_block*)GBlock, Input))!=ERR_NONE) { Changed = 1; NodeDelete((node*)Block); } break; } } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { if ((Result = MATROSKA_BlockReadData((matroska_block*)Block, Input))!=ERR_NONE) { Changed = 1; NodeDelete((node*)Block); } } } return Changed; } static err_t UnReadClusterData(ebml_master *Cluster, bool_t IncludingNotRead) { err_t Result = ERR_NONE; ebml_element *Block, *GBlock; for (Block = EBML_MasterChildren(Cluster);Result==ERR_NONE && Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Block);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EBML_ElementIsType(GBlock, &MATROSKA_ContextBlock)) { Result = MATROSKA_BlockReleaseData((matroska_block*)GBlock,IncludingNotRead); break; } } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) Result = MATROSKA_BlockReleaseData((matroska_block*)Block,IncludingNotRead); } return Result; } static void SetClusterPrevSize(array *Clusters, stream *Input) { ebml_master **Cluster; ebml_element *Elt, *Elt2; filepos_t ClusterSize = INVALID_FILEPOS_T; // Write the Cluster PrevSize for (Cluster = ARRAYBEGIN(*Clusters,ebml_master*);Cluster != ARRAYEND(*Clusters,ebml_master*); ++Cluster) { if (Input!=NULL) ReadClusterData(*Cluster,Input); if (ClusterSize != INVALID_FILEPOS_T) { Elt = EBML_MasterGetChild(*Cluster, &MATROSKA_ContextPrevSize); if (Elt) { EBML_IntegerSetValue((ebml_integer*)Elt, ClusterSize); Elt2 = EBML_MasterFindChild(*Cluster, &MATROSKA_ContextTimecode); if (Elt2) NodeTree_SetParent(Elt,*Cluster,NodeTree_Next(Elt2)); ExtraSizeDiff += (size_t)EBML_ElementFullSize(Elt,0); EBML_ElementUpdateSize(*Cluster,0,1); } } else EBML_ElementUpdateSize(*Cluster,0,1); EBML_ElementSetInfiniteSize((ebml_element*)*Cluster,Live); ClusterSize = EBML_ElementFullSize((ebml_element*)*Cluster,0); if (Input!=NULL) UnReadClusterData(*Cluster, 0); } } static void UpdateCues(ebml_master *Cues, ebml_master *Segment) { ebml_master *Cue,*NextCue; // reevaluate the size needed for the Cues for (Cue=(ebml_master*)EBML_MasterChildren(Cues);Cue;Cue=NextCue) { NextCue =(ebml_master*)EBML_MasterNext(Cue); if (MATROSKA_CuePointUpdate((matroska_cuepoint*)Cue, (ebml_element*)Segment)!=ERR_NONE) { EBML_MasterRemove(Cues,(ebml_element*)Cue); // make sure it doesn't remain in the list NodeDelete((node*)Cue); } } } static void SettleClustersWithCues(array *Clusters, filepos_t ClusterStart, ebml_master *Cues, ebml_master *Segment, bool_t SafeClusters, stream *Input) { ebml_element *Elt, *Elt2; ebml_master **Cluster; filepos_t OriginalSize = EBML_ElementDataSize((ebml_element*)Cues,0); filepos_t ClusterPos = ClusterStart + EBML_ElementFullSize((ebml_element*)Cues,0); filepos_t ClusterSize = INVALID_FILEPOS_T; // reposition all the Clusters for (Cluster=ARRAYBEGIN(*Clusters,ebml_master*);Cluster!=ARRAYEND(*Clusters,ebml_master*);++Cluster) { if (Input!=NULL) ReadClusterData(*Cluster,Input); EBML_ElementForcePosition((ebml_element*)*Cluster, ClusterPos); if (SafeClusters) { Elt = NULL; if (ClusterSize != INVALID_FILEPOS_T) { Elt = EBML_MasterGetChild(*Cluster, &MATROSKA_ContextPrevSize); if (Elt) { EBML_IntegerSetValue((ebml_integer*)Elt, ClusterSize); Elt2 = EBML_MasterFindChild(*Cluster, &MATROSKA_ContextTimecode); if (Elt2) NodeTree_SetParent(Elt,*Cluster,NodeTree_Next(Elt2)); // make sure the PrevSize is just after the ClusterTimecode ExtraSizeDiff += (size_t)EBML_ElementFullSize(Elt,0); } } // output the Cluster position as well if (Elt) Elt2 = Elt; // make sure the Cluster Position is just after the PrevSize else Elt2 = EBML_MasterFindChild(*Cluster, &MATROSKA_ContextTimecode); // make sure the Cluster Position is just after the ClusterTimecode if (Elt2 && DstProfile!=PROFILE_WEBM) { Elt = EBML_MasterGetChild(*Cluster, &MATROSKA_ContextPosition); if (Elt) { EBML_IntegerSetValue((ebml_integer*)Elt, ClusterPos - EBML_ElementPositionData((ebml_element*)Segment)); NodeTree_SetParent(Elt,*Cluster,NodeTree_Next(Elt2)); ExtraSizeDiff += (size_t)EBML_ElementFullSize(Elt,0); } } } EBML_ElementUpdateSize(*Cluster,0,0); ClusterSize = EBML_ElementFullSize((ebml_element*)*Cluster,0); ClusterPos += ClusterSize; if (Input!=NULL) UnReadClusterData(*Cluster, 0); } UpdateCues(Cues, Segment); ClusterPos = EBML_ElementUpdateSize(Cues,0,0); if (ClusterPos != OriginalSize) SettleClustersWithCues(Clusters,ClusterStart,Cues,Segment, SafeClusters, Input); } static void ShowProgress(const ebml_element *RCluster, filepos_t TotalSize) { if (!Quiet) TextPrintf(StdErr,T("Progress %d/%d: %3d%%\r"), CurrentPhase, TotalPhases,Scale32(100,EBML_ElementPosition(RCluster),TotalSize)+1); } static void EndProgress() { if (!Quiet) TextPrintf(StdErr,T("Progress %d/%d: 100%%\r\n"), CurrentPhase, TotalPhases); } static matroska_cluster **LinkCueCluster(matroska_cuepoint *Cue, array *Clusters, matroska_cluster **StartCluster, filepos_t TotalSize) { matroska_cluster **Cluster; matroska_block *Block; int16_t CueTrack; timecode_t CueTimecode; size_t StartBoost = 7; CueTrack = MATROSKA_CueTrackNum(Cue); CueTimecode = MATROSKA_CueTimecode(Cue); ++CurrentPhase; if (StartCluster) { for (Cluster=StartCluster;StartBoost && Cluster!=ARRAYEND(*Clusters,matroska_cluster*);++Cluster,--StartBoost) { Block = MATROSKA_GetBlockForTimecode(*Cluster, CueTimecode, CueTrack); if (Block) { MATROSKA_LinkCuePointBlock(Cue,Block); ShowProgress((ebml_element*)(*Cluster),TotalSize); return Cluster; } } } for (Cluster=ARRAYBEGIN(*Clusters,matroska_cluster*);Cluster!=ARRAYEND(*Clusters,matroska_cluster*);++Cluster) { Block = MATROSKA_GetBlockForTimecode(*Cluster, CueTimecode, CueTrack); if (Block) { MATROSKA_LinkCuePointBlock(Cue,Block); ShowProgress((ebml_element*)(*Cluster),TotalSize); return Cluster; } } TextPrintf(StdErr,T("Could not find the matching block for timecode %0.3f s\r\n"),CueTimecode/1000000000.0); return NULL; } static int LinkClusters(array *Clusters, ebml_master *RSegmentInfo, ebml_master *Tracks, int DstProfile, array *WTracks, timecode_t Offset) { matroska_cluster **Cluster; ebml_element *Block, *GBlock, *BlockTrack, *Type; ebml_integer *Time; int BlockNum; // find out if the Clusters use forbidden features for that DstProfile if (DstProfile == PROFILE_MATROSKA_V1 || DstProfile == PROFILE_DIVX) { for (Cluster=ARRAYBEGIN(*Clusters,matroska_cluster*);Cluster!=ARRAYEND(*Clusters,matroska_cluster*);++Cluster) { for (Block = EBML_MasterChildren(*Cluster);Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { TextPrintf(StdErr,T("Using SimpleBlock in profile '%s' at %") TPRId64 T(" try \"--doctype %d\"\r\n"),GetProfileName(DstProfile),EBML_ElementPosition(Block),GetProfileId(PROFILE_MATROSKA_V2)); return -32; } } } } // link each Block/SimpleBlock with its Track and SegmentInfo for (Cluster=ARRAYBEGIN(*Clusters,matroska_cluster*);Cluster!=ARRAYEND(*Clusters,matroska_cluster*);++Cluster) { if (Offset != INVALID_TIMECODE_T) { Time = (ebml_integer*)EBML_MasterGetChild((ebml_master*)*Cluster, &MATROSKA_ContextTimecode); if (Time) EBML_IntegerSetValue(Time, Offset + EBML_IntegerValue(Time)); } MATROSKA_LinkClusterBlocks(*Cluster, RSegmentInfo, Tracks, 0); ReduceSize((ebml_element*)*Cluster); } // mark all the audio/subtitle tracks as keyframes for (Cluster=ARRAYBEGIN(*Clusters,matroska_cluster*);Cluster!=ARRAYEND(*Clusters,matroska_cluster*);++Cluster) { for (Block = EBML_MasterChildren(*Cluster);Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { GBlock = EBML_MasterFindChild((ebml_master*)Block, &MATROSKA_ContextBlock); if (GBlock) { BlockTrack = MATROSKA_BlockReadTrack((matroska_block*)GBlock); if (!BlockTrack) continue; Type = EBML_MasterFindChild((ebml_master*)BlockTrack,&MATROSKA_ContextTrackType); if (!Type) continue; if (EBML_IntegerValue((ebml_integer*)Type)==TRACK_TYPE_AUDIO || EBML_IntegerValue((ebml_integer*)Type)==TRACK_TYPE_SUBTITLE) { MATROSKA_BlockSetKeyframe((matroska_block*)GBlock,1); MATROSKA_BlockSetDiscardable((matroska_block*)GBlock,0); } BlockNum = MATROSKA_BlockTrackNum((matroska_block*)GBlock); if (MATROSKA_BlockGetFrameCount((matroska_block*)GBlock)>1) ARRAYBEGIN(*WTracks,track_info)[BlockNum].IsLaced = 1; } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { BlockTrack = MATROSKA_BlockReadTrack((matroska_block *)Block); if (!BlockTrack) continue; Type = EBML_MasterFindChild((ebml_master*)BlockTrack,&MATROSKA_ContextTrackType); if (!Type) continue; if (EBML_IntegerValue((ebml_integer*)Type)==TRACK_TYPE_AUDIO || EBML_IntegerValue((ebml_integer*)Type)==TRACK_TYPE_SUBTITLE) { MATROSKA_BlockSetKeyframe((matroska_block*)Block,1); MATROSKA_BlockSetDiscardable((matroska_block*)Block,0); } BlockNum = MATROSKA_BlockTrackNum((matroska_block*)Block); if (MATROSKA_BlockGetFrameCount((matroska_block*)Block)>1) ARRAYBEGIN(*WTracks,track_info)[BlockNum].IsLaced = 1; } } } return 0; } static void OptimizeCues(ebml_master *Cues, array *Clusters, ebml_master *RSegmentInfo, filepos_t StartPos, ebml_master *WSegment, filepos_t TotalSize, bool_t ReLink, bool_t SafeClusters, stream *Input) { matroska_cluster **Cluster; matroska_cuepoint *Cue; ReduceSize((ebml_element*)Cues); if (ReLink) { // link each Cue entry to the segment for (Cue = (matroska_cuepoint*)EBML_MasterChildren(Cues);Cue;Cue=(matroska_cuepoint*)EBML_MasterNext(Cue)) MATROSKA_LinkCueSegmentInfo(Cue,RSegmentInfo); // link each Cue entry to the corresponding Block/SimpleBlock in the Cluster Cluster = NULL; for (Cue = (matroska_cuepoint*)EBML_MasterChildren(Cues);Cue;Cue=(matroska_cuepoint*)EBML_MasterNext(Cue)) Cluster = LinkCueCluster(Cue,Clusters,Cluster,TotalSize); EndProgress(); } // sort the Cues MATROSKA_CuesSort(Cues); SettleClustersWithCues(Clusters,StartPos,Cues,WSegment,SafeClusters, Input); } static ebml_element *CheckMatroskaHead(const ebml_element *Head, const ebml_parser_context *Parser, stream *Input) { ebml_parser_context SubContext; ebml_element *SubElement; int UpperElement=0; tchar_t String[MAXLINE]; SubContext.UpContext = Parser; SubContext.Context = EBML_ElementContext(Head); SubContext.EndPosition = EBML_ElementPositionEnd(Head); SubContext.Profile = Parser->Profile; SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, 1); while (SubElement) { if (EBML_ElementIsType(SubElement, &EBML_ContextReadVersion)) { if (EBML_ElementReadData(SubElement,Input,NULL,0,SCOPE_ALL_DATA,0)!=ERR_NONE) { TextPrintf(StdErr,T("Error reading\r\n")); break; } else if (EBML_IntegerValue((ebml_integer*)SubElement) > EBML_MAX_VERSION) { TextPrintf(StdErr,T("EBML Read version %") TPRId64 T(" not supported\r\n"),EBML_IntegerValue((ebml_integer*)SubElement)); break; } } else if (EBML_ElementIsType(SubElement, &EBML_ContextMaxIdLength)) { if (EBML_ElementReadData(SubElement,Input,NULL,0,SCOPE_ALL_DATA,0)!=ERR_NONE) { TextPrintf(StdErr,T("Error reading\r\n")); break; } else if (EBML_IntegerValue((ebml_integer*)SubElement) > EBML_MAX_ID) { TextPrintf(StdErr,T("EBML Max ID Length %") TPRId64 T(" not supported\r\n"),EBML_IntegerValue((ebml_integer*)SubElement)); break; } } else if (EBML_ElementIsType(SubElement, &EBML_ContextMaxSizeLength)) { if (EBML_ElementReadData(SubElement,Input,NULL,0,SCOPE_ALL_DATA,0)!=ERR_NONE) { TextPrintf(StdErr,T("Error reading\r\n")); break; } else if (EBML_IntegerValue((ebml_integer*)SubElement) > EBML_MAX_SIZE) { TextPrintf(StdErr,T("EBML Max Coded Size %") TPRId64 T(" not supported\r\n"),EBML_IntegerValue((ebml_integer*)SubElement)); break; } } else if (EBML_ElementIsType(SubElement, &EBML_ContextDocType)) { if (EBML_ElementReadData(SubElement,Input,NULL,0,SCOPE_ALL_DATA,0)!=ERR_NONE) { TextPrintf(StdErr,T("Error reading\r\n")); break; } else { EBML_StringGet((ebml_string*)SubElement,String,TSIZEOF(String)); if (tcscmp(String,T("matroska"))==0) SrcProfile = PROFILE_MATROSKA_V1; else if (tcscmp(String,T("webm"))==0) SrcProfile = PROFILE_WEBM; else { TextPrintf(StdErr,T("EBML DocType '%s' not supported\r\n"),String); break; } } } else if (EBML_ElementIsType(SubElement, &EBML_ContextDocTypeReadVersion)) { if (EBML_ElementReadData(SubElement,Input,NULL,0,SCOPE_ALL_DATA,0)!=ERR_NONE) { TextPrintf(StdErr,T("Error reading\r\n")); break; } else if (EBML_IntegerValue((ebml_integer*)SubElement) > MATROSKA_VERSION) { TextPrintf(StdErr,T("EBML Read version %") TPRId64 T(" not supported\r\n"),EBML_IntegerValue((ebml_integer*)SubElement)); break; } else DocVersion = (int)EBML_IntegerValue((ebml_integer*)SubElement); } else if (EBML_ElementIsType(SubElement, &MATROSKA_ContextSegment)) return SubElement; else EBML_ElementSkipData(SubElement,Input,NULL,NULL,0); NodeDelete((node*)SubElement); SubElement = EBML_FindNextElement(Input, &SubContext, &UpperElement, 1); } return NULL; } static bool_t WriteCluster(ebml_master *Cluster, stream *Output, stream *Input, filepos_t PrevSize, timecode_t *PrevTimecode) { filepos_t IntendedPosition = EBML_ElementPosition((ebml_element*)Cluster); ebml_element *Elt; bool_t CuesChanged = ReadClusterData(Cluster, Input); if (*PrevTimecode != INVALID_TIMECODE_T) { timecode_t OrigTimecode = MATROSKA_ClusterTimecode((matroska_cluster*)Cluster); if (*PrevTimecode >= OrigTimecode) { TextPrintf(StdErr,T("The Cluster at position %") TPRId64 T(" has the same timecode %") TPRId64 T(" as the previous cluster %") TPRId64 T(", incrementing\r\n"), EBML_ElementPosition((ebml_element*)Cluster),*PrevTimecode,OrigTimecode); MATROSKA_ClusterSetTimecode((matroska_cluster*)Cluster, *PrevTimecode + MATROSKA_ClusterTimecodeScale((matroska_cluster*)Cluster, 0)); CuesChanged = 1; } } *PrevTimecode = MATROSKA_ClusterTimecode((matroska_cluster*)Cluster); EBML_ElementRender((ebml_element*)Cluster,Output,0,0,1,NULL); UnReadClusterData(Cluster, 1); if (!Live && EBML_ElementPosition((ebml_element*)Cluster) != IntendedPosition) TextPrintf(StdErr,T("Failed to write a Cluster at the required position %") TPRId64 T(" vs %") TPRId64 T("\r\n"), EBML_ElementPosition((ebml_element*)Cluster),IntendedPosition); if (!Live && PrevSize!=INVALID_FILEPOS_T) { Elt = EBML_MasterGetChild(Cluster, &MATROSKA_ContextPrevSize); if (Elt && PrevSize!=EBML_IntegerValue((ebml_integer*)Elt)) TextPrintf(StdErr,T("The PrevSize of the Cluster at the position %") TPRId64 T(" is wrong: %") TPRId64 T(" vs %") TPRId64 T("\r\n"), EBML_ElementPosition((ebml_element*)Cluster),EBML_IntegerValue((ebml_integer*)Elt),PrevSize); } return CuesChanged; } static void MetaSeekUpdate(ebml_master *SeekHead) { matroska_seekpoint *SeekPoint; for (SeekPoint=(matroska_seekpoint*)EBML_MasterChildren(SeekHead); SeekPoint; SeekPoint=(matroska_seekpoint*)EBML_MasterNext(SeekPoint)) MATROSKA_MetaSeekUpdate(SeekPoint); EBML_ElementUpdateSize(SeekHead,0,0); } static ebml_master *GetMainTrack(ebml_master *Tracks, array *TrackOrder) { ebml_master *Track; ebml_element *Elt; int64_t TrackNum = -1; size_t *order; if (TrackOrder) order = ARRAYBEGIN(*TrackOrder,size_t); else order = NULL; // find the video (first) track for (Track = (ebml_master*)EBML_MasterFindChild(Tracks,&MATROSKA_ContextTrackEntry); Track; Track=(ebml_master*)EBML_MasterNextChild(Tracks,Track)) { Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackType); if (EBML_IntegerValue((ebml_integer*)Elt) == TRACK_TYPE_VIDEO) { TrackNum = EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber)); break; } } if (!Track) { // no video track found, look for an audio track for (Track = (ebml_master*)EBML_MasterFindChild(Tracks,&MATROSKA_ContextTrackEntry); Track; Track=(ebml_master*)EBML_MasterNextChild(Tracks,Track)) { Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackType); if (EBML_IntegerValue((ebml_integer*)Elt) == TRACK_TYPE_AUDIO) { TrackNum = EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber)); break; } } } if (order) { for (Elt = EBML_MasterFindChild(Tracks,&MATROSKA_ContextTrackEntry); Elt; Elt=EBML_MasterNextChild(Tracks,Elt)) { if (Elt!=(ebml_element*)Track) *order++ = (size_t)EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextTrackNumber)); } if (Track) *order++ = (size_t)EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber)); } if (!Track) TextPrintf(StdErr,T("Could not find an audio or video track to use as main track")); return Track; } static bool_t GenerateCueEntries(ebml_master *Cues, array *Clusters, ebml_master *Tracks, ebml_master *WSegmentInfo, ebml_element *RSegment, filepos_t TotalSize) { ebml_master *Track; ebml_element *Elt; matroska_block *Block; ebml_element **Cluster; matroska_cuepoint *CuePoint; int64_t TrackNum; timecode_t PrevTimecode = INVALID_TIMECODE_T, BlockTimecode; Track = GetMainTrack(Tracks, NULL); if (!Track) { TextPrintf(StdErr,T("Could not generate the Cue entries")); return 0; } Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); assert(Elt!=NULL); if (Elt) TrackNum = EBML_IntegerValue((ebml_integer*)Elt); // find all the keyframes ++CurrentPhase; for (Cluster = ARRAYBEGIN(*Clusters,ebml_element*);Cluster != ARRAYEND(*Clusters,ebml_element*); ++Cluster) { ShowProgress((ebml_element*)(*Cluster), TotalSize); MATROSKA_LinkClusterWriteSegmentInfo((matroska_cluster*)*Cluster,WSegmentInfo); for (Elt = EBML_MasterChildren(*Cluster); Elt; Elt = EBML_MasterNext(Elt)) { Block = NULL; if (EBML_ElementIsType(Elt, &MATROSKA_ContextSimpleBlock)) { if (MATROSKA_BlockKeyframe((matroska_block*)Elt)) Block = (matroska_block*)Elt; } else if (EBML_ElementIsType(Elt, &MATROSKA_ContextBlockGroup)) { ebml_element *EltB, *BlockRef = NULL; for (EltB = EBML_MasterChildren(Elt); EltB; EltB = EBML_MasterNext(EltB)) { if (EBML_ElementIsType(EltB, &MATROSKA_ContextBlock)) Block = (matroska_block*)EltB; else if (EBML_ElementIsType(EltB, &MATROSKA_ContextReferenceBlock)) BlockRef = EltB; } if (BlockRef && Block) Block = NULL; // not a keyframe } if (Block && MATROSKA_BlockTrackNum(Block) == TrackNum) { BlockTimecode = MATROSKA_BlockTimecode(Block); if ((BlockTimecode - PrevTimecode) < 800000000 && PrevTimecode != INVALID_TIMECODE_T) break; // no more than 1 Cue per Cluster and per 800 ms CuePoint = (matroska_cuepoint*)EBML_MasterAddElt(Cues,&MATROSKA_ContextCuePoint,1); if (!CuePoint) { TextPrintf(StdErr,T("Failed to create a new CuePoint ! out of memory ?\r\n")); return 0; } MATROSKA_LinkCueSegmentInfo(CuePoint,WSegmentInfo); MATROSKA_LinkCuePointBlock(CuePoint,Block); MATROSKA_CuePointUpdate(CuePoint,RSegment); PrevTimecode = BlockTimecode; break; // one Cues per Cluster is enough } } } EndProgress(); if (!EBML_MasterChildren(Cues)) { TextPrintf(StdErr,T("Failed to create the Cue entries, no Block found\r\n")); return 0; } EBML_ElementUpdateSize(Cues,0,0); return 1; } static int TimcodeCmp(const void* Param, const timecode_t *a, const timecode_t *b) { if (*a == *b) return 0; if (*a > *b) return 1; return -1; } static int64_t gcd(int64_t a, int64_t b) { for (;;) { int64_t c = a % b; if(!c) return b; a = b; b = c; } } static void CleanCropValues(ebml_master *Track, int64_t Width, int64_t Height) { ebml_element *Left,*Right,*Top,*Bottom; Left = EBML_MasterGetChild(Track,&MATROSKA_ContextPixelCropLeft); Right = EBML_MasterGetChild(Track,&MATROSKA_ContextPixelCropRight); Top = EBML_MasterGetChild(Track,&MATROSKA_ContextPixelCropTop); Bottom = EBML_MasterGetChild(Track,&MATROSKA_ContextPixelCropBottom); if (EBML_IntegerValue((ebml_integer*)Top)+EBML_IntegerValue((ebml_integer*)Bottom) >= Height || EBML_IntegerValue((ebml_integer*)Left)+EBML_IntegerValue((ebml_integer*)Right) >= Width) { // invalid crop, remove the values NodeDelete((node*)Left); NodeDelete((node*)Right); NodeDelete((node*)Top); NodeDelete((node*)Bottom); } else { if (EBML_IntegerValue((ebml_integer*)Left)==0) NodeDelete((node*)Left); if (EBML_IntegerValue((ebml_integer*)Right)==0) NodeDelete((node*)Right); if (EBML_IntegerValue((ebml_integer*)Top)==0) NodeDelete((node*)Top); if (EBML_IntegerValue((ebml_integer*)Bottom)==0) NodeDelete((node*)Bottom); } } static bool_t HasTrackUID(ebml_master *Tracks, int TrackUID, const ebml_context *UIDType) { ebml_master *Track; for (Track = (ebml_master*)EBML_MasterFindChild(Tracks,&MATROSKA_ContextTrackEntry);Track; Track = (ebml_master*)EBML_MasterNextChild(Tracks,Track)) { ebml_element *Elt = EBML_MasterFindChild(Track,UIDType); if (Elt && EBML_IntegerValue((ebml_integer*)Elt)==TrackUID) return 1; } return 0; } static int CleanTracks(ebml_master *Tracks, int SrcProfile, int *DstProfile, ebml_master *Attachments, array *Alternate3DTracks) { ebml_master *Track, *CurTrack, *OtherTrack; ebml_element *Elt, *Elt2, *DisplayW, *DisplayH; int TrackType, TrackNum, Width, Height; tchar_t CodecID[MAXPATH]; for (Track = (ebml_master*)EBML_MasterFindChild(Tracks,&MATROSKA_ContextTrackEntry); Track;) { CurTrack = Track; Track = (ebml_master*)EBML_MasterNextChild(Tracks,Track); Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextTrackNumber); if (!Elt) { TextPrintf(StdErr,T("The track at %") TPRId64 T(" has no number set!\r\n"),EBML_ElementPosition((ebml_element*)CurTrack)); NodeDelete((node*)CurTrack); continue; } TrackNum = (int)EBML_IntegerValue((ebml_integer*)Elt); Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextCodecID); if (!Elt && !EBML_MasterFindChild(CurTrack,&MATROSKA_ContextTrackOperation)) { TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" has no CodecID set!\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack)); NodeDelete((node*)CurTrack); continue; } Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextTrackType); if (!Elt) { TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" has no type set!\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack)); NodeDelete((node*)CurTrack); continue; } TrackType = (int)EBML_IntegerValue((ebml_integer*)Elt); if (ARRAYCOUNT(*Alternate3DTracks, block_info*) >= (size_t)TrackNum && TrackType!=TRACK_TYPE_VIDEO) ARRAYBEGIN(*Alternate3DTracks, block_info*)[TrackNum] = NULL; // clean the aspect ratio Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextVideo); if (Elt) { Width = (int)EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextPixelWidth)); Height = (int)EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextPixelHeight)); if (Width==0 || Height==0) { TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" has invalid pixel dimensions %dx%d!\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack),Width,Height); NodeDelete((node*)CurTrack); continue; } DisplayW = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextDisplayWidth); DisplayH = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextDisplayHeight); if (DisplayW || DisplayH) { Elt2 = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextDisplayUnit); if (Elt2 && EBML_IntegerValue((ebml_integer*)Elt2)==MATROSKA_DISPLAY_UNIT_DAR) { // if the output size appears in pixel, fix it if ((!DisplayW || Width==EBML_IntegerValue((ebml_integer*)DisplayW)) && (!DisplayH || Height==EBML_IntegerValue((ebml_integer*)DisplayH))) EBML_IntegerSetValue((ebml_integer*)Elt2, MATROSKA_DISPLAY_UNIT_PIXEL); else CleanCropValues((ebml_master*)Elt, 0, 0); } if (!Elt2 || EBML_IntegerValue((ebml_integer*)Elt2)==MATROSKA_DISPLAY_UNIT_PIXEL) // pixel AR { if (!DisplayW) { if (EBML_IntegerValue((ebml_integer*)DisplayH)==Height) { NodeDelete((node*)DisplayH); DisplayH = NULL; // we don't the display values, they are the same as the pixel ones } else { DisplayW = EBML_MasterFindFirstElt((ebml_master*)Elt,&MATROSKA_ContextDisplayWidth,1,0); EBML_IntegerSetValue((ebml_integer*)DisplayW,Width); } } else if (EBML_IntegerValue((ebml_integer*)DisplayW)==0) { TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" has invalid display width %") TPRId64 T("!\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack),EBML_IntegerValue((ebml_integer*)DisplayW)); NodeDelete((node*)CurTrack); continue; } else if (!DisplayH) { if (EBML_IntegerValue((ebml_integer*)DisplayW)==Width) { NodeDelete((node*)DisplayW); DisplayW = NULL; // we don't the display values, they are the same as the pixel ones } else { DisplayH = EBML_MasterFindFirstElt((ebml_master*)Elt,&MATROSKA_ContextDisplayHeight,1,0); EBML_IntegerSetValue((ebml_integer*)DisplayH,Height); } } else if (EBML_IntegerValue((ebml_integer*)DisplayH)==0) { TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" has invalid display height %") TPRId64 T("!\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack),EBML_IntegerValue((ebml_integer*)DisplayH)); NodeDelete((node*)CurTrack); continue; } if (DisplayW && DisplayH) { if (EBML_IntegerValue((ebml_integer*)DisplayH) < Height && EBML_IntegerValue((ebml_integer*)DisplayW) < Width) // Haali's non-pixel shrinking { int64_t DW = EBML_IntegerValue((ebml_integer*)DisplayW); int64_t DH = EBML_IntegerValue((ebml_integer*)DisplayH); int Serious = gcd(DW,DH)==1; // shrank as much as it was possible if (8*DW <= Width && 8*DH <= Height) ++Serious; // shrank too much compared to the original else if (2*DW >= Width && 2*DH >= Height) --Serious; // may be intentional if (Serious) // doesn't seem correct as pixels { if (DW > DH) { EBML_IntegerSetValue((ebml_integer*)DisplayW,Scale64(Height,DW,DH)); EBML_IntegerSetValue((ebml_integer*)DisplayH,Height); } else { EBML_IntegerSetValue((ebml_integer*)DisplayH,Scale64(Width,DH,DW)); EBML_IntegerSetValue((ebml_integer*)DisplayW,Width); } // check if the AR is respected otherwise force it into a DAR if (EBML_IntegerValue((ebml_integer*)DisplayW)*DH != EBML_IntegerValue((ebml_integer*)DisplayH)*DW) { Elt2 = EBML_MasterFindFirstElt((ebml_master*)Elt,&MATROSKA_ContextDisplayUnit, 1, 0); if (Elt2) { EBML_IntegerSetValue((ebml_integer*)Elt2,MATROSKA_DISPLAY_UNIT_DAR); EBML_IntegerSetValue((ebml_integer*)DisplayW,DW); EBML_IntegerSetValue((ebml_integer*)DisplayH,DH); } } } } if (DisplayH && EBML_IntegerValue((ebml_integer*)DisplayH) == Height) { NodeDelete((node*)DisplayH); DisplayH = NULL; } if (DisplayW && EBML_IntegerValue((ebml_integer*)DisplayW) == Width) { NodeDelete((node*)DisplayW); DisplayW = NULL; } } } Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextDisplayUnit); if (EBML_IntegerValue((ebml_integer*)Elt2)!=MATROSKA_DISPLAY_UNIT_DAR) CleanCropValues((ebml_master*)Elt, DisplayW?EBML_IntegerValue((ebml_integer*)DisplayW):Width, DisplayH?EBML_IntegerValue((ebml_integer*)DisplayH):Height); } if (SrcProfile==PROFILE_MATROSKA_V1 || SrcProfile==PROFILE_MATROSKA_V2 || SrcProfile==PROFILE_DIVX) { // clean the older StereoMode values Elt2 = EBML_MasterFindChild(Elt,&MATROSKA_ContextStereoMode); if (!Elt2) Elt2 = EBML_MasterFindChild(Elt,&MATROSKA_ContextOldStereoMode); if (Elt2) { Width = (int)EBML_IntegerValue((ebml_integer*)Elt2); if (Width!=TRACK_OLD_STEREOMODE_MONO && Width <= 3) // upper values are probably the new ones { *DstProfile = PROFILE_MATROSKA_V3; TextPrintf(StdErr,T("The track %d at %") TPRId64 T(" is using an old StereoMode value, converting to profile '%s'\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack),GetProfileName(*DstProfile)); if (EBML_ElementIsType(Elt2, &MATROSKA_ContextOldStereoMode)) // replace the old by a new Elt2->Context = &MATROSKA_ContextStereoMode; // replace the old values with the new ones if (Width==TRACK_OLD_STEREOMODE_BOTH) { TextPrintf(StdErr,T(" turning 'Both Eyes' into 'side by side (left first)\r\n"), TrackNum,EBML_ElementPosition((ebml_element*)CurTrack),GetProfileName(*DstProfile)); EBML_IntegerSetValue((ebml_integer*)Elt2,TRACK_STEREO_MODE_SIDEBYSIDE_L); } else { EBML_IntegerSetValue((ebml_integer*)Elt2,TRACK_STEREO_MODE_MONO); TextPrintf(StdErr,T(" turning %s eye to mono\r\n"), Width==TRACK_OLD_STEREOMODE_LEFT?T("left"):T("right")); // look for the other track for (OtherTrack = (ebml_master*)EBML_MasterNextChild(Tracks,CurTrack);OtherTrack; OtherTrack = (ebml_master*)EBML_MasterNextChild(Tracks,OtherTrack)) { ebml_element *VidElt = EBML_MasterFindChild(OtherTrack,&MATROSKA_ContextVideo); if (VidElt) { // TODO: only use a video track that has the same output pixels as the source ebml_element *OtherStereo = EBML_MasterFindChild(VidElt,&MATROSKA_ContextStereoMode); if (!OtherStereo) OtherStereo = EBML_MasterFindChild(VidElt,&MATROSKA_ContextOldStereoMode); if (OtherStereo && ((Width==TRACK_OLD_STEREOMODE_LEFT && EBML_IntegerValue((ebml_integer*)OtherStereo)==TRACK_OLD_STEREOMODE_RIGHT) || (Width==TRACK_OLD_STEREOMODE_RIGHT && EBML_IntegerValue((ebml_integer*)OtherStereo)==TRACK_OLD_STEREOMODE_LEFT))) { ebml_master *CombinedTrack; int NewTrackUID; TextPrintf(StdErr,T(" turning matching %s eye to mono and creating a new combined track\r\n"), Width==TRACK_OLD_STEREOMODE_RIGHT?T("left"):T("right")); EBML_IntegerSetValue((ebml_integer*)OtherStereo,TRACK_STEREO_MODE_MONO); // create another track that is this one combined CombinedTrack = (ebml_master*)EBML_ElementCopy(CurTrack, NULL); EBML_MasterAppend(Tracks, (ebml_element*)CombinedTrack); // set a new TrackNumber NewTrackUID = TrackNum+1; while (HasTrackUID(Tracks, NewTrackUID, &MATROSKA_ContextTrackNumber)) ++NewTrackUID; Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextTrackNumber); EBML_IntegerSetValue((ebml_integer*)Elt,NewTrackUID); // set a new TrackUID NewTrackUID = 1; while (HasTrackUID(Tracks, NewTrackUID, &MATROSKA_ContextTrackUID)) ++NewTrackUID; Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextTrackUID); EBML_IntegerSetValue((ebml_integer*)Elt,NewTrackUID); // cleaning Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextFlagEnabled); if (Elt) EBML_IntegerSetValue((ebml_integer*)Elt,1); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextFlagLacing); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextMinCache); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextMaxCache); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextDefaultDuration); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextTrackTimecodeScale); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextMaxBlockAdditionID); NodeDelete((node*)Elt); Elt = EBML_MasterGetChild(CombinedTrack,&MATROSKA_ContextCodecID); EBML_StringSetValue((ebml_string*)Elt,"V_COMBINED"); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextCodecPrivate); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextAttachmentLink); NodeDelete((node*)Elt); Elt = EBML_MasterFindChild(CombinedTrack,&MATROSKA_ContextTrackTranslate); NodeDelete((node*)Elt); // add the TrackCombine info Elt = EBML_MasterAddElt(CombinedTrack, &MATROSKA_ContextTrackOperation, 1); if (Elt) Elt = EBML_MasterAddElt((ebml_master*)Elt, &MATROSKA_ContextTrackCombinePlanes, 1); if (Elt) { // track 1 CombinedTrack = (ebml_master*)EBML_MasterAddElt((ebml_master*)Elt, &MATROSKA_ContextTrackPlane, 1); OtherStereo = EBML_MasterFindChild(CurTrack, &MATROSKA_ContextTrackUID); if (!OtherStereo) { OtherStereo = EBML_MasterAddElt((ebml_master*)CurTrack, &MATROSKA_ContextTrackUID, 1); while (HasTrackUID(Tracks, NewTrackUID, &MATROSKA_ContextTrackUID)) ++NewTrackUID; EBML_IntegerSetValue((ebml_integer*)OtherStereo, NewTrackUID); } Elt2 = EBML_MasterGetChild(CombinedTrack, &MATROSKA_ContextTrackPlaneUID); EBML_IntegerSetValue((ebml_integer*)Elt2, EBML_IntegerValue((ebml_integer*)OtherStereo)); Elt2 = EBML_MasterGetChild(CombinedTrack, &MATROSKA_ContextTrackPlaneType); EBML_IntegerSetValue((ebml_integer*)Elt2, Width==TRACK_OLD_STEREOMODE_LEFT? TRACK_PLANE_LEFT : TRACK_PLANE_RIGHT); // track 2 CombinedTrack = (ebml_master*)EBML_MasterAddElt((ebml_master*)Elt, &MATROSKA_ContextTrackPlane, 1); OtherStereo = EBML_MasterFindChild(OtherTrack, &MATROSKA_ContextTrackUID); if (!OtherStereo) { OtherStereo = EBML_MasterAddElt((ebml_master*)OtherTrack, &MATROSKA_ContextTrackUID, 1); while (HasTrackUID(Tracks, NewTrackUID, &MATROSKA_ContextTrackUID)) ++NewTrackUID; EBML_IntegerSetValue((ebml_integer*)OtherStereo, NewTrackUID); } Elt2 = EBML_MasterGetChild(CombinedTrack, &MATROSKA_ContextTrackPlaneUID); EBML_IntegerSetValue((ebml_integer*)Elt2, EBML_IntegerValue((ebml_integer*)OtherStereo)); Elt2 = EBML_MasterGetChild(CombinedTrack, &MATROSKA_ContextTrackPlaneType); EBML_IntegerSetValue((ebml_integer*)Elt2, Width==TRACK_OLD_STEREOMODE_RIGHT? TRACK_PLANE_LEFT : TRACK_PLANE_RIGHT); } return CleanTracks(Tracks, SrcProfile, DstProfile, Attachments, Alternate3DTracks); } } } TextPrintf(StdErr,T(" could not find the matching %s track!\r\n"), Width==TRACK_OLD_STEREOMODE_RIGHT?T("left"):T("right")); } } } } } if (ARRAYCOUNT(*Alternate3DTracks, block_info*) >= (size_t)TrackNum && ARRAYBEGIN(*Alternate3DTracks, block_info*)[TrackNum]) { // force the proper StereoMode value Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextStereoMode); EBML_IntegerSetValue((ebml_integer*)Elt2, TRACK_STEREO_MODE_ALTERNATE_PACKED_L); } if (*DstProfile==PROFILE_WEBM) { // verify that we have only VP8 and Vorbis tracks Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextCodecID); EBML_StringGet((ebml_string*)Elt,CodecID,TSIZEOF(CodecID)); if (!(TrackType==TRACK_TYPE_VIDEO && tcsisame_ascii(CodecID,T("V_VP8")) || (TrackType==TRACK_TYPE_AUDIO && tcsisame_ascii(CodecID,T("A_VORBIS"))))) { TextPrintf(StdErr,T("Wrong codec '%s' for profile '%s' removing track %d\r\n"),CodecID,GetProfileName(*DstProfile),TrackNum); NodeDelete((node*)CurTrack); continue; } } // clean the output sampling freq Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextAudio); if (Elt) { Elt2 = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextOutputSamplingFrequency); if (Elt2) { DisplayH = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextSamplingFrequency); assert(DisplayH!=NULL); if (EBML_FloatValue((ebml_float*)Elt2) == EBML_FloatValue((ebml_float*)DisplayH)) NodeDelete((node*)Elt2); } } // clean the attachment links Elt = EBML_MasterFindChild(CurTrack,&MATROSKA_ContextAttachmentLink); while (Elt) { Elt2 = NULL; if (!Attachments) Elt2 = Elt; else { Elt2 = EBML_MasterFindChild(Attachments,&MATROSKA_ContextAttachedFile); while (Elt2) { DisplayH = EBML_MasterFindChild((ebml_master*)Elt2,&MATROSKA_ContextFileUID); if (DisplayH && EBML_IntegerValue((ebml_integer*)DisplayH)==EBML_IntegerValue((ebml_integer*)Elt)) break; Elt2 = EBML_MasterNextChild(Attachments, Elt2); } if (!Elt2) // the attachment wasn't found, delete Elt Elt2 = Elt; else Elt2 = NULL; } Elt = EBML_MasterNextChild(CurTrack, Elt); if (Elt2) NodeDelete((node*)Elt2); } } // disable Alternate3DTracks handling if there is no matching track TrackNum = -1; for (TrackType=0; TrackType_Begin = TABLE_MARKER; } static bool_t BlockIsCompressed(const matroska_block *Block) { ebml_master *Track = (ebml_master*)MATROSKA_BlockReadTrack(Block); if (Track) { ebml_master *Elt = (ebml_master*)EBML_MasterFindChild(Track, &MATROSKA_ContextContentEncodings); if (Elt) { Elt = (ebml_master*)EBML_MasterFindChild(Elt, &MATROSKA_ContextContentEncoding); if (EBML_MasterChildren(Elt)) { if (EBML_MasterNext(Elt)) return 1; // we don't support cascased encryption/compression Elt = (ebml_master*)EBML_MasterFindChild(Elt, &MATROSKA_ContextContentCompression); if (!Elt) return 1; // we don't support encryption Elt = (ebml_master*)EBML_MasterGetChild(Elt, &MATROSKA_ContextContentCompAlgo); if (EBML_IntegerValue((ebml_integer*)Elt)==MATROSKA_BLOCK_COMPR_ZLIB) return 1; } } } return 0; } static void ShrinkCommonHeader(array *TrackHeader, matroska_block *Block, stream *Input) { size_t Frame,FrameCount,EqualData; matroska_frame FrameData; if (TrackHeader->_Begin != TABLE_MARKER && ARRAYCOUNT(*TrackHeader,uint8_t)==0) return; if (MATROSKA_BlockReadData(Block,Input)!=ERR_NONE) return; if (BlockIsCompressed(Block)) return; FrameCount = MATROSKA_BlockGetFrameCount(Block); Frame = 0; if (FrameCount && TrackHeader->_Begin == TABLE_MARKER) { // use the first frame as the reference MATROSKA_BlockGetFrame(Block,Frame,&FrameData,1); TrackHeader->_Begin = NULL; ArrayAppend(TrackHeader,FrameData.Data,FrameData.Size,0); Frame = 1; } for (;Frame_Begin == TABLE_MARKER) TrackHeader->_Begin = NULL; } static void WriteJunk(stream *Output, size_t Amount) { char Val = 0x0A; while (Amount--) Stream_Write(Output,&Val,1,NULL); } #if defined(TARGET_WIN) && defined(UNICODE) int wmain(int argc, const wchar_t *argv[]) #else int main(int argc, const char *argv[]) #endif { int i,Result = 0; int ShowUsage = 0; int ShowVersion = 0; parsercontext p; textwriter _StdErr; stream *Input = NULL,*Output = NULL; tchar_t Path[MAXPATHFULL]; tchar_t String[MAXLINE],Original[MAXLINE],*s; ebml_master *EbmlHead = NULL, *RSegment = NULL, *RLevel1 = NULL, **Cluster; ebml_master *RSegmentInfo = NULL, *RTrackInfo = NULL, *RChapters = NULL, *RTags = NULL, *RCues = NULL, *RAttachments = NULL; ebml_master *WSegment = NULL, *WMetaSeek = NULL, *WSegmentInfo = NULL, *WTrackInfo = NULL; ebml_element *Elt, *Elt2; matroska_seekpoint *WSeekPoint = NULL, *W1stClusterSeek = NULL; ebml_string *LibName, *AppName; array RClusters, WClusters, *Clusters, WTracks; ebml_parser_context RContext; ebml_parser_context RSegmentContext; int UpperElement; filepos_t MetaSeekBefore, MetaSeekAfter; filepos_t NextPos = 0, SegmentSize = 0, ClusterSize, CuesSize; size_t ExtraVoidSize = 0; timecode_t PrevTimecode; bool_t CuesChanged; bool_t KeepCues = 0, Remux = 0, CuesCreated = 0, Optimize = 0, OptimizeVideo = 1, UnOptimize = 0, ClustersNeedRead = 0, Regression = 0; int InputPathIndex = 1; int64_t TimeCodeScale = 0, OldTimeCodeScale; size_t MaxTrackNum = 0; array TrackMaxHeader; // array of uint8_t (max common header) filepos_t TotalSize; array Alternate3DTracks; // Core-C init phase ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); ProjectSettings((nodecontext*)&p); // EBML & Matroska Init MATROSKA_Init((nodecontext*)&p); ArrayInit(&RClusters); ArrayInit(&WClusters); ArrayInit(&WTracks); ArrayInit(&TrackMaxHeader); ArrayInit(&Alternate3DTracks); Clusters = &RClusters; StdErr = &_StdErr; memset(StdErr,0,sizeof(_StdErr)); StdErr->Stream = (stream*)NodeSingleton(&p,STDERR_ID); #if defined(TARGET_WIN) && defined(UNICODE) Node_FromWcs(&p,Path,TSIZEOF(Path),argv[0]); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[0]); #endif SplitPath(Path,NULL,0,String,TSIZEOF(String),NULL,0); UnOptimize = tcsisame_ascii(String,T("mkWDclean")); if (UnOptimize) TextPrintf(StdErr,T("Running special mkWDclean mode, please fix your player instead of valid Matroska files\r\n")); Path[0] = 0; for (i=1;i [matroska_dst]\r\n")); TextWrite(StdErr,T("Options:\r\n")); TextWrite(StdErr,T(" --keep-cues keep the original Cues content and move it to the front\r\n")); TextWrite(StdErr,T(" --remux redo the Clusters layout\r\n")); TextWrite(StdErr,T(" --doctype force the doctype version\r\n")); TextWrite(StdErr,T(" 1: 'matroska' v1\r\n")); TextWrite(StdErr,T(" 2: 'matroska' v2\r\n")); TextWrite(StdErr,T(" 3: 'matroska' v3\r\n")); TextWrite(StdErr,T(" 4: 'webm'\r\n")); TextWrite(StdErr,T(" 5: 'matroska' v1 with DivX extensions\r\n")); TextWrite(StdErr,T(" --live the output file resembles a live stream\r\n")); TextWrite(StdErr,T(" --timecodescale force the global TimecodeScale to (1000000 is a good value)\r\n")); TextWrite(StdErr,T(" --unsafe don't output elements that are used for file recovery (saves more space)\r\n")); TextWrite(StdErr,T(" --optimize use all possible optimization for the output file\r\n")); TextWrite(StdErr,T(" --optimize_nv use all possible optimization for the output file, except video tracks\r\n")); TextWrite(StdErr,T(" --no-optimize disable some optimization for the output file\r\n")); TextWrite(StdErr,T(" --regression the output file is suitable for regression tests\r\n")); TextWrite(StdErr,T(" --alt-3d the track with ID has alternate 3D fields (left first)\r\n")); TextWrite(StdErr,T(" --quiet only output errors\r\n")); TextWrite(StdErr,T(" --version show the version of mkclean\r\n")); TextWrite(StdErr,T(" --help show this screen\r\n")); } Path[0] = 0; Result = -1; goto exit; } #if defined(TARGET_WIN) && defined(UNICODE) Node_FromWcs(&p,Path,TSIZEOF(Path),argv[InputPathIndex]); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[InputPathIndex]); #endif Input = StreamOpen(&p,Path,SFLAG_RDONLY/*|SFLAG_BUFFERED*/); if (!Input) { TextPrintf(StdErr,T("Could not open file \"%s\" for reading\r\n"),Path); Path[0] = 0; Result = -2; goto exit; } TotalSize = Stream_Seek(Input, 0, SEEK_END); Stream_Seek(Input, 0, SEEK_SET); if (InputPathIndex==argc-1) { tchar_t Ext[MAXDATA]; SplitPath(Path,Original,TSIZEOF(Original),String,TSIZEOF(String),Ext,TSIZEOF(Ext)); if (!Original[0]) Path[0] = 0; else { tcscpy_s(Path,TSIZEOF(Path),Original); AddPathDelimiter(Path,TSIZEOF(Path)); } if (Ext[0]) stcatprintf_s(Path,TSIZEOF(Path),T("clean.%s.%s"),String,Ext); else stcatprintf_s(Path,TSIZEOF(Path),T("clean.%s"),String); } else #if defined(TARGET_WIN) && defined(UNICODE) Node_FromWcs(&p,Path,TSIZEOF(Path),argv[argc-1]); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[argc-1]); #endif Output = StreamOpen(&p,Path,SFLAG_WRONLY|SFLAG_CREATE); if (!Output) { TextPrintf(StdErr,T("Could not open file \"%s\" for writing\r\n"),Path); Result = -3; goto exit; } // parse the source file to determine if it's a Matroska file and determine the location of the key parts RContext.Context = &MATROSKA_ContextStream; RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = NULL; RContext.Profile = 0; EbmlHead = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 0); if (!EbmlHead || !EBML_ElementIsType((ebml_element*)EbmlHead, &EBML_ContextHead)) { TextWrite(StdErr,T("EBML head not found! Are you sure it's a matroska/webm file?\r\n")); Result = -4; goto exit; } RSegment = (ebml_master*)CheckMatroskaHead((ebml_element*)EbmlHead,&RContext,Input); if (SrcProfile==PROFILE_MATROSKA_V1 && DocVersion==2) SrcProfile = PROFILE_MATROSKA_V2; else if (SrcProfile==PROFILE_MATROSKA_V1 && DocVersion==3) SrcProfile = PROFILE_MATROSKA_V3; else if (SrcProfile==PROFILE_MATROSKA_V1 && DocVersion==4) SrcProfile = PROFILE_MATROSKA_V4; if (!DstProfile) DstProfile = SrcProfile; if (DstProfile==PROFILE_WEBM) { UnOptimize = 1; Optimize = 0; } if (!RSegment) { Result = -5; goto exit; } NodeDelete((node*)EbmlHead); EbmlHead = NULL; if (Unsafe) ++TotalPhases; if (!Live) ++TotalPhases; if (EBML_ElementPositionEnd((ebml_element*)RSegment) != INVALID_FILEPOS_T) TotalSize = EBML_ElementPositionEnd((ebml_element*)RSegment); RContext.EndPosition = TotalSize; // avoid reading too far some dummy/void elements for this segment // locate the Segment Info, Track Info, Chapters, Tags, Attachments, Cues Clusters* RSegmentContext.Context = &MATROSKA_ContextSegment; RSegmentContext.EndPosition = EBML_ElementPositionEnd((ebml_element*)RSegment); RSegmentContext.UpContext = &RContext; RSegmentContext.Profile = SrcProfile; UpperElement = 0; //TextPrintf(StdErr,T("Loading the level1 elements in memory\r\n")); RLevel1 = (ebml_master*)EBML_FindNextElement(Input, &RSegmentContext, &UpperElement, 1); while (RLevel1) { ShowProgress((ebml_element*)RLevel1, TotalSize); if (EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextInfo)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RSegmentInfo = RLevel1; } else if (EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextTracks)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RTrackInfo = RLevel1; } else if (!Live && EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextChapters)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RChapters = RLevel1; } else if (!Live && EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextTags)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RTags = RLevel1; } else if (!Live && EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextCues) && KeepCues) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RCues = RLevel1; } else if (!Live && EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextAttachments)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,0)==ERR_NONE) RAttachments = RLevel1; } else if (EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextCluster)) { // only partially read the Cluster data (not the data inside the blocks) if (EBML_ElementReadData((ebml_element*)RLevel1,Input,&RSegmentContext,!Remux,SCOPE_PARTIAL_DATA,0)==ERR_NONE) { ArrayAppend(&RClusters,&RLevel1,sizeof(RLevel1),256); // remove MATROSKA_ContextPosition and MATROSKA_ContextPrevSize until supported EbmlHead = (ebml_master*)EBML_MasterFindChild(RLevel1, &MATROSKA_ContextPosition); if (EbmlHead) NodeDelete((node*)EbmlHead); EbmlHead = (ebml_master*)EBML_MasterFindChild(RLevel1, &MATROSKA_ContextPrevSize); if (EbmlHead) NodeDelete((node*)EbmlHead); EbmlHead = NULL; RLevel1 = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); if (RLevel1 != NULL) continue; } } else { EbmlHead = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); assert(EbmlHead==NULL); NodeDelete((node*)RLevel1); } RLevel1 = (ebml_master*)EBML_FindNextElement(Input, &RSegmentContext, &UpperElement, 1); } EndProgress(); if (!RSegmentInfo) { TextWrite(StdErr,T("The source Segment has no Segment Info section\r\n")); Result = -6; goto exit; } WSegmentInfo = (ebml_master*)EBML_ElementCopy(RSegmentInfo, NULL); EBML_MasterUseChecksum(WSegmentInfo,!Unsafe); RLevel1 = (ebml_master*)EBML_MasterGetChild(WSegmentInfo,&MATROSKA_ContextTimecodeScale); if (!RLevel1) { TextWrite(StdErr,T("Failed to get the TimeCodeScale handle\r\n")); Result = -10; goto exit; } OldTimeCodeScale = EBML_IntegerValue((ebml_integer*)RLevel1); if (TimeCodeScale==0) { // avoid using a TimeCodeScale too small TimeCodeScale = OldTimeCodeScale; while (TimeCodeScale < 100000) TimeCodeScale <<= 1; } EBML_IntegerSetValue((ebml_integer*)RLevel1,TimeCodeScale); RLevel1 = NULL; if (Live) { // remove MATROSKA_ContextDuration from Live streams ebml_float *Duration = (ebml_float*)EBML_MasterFindChild(WSegmentInfo, &MATROSKA_ContextDuration); if (Duration) NodeDelete((node*)Duration); } else if (TimeCodeScale && TimeCodeScale != OldTimeCodeScale) { ebml_float *Duration = (ebml_float*)EBML_MasterFindChild(WSegmentInfo, &MATROSKA_ContextDuration); if (Duration) { double duration = EBML_FloatValue(Duration); EBML_FloatSetValue(Duration, (duration * OldTimeCodeScale) / TimeCodeScale); } } // reorder elements in WSegmentInfo Elt2 = EBML_MasterFindChild(WSegmentInfo, &MATROSKA_ContextTimecodeScale); if (Elt2) NodeTree_SetParent(Elt2,WSegmentInfo,EBML_MasterChildren(WSegmentInfo)); if (!Elt2) Elt2 = EBML_MasterChildren(WSegmentInfo); Elt = EBML_MasterFindChild(WSegmentInfo, &MATROSKA_ContextDuration); if (Elt) NodeTree_SetParent(Elt,WSegmentInfo,Elt2); if (!RTrackInfo && ARRAYCOUNT(RClusters,ebml_element*)) { TextWrite(StdErr,T("The source Segment has no Track Info section\r\n")); Result = -7; goto exit; } if (RTrackInfo) { Result = CleanTracks(RTrackInfo, SrcProfile, &DstProfile, RAttachments, &Alternate3DTracks); if (Result!=0) { TextWrite(StdErr,T("No Tracks left to use!\r\n")); goto exit; } WTrackInfo = (ebml_master*)EBML_ElementCopy(RTrackInfo, NULL); if (WTrackInfo==NULL) { TextWrite(StdErr,T("Failed to copy the track info!\r\n")); goto exit; } EBML_MasterUseChecksum(WTrackInfo,!Unsafe); // count the max track number for (Elt=EBML_MasterChildren(WTrackInfo); Elt; Elt=EBML_MasterNext(Elt)) { if (EBML_ElementIsType(Elt, &MATROSKA_ContextTrackEntry)) { EBML_MasterUseChecksum((ebml_master*)Elt,!Unsafe); Elt2 = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextTrackNumber); if (Elt2 && (size_t)EBML_IntegerValue((ebml_integer*)Elt2) > MaxTrackNum) MaxTrackNum = (size_t)EBML_IntegerValue((ebml_integer*)Elt2); } } // make sure the lacing flag is set on tracks that use it i = -1; for (Elt = EBML_MasterChildren(WTrackInfo);Elt;Elt=EBML_MasterNext(Elt)) { Elt2 = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextTrackNumber); if (Elt2) i = max(i,(int)EBML_IntegerValue((ebml_integer*)Elt2)); } ArrayResize(&WTracks,sizeof(track_info)*(i+1),0); ArrayZero(&WTracks); } // Write the EBMLHead EbmlHead = (ebml_master*)EBML_ElementCreate(&p,&EBML_ContextHead,0,NULL); if (!EbmlHead) goto exit; EBML_MasterUseChecksum(EbmlHead,!Unsafe); NodeTree_Clear((nodetree*)EbmlHead); // remove the default values // DocType RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextDocType); if (!RLevel1) goto exit; assert(Node_IsPartOf(RLevel1,EBML_STRING_CLASS)); if (DstProfile == PROFILE_WEBM) { if (EBML_StringSetValue((ebml_string*)RLevel1,"webm") != ERR_NONE) goto exit; } else { if (EBML_StringSetValue((ebml_string*)RLevel1,"matroska") != ERR_NONE) goto exit; } // Doctype version if (DstProfile==PROFILE_MATROSKA_V2 || DstProfile==PROFILE_WEBM) DocVersion=2; if (DstProfile==PROFILE_MATROSKA_V3) DocVersion=3; if (DstProfile==PROFILE_MATROSKA_V4) DocVersion=4; if (ARRAYCOUNT(Alternate3DTracks, block_info*) && DstProfile!=PROFILE_MATROSKA_V3 && DstProfile!=PROFILE_MATROSKA_V4) { TextPrintf(StdErr,T("Using --alt-3d in profile '%s' try \"--doctype %d\"\r\n"),GetProfileName(DstProfile),GetProfileId(PROFILE_MATROSKA_V3)); goto exit; } RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextDocTypeVersion); if (!RLevel1) goto exit; assert(Node_IsPartOf(RLevel1,EBML_INTEGER_CLASS)); EBML_IntegerSetValue((ebml_integer*)RLevel1, DocVersion); // Doctype readable version RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextDocTypeReadVersion); if (!RLevel1) goto exit; assert(Node_IsPartOf(RLevel1,EBML_INTEGER_CLASS)); EBML_IntegerSetValue((ebml_integer*)RLevel1, DocVersion); if (EBML_ElementRender((ebml_element*)EbmlHead,Output,1,0,1,NULL)!=ERR_NONE) goto exit; NodeDelete((node*)EbmlHead); EbmlHead = NULL; RLevel1 = NULL; // Write the Matroska Segment Head WSegment = (ebml_master*)EBML_ElementCreate(&p,&MATROSKA_ContextSegment,0,NULL); if (Live) EBML_ElementSetInfiniteSize((ebml_element*)WSegment,1); else { // temporary value if (EBML_ElementIsFiniteSize((ebml_element*)RSegment)) EBML_ElementForceDataSize((ebml_element*)WSegment, EBML_ElementDataSize((ebml_element*)RSegment,0)); else EBML_ElementSetSizeLength((ebml_element*)WSegment, EBML_MAX_SIZE); } if (EBML_ElementRenderHead((ebml_element*)WSegment,Output,0,NULL)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the (temporary) Segment head\r\n")); Result = -10; goto exit; } // Compute the Segment Info size ReduceSize((ebml_element*)WSegmentInfo); // change the library names & app name stprintf_s(String,TSIZEOF(String),T("%s + %s"),Node_GetDataStr((node*)&p,CONTEXT_LIBEBML_VERSION),Node_GetDataStr((node*)&p,CONTEXT_LIBMATROSKA_VERSION)); LibName = (ebml_string*)EBML_MasterFindFirstElt(WSegmentInfo, &MATROSKA_ContextMuxingApp, 1, 0); EBML_StringGet(LibName,Original,TSIZEOF(Original)); if (Regression) EBML_UniStringSetValue(LibName,T("libebml2 + libmatroska2")); else EBML_UniStringSetValue(LibName,String); AppName = (ebml_string*)EBML_MasterFindFirstElt(WSegmentInfo, &MATROSKA_ContextWritingApp, 1, 0); EBML_StringGet(AppName,String,TSIZEOF(String)); ExtraSizeDiff = tcslen(String); if (!tcsisame_ascii(String,Original)) // libavformat writes the same twice, we only need one { if (Original[0]) tcscat_s(Original,TSIZEOF(Original),T(" + ")); tcscat_s(Original,TSIZEOF(Original),String); } s = Original; if (tcsnicmp_ascii(Original,T("mkclean "),8)==0) s += 14; if (Regression) { if (s[0]) stprintf_s(String,TSIZEOF(String),T("mkclean regression from %s"),s); else stprintf_s(String,TSIZEOF(String),T("mkclean regression")); } else { stprintf_s(String,TSIZEOF(String),T("mkclean %s"),PROJECT_VERSION); if (Remux || Optimize || Live || UnOptimize || ARRAYCOUNT(Alternate3DTracks, block_info*)) tcscat_s(String,TSIZEOF(String),T(" ")); if (Remux) tcscat_s(String,TSIZEOF(String),T("r")); if (Optimize) tcscat_s(String,TSIZEOF(String),T("o")); if (Live) tcscat_s(String,TSIZEOF(String),T("l")); if (UnOptimize) tcscat_s(String,TSIZEOF(String),T("u")); if (ARRAYCOUNT(Alternate3DTracks, block_info*)) { tcscat_s(String,TSIZEOF(String),T("3")); Remux = 1; } if (s[0]) stcatprintf_s(String,TSIZEOF(String),T(" from %s"),s); } EBML_UniStringSetValue(AppName,String); ExtraSizeDiff = tcslen(String) - ExtraSizeDiff + 2; if (Regression || Remux || !EBML_MasterFindChild(WSegmentInfo, &MATROSKA_ContextDateUTC)) { RLevel1 = (ebml_master*)EBML_MasterGetChild(WSegmentInfo, &MATROSKA_ContextDateUTC); if (Regression) EBML_DateSetDateTime((ebml_date*)RLevel1, 1); else EBML_DateSetDateTime((ebml_date*)RLevel1, GetTimeDate()); RLevel1 = NULL; } if (!Live) { // Prepare the Meta Seek with average values WMetaSeek = (ebml_master*)EBML_MasterAddElt(WSegment,&MATROSKA_ContextSeekHead,0); EBML_MasterUseChecksum(WMetaSeek,!Unsafe); EBML_ElementForcePosition((ebml_element*)WMetaSeek, Stream_Seek(Output,0,SEEK_CUR)); // keep the position for when we need to write it NextPos = 38 + 4* (Unsafe ? 17 : 23); // raw estimation of the SeekHead size if (RAttachments) NextPos += Unsafe ? 18 : 24; if (RChapters) NextPos += Unsafe ? 17 : 23; // segment info WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)WSegmentInfo, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)WSegmentInfo,0) + 60; // 60 for the extra string we add MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)WSegmentInfo); // track info if (WTrackInfo) { WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)WTrackInfo, NextPos); EBML_ElementUpdateSize(WTrackInfo, 0, 0); NextPos += EBML_ElementFullSize((ebml_element*)WTrackInfo,0); MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)WTrackInfo); } else { TextWrite(StdErr,T("Warning: the source Segment has no Track Info section (can be a chapter file)\r\n")); } // chapters if (RChapters) { ReduceSize((ebml_element*)RChapters); if (EBML_MasterUseChecksum(RChapters,!Unsafe)) EBML_ElementUpdateSize(RChapters, 0, 0); if (!EBML_MasterCheckMandatory(RChapters,0)) { TextWrite(StdErr,T("The Chapters section is missing mandatory elements, skipping\r\n")); NodeDelete((node*)RChapters); RChapters = NULL; } else { WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)RChapters, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RChapters,0); MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)RChapters); } } // attachments if (RAttachments) { MATROSKA_AttachmentSort(RAttachments); ReduceSize((ebml_element*)RAttachments); if (EBML_MasterUseChecksum(RAttachments,!Unsafe)) EBML_ElementUpdateSize(RAttachments, 0, 0); if (!EBML_MasterCheckMandatory(RAttachments,0)) { TextWrite(StdErr,T("The Attachments section is missing mandatory elements, skipping\r\n")); NodeDelete((node*)RAttachments); RAttachments = NULL; } else { WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)RAttachments, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RAttachments,0); MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)RAttachments); } } // tags if (RTags) { ReduceSize((ebml_element*)RTags); if (EBML_MasterUseChecksum(RTags,!Unsafe)) EBML_ElementUpdateSize(RTags, 0, 0); if (!EBML_MasterCheckMandatory(RTags,0)) { TextWrite(StdErr,T("The Tags section is missing mandatory elements, skipping\r\n")); NodeDelete((node*)RTags); RTags = NULL; } else { WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)RTags, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RTags,0); MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)RTags); } } } else { WriteJunk(Output,134); NextPos += 134; } Result = LinkClusters(&RClusters,RSegmentInfo,RTrackInfo,DstProfile, &WTracks, Live?12345:INVALID_TIMECODE_T); if (Result!=0) goto exit; // use the output track settings for each block for (Cluster = ARRAYBEGIN(*Clusters,ebml_master*);Cluster != ARRAYEND(*Clusters,ebml_master*); ++Cluster) { //EBML_MasterUseChecksum((ebml_master*)*Cluster,!Unsafe); for (Elt = EBML_MasterChildren(*Cluster);Elt;Elt=(ebml_element*)RLevel1) { RLevel1 = (ebml_master*)EBML_MasterNext((ebml_master*)Elt); if (EBML_ElementIsType(Elt, &MATROSKA_ContextBlockGroup)) { for (Elt2 = EBML_MasterChildren((ebml_master*)Elt);Elt2;Elt2=EBML_MasterNext((ebml_master*)Elt2)) { if (EBML_ElementIsType(Elt2, &MATROSKA_ContextBlock)) { if (MATROSKA_LinkBlockWithWriteTracks((matroska_block*)Elt2,WTrackInfo)!=ERR_NONE) NodeDelete((node*)Elt); else if (MATROSKA_LinkBlockWriteSegmentInfo((matroska_block*)Elt2,WSegmentInfo)!=ERR_NONE) NodeDelete((node*)Elt); break; } } } else if (EBML_ElementIsType(Elt, &MATROSKA_ContextSimpleBlock)) { if (MATROSKA_LinkBlockWithWriteTracks((matroska_block*)Elt,WTrackInfo)!=ERR_NONE) NodeDelete((node*)Elt); else if (MATROSKA_LinkBlockWriteSegmentInfo((matroska_block*)Elt,WSegmentInfo)!=ERR_NONE) NodeDelete((node*)Elt); } } //EBML_ElementUpdateSize(*Cluster, 0, 0); } if (Optimize && !UnOptimize) { int16_t BlockTrack; ebml_element *Block, *GBlock; matroska_cluster **ClusterR; if (!Quiet) TextWrite(StdErr,T("Optimizing...\r\n")); ArrayResize(&TrackMaxHeader, sizeof(array)*(MaxTrackNum+1), 0); ArrayZero(&TrackMaxHeader); for (i=0;(size_t)i<=MaxTrackNum;++i) { bool_t OptimizeTrack = 1; if (!OptimizeVideo) { ebml_master *Track; for (Track = (ebml_master*)EBML_MasterFindChild(WTrackInfo,&MATROSKA_ContextTrackEntry); Track; Track=(ebml_master*)EBML_MasterNextChild(WTrackInfo,Track)) { Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); if (EBML_IntegerValue((ebml_integer*)Elt) != i) continue; Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackType); if (EBML_IntegerValue((ebml_integer*)Elt) == TRACK_TYPE_VIDEO) { Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextContentEncodings); NodeDelete((node*)Elt); OptimizeTrack = 0; } break; } } if (OptimizeTrack) InitCommonHeader(ARRAYBEGIN(TrackMaxHeader,array)+i); } for (ClusterR=ARRAYBEGIN(RClusters,matroska_cluster*);ClusterR!=ARRAYEND(RClusters,matroska_cluster*);++ClusterR) { for (Block = EBML_MasterChildren(*ClusterR);Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { GBlock = EBML_MasterFindChild((ebml_master*)Block, &MATROSKA_ContextBlock); if (GBlock) { BlockTrack = MATROSKA_BlockTrackNum((matroska_block*)GBlock); ShrinkCommonHeader(ARRAYBEGIN(TrackMaxHeader,array)+BlockTrack, (matroska_block*)GBlock, Input); } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { BlockTrack = MATROSKA_BlockTrackNum((matroska_block *)Block); ShrinkCommonHeader(ARRAYBEGIN(TrackMaxHeader,array)+BlockTrack, (matroska_block*)Block, Input); } } } for (i=0;(size_t)i<=MaxTrackNum;++i) ClearCommonHeader(ARRAYBEGIN(TrackMaxHeader,array)+i); } if (Remux && WTrackInfo) { // create WClusters matroska_cluster **ClusterR, *ClusterW; ebml_element *Block, *GBlock; ebml_master *Track; matroska_block *Block1; timecode_t Prev = INVALID_TIMECODE_T, *Tst, BlockTime, BlockDuration, MasterEndTimecode, BlockEnd, MainBlockEnd; size_t MainTrack, BlockTrack; size_t Frame, *pTrackOrder; bool_t Deleted; array KeyFrameTimecodes, TrackBlockCurrIdx, TrackOrder, *pTrackBlock; array TrackBlocks; // array of block_info matroska_frame FrameData; block_info BlockInfo,*pBlockInfo; err_t Result; if (!Quiet) TextWrite(StdErr,T("Remuxing...\r\n")); // count the number of useful tracks Frame = 0; for (Track=(ebml_master*)EBML_MasterChildren(WTrackInfo); Track; Track=(ebml_master*)EBML_MasterNext(Track)) { if (EBML_ElementIsType((ebml_element*)Track, &MATROSKA_ContextTrackEntry)) ++Frame; } ArrayInit(&TrackBlocks); ArrayResize(&TrackBlocks, sizeof(array)*(MaxTrackNum+1), 0); ArrayZero(&TrackBlocks); ArrayInit(&TrackBlockCurrIdx); ArrayResize(&TrackBlockCurrIdx, sizeof(size_t)*(MaxTrackNum+1), 0); ArrayZero(&TrackBlockCurrIdx); ArrayInit(&TrackOrder); // fill TrackBlocks with all the Blocks per track BlockInfo.DecodeTime = INVALID_TIMECODE_T; BlockInfo.FrameStartIndex = 0; for (ClusterR=ARRAYBEGIN(RClusters,matroska_cluster*);ClusterR!=ARRAYEND(RClusters,matroska_cluster*);++ClusterR) { for (Block = EBML_MasterChildren(*ClusterR);Block;Block=EBML_MasterNext(Block)) { if (EBML_ElementIsType(Block, &MATROSKA_ContextBlockGroup)) { GBlock = EBML_MasterFindChild((ebml_master*)Block, &MATROSKA_ContextBlock); if (GBlock) { BlockTrack = MATROSKA_BlockTrackNum((matroska_block*)GBlock); BlockInfo.Block = (matroska_block*)GBlock; ArrayAppend(ARRAYBEGIN(TrackBlocks,array)+BlockTrack,&BlockInfo,sizeof(BlockInfo),1024); } } else if (EBML_ElementIsType(Block, &MATROSKA_ContextSimpleBlock)) { BlockTrack = MATROSKA_BlockTrackNum((matroska_block *)Block); BlockInfo.Block = (matroska_block*)Block; ArrayAppend(ARRAYBEGIN(TrackBlocks,array)+BlockTrack,&BlockInfo,sizeof(BlockInfo),1024); } } } // determine what is the main track num (video track) for (;;) { bool_t Exit = 1; ArrayResize(&TrackOrder, sizeof(size_t)*Frame, 0); ArrayZero(&TrackOrder); Track = GetMainTrack(WTrackInfo,&TrackOrder); if (!Track) { TextWrite(StdErr,T("Impossible to remux without a proper track to use\r\n")); goto exit; } Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackNumber); assert(Elt!=NULL); MainTrack = (int16_t)EBML_IntegerValue((ebml_integer*)Elt); for (pTrackOrder=ARRAYBEGIN(TrackOrder,size_t);pTrackOrder!=ARRAYEND(TrackOrder,size_t);++pTrackOrder) { if (!ARRAYCOUNT(ARRAYBEGIN(TrackBlocks,array)[*pTrackOrder],block_info)) { if (!Quiet) TextPrintf(StdErr,T("Track %d has no blocks! Deleting...\r\n"),(int)*pTrackOrder); for (Elt = EBML_MasterFindChild(WTrackInfo,&MATROSKA_ContextTrackEntry); Elt; Elt=EBML_MasterNextChild(WTrackInfo,Elt)) { if (EBML_IntegerValue((ebml_integer*)EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextTrackNumber))==*pTrackOrder) { NodeDelete((node*)Elt); --Frame; Exit = 0; break; } } } } if (Exit) break; } // process the decoding time for all blocks for (pTrackBlock=ARRAYBEGIN(TrackBlocks,array);pTrackBlock!=ARRAYEND(TrackBlocks,array);++pTrackBlock) { BlockEnd = INVALID_TIMECODE_T; for (pBlockInfo=ARRAYBEGIN(*pTrackBlock,block_info);pBlockInfo!=ARRAYEND(*pTrackBlock,block_info);++pBlockInfo) { BlockTime = MATROSKA_BlockTimecode(pBlockInfo->Block); pBlockInfo->DecodeTime = BlockTime; if ((pBlockInfo+1)!=ARRAYEND(*pTrackBlock,block_info) && BlockEnd!=INVALID_TIMECODE_T) { BlockDuration = MATROSKA_BlockTimecode((pBlockInfo+1)->Block); if (BlockTime > BlockDuration) { //assert(BlockDuration > BlockEnd); pBlockInfo->DecodeTime = BlockEnd + ((BlockTime - BlockDuration) >> 2); } } BlockEnd = pBlockInfo->DecodeTime; } } // get all the keyframe timecodes for our main track ArrayInit(&KeyFrameTimecodes); pTrackBlock=ARRAYBEGIN(TrackBlocks,array) + MainTrack; for (pBlockInfo=ARRAYBEGIN(*pTrackBlock,block_info);pBlockInfo!=ARRAYEND(*pTrackBlock,block_info);++pBlockInfo) { if (MATROSKA_BlockKeyframe(pBlockInfo->Block)) { assert(pBlockInfo->DecodeTime == MATROSKA_BlockTimecode(pBlockInfo->Block)); ArrayAppend(&KeyFrameTimecodes,&pBlockInfo->DecodeTime,sizeof(pBlockInfo->DecodeTime),256); } } if (!ARRAYCOUNT(KeyFrameTimecodes,timecode_t)) { TextPrintf(StdErr,T("Impossible to remux, no keyframe found for track %d\r\n"),(int)MainTrack); goto exit; } // \todo sort Blocks of all tracks (according to the ref frame when available) // sort the timecodes, just in case the file wasn't properly muxed //ArraySort(&KeyFrameTimecodes, timecode_t, (arraycmp)TimcodeCmp, NULL, 1); // discrimate the timecodes we want to use as cluster boundaries // create a new Cluster no shorter than 1s (unless the next one is too distant like 2s) Prev = INVALID_TIMECODE_T; for (Tst = ARRAYBEGIN(KeyFrameTimecodes, timecode_t); Tst!=ARRAYEND(KeyFrameTimecodes, timecode_t);) { Deleted = 0; if (Prev!=INVALID_TIMECODE_T && *Tst < Prev + 1000000000) { // too close if (Tst+1 != ARRAYEND(KeyFrameTimecodes, timecode_t) && *(Tst+1) < Prev + 2000000000) { ArrayRemove(&KeyFrameTimecodes, timecode_t, Tst, (arraycmp)TimcodeCmp, NULL); Deleted = 1; } } if (!Deleted) Prev = *Tst++; } // create each Cluster if (!Quiet) TextWrite(StdErr,T("Reclustering...\r\n")); for (Tst = ARRAYBEGIN(KeyFrameTimecodes, timecode_t); Tst!=ARRAYEND(KeyFrameTimecodes, timecode_t); ++Tst) { bool_t ReachedClusterEnd = 0; ClusterW = (matroska_cluster*)EBML_ElementCreate(Track, &MATROSKA_ContextCluster, 0, NULL); ArrayAppend(&WClusters,&ClusterW,sizeof(ClusterW),256); MATROSKA_LinkClusterReadSegmentInfo(ClusterW, RSegmentInfo, 1); MATROSKA_LinkClusterWriteSegmentInfo(ClusterW, WSegmentInfo); MATROSKA_ClusterSetTimecode(ClusterW,*Tst); // \todo avoid having negative timecodes in the Cluster ? if ((Tst+1)==ARRAYEND(KeyFrameTimecodes, timecode_t)) MasterEndTimecode = INVALID_TIMECODE_T; else MasterEndTimecode = *(Tst+1); while (!ReachedClusterEnd && ARRAYBEGIN(TrackBlockCurrIdx,size_t)[MainTrack] != ARRAYCOUNT(ARRAYBEGIN(TrackBlocks,array)[MainTrack],block_info)) { // next Block end in the master track if (ARRAYBEGIN(TrackBlockCurrIdx,size_t)[MainTrack]+1 == ARRAYCOUNT(ARRAYBEGIN(TrackBlocks,array)[MainTrack],block_info)) MainBlockEnd = INVALID_TIMECODE_T; else { pBlockInfo = ARRAYBEGIN(ARRAYBEGIN(TrackBlocks,array)[MainTrack],block_info) + ARRAYBEGIN(TrackBlockCurrIdx,size_t)[MainTrack] + 1; MainBlockEnd = pBlockInfo->DecodeTime; } if (EBML_ElementPosition((ebml_element*)ClusterW) == INVALID_FILEPOS_T) EBML_ElementForcePosition((ebml_element*)ClusterW, EBML_ElementPosition((ebml_element*)pBlockInfo->Block)); // fake average value // loop on all tracks in their specified order for (pTrackOrder=ARRAYBEGIN(TrackOrder,size_t);pTrackOrder!=ARRAYEND(TrackOrder,size_t);++pTrackOrder) { // output all the blocks until MainBlockEnd (included) for this track while (ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder] < ARRAYCOUNT(ARRAYBEGIN(TrackBlocks,array)[*pTrackOrder],block_info)) { // End of the current Block if (ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder]+1 == ARRAYCOUNT(ARRAYBEGIN(TrackBlocks,array)[*pTrackOrder],block_info)) BlockEnd = INVALID_TIMECODE_T; else { pBlockInfo = ARRAYBEGIN(ARRAYBEGIN(TrackBlocks,array)[*pTrackOrder],block_info) + ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder] + 1; BlockEnd = pBlockInfo->DecodeTime; } pBlockInfo = ARRAYBEGIN(ARRAYBEGIN(TrackBlocks,array)[*pTrackOrder],block_info) + ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder]; if (pBlockInfo->DecodeTime > MainBlockEnd && *pTrackOrder!=MainTrack) { if (ARRAYCOUNT(Alternate3DTracks, block_info*) && ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder]) ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder] = NULL; break; // next track around this timecode } if (pBlockInfo->FrameStartIndex!=0) { // use the frames left from the previous block if (EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextSimpleBlock)) { Block1 = (matroska_block*)EBML_ElementCopy(pBlockInfo->Block, NULL); MATROSKA_LinkBlockWriteSegmentInfo(Block1,WSegmentInfo); for (; pBlockInfo->FrameStartIndex < MATROSKA_BlockGetFrameCount(pBlockInfo->Block); ++pBlockInfo->FrameStartIndex) { if (MATROSKA_BlockGetFrameEnd(pBlockInfo->Block,pBlockInfo->FrameStartIndex) >= MasterEndTimecode) break; MATROSKA_BlockGetFrame(pBlockInfo->Block, pBlockInfo->FrameStartIndex, &FrameData, 1); MATROSKA_BlockAppendFrame(Block1, &FrameData, *Tst); } if (MATROSKA_BlockGetFrameCount(Block1)) EBML_MasterAppend((ebml_master*)ClusterW,(ebml_element*)Block1); else NodeDelete((node*)Block1); if (pBlockInfo->FrameStartIndex!=MATROSKA_BlockGetFrameCount(pBlockInfo->Block)) break; // next track else { ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder]++; continue; } } else if (EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextBlock)) { Elt = EBML_ElementCopy(NodeTree_Parent(pBlockInfo->Block), NULL); Block1 = (matroska_block*)EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextBlock); MATROSKA_LinkBlockWriteSegmentInfo(Block1,WSegmentInfo); for (; pBlockInfo->FrameStartIndex < MATROSKA_BlockGetFrameCount(pBlockInfo->Block); ++pBlockInfo->FrameStartIndex) { if (MATROSKA_BlockGetFrameEnd(pBlockInfo->Block,pBlockInfo->FrameStartIndex) >= MasterEndTimecode) break; MATROSKA_BlockGetFrame(pBlockInfo->Block, pBlockInfo->FrameStartIndex, &FrameData, 1); MATROSKA_BlockAppendFrame(Block1, &FrameData, *Tst); } if (MATROSKA_BlockGetFrameCount(Block1)) EBML_MasterAppend((ebml_master*)ClusterW,(ebml_element*)Elt); else NodeDelete((node*)Elt); if (pBlockInfo->FrameStartIndex!=MATROSKA_BlockGetFrameCount(pBlockInfo->Block)) break; // next track else { ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder]++; continue; } } } if (MainBlockEnd!=INVALID_TIMECODE_T && BlockEnd>MasterEndTimecode && *pTrackOrder!=MainTrack && MATROSKA_BlockLaced(pBlockInfo->Block)) { // relacing //TextPrintf(StdErr,T("\rRelacing block track %d at %") TPRId64 T(" ends %") TPRId64 T(" next cluster at %") TPRId64 T("\r\n"),*pTrackOrder,pBlockInfo->DecodeTime,BlockEnd,MasterEndTimecode); if (MATROSKA_BlockReadData(pBlockInfo->Block,Input)==ERR_NONE) { bool_t HasDuration = MATROSKA_BlockProcessFrameDurations(pBlockInfo->Block,Input)==ERR_NONE; Result = ERR_NONE; if (EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextSimpleBlock)) { // This block needs to be split Block1 = (matroska_block*)EBML_ElementCopy(pBlockInfo->Block, NULL); MATROSKA_LinkBlockWriteSegmentInfo(Block1,WSegmentInfo); for (; pBlockInfo->FrameStartIndex < MATROSKA_BlockGetFrameCount(pBlockInfo->Block); ++pBlockInfo->FrameStartIndex) { if (HasDuration && MATROSKA_BlockGetFrameEnd(pBlockInfo->Block,pBlockInfo->FrameStartIndex) >= MasterEndTimecode) break; MATROSKA_BlockGetFrame(pBlockInfo->Block, pBlockInfo->FrameStartIndex, &FrameData, 1); MATROSKA_BlockAppendFrame(Block1, &FrameData, *Tst); } if (MATROSKA_BlockGetFrameCount(Block1)==MATROSKA_BlockGetFrameCount(pBlockInfo->Block)) { pBlockInfo->FrameStartIndex = 0; // all the frames are for the next Cluster NodeDelete((node*)Block1); } else { if (MATROSKA_BlockGetFrameCount(Block1)) Result = EBML_MasterAppend((ebml_master*)ClusterW,(ebml_element*)Block1); else NodeDelete((node*)Block1); } break; // next track } else { assert(EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextBlock)); // This block needs to be split Elt = EBML_ElementCopy(NodeTree_Parent(pBlockInfo->Block), NULL); Block1 = (matroska_block*)EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextBlock); MATROSKA_LinkBlockWriteSegmentInfo(Block1,WSegmentInfo); for (; pBlockInfo->FrameStartIndex < MATROSKA_BlockGetFrameCount(pBlockInfo->Block); ++pBlockInfo->FrameStartIndex) { if (HasDuration && MATROSKA_BlockGetFrameEnd(pBlockInfo->Block,pBlockInfo->FrameStartIndex) >= MasterEndTimecode) break; MATROSKA_BlockGetFrame(pBlockInfo->Block, pBlockInfo->FrameStartIndex, &FrameData, 1); MATROSKA_BlockAppendFrame(Block1, &FrameData, *Tst); } if (MATROSKA_BlockGetFrameCount(Block1)==MATROSKA_BlockGetFrameCount(pBlockInfo->Block)) { pBlockInfo->FrameStartIndex = 0; // all the frames are for the next Cluster NodeDelete((node*)Elt); } else { if (MATROSKA_BlockGetFrameCount(Block1)) Result = EBML_MasterAppend((ebml_master*)ClusterW,Elt); else NodeDelete((node*)Elt); } break; // next track } if (Result != ERR_NONE) { if (Result==ERR_INVALID_DATA) TextPrintf(StdErr,T("Impossible to remux, the TimecodeScale may be too low, try --timecodescale 1000000\r\n")); else TextPrintf(StdErr,T("Impossible to remux, error appending a block\r\n")); Result = -46; goto exit; } MATROSKA_BlockReleaseData(pBlockInfo->Block,0); } } if (MATROSKA_BlockGetFrameCount(pBlockInfo->Block)) { block_info *prevBlock = NULL; if (ARRAYCOUNT(Alternate3DTracks, block_info*) && ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder]) { prevBlock = ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder]; if (prevBlock==MARKER3D) { ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder] = pBlockInfo; prevBlock = NULL; } else if (MATROSKA_BlockGetFrameCount(prevBlock->Block) >= 2) { ARRAYBEGIN(Alternate3DTracks, block_info*)[*pTrackOrder] = pBlockInfo; prevBlock = NULL; } else { Result = MATROSKA_BlockReadData(prevBlock->Block,Input); } } if (prevBlock) { // add the first frame into the previous Block if (Result==ERR_NONE) { Result = MATROSKA_BlockReadData(pBlockInfo->Block,Input); if (EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextSimpleBlock)) { Block1 = (matroska_block*)pBlockInfo->Block; } else { Elt = EBML_ElementCopy(NodeTree_Parent(pBlockInfo->Block), NULL); Block1 = (matroska_block*)EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextBlock); } assert(!Block1->IsKeyframe); MATROSKA_BlockGetFrame(Block1, pBlockInfo->FrameStartIndex, &FrameData, 1); MATROSKA_BlockAppendFrame(prevBlock->Block, &FrameData, *Tst); MATROSKA_BlockReleaseData(pBlockInfo->Block,0); } MATROSKA_BlockReleaseData(prevBlock->Block,0); } else { if (EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextSimpleBlock)) { Result = MATROSKA_LinkBlockWriteSegmentInfo(pBlockInfo->Block,WSegmentInfo); if (Result == ERR_NONE) Result = EBML_MasterAppend((ebml_master*)ClusterW,(ebml_element*)pBlockInfo->Block); } else { assert(EBML_ElementIsType((ebml_element*)pBlockInfo->Block, &MATROSKA_ContextBlock)); Result = MATROSKA_LinkBlockWriteSegmentInfo(pBlockInfo->Block,WSegmentInfo); if (Result == ERR_NONE) Result = EBML_MasterAppend((ebml_master*)ClusterW,EBML_ElementParent((ebml_element*)pBlockInfo->Block)); } } if (Result != ERR_NONE) { if (Result==ERR_INVALID_DATA) TextPrintf(StdErr,T("Impossible to remux, the TimecodeScale may be too low, try --timecodescale 1000000\r\n")); else TextPrintf(StdErr,T("Impossible to remux, error appending a block\r\n")); Result = -46; goto exit; } ARRAYBEGIN(TrackBlockCurrIdx,size_t)[*pTrackOrder]++; } if (*pTrackOrder==MainTrack) { if (MainBlockEnd == INVALID_TIMECODE_T || BlockEnd == MasterEndTimecode) ReachedClusterEnd = 1; break; } } } } } ArrayClear(&KeyFrameTimecodes); ArrayClear(&TrackBlocks); ArrayClear(&TrackBlockCurrIdx); ArrayClear(&TrackOrder); Clusters = &WClusters; NodeDelete((node*)RCues); RCues = NULL; } if (WTrackInfo) { array *HeaderData = NULL; ebml_binary *CodecPrivate; ebml_master *Encodings; size_t TrackNum; tchar_t CodecID[MAXDATA]; // fix/clean the Lacing flag for each track //assert(MATROSKA_ContextFlagLacing.DefaultValue==1); for (RLevel1 = (ebml_master*)EBML_MasterChildren(WTrackInfo); RLevel1; RLevel1=(ebml_master*)EBML_MasterNext(RLevel1)) { if (EBML_ElementIsType((ebml_element*)RLevel1, &MATROSKA_ContextTrackEntry)) { int encoding = MATROSKA_BLOCK_COMPR_NONE; int zlib_scope = MATROSKA_COMPR_SCOPE_BLOCK; Elt2 = EBML_MasterFindChild(RLevel1,&MATROSKA_ContextTrackNumber); if (!Elt2) continue; TrackNum = (size_t)EBML_IntegerValue((ebml_integer*)Elt2); if (ARRAYBEGIN(WTracks,track_info)[TrackNum].IsLaced) { // has lacing Elt2 = EBML_MasterFindChild(RLevel1,&MATROSKA_ContextFlagLacing); if (Elt2) NodeDelete((node*)Elt2); } else { // doesn't have lacing Elt2 = EBML_MasterFindFirstElt(RLevel1,&MATROSKA_ContextFlagLacing,1,0); EBML_IntegerSetValue((ebml_integer*)Elt2,0); } CodecPrivate = (ebml_binary*) EBML_MasterFindChild(RLevel1,&MATROSKA_ContextCodecPrivate); if (CodecPrivate && CodecPrivate->Base.DataSize==0) { NodeDelete((node*)CodecPrivate); CodecPrivate = NULL; } Encodings = (ebml_master*)EBML_MasterFindChild(RLevel1,&MATROSKA_ContextContentEncodings); if (UnOptimize) // remove the previous track compression encoding = MATROSKA_BLOCK_COMPR_NONE; else if (!Optimize) // keep the same kind of encoding as before encoding = MATROSKA_TrackGetBlockCompression((matroska_trackentry*)RLevel1); else { Elt = EBML_MasterFindFirstElt(RLevel1,&MATROSKA_ContextCodecID,1,0); EBML_StringGet((ebml_string*)Elt,CodecID,TSIZEOF(CodecID)); if (tcsisame_ascii(CodecID,T("S_USF")) || tcsisame_ascii(CodecID,T("S_VOBSUB")) || tcsisame_ascii(CodecID,T("S_HDMV/PGS")) || tcsisame_ascii(CodecID,T("B_VOBBTN")) || tcsisame_ascii(CodecID,T("V_UNCOMPRESSED"))|| tcsstr(CodecID,T("A_PCM"))==CodecID) encoding = MATROSKA_BLOCK_COMPR_ZLIB; else { // don't keep the zlib compression on compressed codecs //encoding = MATROSKA_TrackGetBlockCompression((matroska_trackentry*)RLevel1); //if (encoding == MATROSKA_BLOCK_COMPR_NONE || encoding == MATROSKA_BLOCK_COMPR_HEADER) { HeaderData = ARRAYBEGIN(TrackMaxHeader,array)+TrackNum; if (ARRAYCOUNT(*HeaderData,uint8_t)) encoding = MATROSKA_BLOCK_COMPR_HEADER; } } } if (encoding == MATROSKA_BLOCK_COMPR_NONE) zlib_scope = 0; else { if (Encodings) { Elt = EBML_MasterFindChild((ebml_master*)Encodings,&MATROSKA_ContextContentEncoding); if (Elt) { Elt2 = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentEncodingScope); if (Elt2) zlib_scope = EBML_IntegerValue((ebml_integer*)Elt2); } } } // see if we can add CodecPrivate too if ((Optimize || encoding != MATROSKA_BLOCK_COMPR_NONE) && encoding != MATROSKA_BLOCK_COMPR_HEADER && zlib_scope != MATROSKA_COMPR_SCOPE_PRIVATE) { if (CodecPrivate!=NULL) { size_t ExtraCompHeaderBytes = (encoding == MATROSKA_BLOCK_COMPR_NONE) ? 13 : 3; // extra bytes needed to add the comp header to the track size_t CompressedSize = ARRAYCOUNT(CodecPrivate->Data,uint8_t); uint8_t *Compressed = malloc(CompressedSize); if (CompressFrameZLib(ARRAYBEGIN(CodecPrivate->Data,uint8_t), (size_t)CodecPrivate->Base.DataSize, &Compressed, &CompressedSize)==ERR_NONE && (CompressedSize + ExtraCompHeaderBytes) < CodecPrivate->Base.DataSize) { encoding = MATROSKA_BLOCK_COMPR_ZLIB; zlib_scope |= MATROSKA_COMPR_SCOPE_PRIVATE; } free(Compressed); } } switch (encoding) { case MATROSKA_BLOCK_COMPR_ZLIB: case MATROSKA_BLOCK_COMPR_BZLIB: // transform bzlib into zlib case MATROSKA_BLOCK_COMPR_LZO1X: // transform lzo1x into zlib if (MATROSKA_TrackSetCompressionZlib((matroska_trackentry*)RLevel1, zlib_scope)) ClustersNeedRead = 1; break; case MATROSKA_BLOCK_COMPR_HEADER: if (!HeaderData || MATROSKA_TrackSetCompressionHeader((matroska_trackentry*)RLevel1, ARRAYBEGIN(*HeaderData,uint8_t), ARRAYCOUNT(*HeaderData,uint8_t))) ClustersNeedRead = 1; break; default: if (MATROSKA_TrackSetCompressionNone((matroska_trackentry*)RLevel1)) ClustersNeedRead = 1; break; } Encodings = (ebml_master*)EBML_MasterFindChild(RLevel1,&MATROSKA_ContextContentEncodings); if (Encodings) { if ((Elt2 = EBML_MasterFindChild(Encodings,&MATROSKA_ContextContentEncoding)) != NULL) { Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentEncodingScope); if (EBML_IntegerValue((ebml_integer*)Elt) & MATROSKA_COMPR_SCOPE_BLOCK) { Elt = EBML_MasterGetChild((ebml_master*)Elt2,&MATROSKA_ContextContentCompression); Elt = EBML_MasterGetChild((ebml_master*)Elt,&MATROSKA_ContextContentCompAlgo); if (EBML_IntegerValue((ebml_integer*)Elt)!=MATROSKA_BLOCK_COMPR_HEADER) ClustersNeedRead = 1; } } } } } } if (!Live) { // cues if (ARRAYCOUNT(*Clusters,ebml_element*) < 2) { NodeDelete((node*)RCues); RCues = NULL; } else if (RCues) { ReduceSize((ebml_element*)RCues); if (!EBML_MasterCheckMandatory(RCues,0)) { TextWrite(StdErr,T("The original Cues are missing mandatory elements, creating from scratch\r\n")); NodeDelete((node*)RCues); RCues = NULL; } else if (EBML_MasterUseChecksum(RCues,!Unsafe)) EBML_ElementUpdateSize(RCues,0,0); } if (!RCues && WTrackInfo && ARRAYCOUNT(*Clusters,ebml_element*) > 1) { // generate the cues RCues = (ebml_master*)EBML_ElementCreate(&p,&MATROSKA_ContextCues,0,NULL); EBML_MasterUseChecksum(RCues,!Unsafe); if (!Quiet) TextWrite(StdErr,T("Generating Cues from scratch\r\n")); CuesCreated = GenerateCueEntries(RCues,Clusters,WTrackInfo,WSegmentInfo,(ebml_element*)RSegment, TotalSize); if (!CuesCreated) { NodeDelete((node*)RCues); RCues = NULL; } } if (RCues) { WSeekPoint = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)WSeekPoint,!Unsafe); EBML_ElementForcePosition((ebml_element*)RCues, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RCues,0); MATROSKA_LinkMetaSeekElement(WSeekPoint,(ebml_element*)RCues); } ExtraVoidSize = 2 * EXTRA_SEEK_SPACE; // leave room for 2 unknown level1 elements if (!RTags) ExtraVoidSize += EXTRA_SEEK_SPACE; if (!RAttachments) ExtraVoidSize += EXTRA_SEEK_SPACE; if (!RChapters) ExtraVoidSize += EXTRA_SEEK_SPACE; // first cluster if (ARRAYCOUNT(RClusters,matroska_cluster*)) { W1stClusterSeek = (matroska_seekpoint*)EBML_MasterAddElt(WMetaSeek,&MATROSKA_ContextSeek,0); EBML_MasterUseChecksum((ebml_master*)W1stClusterSeek,!Unsafe); EBML_ElementForcePosition(ARRAYBEGIN(*Clusters,ebml_element*)[0], NextPos + ExtraVoidSize); NextPos += EBML_ElementFullSize(ARRAYBEGIN(*Clusters,ebml_element*)[0],0); MATROSKA_LinkMetaSeekElement(W1stClusterSeek,ARRAYBEGIN(*Clusters,ebml_element*)[0]); } // first estimation of the MetaSeek size MetaSeekUpdate(WMetaSeek); MetaSeekBefore = EBML_ElementFullSize((ebml_element*)WMetaSeek,0); NextPos = EBML_ElementPositionData((ebml_element*)WSegment) + EBML_ElementFullSize((ebml_element*)WMetaSeek,0); NextPos += ExtraVoidSize; } EBML_ElementUpdateSize(WSegmentInfo,0,0); EBML_ElementForcePosition((ebml_element*)WSegmentInfo, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)WSegmentInfo,0); // Compute the Track Info size if (WTrackInfo) { ReduceSize((ebml_element*)WTrackInfo); EBML_ElementUpdateSize(WTrackInfo,0,0); EBML_ElementForcePosition((ebml_element*)WTrackInfo, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)WTrackInfo,0); } if (!Live) { ebml_element *Void; // Compute the Chapters size if (RChapters) { ReduceSize((ebml_element*)RChapters); EBML_ElementUpdateSize(RChapters,0,0); EBML_ElementForcePosition((ebml_element*)RChapters, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RChapters,0); } // Compute the Attachments size if (RAttachments) { ReduceSize((ebml_element*)RAttachments); EBML_ElementUpdateSize(RAttachments,0,0); EBML_ElementForcePosition((ebml_element*)RAttachments, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RAttachments,0); } // Compute the Tags size if (RTags) { EBML_ElementUpdateSize(RTags,0,0); EBML_ElementForcePosition((ebml_element*)RTags, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RTags,0); } MetaSeekUpdate(WMetaSeek); NextPos += EBML_ElementFullSize((ebml_element*)WMetaSeek,0) - MetaSeekBefore; // Compute the Cues size if (WTrackInfo && RCues) { OptimizeCues(RCues,Clusters,WSegmentInfo,NextPos, WSegment, TotalSize, !CuesCreated, !Unsafe, ClustersNeedRead?Input:NULL); EBML_ElementForcePosition((ebml_element*)RCues, NextPos); NextPos += EBML_ElementFullSize((ebml_element*)RCues,0); } else if (ARRAYCOUNT(*Clusters,ebml_element*)==1) EBML_ElementForcePosition(ARRAYBEGIN(*Clusters,ebml_element*)[0], NextPos); // update and write the MetaSeek and the elements following // write without the fake Tags pointer Stream_Seek(Output,EBML_ElementPosition((ebml_element*)WMetaSeek),SEEK_SET); MetaSeekUpdate(WMetaSeek); EBML_ElementFullSize((ebml_element*)WMetaSeek,0); if (EBML_ElementRender((ebml_element*)WMetaSeek,Output,0,0,1,&MetaSeekBefore)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the final Meta Seek\r\n")); Result = -22; goto exit; } SegmentSize += MetaSeekBefore; // create a fake placeholder elements to have its position prepared in the SeekHead Void = EBML_ElementCreate(WMetaSeek,&EBML_ContextEbmlVoid,1,NULL); EBML_VoidSetFullSize(Void, ExtraVoidSize); if (EBML_ElementRender((ebml_element*)Void,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Void after Meta Seek\r\n")); Result = -24; goto exit; } NodeDelete((node*)Void); SegmentSize += ClusterSize; } else if (!Unsafe) SetClusterPrevSize(Clusters, ClustersNeedRead?Input:NULL); if (EBML_ElementRender((ebml_element*)WSegmentInfo,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Segment Info\r\n")); Result = -11; goto exit; } SegmentSize += ClusterSize; if (WTrackInfo) { if (EBML_ElementRender((ebml_element*)WTrackInfo,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Track Info\r\n")); Result = -12; goto exit; } SegmentSize += ClusterSize; } if (!Live && RChapters) { if (EBML_ElementRender((ebml_element*)RChapters,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Chapters\r\n")); Result = -13; goto exit; } SegmentSize += ClusterSize; } // Write the Attachments if (!Live && RAttachments) { ReduceSize((ebml_element*)RAttachments); if (EBML_ElementRender((ebml_element*)RAttachments,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Attachments\r\n")); Result = -17; goto exit; } SegmentSize += ClusterSize; } if (!Live && RTags) { if (EBML_ElementRender((ebml_element*)RTags,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Tags\r\n")); Result = -14; goto exit; } SegmentSize += ClusterSize; } if (!Live && RCues) { if (EBML_ElementRender((ebml_element*)RCues,Output,0,0,1,&CuesSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Cues\r\n")); Result = -15; goto exit; } SegmentSize += CuesSize; } // Write the Clusters ClusterSize = INVALID_FILEPOS_T; PrevTimecode = INVALID_TIMECODE_T; CuesChanged = 0; CurrentPhase = TotalPhases; for (Cluster = ARRAYBEGIN(*Clusters,ebml_master*);Cluster != ARRAYEND(*Clusters,ebml_master*); ++Cluster) { ShowProgress((ebml_element*)*Cluster, TotalSize); CuesChanged = WriteCluster(*Cluster,Output,Input, ClusterSize, &PrevTimecode) || CuesChanged; if (!Unsafe) ClusterSize = EBML_ElementFullSize((ebml_element*)*Cluster,0); SegmentSize += EBML_ElementFullSize((ebml_element*)*Cluster,0); } EndProgress(); if (CuesChanged && !Live && RCues) { filepos_t PosBefore = Stream_Seek(Output,0,SEEK_CUR); Stream_Seek(Output,EBML_ElementPosition((ebml_element*)RCues),SEEK_SET); UpdateCues(RCues, WSegment); if (EBML_ElementRender((ebml_element*)RCues,Output,0,0,1,&ClusterSize)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the Cues\r\n")); Result = -16; goto exit; } if (CuesSize >= ClusterSize+2) { // the cues were shrinked, write a void element ebml_element *Void = EBML_ElementCreate(RCues,&EBML_ContextEbmlVoid,1,NULL); EBML_VoidSetFullSize(Void, CuesSize - ClusterSize); EBML_ElementRender(Void,Output,0,0,1,NULL); } else { assert(ClusterSize == CuesSize); if (ClusterSize != CuesSize) { TextWrite(StdErr,T("The Cues size changed after a Cluster timecode was altered!\r\n")); Result = -18; goto exit; } } Stream_Seek(Output,PosBefore,SEEK_SET); } // update the WSegment size if (!Live) { if (EBML_ElementDataSize((ebml_element*)WSegment,0)!=INVALID_FILEPOS_T && SegmentSize - ExtraSizeDiff - ExtraVoidSize > EBML_ElementDataSize((ebml_element*)WSegment,0)) { if (EBML_CodedSizeLength(SegmentSize,EBML_ElementSizeLength((ebml_element*)WSegment),0) != EBML_CodedSizeLength(SegmentSize,EBML_ElementSizeLength((ebml_element*)WSegment),0)) { // TODO: this check is always false TextPrintf(StdErr,T("The segment written is much bigger than the original %") TPRId64 T(" vs %") TPRId64 T(" !\r\n"),SegmentSize,EBML_ElementDataSize((ebml_element*)WSegment,0)); Result = -20; goto exit; } if (!Quiet) TextPrintf(StdErr,T("The segment written is bigger than the original %") TPRId64 T(" vs %") TPRId64 T(" !\r\n"),SegmentSize,EBML_ElementDataSize((ebml_element*)WSegment,0)); } if (EBML_CodedSizeLength(EBML_ElementDataSize((ebml_element*)WSegment,0),0,!Live) > EBML_CodedSizeLength(SegmentSize,0,!Live)) EBML_ElementSetSizeLength((ebml_element*)WSegment, EBML_CodedSizeLength(EBML_ElementDataSize((ebml_element*)WSegment,0),0,!Live)); EBML_ElementForceDataSize((ebml_element*)WSegment, SegmentSize); Stream_Seek(Output,EBML_ElementPosition((ebml_element*)WSegment),SEEK_SET); if (EBML_ElementRenderHead((ebml_element*)WSegment, Output, 0, NULL)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the final Segment size !\r\n")); Result = -21; goto exit; } // update the Meta Seek MetaSeekUpdate(WMetaSeek); //Stream_Seek(Output,EBML_ElementPosition(WMetaSeek,SEEK_SET); if (EBML_ElementRender((ebml_element*)WMetaSeek,Output,0,0,1,&MetaSeekAfter)!=ERR_NONE) { TextWrite(StdErr,T("Failed to write the final Meta Seek\r\n")); Result = -22; goto exit; } if (MetaSeekBefore != MetaSeekAfter) { TextPrintf(StdErr,T("The final Meta Seek size has changed %") TPRId64 T(" vs %") TPRId64 T(" !\r\n"),MetaSeekBefore,MetaSeekAfter); Result = -23; goto exit; } } if (!Quiet) TextPrintf(StdErr,T("Finished cleaning & optimizing \"%s\"\r\n"),Path); exit: NodeDelete((node*)WSegment); for (Cluster = ARRAYBEGIN(RClusters,ebml_master*);Cluster != ARRAYEND(RClusters,ebml_master*); ++Cluster) NodeDelete((node*)*Cluster); ArrayClear(&RClusters); for (Cluster = ARRAYBEGIN(WClusters,ebml_master*);Cluster != ARRAYEND(WClusters,ebml_master*); ++Cluster) NodeDelete((node*)*Cluster); for (MaxTrackNum=0;MaxTrackNumStream = (stream*)NodeSingleton(&p,STDERR_ID); memset(&RegParser,0,sizeof(RegParser)); #if 1 tcscpy_s(MkPath,TSIZEOF(MkPath),T("mkclean")); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[0]); SplitPath(Path,MkPath,TSIZEOF(MkPath),NULL,0,NULL,0); if (MkPath[0]) AddPathDelimiter(MkPath,TSIZEOF(MkPath)); tcscat_s(MkPath,TSIZEOF(MkPath),T("mkclean")); #endif if (argc<2) { TextWrite(StdErr,T("No list of regression files provided!\r\n")); Result = -1; goto exit; } for (i=1;i\r\n")); TextWrite(StdErr,T("Options:\r\n")); TextWrite(StdErr,T(" --mkclean path to mkclean to test (default is current path)\r\n")); TextWrite(StdErr,T(" --generate output is usable as a regression list file\r\n")); TextWrite(StdErr,T(" --quiet don't display messages from mkvalidator\r\n")); TextWrite(StdErr,T(" --keep keep the output files\r\n")); TextWrite(StdErr,T(" --version show the version of mkvalidator\r\n")); TextWrite(StdErr,T(" --help show this screen\r\n")); TextWrite(StdErr,T("regression file format:\r\n")); TextWrite(StdErr,T("\"\" \"\" \r\n")); } Result = -2; goto exit; } #if defined(TARGET_WIN) && defined(UNICODE) Node_FromWcs(&p,Path,TSIZEOF(Path),argv[argc-1]); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[argc-1]); #endif if (!FileExists((nodecontext*)&p, Path)) { TextPrintf(StdErr,T("The file with the list of regression files '%s' could not be found!\r\n"),Path); Result = -3; goto exit; } RegList = StreamOpen(&p, Path, SFLAG_RDONLY); if (!RegList) { TextPrintf(StdErr,T("Could not read '%s'\r\n"),Path); Result = -4; goto exit; } if (ParserStream(&RegParser,RegList,&p)!=ERR_NONE) { TextPrintf(StdErr,T("Could not parse '%s'\r\n"),Path); Result = -5; goto exit; } SplitPath(Path,FileRoot,TSIZEOF(FileRoot),NULL,0,NULL,0); if (!FileRoot[0]) { FileRoot[0] = '.'; FileRoot[1] = 0; } AddPathDelimiter(FileRoot,TSIZEOF(FileRoot)); LineNum = 1; while (ParserLine(&RegParser, Line, TSIZEOF(Line))) { const tchar_t *s = Line; // parse the line and if it's OK, launch the process if (!ExprIsTokenEx(&s,T("\"%s\" \"%s\" %") TPRId64 T(" %s"),Path,TSIZEOF(Path),String,TSIZEOF(String),&Size,MD5,TSIZEOF(MD5))) { if (!Generate) TextPrintf(StdErr,T("Fail:100:%d: Invalid Line %s\r\n"),LineNum,Line); } else { // transform the path relative to the regression file to an absolute file tcscpy_s(Line,TSIZEOF(Line),FileRoot); tcscat_s(Line,TSIZEOF(Line),Path); testFile((nodecontext*)&p, LineNum, Line, String, Size, MD5); } ++LineNum; } // TODO: compare the extracted raw tracks MD5 to the original tracks exit: ParserStream(&RegParser,NULL,NULL); StreamClose(RegList); // Core-C ending StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return Result; } bcmatroska2-5.3.101/mkclean/regression/regression.mkc000066400000000000000000000353661462133141200225510ustar00rootroot00000000000000"ar-odd.mkv" " " 1035532 26668df091663de62579e8711b900046 "ar-odd.mkv" "--remux " 1035461 167647b5995ec2315f9b898fa3e5d806 "ar-odd.mkv" "--optimize " 1035331 7df0f3f40ae97609799774bfc5c56ca0 "ar-odd.mkv" "--remux --optimize" 1035260 7fec7cf54eeb8178a51e89d08ea95fe2 "ar-odd.mkv" "--unsafe " 1035452 cfb9e8567412ba4f5cbc4742b23a8045 "ar-odd.mkv" "--remux --unsafe " 1035407 ab64ab5c1c515705215450a2fd3fcfa3 "null-junk.mkv" " " 1035049 f4d24a69231e80d3fdbea97fbe630d7e "null-junk.mkv" "--remux " 1035049 f4d24a69231e80d3fdbea97fbe630d7e "null-junk.mkv" "--optimize " 1034848 579a9512baffcd05706df954b4512f92 "null-junk.mkv" "--unsafe " 1034995 759263889edcc08f04b605aec4e32ae8 "ar-set_to_0.mkv" " " 156727 428a01286245cd875bd0266342fbb84c "ar-set_to_0.mkv" "--remux " 156779 9f938a800a93972284639e9fe3a0e3b3 "ar-set_to_0.mkv" "--optimize " 156571 cb4f049627340b31b4ff416a92abc3ec "ar-set_to_0.mkv" "--remux --optimize" 156623 6ce06c5d3742d027ef72f26d94f732b4 "ar-set_to_0.mkv" "--unsafe " 156653 01f824235460e6cd8df30eb4a074e4eb "ar-set_to_0.mkv" "--remux --unsafe " 156688 04d67565302862c055752f8d6b013e87 "3D-v2-left.mkv" " " 1657173 b30acae2fdd8a839012bb5ca3bd6dfda "3D-v2-left.mkv" "--remux " 1657155 6ea57a7a48b41e41ebb4681a70e9e74d "3D-v2-left-right.mkv" " " 2988245 6cbb69ff690caa0eb25efe51fb0123c1 "3D-v2-left-right.mkv" "--remux --unsafe " 2987905 2b707d8d7e8b3acfc0dfe8de9128d2d7 "mkclean-crash.mkv" " " 1035483 05aa4f5cb6f151811ba88a052e9e171f "mkclean-crash.mkv" "--remux " 1035493 80d2fc58c9a6929e776e652cdbc9dced "mkclean-crash.mkv" "--optimize " 1035282 2db17059465166491144c3831af79738 "mkclean-crash.mkv" "--remux --optimize" 1035292 ec2f63d4007825bf2afb989bf41ac753 "mkclean-crash.mkv" "--unsafe " 1035403 8ef72e70c2e4e0f82ae93934a1d060eb "mkclean-crash.mkv" "--remux --unsafe " 1035413 50e70b91ea764897d77e6c1acdc455bb "haali.mkv" " " 1034769 2115ecce5795bd4f49796f224d01f1a0 "haali.mkv" "--remux " 1034769 d1f94211c4473dbbf02481bb9fbd71a0 "haali.mkv" "--optimize " 1034724 49a3d6e6aaeae6fd7e0480f8fb4bc84c "haali.mkv" "--remux --optimize" 1034724 28fac9fc3575c500e1af43b21d494714 "haali.mkv" "--unsafe " 1034715 791e9c858d8f7ad448e17926fb2cb57a "haali.mkv" "--remux --unsafe " 1034715 ec941d63fdc54777286e1fee7b93c2b7 "video-only.mkv" "--doctype 2 --remux" 75420 70fef2f47d8fa449e725859874240f8a "video-only.mkv" "--doctype 2 --optimize" 74755 b9e8f8d38d2bccde0e647a54da31eb56 "video-only.mkv" "--doctype 2 --remux --optimize" 74755 b9e8f8d38d2bccde0e647a54da31eb56 "video-only.mkv" "--doctype 2 --remux --unsafe" 75291 7dbd48ccbd6c8dd4d5588de3da97512a "sample252kb.mkv" "--doctype 2 " 201247 28ac0cf2e0c85be6f6c239510a59d6ea "sample252kb.mkv" "--doctype 2 --remux" 201247 b7db8e6800b0ecbf69c02c8039524552 "sample252kb.mkv" "--doctype 2 --optimize" 200936 6fcf31a0afa143d5b77b135107da671f "sample252kb.mkv" "--doctype 2 --remux --optimize" 200936 4ff50956a3a67be6129312a0fc46afb1 "sample252kb.mkv" "--doctype 2 --unsafe" 201181 8518c40c88bc3013f8ca2a586bf74925 "sample252kb.mkv" "--doctype 2 --remux --unsafe" 201181 6aa8893c1945efa6e1750af4d0de16bb "live-stream.webm" "--live " 305596 15fa200fa2c117a89960ea12a3bdecda "live-stream.webm" "--live --remux " 305596 2b810da789caab9679d405b055c091f0 "live-stream.webm" "--live --unsafe " 305545 8225a24d5b141265e317f430a077ec0e "live-stream.webm" "--live --remux --unsafe" 305557 648cd7b5687c54f4423e285a52deb4e5 "bad-stereo.mkv" " " 1035056 e36cbbede4c231113fd4fadfe8d1093f "bad-stereo.mkv" "--remux " 1034985 e373f1701b5fc49a8c37488ab20502cb "bad-stereo.mkv" "--optimize " 1034855 5a57ca017f2dd9cccff1b8db1e949586 "bad-stereo.mkv" "--remux --optimize" 1034784 fa1042ca209c3010cd656eccb4347827 "bad-stereo.mkv" "--unsafe " 1034976 68320a1b230fe06536dda806670bf284 "bad-stereo.mkv" "--remux --unsafe " 1034931 2bf99974a3f8c90cf21f1948b69e03e0 "audio-only.mka" " " 2055631 192c4eff82a071955c62144a087d539b "audio-only.mka" "--remux " 2054226 29789897bc45f3d8d831f1d6c7d59699 "audio-only.mka" "--optimize " 2044730 e825cfc8dc01e4e1a8582c96aaf9a2c3 "audio-only.mka" "--remux --optimize" 2043325 8328b7d803215d19d90b3d2f98cfc875 "audio-only.mka" "--unsafe " 2052203 dd60ed6d9625f988fc566ce36b951500 "audio-only.mka" "--remux --unsafe " 2051910 506af34d56fa2e33f8bf49f55abe01a4 "FTDcom30-WebM_640x480.webm" "--doctype 2 --optimize" 5079761 425689057fd14a6e32f3676429e73af0 "FTDcom30-WebM_640x480_optimized.mkv" "--doctype 4 " 5081398 bf6789e54c81aa02401d1c1cd933aecf "odd-cues.mkv" " " 14621026 de4e33b7bc2abd60eff52e7fd953aa29 "odd-cues.mkv" "--remux " 14621026 685dc9c989bafb249187916685ad6536 "odd-cues.mkv" "--optimize " 14617391 32b8eed4e012968eb8fd2ac7d5ae47f0 "odd-cues.mkv" "--remux --unsafe " 14620747 8a289f9d5596571ee42061ae03e18eae "crc.mkv" " " 14621053 3521f335b74974d6aad2af05849e90bf "crc.mkv" "--remux " 14620962 f5ea486d0d0333e8f54ea1e9782d5a36 "crc.mkv" "--optimize " 14617418 70eefed9068a7d8abe0b2e6b10873371 "crc.mkv" "--remux --optimize" 14617327 29fa40364d653247844f00cb67075052 "crc.mkv" "--unsafe " 14620643 7be41458ff8c9c1294ebde00328bb017 "crc.mkv" "--remux --unsafe " 14620683 be47f44903dca49fd080b8e122e27bcb "lzo.mkv" " " 14622599 b7d2d37a747e0b342d49f4433ed49616 "lzo.mkv" "--remux " 14622606 7b10d81a9aa6c3e73769a0fafb225038 "lzo.mkv" "--optimize " 14606392 c2c3e662cea7a937d4c582a850d390c9 "lzo.mkv" "--remux --optimize" 14606399 995bb6ff2421634a354b13f019e777e8 "lzo.mkv" "--unsafe " 14622350 3c460a1fd053246ea3f1b0f34fc91e04 "lzo.mkv" "--remux --unsafe " 14622387 ed7e4f2f81a67dc0bcd4da0aace479bd "WorldFontsDemo.mkv" " " 14727090 e6e14558c86e3f5ae36b5104ae8f3123 "WorldFontsDemo.mkv" "--remux " 14725875 75e6ce05962926b666a97db04844bfac "WorldFontsDemo.mkv" "--optimize " 14723454 6b350b46a0c02e8b0e948742912fe9be "WorldFontsDemo.mkv" "--remux --optimize" 14722239 61daaa3214694dc775ebc178d8b1dd59 "WorldFontsDemo.mkv" "--unsafe " 14726225 854e4b55b409934c6858c059fda7d80c "WorldFontsDemo.mkv" "--remux --unsafe " 14725581 dde3cbdf802e892a42efbf80016f3de8 "SmoothFFRWDemo.mkv" " " 15486131 00644b9f2c74eff381d970894ad1631c "SmoothFFRWDemo.mkv" "--remux " 15485840 0861a7d3111ec358130255e45db20677 "SmoothFFRWDemo.mkv" "--optimize " 15482444 16a634b6b5b411cacec9b22f2d5f59a5 "SmoothFFRWDemo.mkv" "--remux --optimize" 15482153 f29ed393d5fd9be2fafa3525be8d4af0 "SmoothFFRWDemo.mkv" "--unsafe " 15485757 1bc8518b70b11cc54a0a2675765b3c0b "SmoothFFRWDemo.mkv" "--remux --unsafe " 15485605 a397578b492d07f8b52dbf3fe6556f8e "Handbrake-3441.mkv" " " 17929533 da96ec31f7fb32c74518fc9eddc18dbf "Handbrake-3441.mkv" "--remux " 17929659 5c760044b9c673bd8ce41230f259076d "Handbrake-3441.mkv" "--optimize " 17928935 e9028c6598c62c9b8e22c4ca0ac2ddab "Handbrake-3441.mkv" "--remux --optimize" 17929061 5a8e62eb4c821fa1d239aaef1e6be366 "Handbrake-3441.mkv" "--unsafe " 17929433 e7866698e5e24461397e96dc05e6cb7f "Handbrake-3441.mkv" "--remux --unsafe " 17929529 5322150ad26f9d4713b7db3a6703e6fc "mp3-compr.mkv" " " 21620883 399c467fcf1b896a22d2d9449aadf10a "mp3-compr.mkv" "--remux " 21620717 a2a32fe4e86485328437e84c91c6b0b4 "mp3-compr.mkv" "--optimize " 21614426 80caa1c01e37208ecb2326f4cd5ff56e "mp3-compr.mkv" "--remux --optimize" 21614260 518f92ece7a2ab5d5b4db47e1e3fa330 "mp3-compr.mkv" "--unsafe " 21620261 f41c1d0ee500bcda1abdbd077b5a75e7 "mp3-compr.mkv" "--remux --unsafe " 21620276 618730d70d4ba9f8a29afbc3e527b45f "attachment.mkv" " " 23352190 ed6aaa8be549a46187b0c9d62f71d6d4 "attachment.mkv" "--remux " 23351633 6eb32e27ecddf12c9eea3c11c5516a73 "attachment.mkv" "--optimize " 23344930 44b458a81b5c5db3e6b27605241e6437 "attachment.mkv" "--remux --optimize" 23344373 37606e01968d65e4877526b289796490 "attachment.mkv" "--unsafe " 23351707 f744ea42e690626097044c1498111501 "attachment.mkv" "--remux --unsafe " 23351436 4dbe28e0f78a9aa2e62d53868649b6db "ac3.mkv" " " 25818234 b9b79f84a020545b07251dbca6a0fdea "ac3.mkv" "--remux " 25817936 cfeda94b08769fb6b8605e17b8759b9b "ac3.mkv" "--optimize " 25816586 0289abe74ab30e8d0013e75de738dea3 "ac3.mkv" "--remux --optimize" 25816288 7eab579052635d12d1afac9d6fb7cd32 "ac3.mkv" "--remux --unsafe " 25817764 5bda06570bc73993913d71232ea2b41c "zlib-audio.mkv" " " 25842518 b00ef7f86bd744591964a5e56a170c90 "zlib-audio.mkv" "--remux " 25842220 86f41da158c77c6493284c9fc4a65c0c "zlib-audio.mkv" "--optimize " 25820982 4f6c78903bfa8f2aa1a7eb8be8ef81ba "zlib-audio.mkv" "--remux --optimize" 25820684 bcdcbe462fcd1ae7b4f262c110e3e432 "zlib-audio.mkv" "--unsafe " 25842201 d1319eca6af1eac8e2a5263154326786 "zlib-audio.mkv" "--remux --unsafe " 25842048 56258f13d3b04a82f3eb930cd74348e9 "zlib-audio.mkv" "--no-optimize " 25822630 74ff2093d58a61ce8c0268f5697bf813 "zlib-audio.mkv" "--remux --no-optimize" 25822332 07f6a3adba71c5dd444dcee9eec45b3c "zlib-audio.mkv" "--unsafe --no-optimize" 25822313 1f5339502d7f94bdc0e14ddd2f007130 "zlib-audio.mkv" "--remux --unsafe --no-optimize" 25822160 3127f1f058c2f590ddfb4c63d79c794d "ar.mkv" " " 54089814 b3174bd7b88949442baa2475ff454289 "ar.mkv" "--remux " 54089362 ddc19ac6d5d933f66561e8349b85a316 "ar.mkv" "--optimize " 54079938 51f6731d6a6e135fc5130fb051a1cd00 "ar.mkv" "--remux --optimize" 54079486 bd25e8fbb7627c0334d64196aa186cac "ar.mkv" "--unsafe " 54089133 7accae557a281a19502254b9eefd1784 "ar.mkv" "--remux --unsafe " 54089002 ca404d7bad426d5a1ce19f1451b12dfb "dts.mkv" " " 59794059 fd4064cbceb08ce9895b0a19fd15701a "dts.mkv" "--remux " 59794020 b97b4e7267619df447448db2ecd9f49d "dts.mkv" "--optimize " 59606224 f5044dac2e72c4bbd411dc5e054d3a10 "dts.mkv" "--remux --optimize" 59606185 092b91530d99116616c869f0440773a5 "dts.mkv" "--unsafe " 59793875 b9a26fea10b6911688bb69a38bb538c8 "dts.mkv" "--remux --unsafe " 59793842 98266572ea2586325f8c77ce4c6d33bc "dts-lzo.mkv" " " 59755645 8320dbc539fce1067e04c5d8b377e946 "dts-lzo.mkv" "--remux " 59754892 e921a0b7814ebbc68240cb3f3e35ac7b "dts-lzo.mkv" "--optimize " 59611198 2dcb15310e58d0b919b9e9bf2d3df1ad "dts-lzo.mkv" "--remux --optimize" 59610445 7f75024b41a9214bd1a79d79c6f8ebf3 "dts-lzo.mkv" "--unsafe " 59755104 601b96e755f69439afad52b0d844bb30 "dts-lzo.mkv" "--remux --unsafe " 59754726 12bac7553e7d354f239e094d1dcc8b96 "dts-bz2.mkv" " " 59755661 f4f9e9cc6311d70d6ed11bc75e744fd1 "dts-bz2.mkv" "--remux " 59754887 0f1d6fc163713c8d851f8503dde02f58 "dts-bz2.mkv" "--optimize " 59611214 51eaf905181078ac290a91d83c0bf1f5 "dts-bz2.mkv" "--remux --optimize" 59610440 7b6118ca681d5ff3d65c573c3d6fee91 "dts-bz2.mkv" "--unsafe " 59755110 00dfcdc5b9c7a2f0436686e0b0f388a6 "dts-bz2.mkv" "--remux --unsafe " 59754721 c7404d08feebe398c766e35b21159304 "chrome_linux_x64_fail.webm" " " 138037768 240d01b22ef925f27868efd48470ab63 "chrome_linux_x64_fail.webm" "--remux " 138037768 dcdb434ab0c953f5502b84799f09e012 "chrome_linux_x64_fail.webm" "--remux --optimize" 138037768 dcdb434ab0c953f5502b84799f09e012 "chrome_linux_x64_fail.webm" "--remux --unsafe " 138036732 fbe72bfdf6bfe463fe7cf67f25572ac2 "A_Digital_Media_Primer_For_Geeks-360p.webm" " " 138041303 560ef9192e79c610d040d7f2b82d0950 "A_Digital_Media_Primer_For_Geeks-360p.webm" "--remux " 138037655 a3c59c22899bbcf98120e8eb59fe6106 "A_Digital_Media_Primer_For_Geeks-360p.webm" "--optimize " 138041303 560ef9192e79c610d040d7f2b82d0950 "A_Digital_Media_Primer_For_Geeks-360p.webm" "--remux --optimize" 138037655 a3c59c22899bbcf98120e8eb59fe6106 "A_Digital_Media_Primer_For_Geeks-360p.webm" "--unsafe " 138039084 63c1c373b73312b0bee1d5847957c48b "A_Digital_Media_Primer_For_Geeks-360p.webm" "--remux --unsafe " 138036619 5289dc5076aa59f010c8b982dad7c478 "fake-side-by-side.webm" " " 138037777 9640e786a92f2ede26b6f45ad70fae62 "fake-side-by-side.webm" "--remux " 138037777 7f13e2640c0f2c0b885e38c9b5313c78 "fake-side-by-side.webm" "--optimize " 138037777 9640e786a92f2ede26b6f45ad70fae62 "fake-side-by-side.webm" "--unsafe " 138036741 e39157d9e0a4365fbf9b1c7ccc763e46 "broken.mkv" " " 76166476 0747a7a5a16bfa03156b7f254759608b "broken.mkv" "--doctype 2 --remux " 76165362 85e20836567929ba4d2b55d4ef4b734d "broken.mkv" "--optimize " 76139326 f1ed7e068b11b4870a4f2ce58caa080f "broken.mkv" "--doctype 2 --remux --optimize" 76138212 6f4108deb76e14081037c3ed3534e9e5 "broken.mkv" "--unsafe " 76164306 a2f54cdef1d7f0cafbea4b7ec2551e9a "broken.mkv" "--doctype 2 --remux --unsafe " 76164433 b541aa9fd83c1ddc1169740d171db0f9 "guadec-2010-07-30-0900-1330.webm" " " 1006694743 bde72ff9c2e7c066d269c21c0ece485c "guadec-2010-07-30-0900-1330.webm" "--remux " 1006694680 191379a45af015f325bb62242a8b4c67 "guadec-2010-07-30-0900-1330.webm" "--optimize " 1006693334 0c7ed24046b053c0018ec1fc3b663770 "guadec-2010-07-30-0900-1330.webm" "--remux --optimize" 1006693271 fdc9fdb787dfb932a48223cf38fade9f "guadec-2010-07-30-0900-1330.webm" "--unsafe " 1006643493 bce41186f448a65445093772737c5bd4 "guadec-2010-07-30-0900-1330.webm" "--remux --unsafe " 1006643451 4e680ee24e2e34e1bfe938c1fc054c90 "damaged.mkv" " " 1171112918 ebcc39be7d30bbe778f8131d9f75ac3f "damaged.mkv" "--remux " 1171094447 88504accab8ecc094743d49c31f39f24 "damaged.mkv" "--optimize " 1171050791 ad4bc00ffb2c788815d803616c608f85 "damaged.mkv" "--remux --optimize" 1171032320 e294f897e7e2cb2dcf327d741205e2ec "damaged.mkv" "--unsafe " 1171095749 80e57c0a8d594f71c9e1dd5b600ccfca "damaged.mkv" "--remux --unsafe " 1171088087 b5bcc5cc98c8cc11a36564191fbfce92 "large.mkv" " " 4695069980 8bb88768bcd331ecdae3c6644384d34d "large.mkv" "--remux " 4695015951 4896f98681ea20ac3cfc1d9150357f5e "large.mkv" "--remux --optimize" 4672242369 8ac24f4eb6ec0d3a2b5a94210fe3a2ab "large.mkv" "--unsafe " 4695031434 d80fe6426a2b7d65d4163aca8299f954 bcmatroska2-5.3.101/mkclean/regression/regression.proj000066400000000000000000000002431462133141200227330ustar00rootroot00000000000000CON mkcleanreg { PROJECT_NAME "mkcleanreg" PROJECT_VERSION 0.1.0 PROJECT_VENDOR "Matroska" USE parser USE md5 USE ccsystem SOURCE mkcleanreg.c } bcmatroska2-5.3.101/mkclean/src.br000066400000000000000000000015501462133141200166150ustar00rootroot00000000000000# corec %(!ROOTPATH)corec %(PROJECT_NAME)-%(PROJECT_VERSION)/corec # libebml2 %(!ROOTPATH)libebml2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libebml2 # libmatroska2 %(!ROOTPATH)libmatroska2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libmatroska2 # %(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME) %(PROJECT_NAME)-%(PROJECT_VERSION)/%(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME)/default_config.h %(PROJECT_NAME)-%(PROJECT_VERSION)/config.h %(!ROOTPATH)%(PROJECT_NAME)/ChangeLog.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ChangeLog.txt %(!ROOTPATH)%(PROJECT_NAME)/ReadMe.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ReadMe.txt %(!ROOTPATH)root.proj %(PROJECT_NAME)-%(PROJECT_VERSION)/root.proj %(¯!BASE)configure %(PROJECT_NAME)-%(PROJECT_VERSION)/configure %(!ROOTPATH)corec/tools/coremake/coremake - *.br - *.vs - Makefile - *.vcproj - *.sln - *_project.h - *_stdafx.* - bcmatroska2-5.3.101/mkclean/tremor/000077500000000000000000000000001462133141200170105ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/CHANGELOG000066400000000000000000000007231462133141200202240ustar00rootroot00000000000000*** 20020517: 1.0.2 *** Playback bugfix to floor1; mode mistakenly used for sizing instead of blockflag *** 20020515: 1.0.1 *** Added complete API documentation to source tarball. No code changes. *** 20020412: 1.0.1 *** Fixed a clipping bug that affected ARM processors; negative overflows were being properly clipped, but then clobbered to positive by the positive overflow chec (asm_arm.h:CLIP_TO_15) *** 20020403: 1.0.0 *** Initial versionbcmatroska2-5.3.101/mkclean/tremor/COPYING000066400000000000000000000026721462133141200200520ustar00rootroot00000000000000Copyright (c) 2002, Xiph.org Foundation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. bcmatroska2-5.3.101/mkclean/tremor/Makefile.am000066400000000000000000000027641462133141200210550ustar00rootroot00000000000000AUTOMAKE_OPTIONS = foreign INCLUDES = -I./ pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = vorbisidec.pc lib_LTLIBRARIES = libvorbisidec.la libvorbisidec_la_SOURCES = mdct.c block.c window.c \ synthesis.c info.c \ floor1.c floor0.c vorbisfile.c \ res012.c mapping0.c registry.c codebook.c \ sharedbook.c framing.c bitwise.c \ codebook.h misc.h mdct_lookup.h\ os.h mdct.h block.h ivorbisfile.h lsp_lookup.h\ registry.h window.h window_lookup.h\ codec_internal.h backends.h ogg.h \ asm_arm.h ivorbiscodec.h libvorbisidec_la_LDFLAGS = -version-info @V_LIB_CURRENT@:@V_LIB_REVISION@:@V_LIB_AGE@ EXTRA_PROGRAMS = ivorbisfile_example iseeking_example CLEANFILES = $(EXTRA_PROGRAMS) $(lib_LTLIBRARIES) ivorbisfile_example_SOURCES = ivorbisfile_example.c ivorbisfile_example_LDFLAGS = -static ivorbisfile_example_LDADD = libvorbisidec.la iseeking_example_SOURCES = iseeking_example.c iseeking_example_LDFLAGS = -static iseeking_example_LDADD = libvorbisidec.la includedir = $(prefix)/include/tremor include_HEADERS = ivorbiscodec.h ivorbisfile.h ogg.h os_types.h config_types.h EXTRA_DIST = vorbisidec.pc.in \ $(srcdir)/doc/*.html $(srcdir)/win32/VS*/libtremor/*.vcproj example: -ln -fs . vorbis $(MAKE) ivorbisfile_example $(MAKE) iseeking_example debug: $(MAKE) all CFLAGS="@DEBUG@" profile: $(MAKE) all CFLAGS="@PROFILE@" bcmatroska2-5.3.101/mkclean/tremor/README000066400000000000000000000036251462133141200176760ustar00rootroot00000000000000This README covers the Ogg Vorbis 'Tremor' integer playback codec source as of date 2002 09 02, version 1.0.0. ****** The C source in this package will build on any ANSI C compiler and function completely and properly on any platform. The included build system assumes GNU build system and make tools (m4, automake, autoconf, libtool and gmake). GCC is not required, although GCC is the most tested compiler. To build using GNU tools, type in the source directory: ./autogen.sh make Currently, the source implements playback in pure C on all platforms except ARM, where a [currently] small amount of assembly (see asm_arm.h) is used to implement 64 bit math operations and fast LSP computation. If building on ARM without the benefit of GNU build system tools, be sure that '_ARM_ASSEM_' is #defined by the build system if this assembly is desired, else the resulting library will use whatever 64 bit math builtins the compiler implements. No math library is required by this source. No floating point operations are used at any point in either setup or decode. This decoder library will properly decode any past, current or future Vorbis I file or stream. ******** The build system produces a static and [when supported by the OS] dynamic library named 'libvorbisidec'. This library exposes an API nearly identical to the BSD reference library's 'libvorbisfile', including all the features familiar to users of vorbisfile. This API is similar enough that the proper header file to include is named 'ivorbisfile.h' [included in the source build directory]. Lower level libvorbis-style headers and structures are in 'ivorbiscodec.h' [included in the source build directory]. A simple example program, ivorbisfile_example.c, can be built with 'make example'. ******** Detailed Tremor API Documentation begins at doc/index.html Monty xiph.org bcmatroska2-5.3.101/mkclean/tremor/Version_script.in000066400000000000000000000021561462133141200223550ustar00rootroot00000000000000# # Export file for libvorbisidec # # Only the symbols listed in the global section will be callable from # applications linking to libvorbisidec. # @PACKAGE@.so.1 { global: ov_clear; ov_open; ov_open_callbacks; ov_test; ov_test_callbacks; ov_test_open; ov_bitrate; ov_bitrate_instant; ov_streams; ov_seekable; ov_serialnumber; ov_raw_total; ov_pcm_total; ov_time_total; ov_raw_seek; ov_pcm_seek; ov_pcm_seek_page; ov_time_seek; ov_time_seek_page; ov_raw_tell; ov_pcm_tell; ov_time_tell; ov_info; ov_comment; ov_read; vorbis_info_init; vorbis_info_clear; vorbis_info_blocksize; vorbis_comment_init; vorbis_comment_add; vorbis_comment_add_tag; vorbis_comment_query; vorbis_comment_query_count; vorbis_comment_clear; vorbis_block_init; vorbis_block_clear; vorbis_dsp_clear; vorbis_synthesis_idheader; vorbis_synthesis_headerin; vorbis_synthesis_init; vorbis_synthesis_restart; vorbis_synthesis; vorbis_synthesis_trackonly; vorbis_synthesis_blockin; vorbis_synthesis_pcmout; vorbis_synthesis_read; vorbis_packet_blocksize; local: *; }; bcmatroska2-5.3.101/mkclean/tremor/asm_arm.h000066400000000000000000000145511462133141200206060ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: arm7 and later wide math functions ********************************************************************/ #ifdef _ARM_ASSEM_ #if !defined(_V_WIDE_MATH) && !defined(_LOW_ACCURACY_) #define _V_WIDE_MATH static inline ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { int lo,hi; asm volatile("smull\t%0, %1, %2, %3" : "=&r"(lo),"=&r"(hi) : "%r"(x),"r"(y) : "cc"); return(hi); } static inline ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { return MULT32(x,y)<<1; } static inline ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { int lo,hi; asm volatile("smull %0, %1, %2, %3\n\t" "movs %0, %0, lsr #15\n\t" "adc %1, %0, %1, lsl #17\n\t" : "=&r"(lo),"=&r"(hi) : "%r"(x),"r"(y) : "cc"); return(hi); } #define MB() asm volatile ("" : : : "memory") static inline void XPROD32(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { int x1, y1, l; asm( "smull %0, %1, %4, %6\n\t" "smlal %0, %1, %5, %7\n\t" "rsb %3, %4, #0\n\t" "smull %0, %2, %5, %6\n\t" "smlal %0, %2, %3, %7" : "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a) : "3" (a), "r" (b), "r" (t), "r" (v) : "cc" ); *x = x1; MB(); *y = y1; } static inline void XPROD31(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { int x1, y1, l; asm( "smull %0, %1, %4, %6\n\t" "smlal %0, %1, %5, %7\n\t" "rsb %3, %4, #0\n\t" "smull %0, %2, %5, %6\n\t" "smlal %0, %2, %3, %7" : "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a) : "3" (a), "r" (b), "r" (t), "r" (v) : "cc" ); *x = x1 << 1; MB(); *y = y1 << 1; } static inline void XNPROD31(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { int x1, y1, l; asm( "rsb %2, %4, #0\n\t" "smull %0, %1, %3, %5\n\t" "smlal %0, %1, %2, %6\n\t" "smull %0, %2, %4, %5\n\t" "smlal %0, %2, %3, %6" : "=&r" (l), "=&r" (x1), "=&r" (y1) : "r" (a), "r" (b), "r" (t), "r" (v) : "cc" ); *x = x1 << 1; MB(); *y = y1 << 1; } #endif #ifndef _V_CLIP_MATH #define _V_CLIP_MATH static inline ogg_int32_t CLIP_TO_15(ogg_int32_t x) { int tmp; asm volatile("subs %1, %0, #32768\n\t" "movpl %0, #0x7f00\n\t" "orrpl %0, %0, #0xff\n" "adds %1, %0, #32768\n\t" "movmi %0, #0x8000" : "+r"(x),"=r"(tmp) : : "cc"); return(x); } #endif #ifndef _V_LSP_MATH_ASM #define _V_LSP_MATH_ASM static inline void lsp_loop_asm(ogg_uint32_t *qip,ogg_uint32_t *pip, ogg_int32_t *qexpp, ogg_int32_t *ilsp,ogg_int32_t wi, ogg_int32_t m){ ogg_uint32_t qi=*qip,pi=*pip; ogg_int32_t qexp=*qexpp; asm("mov r0,%3;" "mov r1,%5,asr#1;" "add r0,r0,r1,lsl#3;" "1:" "ldmdb r0!,{r1,r3};" "subs r1,r1,%4;" //ilsp[j]-wi "rsbmi r1,r1,#0;" //labs(ilsp[j]-wi) "umull %0,r2,r1,%0;" //qi*=labs(ilsp[j]-wi) "subs r1,r3,%4;" //ilsp[j+1]-wi "rsbmi r1,r1,#0;" //labs(ilsp[j+1]-wi) "umull %1,r3,r1,%1;" //pi*=labs(ilsp[j+1]-wi) "cmn r2,r3;" // shift down 16? "beq 0f;" "add %2,%2,#16;" "mov %0,%0,lsr #16;" "orr %0,%0,r2,lsl #16;" "mov %1,%1,lsr #16;" "orr %1,%1,r3,lsl #16;" "0:" "cmp r0,%3;\n" "bhi 1b;\n" // odd filter assymetry "ands r0,%5,#1;\n" "beq 2f;\n" "add r0,%3,%5,lsl#2;\n" "ldr r1,[r0,#-4];\n" "mov r0,#0x4000;\n" "subs r1,r1,%4;\n" //ilsp[j]-wi "rsbmi r1,r1,#0;\n" //labs(ilsp[j]-wi) "umull %0,r2,r1,%0;\n" //qi*=labs(ilsp[j]-wi) "umull %1,r3,r0,%1;\n" //pi*=labs(ilsp[j+1]-wi) "cmn r2,r3;\n" // shift down 16? "beq 2f;\n" "add %2,%2,#16;\n" "mov %0,%0,lsr #16;\n" "orr %0,%0,r2,lsl #16;\n" "mov %1,%1,lsr #16;\n" "orr %1,%1,r3,lsl #16;\n" //qi=(pi>>shift)*labs(ilsp[j]-wi); //pi=(qi>>shift)*labs(ilsp[j+1]-wi); //qexp+=shift; //} /* normalize to max 16 sig figs */ "2:" "mov r2,#0;" "orr r1,%0,%1;" "tst r1,#0xff000000;" "addne r2,r2,#8;" "movne r1,r1,lsr #8;" "tst r1,#0x00f00000;" "addne r2,r2,#4;" "movne r1,r1,lsr #4;" "tst r1,#0x000c0000;" "addne r2,r2,#2;" "movne r1,r1,lsr #2;" "tst r1,#0x00020000;" "addne r2,r2,#1;" "movne r1,r1,lsr #1;" "tst r1,#0x00010000;" "addne r2,r2,#1;" "mov %0,%0,lsr r2;" "mov %1,%1,lsr r2;" "add %2,%2,r2;" : "+r"(qi),"+r"(pi),"+r"(qexp) : "r"(ilsp),"r"(wi),"r"(m) : "r0","r1","r2","r3","cc"); *qip=qi; *pip=pi; *qexpp=qexp; } static inline void lsp_norm_asm(ogg_uint32_t *qip,ogg_int32_t *qexpp){ ogg_uint32_t qi=*qip; ogg_int32_t qexp=*qexpp; asm("tst %0,#0x0000ff00;" "moveq %0,%0,lsl #8;" "subeq %1,%1,#8;" "tst %0,#0x0000f000;" "moveq %0,%0,lsl #4;" "subeq %1,%1,#4;" "tst %0,#0x0000c000;" "moveq %0,%0,lsl #2;" "subeq %1,%1,#2;" "tst %0,#0x00008000;" "moveq %0,%0,lsl #1;" "subeq %1,%1,#1;" : "+r"(qi),"+r"(qexp) : : "cc"); *qip=qi; *qexpp=qexp; } #endif #endif bcmatroska2-5.3.101/mkclean/tremor/autogen.sh000066400000000000000000000071111462133141200210060ustar00rootroot00000000000000#!/bin/sh # Run this to set up the build system: configure, makefiles, etc. # (based on the version in enlightenment's cvs) package="vorbisdec" olddir=`pwd` srcdir=`dirname $0` test -z "$srcdir" && srcdir=. cd "$srcdir" DIE=0 echo "checking for autoconf... " (autoconf --version) < /dev/null > /dev/null 2>&1 || { echo echo "You must have autoconf installed to compile $package." echo "Download the appropriate package for your distribution," echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" DIE=1 } VERSIONGREP="sed -e s/.*[^0-9\.]\([0-9]\.[0-9]\).*/\1/" VERSIONMKINT="sed -e s/[^0-9]//" # do we need automake? if test -r Makefile.am; then AM_OPTIONS=`fgrep AUTOMAKE_OPTIONS Makefile.am` AM_NEEDED=`echo $AM_OPTIONS | $VERSIONGREP` if test x"$AM_NEEDED" = "x$AM_OPTIONS"; then AM_NEEDED="" fi if test -z $AM_NEEDED; then echo -n "checking for automake... " AUTOMAKE=automake ACLOCAL=aclocal if ($AUTOMAKE --version < /dev/null > /dev/null 2>&1); then echo "yes" else echo "no" AUTOMAKE= fi else echo -n "checking for automake $AM_NEEDED or later... " for am in automake-$AM_NEEDED automake$AM_NEEDED automake; do ($am --version < /dev/null > /dev/null 2>&1) || continue ver=`$am --version < /dev/null | head -n 1 | $VERSIONGREP | $VERSIONMKINT` verneeded=`echo $AM_NEEDED | $VERSIONMKINT` if test $ver -ge $verneeded; then AUTOMAKE=$am echo $AUTOMAKE break fi done test -z $AUTOMAKE && echo "no" echo -n "checking for aclocal $AM_NEEDED or later... " for ac in aclocal-$AM_NEEDED aclocal$AM_NEEDED aclocal; do ($ac --version < /dev/null > /dev/null 2>&1) || continue ver=`$ac --version < /dev/null | head -n 1 | $VERSIONGREP | $VERSIONMKINT` verneeded=`echo $AM_NEEDED | $VERSIONMKINT` if test $ver -ge $verneeded; then ACLOCAL=$ac echo $ACLOCAL break fi done test -z $ACLOCAL && echo "no" fi test -z $AUTOMAKE || test -z $ACLOCAL && { echo echo "You must have automake installed to compile $package." echo "Download the appropriate package for your distribution," echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" exit 1 } fi echo -n "checking for libtool... " for LIBTOOLIZE in libtoolize glibtoolize nope; do ($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 && break done if test x$LIBTOOLIZE = xnope; then echo "nope." LIBTOOLIZE=libtoolize else echo $LIBTOOLIZE fi ($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 || { echo echo "You must have libtool installed to compile $package." echo "Download the appropriate package for your system," echo "or get the source from one of the GNU ftp sites" echo "listed in http://www.gnu.org/order/ftp.html" DIE=1 } if test "$DIE" -eq 1; then exit 1 fi if test -z "$*"; then echo "I am going to run ./configure with no arguments - if you wish " echo "to pass any to it, please specify them on the $0 command line." fi echo "Generating configuration files for $package, please wait...." echo " $ACLOCAL $ACLOCAL_FLAGS" $ACLOCAL $ACLOCAL_FLAGS || exit 1 echo " $LIBTOOLIZE --automake" $LIBTOOLIZE --automake || exit 1 echo " autoheader" autoheader || exit 1 echo " $AUTOMAKE --add-missing $AUTOMAKE_FLAGS" $AUTOMAKE --add-missing $AUTOMAKE_FLAGS || exit 1 echo " autoconf" autoconf || exit 1 cd $olddir $srcdir/configure --enable-maintainer-mode "$@" && echo bcmatroska2-5.3.101/mkclean/tremor/backends.h000066400000000000000000000107431462133141200207400ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: backend and mapping structures ********************************************************************/ /* this is exposed up here because we need it for static modes. Lookups for each backend aren't exposed because there's no reason to do so */ #ifndef _vorbis_backend_h_ #define _vorbis_backend_h_ #include "codec_internal.h" /* this would all be simpler/shorter with templates, but.... */ /* Transform backend generic *************************************/ /* only mdct right now. Flesh it out more if we ever transcend mdct in the transform domain */ /* Floor backend generic *****************************************/ typedef struct{ vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *); vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_mode *, vorbis_info_floor *); void (*free_info) (vorbis_info_floor *); void (*free_look) (vorbis_look_floor *); void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *); int (*inverse2) (struct vorbis_block *,vorbis_look_floor *, void *buffer,ogg_int32_t *); } vorbis_func_floor; typedef struct{ int order; long rate; long barkmap; int ampbits; int ampdB; int numbooks; /* <= 16 */ int books[16]; } vorbis_info_floor0; #define VIF_POSIT 63 #define VIF_CLASS 16 #define VIF_PARTS 31 typedef struct{ int partitions; /* 0 to 31 */ int partitionclass[VIF_PARTS]; /* 0 to 15 */ int class_dim[VIF_CLASS]; /* 1 to 8 */ int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1< #include #include "ogg.h" static unsigned long mask[]= {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f, 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff, 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff, 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff, 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff, 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff, 0x3fffffff,0x7fffffff,0xffffffff }; /* mark read process as having run off the end */ static void _adv_halt(oggpack_buffer *b){ b->headptr=b->head->buffer->data+b->head->begin+b->head->length; b->headend=-1; b->headbit=0; } /* spans forward, skipping as many bytes as headend is negative; if headend is zero, simply finds next byte. If we're up to the end of the buffer, leaves headend at zero. If we've read past the end, halt the decode process. */ static void _span(oggpack_buffer *b){ while(b->headend<1){ if(b->head->next){ b->count+=b->head->length; b->head=b->head->next; b->headptr=b->head->buffer->data+b->head->begin-b->headend; b->headend+=b->head->length; }else{ /* we've either met the end of decode, or gone past it. halt only if we're past */ if(b->headend<0 || b->headbit) /* read has fallen off the end */ _adv_halt(b); break; } } } void oggpack_readinit(oggpack_buffer *b,ogg_reference *r){ memset(b,0,sizeof(*b)); b->tail=b->head=r; b->count=0; b->headptr=b->head->buffer->data+b->head->begin; b->headend=b->head->length; _span(b); } #define _lookspan() while(!end){\ head=head->next;\ if(!head) return -1;\ ptr=head->buffer->data + head->begin;\ end=head->length;\ } /* Read in bits without advancing the bitptr; bits <= 32 */ long oggpack_look(oggpack_buffer *b,int bits){ unsigned long m=mask[bits]; unsigned long ret=-1; bits+=b->headbit; if(bits >= b->headend<<3){ int end=b->headend; unsigned char *ptr=b->headptr; ogg_reference *head=b->head; if(end<0)return -1; if(bits){ _lookspan(); ret=*ptr++>>b->headbit; if(bits>8){ --end; _lookspan(); ret|=*ptr++<<(8-b->headbit); if(bits>16){ --end; _lookspan(); ret|=*ptr++<<(16-b->headbit); if(bits>24){ --end; _lookspan(); ret|=*ptr++<<(24-b->headbit); if(bits>32 && b->headbit){ --end; _lookspan(); ret|=*ptr<<(32-b->headbit); } } } } } }else{ /* make this a switch jump-table */ ret=b->headptr[0]>>b->headbit; if(bits>8){ ret|=b->headptr[1]<<(8-b->headbit); if(bits>16){ ret|=b->headptr[2]<<(16-b->headbit); if(bits>24){ ret|=b->headptr[3]<<(24-b->headbit); if(bits>32 && b->headbit) ret|=b->headptr[4]<<(32-b->headbit); } } } } ret&=m; return ret; } /* limited to 32 at a time */ void oggpack_adv(oggpack_buffer *b,int bits){ bits+=b->headbit; b->headbit=bits&7; b->headptr+=bits/8; if((b->headend-=bits/8)<1)_span(b); } /* spans forward and finds next byte. Never halts */ static void _span_one(oggpack_buffer *b){ while(b->headend<1){ if(b->head->next){ b->count+=b->head->length; b->head=b->head->next; b->headptr=b->head->buffer->data+b->head->begin; b->headend=b->head->length; }else break; } } static int _halt_one(oggpack_buffer *b){ if(b->headend<1){ _adv_halt(b); return -1; } return 0; } int oggpack_eop(oggpack_buffer *b){ if(b->headend<0)return -1; return 0; } /* bits <= 32 */ long oggpack_read(oggpack_buffer *b,int bits){ unsigned long m=mask[bits]; ogg_uint32_t ret=-1; bits+=b->headbit; if(bits >= b->headend<<3){ if(b->headend<0)return -1; if(bits){ if (_halt_one(b)) return -1; ret=*b->headptr>>b->headbit; if(bits>=8){ ++b->headptr; --b->headend; _span_one(b); if(bits>8){ if (_halt_one(b)) return -1; ret|=*b->headptr<<(8-b->headbit); if(bits>=16){ ++b->headptr; --b->headend; _span_one(b); if(bits>16){ if (_halt_one(b)) return -1; ret|=*b->headptr<<(16-b->headbit); if(bits>=24){ ++b->headptr; --b->headend; _span_one(b); if(bits>24){ if (_halt_one(b)) return -1; ret|=*b->headptr<<(24-b->headbit); if(bits>=32){ ++b->headptr; --b->headend; _span_one(b); if(bits>32){ if (_halt_one(b)) return -1; if(b->headbit)ret|=*b->headptr<<(32-b->headbit); } } } } } } } } } }else{ ret=b->headptr[0]>>b->headbit; if(bits>8){ ret|=b->headptr[1]<<(8-b->headbit); if(bits>16){ ret|=b->headptr[2]<<(16-b->headbit); if(bits>24){ ret|=b->headptr[3]<<(24-b->headbit); if(bits>32 && b->headbit){ ret|=b->headptr[4]<<(32-b->headbit); } } } } b->headptr+=bits/8; b->headend-=bits/8; } ret&=m; b->headbit=bits&7; return ret; } long oggpack_bytes(oggpack_buffer *b){ return(b->count+b->headptr-b->head->buffer->data-b->head->begin+ (b->headbit+7)/8); } long oggpack_bits(oggpack_buffer *b){ return((b->count+b->headptr-b->head->buffer->data-b->head->begin)*8+ b->headbit); } bcmatroska2-5.3.101/mkclean/tremor/block.c000066400000000000000000000314551462133141200202560ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: PCM data vector blocking, windowing and dis/reassembly ********************************************************************/ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "window.h" #include "registry.h" #include "misc.h" static int ilog(unsigned int v){ int ret=0; if(v)--v; while(v){ ret++; v>>=1; } return(ret); } /* pcm accumulator examples (not exhaustive): <-------------- lW ----------------> <--------------- W ----------------> : .....|..... _______________ | : .''' | '''_--- | |\ | :.....''' |_____--- '''......| | \_______| :.................|__________________|_______|__|______| |<------ Sl ------>| > Sr < |endW |beginSl |endSl | |endSr |beginW |endlW |beginSr |< lW >| <--------------- W ----------------> | | .. ______________ | | | ' `/ | ---_ | |___.'___/`. | ---_____| |_______|__|_______|_________________| | >|Sl|< |<------ Sr ----->|endW | | |endSl |beginSr |endSr |beginW | |endlW mult[0] |beginSl mult[n] <-------------- lW -----------------> |<--W-->| : .............. ___ | | : .''' |`/ \ | | :.....''' |/`....\|...| :.........................|___|___|___| |Sl |Sr |endW | | |endSr | |beginSr | |endSl |beginSl |beginW */ /* block abstraction setup *********************************************/ #ifndef WORD_ALIGN #define WORD_ALIGN 8 #endif int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){ memset(vb,0,sizeof(*vb)); vb->vd=v; vb->localalloc=0; vb->localstore=NULL; return(0); } void *_vorbis_block_alloc(vorbis_block *vb,long bytes){ bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1); if(bytes+vb->localtop>vb->localalloc){ /* can't just _ogg_realloc... there are outstanding pointers */ if(vb->localstore){ struct alloc_chain *link=(struct alloc_chain *)_ogg_malloc(sizeof(*link)); vb->totaluse+=vb->localtop; link->next=vb->reap; link->ptr=vb->localstore; vb->reap=link; } /* highly conservative */ vb->localalloc=bytes; vb->localstore=_ogg_malloc(vb->localalloc); vb->localtop=0; } { void *ret=(void *)(((char *)vb->localstore)+vb->localtop); vb->localtop+=bytes; return ret; } } /* reap the chain, pull the ripcord */ void _vorbis_block_ripcord(vorbis_block *vb){ /* reap the chain */ struct alloc_chain *reap=vb->reap; while(reap){ struct alloc_chain *next=reap->next; _ogg_free(reap->ptr); memset(reap,0,sizeof(*reap)); _ogg_free(reap); reap=next; } /* consolidate storage */ if(vb->totaluse){ vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc); vb->localalloc+=vb->totaluse; vb->totaluse=0; } /* pull the ripcord */ vb->localtop=0; vb->reap=NULL; } int vorbis_block_clear(vorbis_block *vb){ _vorbis_block_ripcord(vb); if(vb->localstore)_ogg_free(vb->localstore); memset(vb,0,sizeof(*vb)); return(0); } static int _vds_init(vorbis_dsp_state *v,vorbis_info *vi){ int i; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; private_state *b=NULL; memset(v,0,sizeof(*v)); b=(private_state *)(v->backend_state=_ogg_calloc(1,sizeof(*b))); v->vi=vi; b->modebits=ilog(ci->modes); /* Vorbis I uses only window type 0 */ b->window[0]=_vorbis_window(0,ci->blocksizes[0]/2); b->window[1]=_vorbis_window(0,ci->blocksizes[1]/2); /* finish the codebooks */ if(!ci->fullbooks){ ci->fullbooks=(codebook *)_ogg_calloc(ci->books,sizeof(*ci->fullbooks)); for(i=0;ibooks;i++){ vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]); /* decode codebooks are now standalone after init */ vorbis_staticbook_destroy(ci->book_param[i]); ci->book_param[i]=NULL; } } v->pcm_storage=ci->blocksizes[1]; v->pcm=(ogg_int32_t **)_ogg_malloc(vi->channels*sizeof(*v->pcm)); v->pcmret=(ogg_int32_t **)_ogg_malloc(vi->channels*sizeof(*v->pcmret)); for(i=0;ichannels;i++) v->pcm[i]=(ogg_int32_t *)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i])); /* all 1 (large block) or 0 (small block) */ /* explicitly set for the sake of clarity */ v->lW=0; /* previous window size */ v->W=0; /* current window size */ /* initialize all the mapping/backend lookups */ b->mode=(vorbis_look_mapping **)_ogg_calloc(ci->modes,sizeof(*b->mode)); for(i=0;imodes;i++){ int mapnum=ci->mode_param[i]->mapping; int maptype=ci->map_type[mapnum]; b->mode[i]=_mapping_P[maptype]->look(v,ci->mode_param[i], ci->map_param[mapnum]); } return(0); } int vorbis_synthesis_restart(vorbis_dsp_state *v){ vorbis_info *vi=v->vi; codec_setup_info *ci; if(!v->backend_state)return -1; if(!vi)return -1; ci=vi->codec_setup; if(!ci)return -1; v->centerW=ci->blocksizes[1]/2; v->pcm_current=v->centerW; v->pcm_returned=-1; v->granulepos=-1; v->sequence=-1; ((private_state *)(v->backend_state))->sample_count=-1; return(0); } int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){ _vds_init(v,vi); vorbis_synthesis_restart(v); return(0); } void vorbis_dsp_clear(vorbis_dsp_state *v){ int i; if(v){ vorbis_info *vi=v->vi; codec_setup_info *ci=(codec_setup_info *)(vi?vi->codec_setup:NULL); private_state *b=(private_state *)v->backend_state; if(v->pcm){ for(i=0;ichannels;i++) if(v->pcm[i])_ogg_free(v->pcm[i]); _ogg_free(v->pcm); if(v->pcmret)_ogg_free(v->pcmret); } /* free mode lookups; these are actually vorbis_look_mapping structs */ if(ci){ for(i=0;imodes;i++){ int mapnum=ci->mode_param[i]->mapping; int maptype=ci->map_type[mapnum]; if(b && b->mode)_mapping_P[maptype]->free_look(b->mode[i]); } } if(b){ if(b->mode)_ogg_free(b->mode); _ogg_free(b); } memset(v,0,sizeof(*v)); } } /* Unlike in analysis, the window is only partially applied for each block. The time domain envelope is not yet handled at the point of calling (as it relies on the previous block). */ int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){ vorbis_info *vi=v->vi; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; private_state *b=v->backend_state; int i,j; if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL); v->lW=v->W; v->W=vb->W; v->nW=-1; if((v->sequence==-1)|| (v->sequence+1 != vb->sequence)){ v->granulepos=-1; /* out of sequence; lose count */ b->sample_count=-1; } v->sequence=vb->sequence; if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly was called on block */ int n=ci->blocksizes[v->W]/2; int n0=ci->blocksizes[0]/2; int n1=ci->blocksizes[1]/2; int thisCenter; int prevCenter; if(v->centerW){ thisCenter=n1; prevCenter=0; }else{ thisCenter=0; prevCenter=n1; } /* v->pcm is now used like a two-stage double buffer. We don't want to have to constantly shift *or* adjust memory usage. Don't accept a new block until the old is shifted out */ /* overlap/add PCM */ for(j=0;jchannels;j++){ /* the overlap/add section */ if(v->lW){ if(v->W){ /* large/large */ ogg_int32_t *pcm=v->pcm[j]+prevCenter; ogg_int32_t *p=vb->pcm[j]; for(i=0;ipcm[j]+prevCenter+n1/2-n0/2; ogg_int32_t *p=vb->pcm[j]; for(i=0;iW){ /* small/large */ ogg_int32_t *pcm=v->pcm[j]+prevCenter; ogg_int32_t *p=vb->pcm[j]+n1/2-n0/2; for(i=0;ipcm[j]+prevCenter; ogg_int32_t *p=vb->pcm[j]; for(i=0;ipcm[j]+thisCenter; ogg_int32_t *p=vb->pcm[j]+n; for(i=0;icenterW) v->centerW=0; else v->centerW=n1; /* deal with initial packet state; we do this using the explicit pcm_returned==-1 flag otherwise we're sensitive to first block being short or long */ if(v->pcm_returned==-1){ v->pcm_returned=thisCenter; v->pcm_current=thisCenter; }else{ v->pcm_returned=prevCenter; v->pcm_current=prevCenter+ ci->blocksizes[v->lW]/4+ ci->blocksizes[v->W]/4; } } /* track the frame number... This is for convenience, but also making sure our last packet doesn't end with added padding. If the last packet is partial, the number of samples we'll have to return will be past the vb->granulepos. This is not foolproof! It will be confused if we begin decoding at the last page after a seek or hole. In that case, we don't have a starting point to judge where the last frame is. For this reason, vorbisfile will always try to make sure it reads the last two marked pages in proper sequence */ if(b->sample_count==-1){ b->sample_count=0; }else{ b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4; } if(v->granulepos==-1){ if(vb->granulepos!=-1){ /* only set if we have a position to set to */ v->granulepos=vb->granulepos; /* is this a short page? */ if(b->sample_count>v->granulepos){ /* corner case; if this is both the first and last audio page, then spec says the end is cut, not beginning */ if(vb->eofflag){ /* trim the end */ /* no preceeding granulepos; assume we started at zero (we'd have to in a short single-page stream) */ /* granulepos could be -1 due to a seek, but that would result in a long coun`t, not short count */ v->pcm_current-=(b->sample_count-v->granulepos); }else{ /* trim the beginning */ v->pcm_returned+=(b->sample_count-v->granulepos); if(v->pcm_returned>v->pcm_current) v->pcm_returned=v->pcm_current; } } } }else{ v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4; if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){ if(v->granulepos>vb->granulepos){ long extra=v->granulepos-vb->granulepos; if(extra) if(vb->eofflag){ /* partial last frame. Strip the extra samples off */ v->pcm_current-=extra; } /* else {Shouldn't happen *unless* the bitstream is out of spec. Either way, believe the bitstream } */ } /* else {Shouldn't happen *unless* the bitstream is out of spec. Either way, believe the bitstream } */ v->granulepos=vb->granulepos; } } /* Update, cleanup */ if(vb->eofflag)v->eofflag=1; return(0); } /* pcm==NULL indicates we just want the pending samples, no more */ int vorbis_synthesis_pcmout(vorbis_dsp_state *v,ogg_int32_t ***pcm){ vorbis_info *vi=v->vi; if(v->pcm_returned>-1 && v->pcm_returnedpcm_current){ if(pcm){ int i; for(i=0;ichannels;i++) v->pcmret[i]=v->pcm[i]+v->pcm_returned; *pcm=v->pcmret; } return(v->pcm_current-v->pcm_returned); } return(0); } int vorbis_synthesis_read(vorbis_dsp_state *v,int bytes){ if(bytes && v->pcm_returned+bytes>v->pcm_current)return(OV_EINVAL); v->pcm_returned+=bytes; return(0); } bcmatroska2-5.3.101/mkclean/tremor/block.h000066400000000000000000000021251462133141200202530ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2008 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: shared block functions ********************************************************************/ #ifndef _V_BLOCK_ #define _V_BLOCK_ extern void _vorbis_block_ripcord(vorbis_block *vb); extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes); #endif bcmatroska2-5.3.101/mkclean/tremor/codebook.c000066400000000000000000000231501462133141200207420ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: basic codebook pack/unpack/code/decode operations ********************************************************************/ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codebook.h" #include "misc.h" /* unpacks a codebook from the packet buffer into the codebook struct, readies the codebook auxiliary structures for decode *************/ int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){ long i,j; memset(s,0,sizeof(*s)); /* make sure alignment is correct */ if(oggpack_read(opb,24)!=0x564342)goto _eofout; /* first the basic parameters */ s->dim=oggpack_read(opb,16); s->entries=oggpack_read(opb,24); if(s->entries==-1)goto _eofout; /* codeword ordering.... length ordered or unordered? */ switch((int)oggpack_read(opb,1)){ case 0: /* unordered */ s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries); /* allocated but unused entries? */ if(oggpack_read(opb,1)){ /* yes, unused entries */ for(i=0;ientries;i++){ if(oggpack_read(opb,1)){ long num=oggpack_read(opb,5); if(num==-1)goto _eofout; s->lengthlist[i]=num+1; }else s->lengthlist[i]=0; } }else{ /* all entries used; no tagging */ for(i=0;ientries;i++){ long num=oggpack_read(opb,5); if(num==-1)goto _eofout; s->lengthlist[i]=num+1; } } break; case 1: /* ordered */ { long length=oggpack_read(opb,5)+1; s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries); for(i=0;ientries;){ long num=oggpack_read(opb,_ilog(s->entries-i)); if(num==-1)goto _eofout; for(j=0;jentries;j++,i++) s->lengthlist[i]=length; length++; } } break; default: /* EOF */ return(-1); } /* Do we have a mapping to unpack? */ switch((s->maptype=oggpack_read(opb,4))){ case 0: /* no mapping */ break; case 1: case 2: /* implicitly populated value mapping */ /* explicitly populated value mapping */ s->q_min=oggpack_read(opb,32); s->q_delta=oggpack_read(opb,32); s->q_quant=oggpack_read(opb,4)+1; s->q_sequencep=oggpack_read(opb,1); { int quantvals=0; switch(s->maptype){ case 1: quantvals=_book_maptype1_quantvals(s); break; case 2: quantvals=s->entries*s->dim; break; } /* quantized values */ s->quantlist=(long *)_ogg_malloc(sizeof(*s->quantlist)*quantvals); for(i=0;iquantlist[i]=oggpack_read(opb,s->q_quant); if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout; } break; default: goto _errout; } /* all set */ return(0); _errout: _eofout: vorbis_staticbook_clear(s); return(-1); } /* the 'eliminate the decode tree' optimization actually requires the codewords to be MSb first, not LSb. This is an annoying inelegancy (and one of the first places where carefully thought out design turned out to be wrong; Vorbis II and future Ogg codecs should go to an MSb bitpacker), but not actually the huge hit it appears to be. The first-stage decode table catches most words so that bitreverse is not in the main execution path. */ static ogg_uint32_t bitreverse(ogg_uint32_t x){ x= ((x>>16)&0x0000ffff) | ((x<<16)&0xffff0000); x= ((x>> 8)&0x00ff00ff) | ((x<< 8)&0xff00ff00); x= ((x>> 4)&0x0f0f0f0f) | ((x<< 4)&0xf0f0f0f0); x= ((x>> 2)&0x33333333) | ((x<< 2)&0xcccccccc); return((x>> 1)&0x55555555) | ((x<< 1)&0xaaaaaaaa); } STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){ int read=book->dec_maxlength; long lo,hi; long lok = oggpack_look(b,book->dec_firsttablen); if (lok >= 0) { long entry = book->dec_firsttable[lok]; if(entry&0x80000000UL){ lo=(entry>>15)&0x7fff; hi=book->used_entries-(entry&0x7fff); }else{ oggpack_adv(b, book->dec_codelengths[entry-1]); return(entry-1); } }else{ lo=0; hi=book->used_entries; } lok = oggpack_look(b, read); while(lok<0 && read>1) lok = oggpack_look(b, --read); if(lok<0){ oggpack_adv(b,1); /* force eop */ return -1; } /* bisect search for the codeword in the ordered list */ { ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok); while(hi-lo>1){ long p=(hi-lo)>>1; long test=book->codelist[lo+p]>testword; lo+=p&(test-1); hi-=p&(-test); } if(book->dec_codelengths[lo]<=read){ oggpack_adv(b, book->dec_codelengths[lo]); return(lo); } } oggpack_adv(b, read+1); return(-1); } /* Decode side is specced and easier, because we don't need to find matches using different criteria; we simply read and map. There are two things we need to do 'depending': We may need to support interleave. We don't really, but it's convenient to do it here rather than rebuild the vector later. Cascades may be additive or multiplicitive; this is not inherent in the codebook, but set in the code using the codebook. Like interleaving, it's easiest to do it here. addmul==0 -> declarative (set the value) addmul==1 -> additive addmul==2 -> multiplicitive */ /* returns the [original, not compacted] entry number or -1 on eof *********/ long vorbis_book_decode(codebook *book, oggpack_buffer *b){ if(book->used_entries>0){ long packed_entry=decode_packed_entry_number(book,b); if(packed_entry>=0) return(book->dec_index[packed_entry]); } /* if there's no dec_index, the codebook unpacking isn't collapsed */ return(-1); } /* returns 0 on OK or -1 on eof *************************************/ long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ int step=n/book->dim; long *entry = (long *)alloca(sizeof(*entry)*step); ogg_int32_t **t = (ogg_int32_t **)alloca(sizeof(*t)*step); int i,j,o; int shift=point-book->binarypoint; if(shift>=0){ for (i = 0; i < step; i++) { entry[i]=decode_packed_entry_number(book,b); if(entry[i]==-1)return(-1); t[i] = book->valuelist+entry[i]*book->dim; } for(i=0,o=0;idim;i++,o+=step) for (j=0;j>shift; }else{ for (i = 0; i < step; i++) { entry[i]=decode_packed_entry_number(book,b); if(entry[i]==-1)return(-1); t[i] = book->valuelist+entry[i]*book->dim; } for(i=0,o=0;idim;i++,o+=step) for (j=0;jused_entries>0){ int i,j,entry; ogg_int32_t *t; int shift=point-book->binarypoint; if(shift>=0){ for(i=0;ivaluelist+entry*book->dim; for (j=0;jdim;) a[i++]+=t[j++]>>shift; } }else{ for(i=0;ivaluelist+entry*book->dim; for (j=0;jdim;) a[i++]+=t[j++]<<-shift; } } } return(0); } long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ int i,j,entry; ogg_int32_t *t; int shift=point-book->binarypoint; if(shift>=0){ for(i=0;ivaluelist+entry*book->dim; for (j=0;jdim;){ a[i++]=t[j++]>>shift; } } }else{ for(i=0;ivaluelist+entry*book->dim; for (j=0;jdim;){ a[i++]=t[j++]<<-shift; } } } }else{ int i,j; for(i=0;idim;){ a[i++]=0; } } } return(0); } long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a,\ long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ long i,j,entry; int chptr=0; int shift=point-book->binarypoint; if(shift>=0){ for(i=offset;ivaluelist+entry*book->dim; for (j=0;jdim;j++){ a[chptr++][i]+=t[j]>>shift; if(chptr==ch){ chptr=0; i++; } } } } }else{ for(i=offset;ivaluelist+entry*book->dim; for (j=0;jdim;j++){ a[chptr++][i]+=t[j]<<-shift; if(chptr==ch){ chptr=0; i++; } } } } } } return(0); } bcmatroska2-5.3.101/mkclean/tremor/codebook.h000066400000000000000000000100511462133141200207430ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: basic shared codebook operations ********************************************************************/ #ifndef _V_CODEBOOK_H_ #define _V_CODEBOOK_H_ #include "ogg.h" /* This structure encapsulates huffman and VQ style encoding books; it doesn't do anything specific to either. valuelist/quantlist are nonNULL (and q_* significant) only if there's entry->value mapping to be done. If encode-side mapping must be done (and thus the entry needs to be hunted), the auxiliary encode pointer will point to a decision tree. This is true of both VQ and huffman, but is mostly useful with VQ. */ typedef struct static_codebook{ long dim; /* codebook dimensions (elements per vector) */ long entries; /* codebook entries */ long *lengthlist; /* codeword lengths in bits */ /* mapping ***************************************************************/ int maptype; /* 0=none 1=implicitly populated values from map column 2=listed arbitrary values */ /* The below does a linear, single monotonic sequence mapping. */ long q_min; /* packed 32 bit float; quant value 0 maps to minval */ long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */ int q_quant; /* bits: 0 < quant <= 16 */ int q_sequencep; /* bitflag */ long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map map == 2: list of dim*entries quantized entry vals */ } static_codebook; typedef struct codebook{ long dim; /* codebook dimensions (elements per vector) */ long entries; /* codebook entries */ long used_entries; /* populated codebook entries */ /* the below are ordered by bitreversed codeword and only used entries are populated */ int binarypoint; ogg_int32_t *valuelist; /* list of dim*entries actual entry values */ ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */ int *dec_index; char *dec_codelengths; ogg_uint32_t *dec_firsttable; int dec_firsttablen; int dec_maxlength; long q_min; /* packed 32 bit float; quant value 0 maps to minval */ long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */ } codebook; extern void vorbis_staticbook_clear(static_codebook *b); extern void vorbis_staticbook_destroy(static_codebook *b); extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source); extern void vorbis_book_clear(codebook *b); extern long _book_maptype1_quantvals(const static_codebook *b); extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c); extern long vorbis_book_decode(codebook *book, oggpack_buffer *b); extern long vorbis_book_decodevs_add(codebook *book, ogg_int32_t *a, oggpack_buffer *b,int n,int point); extern long vorbis_book_decodev_set(codebook *book, ogg_int32_t *a, oggpack_buffer *b,int n,int point); extern long vorbis_book_decodev_add(codebook *book, ogg_int32_t *a, oggpack_buffer *b,int n,int point); extern long vorbis_book_decodevv_add(codebook *book, ogg_int32_t **a, long off,int ch, oggpack_buffer *b,int n,int point); extern int _ilog(unsigned int v); #endif bcmatroska2-5.3.101/mkclean/tremor/codec_internal.h000066400000000000000000000060141462133141200221330ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: libvorbis codec headers ********************************************************************/ #ifndef _V_CODECI_H_ #define _V_CODECI_H_ #include "codebook.h" typedef void vorbis_look_mapping; typedef void vorbis_look_floor; typedef void vorbis_look_residue; typedef void vorbis_look_transform; /* mode ************************************************************/ typedef struct { int blockflag; int windowtype; int transformtype; int mapping; } vorbis_info_mode; typedef void vorbis_info_floor; typedef void vorbis_info_residue; typedef void vorbis_info_mapping; typedef struct private_state { /* local lookup storage */ const void *window[2]; /* backend lookups are tied to the mode, not the backend or naked mapping */ int modebits; vorbis_look_mapping **mode; ogg_int64_t sample_count; } private_state; /* codec_setup_info contains all the setup information specific to the specific compression/decompression mode in progress (eg, psychoacoustic settings, channel setup, options, codebook etc). *********************************************************************/ typedef struct codec_setup_info { /* Vorbis supports only short and long blocks, but allows the encoder to choose the sizes */ long blocksizes[2]; /* modes are the primary means of supporting on-the-fly different blocksizes, different channel mappings (LR or M/A), different residue backends, etc. Each mode consists of a blocksize flag and a mapping (along with the mapping setup */ int modes; int maps; int times; int floors; int residues; int books; vorbis_info_mode *mode_param[64]; int map_type[64]; vorbis_info_mapping *map_param[64]; int time_type[64]; int floor_type[64]; vorbis_info_floor *floor_param[64]; int residue_type[64]; vorbis_info_residue *residue_param[64]; static_codebook *book_param[256]; codebook *fullbooks; int passlimit[32]; /* iteration limit per couple/quant pass */ int coupling_passes; } codec_setup_info; #endif bcmatroska2-5.3.101/mkclean/tremor/config_types.h000066400000000000000000000022001462133141200216440ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: #ifdef jail to whip a few platforms into the UNIX ideal. ********************************************************************/ #ifndef _OS_CVTYPES_H #define _OS_CVTYPES_H typedef long long ogg_int64_t; typedef int ogg_int32_t; typedef unsigned int ogg_uint32_t; typedef short ogg_int16_t; #endif bcmatroska2-5.3.101/mkclean/tremor/configure.in000066400000000000000000000065311462133141200213260ustar00rootroot00000000000000dnl Process this file with autoconf to produce a configure script dnl ------------------------------------------------ dnl Initialization and Versioning dnl ------------------------------------------------ AC_INIT(mdct.c) AC_CANONICAL_HOST AC_CANONICAL_TARGET AM_CONFIG_HEADER([config.h]) AM_INIT_AUTOMAKE(libvorbisidec,1.2.0) dnl AM_MAINTAINER_MODE only provides the option to configure to enable it AM_MAINTAINER_MODE dnl Library versioning V_LIB_CURRENT=1 V_LIB_REVISION=2 V_LIB_AGE=0 AC_SUBST(V_LIB_CURRENT) AC_SUBST(V_LIB_REVISION) AC_SUBST(V_LIB_AGE) dnl -------------------------------------------------- dnl Check for programs dnl -------------------------------------------------- dnl save $CFLAGS since AC_PROG_CC likes to insert "-g -O2" dnl if $CFLAGS is blank cflags_save="$CFLAGS" AC_PROG_CC AC_PROG_CPP CFLAGS="$cflags_save" AM_PROG_LIBTOOL dnl -------------------------------------------------- dnl Set build flags based on environment dnl -------------------------------------------------- dnl Set some target options cflags_save="$CFLAGS" ldflags_save="$LDFLAGS" if test -z "$GCC"; then case $host in arm-*-*) DEBUG="-g -D_ARM_ASSEM_" CFLAGS="-O -D_ARM_ASSEM_" PROFILE="-p -g -O -D_ARM_ASSEM_" ;; *) DEBUG="-g" CFLAGS="-O" PROFILE="-g -p" ;; esac else case $host in arm-*-*) DEBUG="-g -Wall -D__NO_MATH_INLINES -fsigned-char -D_ARM_ASSEM_" CFLAGS="-O2 -D_ARM_ASSEM_ -fsigned-char" PROFILE="-W -pg -g -O2 -D_ARM_ASSEM_ -fsigned-char -fno-inline-functions";; *) DEBUG="-g -Wall -D__NO_MATH_INLINES -fsigned-char" CFLAGS="-O2 -Wall -fsigned-char" PROFILE="-Wall -pg -g -O2 -fsigned-char -fno-inline-functions";; esac fi CFLAGS="$CFLAGS $cflags_save -D_REENTRANT" LDFLAGS="$LDFLAGS $ldflags_save" # Test whenever ld supports -version-script AC_PROG_LD AC_PROG_LD_GNU if test "x$lt_cv_prog_gnu_ld" = "xyes"; then SHLIB_VERSION_ARG="Wl,--version-script=Version_script" dnl Set extra linker options case "$target_os" in linux* | solaris* ) SHLIB_VERSION_ARG="-Wl,--version-script=Version_script" ;; *) ;; esac LDFLAGS="$LDFLAGS $SHLIB_VERSION_ARG" fi dnl -------------------------------------------------- dnl Options dnl -------------------------------------------------- AC_ARG_ENABLE( low-accuracy, [ --enable-low-accuracy enable 32 bit only multiply operations], CFLAGS="$CFLAGS -D_LOW_ACCURACY_" ) dnl -------------------------------------------------- dnl Check for headers dnl -------------------------------------------------- AC_CHECK_HEADER(memory.h,CFLAGS="$CFLAGS -DUSE_MEMORY_H",:) dnl -------------------------------------------------- dnl Check for typedefs, structures, etc dnl -------------------------------------------------- dnl none dnl -------------------------------------------------- dnl Check for library functions dnl -------------------------------------------------- AC_FUNC_ALLOCA AC_FUNC_MEMCMP dnl -------------------------------------------------- dnl Do substitutions dnl -------------------------------------------------- LIBS="$LIBS" AC_SUBST(LIBS) AC_SUBST(DEBUG) AC_SUBST(PROFILE) AC_OUTPUT(Makefile Version_script vorbisidec.pc) bcmatroska2-5.3.101/mkclean/tremor/debian/000077500000000000000000000000001462133141200202325ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/debian/Makefile.am000066400000000000000000000002711462133141200222660ustar00rootroot00000000000000## Process this file with automake to produce Makefile.in AUTOMAKE_OPTIONS = foreign EXTRA_DIST = changelog control copyright libvorbisidec1.install\ libvorbisidec-dev.install rules bcmatroska2-5.3.101/mkclean/tremor/debian/changelog000066400000000000000000000003021462133141200220770ustar00rootroot00000000000000libvorbisidec (1.2.0-1) unstable; urgency=low * Initial Release. -- Christopher L Cheney Wed, 09 Oct 2002 22:00:00 -0500 Local variables: mode: debian-changelog End: bcmatroska2-5.3.101/mkclean/tremor/debian/control000066400000000000000000000013421462133141200216350ustar00rootroot00000000000000Source: libvorbisidec Section: libs Priority: optional Maintainer: Christopher L Cheney Build-Depends: autotools-dev, debhelper (>> 4.0.18), devscripts, gawk Standards-Version: 3.5.7.0 Package: libvorbisidec1 Architecture: any Section: libs Depends: ${shlibs:Depends} Description: Ogg Bitstream Library Libogg is a library for manipulating ogg bitstreams. It handles both making ogg bitstreams and getting packets from ogg bitstreams. Package: libvorbisidec-dev Architecture: any Section: devel Depends: libvorbisidec1 (= ${Source-Version}), libc6-dev Description: Ogg Bitstream Library Development The libogg-dev package contains the header files and documentation needed to develop applications with libogg. bcmatroska2-5.3.101/mkclean/tremor/debian/copyright000066400000000000000000000031721462133141200221700ustar00rootroot00000000000000This package was debianized by Christopher L Cheney on Wed, 09 Oct 2002 22:00:00 -0500. It was downloaded from cvs. Upstream Author(s): Monty Copyright: Copyright (c) 2002, Xiph.org Foundation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.Org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. bcmatroska2-5.3.101/mkclean/tremor/debian/libvorbisidec-dev.install000066400000000000000000000004761462133141200252250ustar00rootroot00000000000000debian/tmp/usr/include/tremor/config_types.h debian/tmp/usr/include/tremor/ivorbiscodec.h debian/tmp/usr/include/tremor/ivorbisfile.h debian/tmp/usr/include/tremor/ogg.h debian/tmp/usr/include/tremor/os_types.h debian/tmp/usr/lib/libvorbisidec.a debian/tmp/usr/lib/libvorbisidec.la debian/tmp/usr/lib/libvorbisidec.so bcmatroska2-5.3.101/mkclean/tremor/debian/libvorbisidec1.install000066400000000000000000000000461462133141200245230ustar00rootroot00000000000000debian/tmp/usr/lib/libvorbisidec.so.* bcmatroska2-5.3.101/mkclean/tremor/debian/rules000066400000000000000000000071301462133141200213100ustar00rootroot00000000000000#!/usr/bin/make -f # Sample debian/rules that uses debhelper. # GNU copyright 1997 to 1999 by Joey Hess. # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 # This is the debhelper compatibility version to use. export DH_COMPAT=4 # This has to be exported to make some magic below work. export DH_OPTIONS # These are used for cross-compiling and for saving the configure script # from having to guess our platform (since we know it already) DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) objdir = $(CURDIR)/obj-$(DEB_BUILD_GNU_TYPE) ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS))) CFLAGS += -g endif ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) INSTALL_PROGRAM += -s endif configure: configure-stamp configure-stamp: dh_testdir # make build directory mkdir $(objdir) # run configure with build tree $(objdir) # change ../configure to ../autogen.sh for CVS build cd $(objdir) && \ ../configure --build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE) \ --prefix=/usr touch configure-stamp build: build-stamp build-stamp: configure-stamp dh_testdir cd $(objdir) && \ $(MAKE) touch build-stamp autotools: OLDDATESUB=`./config.sub -t | tr -d -` ;\ OLDDATEGUESS=`./config.guess -t | tr -d -` ;\ NEWDATESUB=`/usr/share/misc/config.sub -t | tr -d -` ;\ NEWDATEGUESS=`/usr/share/misc/config.guess -t | tr -d -` ;\ if [ $$OLDDATESUB -lt $$NEWDATESUB -o \ $$OLDDATEGUESS -lt $$NEWDATEGUESS ]; then \ dch -a -p "GNU config automated update: config.sub\ ($$OLDDATESUB to $$NEWDATESUB), config.guess\ ($$OLDDATEGUESS to $$NEWDATEGUESS)" ;\ cp -f /usr/share/misc/config.sub config.sub ;\ cp -f /usr/share/misc/config.guess config.guess ;\ echo WARNING: GNU config scripts updated from master copies 1>&2 ;\ fi debian-clean: dh_testdir dh_testroot dh_clean clean: autotools dh_testdir dh_testroot rm -f build-stamp configure-stamp # Remove build tree rm -rf $(objdir) # if Makefile exists run distclean if test -f Makefile; then \ $(MAKE) distclean; \ fi #if test -d CVS; then \ $(MAKE) cvs-clean ;\ fi dh_clean install: DH_OPTIONS= install: build dh_testdir dh_testroot dh_clean -k dh_installdirs cd $(objdir) && \ $(MAKE) install DESTDIR=$(CURDIR)/debian/tmp dh_install --list-missing # This single target is used to build all the packages, all at once, or # one at a time. So keep in mind: any options passed to commands here will # affect _all_ packages. Anything you want to only affect one package # should be put in another target, such as the install target. binary-common: dh_testdir dh_testroot # dh_installxfonts dh_installchangelogs dh_installdocs dh_installexamples # dh_installmenu # dh_installdebconf # dh_installlogrotate # dh_installemacsen # dh_installpam # dh_installmime # dh_installinit # dh_installcron # dh_installinfo # dh_undocumented dh_installman dh_strip dh_link dh_compress dh_fixperms dh_makeshlibs -V dh_installdeb # dh_perl dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb # Build architecture independant packages using the common target. binary-indep: build install # $(MAKE) -f debian/rules DH_OPTIONS=-i binary-common # Build architecture dependant packages using the common target. binary-arch: build install $(MAKE) -f debian/rules DH_OPTIONS=-a binary-common # Any other binary targets build just one binary package at a time. binary-%: build install $(MAKE) -f debian/rules binary-common DH_OPTIONS=-p$* binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary install configure bcmatroska2-5.3.101/mkclean/tremor/doc/000077500000000000000000000000001462133141200175555ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/doc/OggVorbis_File.html000066400000000000000000000105371462133141200233110ustar00rootroot00000000000000 Tremor - datatype - OggVorbis_File

Tremor documentation

Tremor version 1.0 - 20020403

OggVorbis_File

declared in "ivorbisfile.h"

The OggVorbis_File structure defines an Ogg Vorbis file.

This structure is used in all libvorbisidec routines. Before it can be used, it must be initialized by ov_open() or ov_open_callbacks().

After use, the OggVorbis_File structure must be deallocated with a call to ov_clear().

Once a file or data source is opened successfully by libvorbisidec (using ov_open() or ov_open_callbacks()), it is owned by libvorbisidec. The file should not be used by any other applications or functions outside of the libvorbisidec API. The file must not be closed directly by the application at any time after a successful open; libvorbisidec expects to close the file within ov_clear().

If the call to ov_open() or ov_open_callbacks() fails, libvorbisidec does not assume ownership of the file and the application is expected to close it if necessary.

typedef struct {
  void             *datasource; /* Pointer to a FILE *, etc. */
  int              seekable;
  ogg_int64_t      offset;
  ogg_int64_t      end;
  ogg_sync_state   oy; 

  /* If the FILE handle isn't seekable (eg, a pipe), only the current
     stream appears */
  int              links;
  ogg_int64_t      *offsets;
  ogg_int64_t      *dataoffsets;
  long             *serialnos;
  ogg_int64_t      *pcmlengths;
  vorbis_info      *vi;
  vorbis_comment   *vc;

  /* Decoding working state local storage */
  ogg_int64_t      pcm_offset;
  int              ready_state;
  long             current_serialno;
  int              current_link;

  ogg_int64_t      bittrack;
  ogg_int64_t      samptrack;

  ogg_stream_state os; /* take physical pages, weld into a logical
                          stream of packets */
  vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  vorbis_block     vb; /* local working space for packet->PCM decode */

  ov_callbacks callbacks;

} OggVorbis_File;

Relevant Struct Members

datasource
Pointer to file or other ogg source. When using stdio based file/stream access, this field contains a FILE pointer. When using custom IO via callbacks, libvorbisidec treats this void pointer as a black box only to be passed to the callback routines provided by the application.
seekable
Read-only int indicating whether file is seekable. E.g., a physical file is seekable, a pipe isn't.
links
Read-only int indicating the number of logical bitstreams within the physical bitstream.
ov_callbacks
Collection of file manipulation routines to be used on this data source. When using stdio/FILE access via ov_open(), the callbacks will be filled in with stdio calls or wrappers to stdio calls.

Notes

Tremor requires a native 64 bit integer type to compile and function; The GNU build system will locate and typedef ogg_int64_t to the appropriate native type. If not using the GNU build tools, you will need to define ogg_int64_t as a 64-bit type inside your system's project file/Makefile, etc. On win32, for example, this should be defined as __int64.




copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/build.html000066400000000000000000000061601462133141200215450ustar00rootroot00000000000000 Tremor - Build

Tremor documentation

Tremor version 1.0 - 20020403

Tremor: Building libvorbisidec

The C source in the Tremor package will build on any ANSI C compiler and function completely and properly on any platform. The included build system assumes GNU build system and make tools (m4, automake, autoconf, libtool and gmake). GCC is not required, although GCC is the most tested compiler. To build using GNU tools, type in the source directory:


./autogen.sh
gmake

or if GNU make is the standard make on the build system:


./autogen.sh
make

Currently, the source implements playback in pure C on all platforms except ARM, where a [currently] small amount of assembly (see the file asm_arm.h) is used to implement 64 bit math operations and fast LSP computation. If building on ARM without the benefit of GNU build system tools, be sure that _ARM_ASSEM_ is #defined by the build system if this assembly is desired, else the resulting library will use whatever 64 bit math builtins the compiler implements.

No math library is required by this source. No floating point operations are used at any point in either setup or decode. This decoder library will properly decode any past, current or future Vorbis I file or stream.

The GNU build system produces static and, when supported by the OS, dynamic libraries named 'libvorbisidec'. This library exposes an API nearly identical to the BSD reference library's 'libvorbisfile', including all the features familiar to users of vorbisfile. This API is similar enough that the proper header file to include is named 'ivorbisfile.h', included in the source build directory. Lower level libvorbis-style headers and structures are in 'ivorbiscodec.h', also included in the source build directory. A simple example program, ivorbisfile_example.c, can be built with 'make ivorbisfile_example'.

(We've summarized differences between the free, reference vorbisfile library and Tremor's libvorbisidec in a separate document.)

Notes

Tremor requires a native 64 bit integer type to compile and function; The GNU build system will locate and typedef ogg_int64_t to the appropriate native type. If not using the GNU build tools, you will need to define ogg_int64_t as a 64-bit type inside your system's project file/Makefile, etc. On win32, for example, this should be defined as __int64.




copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/callbacks.html000066400000000000000000000103031462133141200223570ustar00rootroot00000000000000 Tremor - Callbacks and non-stdio I/O

Tremor documentation

Tremor version 1.0 - 20020403

Callbacks and non-stdio I/O

Although stdio is convenient and nearly universally implemented as per ANSI C, it is not suited to all or even most potential uses of Vorbis. For additional flexibility, embedded applications may provide their own I/O functions for use with Tremor when stdio is unavailable or not suitable. One common example is decoding a Vorbis stream from a memory buffer.

Use custom I/O functions by populating an ov_callbacks structure and calling ov_open_callbacks() or ov_test_callbacks() rather than the typical ov_open() or ov_test(). Past the open call, use of libvorbisidec is identical to using it with stdio.

Read function

The read-like function provided in the read_func field is used to fetch the requested amount of data. It expects the fetch operation to function similar to file-access, that is, a multiple read operations will retrieve contiguous sequential pieces of data, advancing a position cursor after each read.

The following behaviors are also expected:

  • a return of '0' indicates end-of-data (if the by-thread errno is unset)
  • short reads mean nothing special (short reads are not treated as error conditions)
  • a return of zero with the by-thread errno set to nonzero indicates a read error

Seek function

The seek-like function provided in the seek_func field is used to request non-sequential data access by libvorbisidec, moving the access cursor to the requested position.

libvorbisidec expects the following behavior:

  • The seek function must always return -1 (failure) if the given data abstraction is not seekable. It may choose to always return -1 if the application desires libvorbisidec to treat the Vorbis data strictly as a stream (which makes for a less expensive open operation).

  • If the seek function initially indicates seekability, it must always succeed upon being given a valid seek request.

  • The seek function must implement all of SEEK_SET, SEEK_CUR and SEEK_END. The implementation of SEEK_END should set the access cursor one past the last byte of accessible data, as would stdio fseek()

Close function

The close function should deallocate any access state used by the passed in instance of the data access abstraction and invalidate the instance handle. The close function is assumed to succeed.

One common use of callbacks and the close function is to change the behavior of libvorbisidec with respect to file closure for applications that must fclose data files themselves. By passing the normal stdio calls as callback functions, but passing a close_func that does nothing, an application may call ov_clear() and then fclose() the file originally passed to libvorbisidec.

Tell function

The tell function is intended to mimic the behavior of ftell() and must return the byte position of the next data byte that would be read. If the data access cursor is at the end of the 'file' (pointing to one past the last byte of data, as it would be after calling fseek(file,SEEK_END,0)), the tell function must return the data position (and thus the total file size), not an error.

The tell function need not be provided if the data IO abstraction is not seekable.


copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/datastructures.html000066400000000000000000000045151462133141200235250ustar00rootroot00000000000000 Tremor - Base Data Structures

Tremor documentation

Tremor version 1.0 - 20020403

Base Data Structures

There are several data structures used to hold file and bitstream information during libvorbisidec decoding. These structures are declared in "ivorbisfile.h" and "ivorbiscodec.h".

When using libvorbisidec, it's not necessary to know about most of the contents of these data structures, but it may be helpful to understand what they contain.

datatype purpose
OggVorbis_File This structure represents the basic file information. It contains a pointer to the physical file or bitstream and various information about that bitstream.
vorbis_comment This structure contains the file comments. It contains a pointer to unlimited user comments, information about the number of comments, and a vendor description.
vorbis_info This structure contains encoder-related information about the bitstream. It includes encoder info, channel info, and bitrate limits.
ov_callbacks This structure contains pointers to the application-specified file manipulation routines set for use by ov_open_callbacks(). See also the provided document on using application-provided callbacks instead of stdio.



copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/decoding.html000066400000000000000000000051441462133141200222230ustar00rootroot00000000000000 Tremor - Decoding

Tremor documentation

Tremor version 1.0 - 20020403

Decoding

All libivorbisdec decoding routines are declared in "ivorbisfile.h".

After initialization, decoding audio is as simple as calling ov_read(). This function works similarly to reading from a normal file using read().

However, a few differences are worth noting:

multiple stream links

A Vorbis stream may consist of multiple sections (called links) that encode differing numbers of channels or sample rates. It is vitally important to pay attention to the link numbers returned by ov_read and handle audio changes that may occur at link boundaries. Such multi-section files do exist in the wild and are not merely a specification curiosity.

returned data amount

ov_read does not attempt to completely fill a large, passed in data buffer; it merely guarantees that the passed back data does not overflow the passed in buffer size. Large buffers may be filled by iteratively looping over calls to ov_read (incrementing the buffer pointer) until the original buffer is filled.

file cursor position

Vorbis files do not necessarily start at a sample number or time offset of zero. Do not be surprised if a file begins at a positive offset of several minutes or hours, such as would happen if a large stream (such as a concert recording) is chopped into multiple seperate files.

function purpose
ov_read This function makes up the main chunk of a decode loop. It takes an OggVorbis_File structure, which must have been initialized by a previous call to ov_open().



copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/diff.html000066400000000000000000000041131462133141200213520ustar00rootroot00000000000000 Tremor - Vorbisfile Differences

Tremor documentation

Tremor version 1.0 - 20020403

Tremor / Vorbisfile API Differences

The Tremor libvorbisidec library exposes an API intended to be as similar as possible to the familiar 'vorbisfile' library included with the open source Vorbis reference libraries distributed for free by Xiph.org. Differences are summarized below.

OggVorbis_File structure

The bittrack and samptrack fields in the OggVorbis_File structure are changed to 64 bit integers in Tremor, from doubles in vorbisfile.

Time-related seek and tell function calls

The ov_time_total() and ov_time_tell() functions return milliseconds as 64 bit integers in Tremor. In vorbisfile, these functions returned seconds as doubles.

In Tremor, the ov_time_seek() and ov_time_seek_page() calls take seeking positions in milliseconds as 64 bit integers, rather than in seconds as doubles as in Vorbisfile.

Reading decoded data

Tremor ov_read() always returns data as signed 16 bit interleaved PCM in host byte order. As such, it does not take arguments to request specific signedness, byte order or bit depth as in Vorbisfile.

Tremor does not implement ov_read_float().




copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/example.html000066400000000000000000000121141462133141200220750ustar00rootroot00000000000000 Tremor - Example Code

Tremor documentation

Tremor version 1.0 - 20020403

Example Code

The following is a run-through of the decoding example program supplied with libvorbisidec, ivorbisfile_example.c. This program takes a vorbis bitstream from stdin and writes raw pcm to stdout.

First, relevant headers, including vorbis-specific "ivorbiscodec.h" and "ivorbisfile.h" have to be included.


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ivorbiscodec.h"
#include "ivorbisfile.h"

We also have to make a concession to Windows users here. If we are using windows for decoding, we must declare these libraries so that we can set stdin/stdout to binary.


#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif

Next, a buffer for the pcm audio output is declared.


char pcmout[4096];

Inside main(), we declare our primary OggVorbis_File structure. We also declare a few other helpful variables to track out progress within the file. Also, we make our final concession to Windows users by setting the stdin and stdout to binary mode.


int main(int argc, char **argv){
  OggVorbis_File vf;
  int eof=0;
  int current_section;

#ifdef _WIN32
  _setmode( _fileno( stdin ), _O_BINARY );
  _setmode( _fileno( stdout ), _O_BINARY );
#endif

ov_open() must be called to initialize the OggVorbis_File structure with default values. ov_open() also checks to ensure that we're reading Vorbis format and not something else.


  if(ov_open(stdin, &vf, NULL, 0) < 0) {
      fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n");
      exit(1);
  }

We're going to pull the channel and bitrate info from the file using ov_info() and show them to the user. We also want to pull out and show the user a comment attached to the file using ov_comment().


  {
    char **ptr=ov_comment(&vf,-1)->user_comments;
    vorbis_info *vi=ov_info(&vf,-1);
    while(*ptr){
      fprintf(stderr,"%s\n",*ptr);
      ++ptr;
    }
    fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi->channels,vi->rate);
    fprintf(stderr,"\nDecoded length: %ld samples\n",
            (long)ov_pcm_total(&vf,-1));
    fprintf(stderr,"Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor);
  }
  

Here's the read loop:



  while(!eof){
    long ret=ov_read(&vf,pcmout,sizeof(pcmout),¤t_section);
    if (ret == 0) {
      /* EOF */
      eof=1;
    } else if (ret < 0) {
      /* error in the stream.  Not a problem, just reporting it in
	 case we (the app) cares.  In this case, we don't. */
    } else {
      /* we don't bother dealing with sample rate changes, etc, but
	 you'll have to*/
      fwrite(pcmout,1,ret,stdout);
    }
  }

  

The code is reading blocks of data using ov_read(). Based on the value returned, we know if we're at the end of the file or have invalid data. If we have valid data, we write it to the pcm output.

Now that we've finished playing, we can pack up and go home. It's important to call ov_clear() when we're finished.



  ov_clear(&vf);
    
  fprintf(stderr,"Done.\n");
  return(0);
}




copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/fileinfo.html000066400000000000000000000066471462133141200222530ustar00rootroot00000000000000 Tremor - File Information

Tremor documentation

Tremor version 1.0 - 20020403

File Information

Libvorbisidec contains many functions to get information about bitstream attributes and decoding status.

All libvorbisidec file information routines are declared in "ivorbisfile.h".

function purpose
ov_bitrate Returns the average bitrate of the current logical bitstream.
ov_bitrate_instant Returns the exact bitrate since the last call of this function, or -1 if at the beginning of the bitream or no new information is available.
ov_streams Gives the number of logical bitstreams within the current physical bitstream.
ov_seekable Indicates whether the bitstream is seekable.
ov_serialnumber Returns the unique serial number of the specified logical bitstream.
ov_raw_total Returns the total (compressed) bytes in a physical or logical seekable bitstream.
ov_pcm_total Returns the total number of samples in a physical or logical seekable bitstream.
ov_time_total Returns the total time length in seconds of a physical or logical seekable bitstream.
ov_raw_tell Returns the byte location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_pcm_tell Returns the sample location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_time_tell Returns the time location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_info Returns the vorbis_info struct for a specific bitstream section.
ov_comment Returns attached comments for the current bitstream.



copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/index.html000066400000000000000000000031721462133141200215550ustar00rootroot00000000000000 Tremor - Documentation

Tremor documentation

Tremor version 1.0 - 20020403

Tremor Documentation

The Tremor Vorbis I stream and file decoder provides an embeddable, integer-only library [libvorbisidec] intended for decoding all current and future Vorbis I compliant streams. The Tremor libvorbisidec library exposes an API intended to be as similar as possible to the familiar 'vorbisfile' library included with the open source Vorbis reference libraries distributed for free by Xiph.org.

Tremor can be used along with any ANSI compliant stdio implementation for file/stream access, or use custom stream i/o routines provided by the embedded environment. Both uses are described in detail in this documentation.

Building libvorbisidec
API overview
API reference
Example code
Tremor / vorbisfile API differences



copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/initialization.html000066400000000000000000000076471462133141200235100ustar00rootroot00000000000000 Tremor - Setup/Teardown

Tremor documentation

Tremor version 1.0 - 20020403

Setup/Teardown

In order to decode audio using libvorbisidec, a bitstream containing Vorbis audio must be properly initialized before decoding and cleared when decoding is finished. The simplest possible case is to use fopen() to open a Vorbis file and then pass the FILE * to an ov_open() call. A successful return code from ov_open() indicates the file is ready for use. Once the file is no longer needed, ov_clear() is used to close the file and deallocate decoding resources. Do not call fclose() on the file; libvorbisidec does this in the ov_clear() call.

All libvorbisidec initialization and deallocation routines are declared in "ivorbisfile.h".

function purpose
ov_open Initializes the Ogg Vorbis bitstream with a pointer to a bitstream and default values. This must be called before other functions in the library may be used.
ov_open_callbacks Initializes the Ogg Vorbis bitstream with a pointer to a bitstream, default values, and custom file/bitstream manipulation routines. Used instead of ov_open() when working with other than stdio based I/O.
ov_test Partially opens a file just far enough to determine if the file is an Ogg Vorbis file or not. A successful return indicates that the file appears to be an Ogg Vorbis file, but the OggVorbis_File struct is not yet fully initialized for actual decoding. After a successful return, the file may be closed using ov_clear() or fully opened for decoding using ov_test_open().

This call is intended to be used as a less expensive file open test than a full ov_open().

Note that libvorbisidec owns the passed in file resource is it returns success; do not fclose() files owned by libvorbisidec.

ov_test_callbacks As above but allowing application-define I/O callbacks.

Note that libvorbisidec owns the passed in file resource is it returns success; do not fclose() files owned by libvorbisidec.

ov_test_open Finish opening a file after a successful call to ov_test() or ov_test_callbacks().
ov_clear Closes the bitstream and cleans up loose ends. Must be called when finished with the bitstream. After return, the OggVorbis_File struct is invalid and may not be used before being initialized again before begin reinitialized.



copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

bcmatroska2-5.3.101/mkclean/tremor/doc/ov_bitrate.html000066400000000000000000000046641462133141200226130ustar00rootroot00000000000000 Tremor - function - ov_bitrate

Tremor documentation

Tremor version 1.0 - 20020403

ov_bitrate

declared in "ivorbisfile.h";

This function returns the average bitrate for the specified logical bitstream. This may be different from the ov_info->nominal_bitrate value, as it is based on the actual average for this bitstream if the file is seekable.

Nonseekable files will return the nominal bitrate setting or the average of the upper and lower bounds, if any of these values are set.




long ov_bitrate(OggVorbis_File *vf,int i);

Parameters

vf
A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
i
Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the bitrate for the entire bitstream, this parameter should be set to -1.

Return Values

  • OV_EINVAL indicates that an invalid argument value was submitted or that the stream represented by vf is not open.
  • OV_FALSE means the call returned a 'false' status, which in this case most likely indicates that the file is nonseekable and the upper, lower, and nominal bitrates were unset.
  • n indicates the bitrate for the given logical bitstream or the entire physical bitstream. If the file is open for random (seekable) access, it will find the *actual* average bitrate. If the file is streaming (nonseekable), it returns the nominal bitrate (if set) or else the average of the upper/lower bounds (if set).



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_bitrate_instant.html000066400000000000000000000033071462133141200243440ustar00rootroot00000000000000 Tremor - function - ov_bitrate

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_bitrate_instant

    declared in "ivorbisfile.h";

    Used to find the most recent bitrate played back within the file. Will return 0 if the bitrate has not changed or it is the beginning of the file.

    
    long ov_bitrate_instant(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • 0 indicates the beginning of the file or unchanged bitrate info.
  • n indicates the actual bitrate since the last call.
  • OV_FALSE indicates that playback is not in progress, and thus there is no instantaneous bitrate information to report.
  • OV_EINVAL indicates that the stream represented by vf is not open.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_callbacks.html000066400000000000000000000046511462133141200230740ustar00rootroot00000000000000 Tremor - datatype - ov_callbacks

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_callbacks

    declared in "ivorbiscodec.h"

    The ov_callbacks structure contains file manipulation function prototypes necessary for opening, closing, seeking, and location.

    The ov_callbacks structure does not need to be user-defined if you are working with stdio-based file manipulation; the ov_open() call provides default callbacks for stdio. ov_callbacks are defined and passed to ov_open_callbacks() when implementing non-stdio based stream manipulation (such as playback from a memory buffer).

    typedef struct {
      size_t (*read_func)  (void *ptr, size_t size, size_t nmemb, void *datasource);
      int    (*seek_func)  (void *datasource, ogg_int64_t offset, int whence);
      int    (*close_func) (void *datasource);
      long   (*tell_func)  (void *datasource);
    } ov_callbacks;

    Relevant Struct Members

    read_func
    Pointer to custom data reading function.
    seek_func
    Pointer to custom data seeking function. If the data source is not seekable (or the application wants the data source to be treated as unseekable at all times), the provided seek callback should always return -1 (failure).
    close_func
    Pointer to custom data source closure function.
    tell_func
    Pointer to custom data location function.

    See the callbacks and non-stdio I/O document for more detailed information on required behavior of the various callback functions.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_clear.html000066400000000000000000000033411462133141200222360ustar00rootroot00000000000000 Tremor - function - ov_clear

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_clear

    declared in "ivorbisfile.h";

    After a bitstream has been opened using ov_open()/ov_open_callbacks() and decoding is complete, the application must call ov_clear() to clear the decoder's buffers and close the file.

    ov_clear() must also be called after a successful call to ov_test() or ov_test_callbacks().



    
    int ov_clear(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. After ov_clear has been called, the structure is deallocated and can no longer be used.

    Return Values

  • 0 for success



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_comment.html000066400000000000000000000034741462133141200226210ustar00rootroot00000000000000 Tremor - function - ov_bitrate

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_comment

    declared in "ivorbisfile.h";

    Returns a pointer to the vorbis_comment struct for the specified bitstream. For nonseekable streams, returns the struct for the current bitstream.



    
    vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the vorbis_comment struct for the current bitstream, this parameter should be set to -1.

    Return Values

  • Returns the vorbis_comment struct for the specified bitstream.
  • NULL if the specified bitstream does not exist or the file has been initialized improperly.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_info.html000066400000000000000000000036001462133141200221010ustar00rootroot00000000000000 Tremor - function - ov_info

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_info

    declared in "ivorbisfile.h";

    Returns the vorbis_info struct for the specified bitstream. For nonseekable files, always returns the current vorbis_info struct.

    
    vorbis_info *ov_info(OggVorbis_File *vf,int link);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the vorbis_info struct for the current bitstream, this parameter should be set to -1.

    Return Values

  • Returns the vorbis_info struct for the specified bitstream. Returns vorbis_info for current bitstream if the file is nonseekable or i=-1.
  • NULL if the specified bitstream does not exist or the file has been initialized improperly.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_open.html000066400000000000000000000107241462133141200221140ustar00rootroot00000000000000 Tremor - function - ov_open

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_open

    declared in "ivorbisfile.h";

    This is the main function used to open and initialize an OggVorbis_File structure. It sets up all the related decoding structure.

    The first argument must be a file pointer to an already opened file or pipe (it need not be seekable--though this obviously restricts what can be done with the bitstream). vf should be a pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.

    Also, you should be aware that ov_open(), once successful, takes complete possession of the file resource. After you have opened a file using ov_open(), you MUST close it using ov_clear(), not fclose() or any other function.

    It is often useful to call ov_open() simply to determine whether a given file is a vorbis bitstream. If the ov_open() call fails, then the file is not recognizable as such. When you use ov_open() for this, you should fclose() the file pointer if, and only if, the ov_open() call fails. If it succeeds, you must call ov_clear() to clear the decoder's buffers and close the file for you.

    (Note that ov_test() provides a less expensive way to test a file for Vorbisness.)



    
    int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
    

    Parameters

    f
    File pointer to an already opened file or pipe (it need not be seekable--though this obviously restricts what can be done with the bitstream).
    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.
    initial
    Typically set to NULL. This parameter is useful if some data has already been read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial should be a pointer to a buffer containing the data read.
    ibytes
    Typically set to 0. This parameter is useful if some data has already been read from the file and the stream is not seekable. In this case, ibytes should contain the length (in bytes) of the buffer. Used together with initial

    Return Values

  • 0 indicates success
  • less than zero for failure:
    • OV_EREAD - A read from media returned an error.
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • OV_EVERSION - Vorbis version mismatch.
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.

    Notes

    If your decoder is threaded, it is recommended that you NOT call ov_open() in the main control thread--instead, call ov_open() IN your decode/playback thread. This is important because ov_open() may be a fairly time-consuming call, given that the full structure of the file is determined at this point, which may require reading large parts of the file under certain circumstances (determining all the logical bitstreams in one physical bitstream, for example). See Thread Safety for other information on using libvorbisidec with threads.


    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_open_callbacks.html000066400000000000000000000105361462133141200241140ustar00rootroot00000000000000 Tremor - function - ov_open_callbacks

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_open_callbacks

    declared in "ivorbisfile.h";

    This is an alternative function used to open and initialize an OggVorbis_File structure when using a data source other than a file. It allows you to specify custom file manipulation routines and sets up all the related decoding structure.

    Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.

    It is often useful to call ov_open_callbacks() simply to determine whether a given file is a vorbis bitstream. If the ov_open_callbacks() call fails, then the file is not recognizable as such. When you use ov_open_callbacks() for this, you should fclose() the file pointer if, and only if, the ov_open_callbacks() call fails. If it succeeds, you must call ov_clear() to clear the decoder's buffers and close the file for you.

    See also Callbacks and Non-stdio I/O for information on designing and specifying the required callback functions.



    
    int ov_open_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks);
    

    Parameters

    f
    File pointer to an already opened file or pipe (it need not be seekable--though this obviously restricts what can be done with the bitstream).
    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.
    initial
    Typically set to NULL. This parameter is useful if some data has already been read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial should be a pointer to a buffer containing the data read.
    ibytes
    Typically set to 0. This parameter is useful if some data has already been read from the file and the stream is not seekable. In this case, ibytes should contain the length (in bytes) of the buffer. Used together with initial.
    callbacks
    Pointer to a completed ov_callbacks struct which indicates desired custom file manipulation routines.

    Return Values

  • 0 for success
  • less than zero for failure:
    • OV_EREAD - A read from media returned an error.
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • OV_EVERSION - Vorbis version mismatch.
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.

    Notes

    If your decoder is threaded, it is recommended that you NOT call ov_open_callbacks() in the main control thread--instead, call ov_open_callbacks() IN your decode/playback thread. This is important because ov_open_callbacks() may be a fairly time-consuming call, given that the full structure of the file is determined at this point, which may require reading large parts of the file under certain circumstances (determining all the logical bitstreams in one physical bitstream, for example). See Thread Safety for other information on using libvorbisidec with threads.


    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_pcm_seek.html000066400000000000000000000040331462133141200227350ustar00rootroot00000000000000 Tremor - function - ov_pcm_seek

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_pcm_seek

    declared in "ivorbisfile.h";

    Seeks to the offset specified (in pcm samples) within the physical bitstream. This function only works for seekable streams.

    This also updates everything needed within the decoder, so you can immediately call ov_read() and get data from the newly seeked to position.



    
    int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    pos
    Position in pcm samples to seek to in the bitstream.

    Return Values

  • 0 for success
  • nonzero indicates failure, described by several error codes:
    • OV_ENOSEEK - Bitstream is not seekable.
    • OV_EINVAL - Invalid argument value.
    • OV_EREAD - A read from media returned an error.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_pcm_seek_page.html000066400000000000000000000044761462133141200237440ustar00rootroot00000000000000 Tremor - function - ov_pcm_seek_page

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_pcm_seek_page

    declared in "ivorbisfile.h";

    Seeks to the closest page preceding the specified location (in pcm samples) within the physical bitstream. This function only works for seekable streams.

    This function is faster than ov_pcm_seek because the function can begin decoding at a page boundary rather than seeking through any remaining samples before the specified location. However, it is less accurate.

    This also updates everything needed within the decoder, so you can immediately call ov_read() and get data from the newly seeked to position.



    
    int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    pos
    Position in pcm samples to seek to in the bitstream.

    Return Values

  • 0 for success
  • nonzero indicates failure, described by several error codes:
    • OV_ENOSEEK - Bitstream is not seekable.
    • OV_EINVAL - Invalid argument value.
    • OV_EREAD - A read from media returned an error.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_pcm_tell.html000066400000000000000000000026371462133141200227560ustar00rootroot00000000000000 Tremor - function - ov_pcm_tell

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_pcm_tell

    declared in "ivorbisfile.h";

    Returns the current offset in samples.

    
    ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • n indicates the current offset in samples.
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_pcm_total.html000066400000000000000000000033461462133141200231370ustar00rootroot00000000000000 Tremor - function - ov_pcm_total

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_pcm_total

    declared in "ivorbisfile.h";

    Returns the total pcm samples of the physical bitstream or a specified logical bitstream.

    
    ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. To retrieve the total pcm samples for the entire physical bitstream, this parameter should be set to -1.

    Return Values

  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is unseekable.
  • total length in pcm samples of content if i=-1.
  • length in pcm samples of logical bitstream if i=1 to n.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_raw_seek.html000066400000000000000000000037331462133141200227550ustar00rootroot00000000000000 Tremor - function - ov_raw_seek

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_raw_seek

    declared in "ivorbisfile.h";

    Seeks to the offset specified (in compressed raw bytes) within the physical bitstream. This function only works for seekable streams.

    This also updates everything needed within the decoder, so you can immediately call ov_read() and get data from the newly seeked to position.

    When seek speed is a priority, this is the best seek funtion to use.

    
    int ov_raw_seek(OggVorbis_File *vf,long pos);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    pos
    Position in compressed bytes to seek to in the bitstream.

    Return Values

  • 0 indicates success
  • nonzero indicates failure, described by several error codes:
    • OV_ENOSEEK - Bitstream is not seekable.
    • OV_EINVAL - Invalid argument value.
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_raw_tell.html000066400000000000000000000026521462133141200227650ustar00rootroot00000000000000 Tremor - function - ov_raw_tell

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_raw_tell

    declared in "ivorbisfile.h";

    Returns the current offset in raw compressed bytes.

    
    ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • n indicates the current offset in bytes.
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_raw_total.html000066400000000000000000000034071462133141200231470ustar00rootroot00000000000000 Tremor - function - ov_raw_total

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_raw_total

    declared in "ivorbisfile.h";

    Returns the total (compressed) bytes of the physical bitstream or a specified logical bitstream.

    
    ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. To retrieve the total bytes for the entire physical bitstream, this parameter should be set to -1.

    Return Values

  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is nonseekable
  • n total length in compressed bytes of content if i=-1.
  • n length in compressed bytes of logical bitstream if i=1 to n.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_read.html000066400000000000000000000072061462133141200220670ustar00rootroot00000000000000 Tremor - function - ov_read

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_read()

    declared in "ivorbisfile.h";

    This is the main function used to decode a Vorbis file within a loop. It returns up to the specified number of bytes of decoded audio in host-endian, signed 16 bit PCM format. If the audio is multichannel, the channels are interleaved in the output buffer. If the passed in buffer is large, ov_read() will not fill it; the passed in buffer size is treated as a limit and not a request.

    Note that up to this point, the Tremor API could more or less hide the multiple logical bitstream nature of chaining from the toplevel application if the toplevel application didn't particularly care. However, when reading audio back, the application must be aware that multiple bitstream sections do not necessarily use the same number of channels or sampling rate.

    ov_read() passes back the index of the sequential logical bitstream currently being decoded (in *bitstream) along with the PCM data in order that the toplevel application can handle channel and/or sample rate changes. This number will be incremented at chaining boundaries even for non-seekable streams. For seekable streams, it represents the actual chaining index within the physical bitstream.



    
    long ov_read(OggVorbis_File *vf, char *buffer, int length, int *bitstream);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    buffer
    A pointer to an output buffer. The decoded output is inserted into this buffer.
    length
    Number of bytes to be read into the buffer. Should be the same size as the buffer. A typical value is 4096.
    bitstream
    A pointer to the number of the current logical bitstream.

    Return Values

    OV_HOLE
    indicates there was an interruption in the data.
    (one of: garbage between pages, loss of sync followed by recapture, or a corrupt page)
    OV_EBADLINK
    indicates that an invalid stream section was supplied to libvorbisidec, or the requested link is corrupt.
    0
    indicates EOF
    n
    indicates actual number of bytes read. ov_read() will decode at most one vorbis packet per invocation, so the value returned will generally be less than length.

    Notes

    Typical usage:

    bytes_read = ov_read(&vf, buffer, 4096,&current_section)
    This reads up to 4096 bytes into a buffer, with signed 16-bit little-endian samples.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_seekable.html000066400000000000000000000025531462133141200227270ustar00rootroot00000000000000 Tremor - function - ov_seekable

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_seekable

    declared in "ivorbisfile.h";

    This indicates whether or not the bitstream is seekable.

    
    long ov_seekable(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • 0 indicates that the file is not seekable.
  • nonzero indicates that the file is seekable.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_serialnumber.html000066400000000000000000000033631462133141200236440ustar00rootroot00000000000000 Tremor - function - ov_serialnumber

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_serialnumber

    declared in "ivorbisfile.h";

    Returns the serialnumber of the specified logical bitstream link number within the overall physical bitstream.

    
    long ov_serialnumber(OggVorbis_File *vf,int i);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the serial number of the current bitstream, this parameter should be set to -1.

    Return Values

  • -1 if the specified logical bitstream i does not exist.
  • Returns the serial number of the logical bitstream i or the serial number of the current bitstream if the file is nonseekable.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_streams.html000066400000000000000000000026241462133141200226310ustar00rootroot00000000000000 Tremor - function - ov_streams

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_streams

    declared in "ivorbisfile.h";

    Returns the number of logical bitstreams within our physical bitstream.

    
    long ov_streams(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • 1 indicates a single logical bitstream or an unseekable file.
  • n indicates the number of logical bitstreams.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_test.html000066400000000000000000000053661462133141200221400ustar00rootroot00000000000000 Tremor - function - ov_test

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_test

    declared in "ivorbisfile.h";

    This partially opens a vorbis file to test for Vorbis-ness. It loads the headers for the first chain, and tests for seekability (but does not seek). Use ov_test_open() to finish opening the file or ov_clear to close/free it.

    
    int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
    

    Parameters

    f
    File pointer to an already opened file or pipe (it need not be seekable--though this obviously restricts what can be done with the bitstream).
    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.
    initial
    Typically set to NULL. This parameter is useful if some data has already been read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial should be a pointer to a buffer containing the data read.
    ibytes
    Typically set to 0. This parameter is useful if some data has already been read from the file and the stream is not seekable. In this case, ibytes should contain the length (in bytes) of the buffer. Used together with initial

    Return Values

  • 0 for success
  • less than zero for failure:
    • OV_EREAD - A read from media returned an error.
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • OV_EVERSION - Vorbis version mismatch.
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_test_callbacks.html000066400000000000000000000061221462133141200241260ustar00rootroot00000000000000 Tremor - function - ov_test_callbacks

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_test_callbacks

    declared in "ivorbisfile.h";

    This is an alternative function used to open and test an OggVorbis_File structure when using a data source other than a file. It allows you to specify custom file manipulation routines and sets up all the related decoding structures.

    Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.



    
    int ov_test_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks);
    

    Parameters

    f
    File pointer to an already opened file or pipe (it need not be seekable--though this obviously restricts what can be done with the bitstream).
    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.
    initial
    Typically set to NULL. This parameter is useful if some data has already been read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial should be a pointer to a buffer containing the data read.
    ibytes
    Typically set to 0. This parameter is useful if some data has already been read from the file and the stream is not seekable. In this case, ibytes should contain the length (in bytes) of the buffer. Used together with initial.
    callbacks
    Pointer to a completed ov_callbacks struct which indicates desired custom file manipulation routines.

    Return Values

  • 0 for success
  • less than zero for failure:
    • OV_EREAD - A read from media returned an error.
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • OV_EVERSION - Vorbis version mismatch.
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_test_open.html000066400000000000000000000035551462133141200231570ustar00rootroot00000000000000 Tremor - function - ov_test_open

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_test_open

    declared in "ivorbisfile.h";

    Finish opening a file partially opened with ov_test() or ov_test_callbacks().

    
    int ov_test_open(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions. Once this has been called, the same OggVorbis_File struct should be passed to all the libvorbisidec functions.

    Return Values

  • 0 for success
  • less than zero for failure:
    • OV_EREAD - A read from media returned an error.
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • OV_EVERSION - Vorbis version mismatch.
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_time_seek.html000066400000000000000000000033071462133141200231170ustar00rootroot00000000000000 Tremor - function - ov_time_seek

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_time_seek

    declared in "ivorbisfile.h";

    For seekable streams, this seeks to the given time. For implementing seeking in a player, this is the only function generally needed. This also updates everything needed within the decoder, so you can immediately call ov_read() and get data from the newly seeked to position. This function does not work for unseekable streams.

    
    int ov_time_seek(OggVorbis_File *vf, ogg_int64_t ms);
    

    Parameters

    vf
    Pointer to our already opened and initialized OggVorbis_File structure.
    ms
    Location to seek to within the file, specified in milliseconds.

    Return Values

  • 0 for success
  • Nonzero for failure



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_time_seek_page.html000066400000000000000000000044471462133141200241210ustar00rootroot00000000000000 Tremor - function - ov_time_seek_page

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_time_seek_page

    declared in "ivorbisfile.h";

    For seekable streams, this seeks to closest full page preceding the given time. This function is faster than ov_time_seek because it doesn't seek through the last few samples to reach an exact time, but it is also less accurate. This should be used when speed is important.

    This function also updates everything needed within the decoder, so you can immediately call ov_read() and get data from the newly seeked to position.

    This function does not work for unseekable streams.

    
    int ov_time_seek_page(OggVorbis_File *vf, ogg_int64_t ms);
    

    Parameters

    vf
    Pointer to our already opened and initialized OggVorbis_File structure.
    ms
    Location to seek to within the file, specified in milliseconds.

    Return Values

  • 0 for success
  • nonzero indicates failure, described by several error codes:
    • OV_ENOSEEK - Bitstream is not seekable.
    • OV_EINVAL - Invalid argument value.
    • OV_EREAD - A read from media returned an error.
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_time_tell.html000066400000000000000000000027011462133141200231250ustar00rootroot00000000000000 Tremor - function - ov_bitrate

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_time_tell

    declared in "ivorbisfile.h";

    Returns the current decoding offset in milliseconds.

    
    ogg_int64_t ov_time_tell(OggVorbis_File *vf);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.

    Return Values

  • n indicates the current decoding time offset in milliseconds.
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/ov_time_total.html000066400000000000000000000034031462133141200233100ustar00rootroot00000000000000 Tremor - function - ov_time_total

    Tremor documentation

    Tremor version 1.0 - 20020403

    ov_time_total

    declared in "ivorbisfile.h";

    Returns the total time in seconds of the physical bitstream or a specified logical bitstream.

    
    ogg_int64_t ov_time_total(OggVorbis_File *vf,int i);
    

    Parameters

    vf
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec functions.
    i
    Link to the desired logical bitstream. To retrieve the time total for the entire physical bitstream, this parameter should be set to -1.

    Return Values

  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is nonseekable.
  • n total length in milliseconds of content if i=-1.
  • n length in milliseconds of logical bitstream if i=1 to n.



  • copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/overview.html000066400000000000000000000033101462133141200223060ustar00rootroot00000000000000 Tremor - API Overview

    Tremor documentation

    Tremor version 1.0 - 20020403

    Tremor API Overview

    The makeup of the Tremor libvorbisidec library API is relatively simple. It revolves around a single file resource. This file resource is passed to libvorbisidec, where it is opened, manipulated, and closed, in the form of an OggVorbis_File struct.

    The Tremor API consists of the following functional categories:

    In addition, the following subjects deserve attention additional to the above general overview:




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/reference.html000066400000000000000000000046051462133141200224060ustar00rootroot00000000000000 Tremor API Reference

    Tremor documentation

    Tremor version 1.0 - 20020403

    Tremor API Reference

    Data Structures
    OggVorbis_File
    vorbis_comment
    vorbis_info
    ov_callbacks

    Setup/Teardown
    ov_open()
    ov_open_callbacks()
    ov_clear()
    ov_test()
    ov_test_callbacks()
    ov_test_open()

    Decoding
    ov_read()

    Seeking
    ov_raw_seek()
    ov_pcm_seek()
    ov_time_seek()
    ov_pcm_seek_page()
    ov_time_seek_page()

    File Information
    ov_bitrate()
    ov_bitrate_instant()
    ov_streams()
    ov_seekable()
    ov_serialnumber()
    ov_raw_total()
    ov_pcm_total()
    ov_time_total()
    ov_raw_tell()
    ov_pcm_tell()
    ov_time_tell()
    ov_info()
    ov_comment()

    Return Codes



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/return.html000066400000000000000000000041061462133141200217630ustar00rootroot00000000000000 Tremor - Return Codes

    Tremor documentation

    Tremor version 1.0 - 20020403

    Return Codes

    The following return codes are #defined in "ivorbiscodec.h" may be returned by libvorbisidec. Descriptions of a code relevant to a specific function are found in the reference description of that function.

    OV_FALSE
    Not true, or no data available
    OV_HOLE
    Tremor encoutered missing or corrupt data in the bitstream. Recovery is normally automatic and this return code is for informational purposes only.
    OV_EREAD
    Read error while fetching compressed data for decode
    OV_EFAULT
    Internal inconsistency in decode state. Continuing is likely not possible.
    OV_EIMPL
    Feature not implemented
    OV_EINVAL
    Either an invalid argument, or incompletely initialized argument passed to libvorbisidec call
    OV_ENOTVORBIS
    The given file/data was not recognized as Ogg Vorbis data.
    OV_EBADHEADER
    The file/data is apparently an Ogg Vorbis stream, but contains a corrupted or undecipherable header.
    OV_EVERSION
    The bitstream format revision of the given stream is not supported.
    OV_EBADLINK
    The given link exists in the Vorbis data stream, but is not decipherable due to garbacge or corruption.
    OV_ENOSEEK
    The given stream is not seekable



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/seeking.html000066400000000000000000000052711462133141200220750ustar00rootroot00000000000000 Tremor - Seeking

    Tremor documentation

    Tremor version 1.0 - 20020403

    Seeking

    Seeking functions allow you to specify a specific point in the stream to begin or continue decoding.

    All libvorbisidec seeking routines are declared in "ivorbisfile.h".

    Certain seeking functions are best suited to different situations. When speed is important and exact positioning isn't required, page-level seeking should be used. Note also that Vorbis files do not necessarily start at a sample number or time offset of zero. Do not be surprised if a file begins at a positive offset of several minutes or hours, such as would happen if a large stream (such as a concert recording) is chopped into multiple separate files. Requesting to seek to a position before the beginning of such a file will seek to the position where audio begins.

    function purpose
    ov_raw_seek This function seeks to a position specified in the compressed bitstream, specified in bytes.
    ov_pcm_seek This function seeks to a specific audio sample number, specified in pcm samples.
    ov_pcm_seek_page This function seeks to the closest page preceding the specified audio sample number, specified in pcm samples.
    ov_time_seek This function seeks to the specific time location in the bitstream, specified in integer milliseconds. Note that this differs from the reference vorbisfile implementation, which takes seconds as a float.
    ov_time_seek_page This function seeks to the closest page preceding the specified time position in the bitstream, specified in integer milliseconds.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/style.css000066400000000000000000000004271462133141200214320ustar00rootroot00000000000000BODY { font-family: Helvetica, sans-serif } TD { font-family: Helvetica, sans-serif } P { font-family: Helvetica, sans-serif } H1 { font-family: Helvetica, sans-serif } H2 { font-family: Helvetica, sans-serif } H4 { font-family: Helvetica, sans-serif } P.tiny { font-size: 8pt } bcmatroska2-5.3.101/mkclean/tremor/doc/threads.html000066400000000000000000000027661462133141200221100ustar00rootroot00000000000000 Tremor - Thread Safety

    Tremor documentation

    Tremor version 1.0 - 20020403

    Thread Safety

    Tremor's libvorbisidec may be used safely in a threading environment so long as thread access to individual OggVorbis_File instances is serialized.
    • Only one thread at a time may enter a function that takes a given OggVorbis_File instance, even if the functions involved appear to be read-only.

    • Multiple threads may enter libvorbisidec at a given time, so long as each thread's function calls are using different OggVorbis_File instances.

    • Any one OggVorbis_File instance may be used safely from multiple threads so long as only one thread at a time is making calls using that instance.




    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/vorbis_comment.html000066400000000000000000000041441462133141200234740ustar00rootroot00000000000000 Tremor - datatype - vorbis_comment

    Tremor documentation

    Tremor version 1.0 - 20020403

    vorbis_comment

    declared in "ivorbiscodec.h"

    The vorbis_comment structure defines an Ogg Vorbis comment.

    Only the fields the program needs must be defined. If a field isn't defined by the application, it will either be blank (if it's a string value) or set to some reasonable default (usually 0).

    typedef struct vorbis_comment{
      /* unlimited user comment fields. */
      char **user_comments;
      int  *comment_lengths;
      int  comments;
      char *vendor;
    
    } vorbis_comment;

    Parameters

    user_comments
    Unlimited user comment array. The individual strings in the array are 8 bit clean, by the Vorbis specification, and as such the comment_lengths array should be consulted to determine string length. For convenience, each string is also NULL-terminated by the decode library (although Vorbis comments are not NULL terminated within the bitstream itself).
    comment_lengths
    An int array that stores the length of each comment string
    comments
    Int signifying number of user comments in user_comments field.
    vendor
    Information about the creator of the file. Stored in a standard C 0-terminated string.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/doc/vorbis_info.html000066400000000000000000000045101462133141200227620ustar00rootroot00000000000000 Tremor - datatype - vorbis_info

    Tremor documentation

    Tremor version 1.0 - 20020403

    vorbis_info

    declared in "ivorbiscodec.h"

    The vorbis_info structure contains basic information about the audio in a vorbis bitstream.

    typedef struct vorbis_info{
      int version;
      int channels;
      long rate;
      
      long bitrate_upper;
      long bitrate_nominal;
      long bitrate_lower;
      long bitrate_window;
    
      void *codec_setup;
    
    } vorbis_info;

    Relevant Struct Members

    version
    Vorbis encoder version used to create this bitstream.
    channels
    Int signifying number of channels in bitstream.
    rate
    Sampling rate of the bitstream.
    bitrate_upper
    Specifies the upper limit in a VBR bitstream. If the value matches the bitrate_nominal and bitrate_lower parameters, the stream is fixed bitrate. May be unset if no limit exists.
    bitrate_nominal
    Specifies the average bitrate for a VBR bitstream. May be unset. If the bitrate_upper and bitrate_lower parameters match, the stream is fixed bitrate.
    bitrate_lower
    Specifies the lower limit in a VBR bitstream. If the value matches the bitrate_nominal and bitrate_upper parameters, the stream is fixed bitrate. May be unset if no limit exists.
    bitrate_window
    Currently unset.
    codec_setup
    Internal structure that contains the detailed/unpacked configuration for decoding the current Vorbis bitstream.



    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    bcmatroska2-5.3.101/mkclean/tremor/floor0.c000066400000000000000000000302211462133141200203530ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: floor backend 0 implementation ********************************************************************/ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "codebook.h" #include "misc.h" #include "block.h" #define LSP_FRACBITS 14 typedef struct { long n; int ln; int m; int *linearmap; vorbis_info_floor0 *vi; ogg_int32_t *lsp_look; } vorbis_look_floor0; /*************** LSP decode ********************/ #include "lsp_lookup.h" /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in 16.16 format returns in m.8 format */ static long ADJUST_SQRT2[2]={8192,5792}; STIN ogg_int32_t vorbis_invsqlook_i(long a,long e){ long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1); long d=a&INVSQ_LOOKUP_I_MASK; /* 0.10 */ long val=INVSQ_LOOKUP_I[i]- /* 1.16 */ ((INVSQ_LOOKUP_IDel[i]*d)>>INVSQ_LOOKUP_I_SHIFT); /* result 1.16 */ val*=ADJUST_SQRT2[e&1]; e=(e>>1)+21; return(val>>e); } /* interpolated lookup based fromdB function, domain -140dB to 0dB only */ /* a is in n.12 format */ STIN ogg_int32_t vorbis_fromdBlook_i(long a){ int i=(-a)>>(12-FROMdB2_SHIFT); if(i<0) return 0x7fffffff; if(i>=(FROMdB_LOOKUP_SZ<>FROMdB_SHIFT] * FROMdB2_LOOKUP[i&FROMdB2_MASK]; } /* interpolated lookup based cos function, domain 0 to PI only */ /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */ STIN ogg_int32_t vorbis_coslook_i(long a){ int i=a>>COS_LOOKUP_I_SHIFT; int d=a&COS_LOOKUP_I_MASK; return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>> COS_LOOKUP_I_SHIFT); } /* interpolated lookup based cos function */ /* a is in 0.16 format, where 0==0, 2^^16==PI, return .LSP_FRACBITS */ STIN ogg_int32_t vorbis_coslook2_i(long a){ a=a&0x1ffff; if(a>0x10000)a=0x20000-a; { int i=a>>COS_LOOKUP_I_SHIFT; int d=a&COS_LOOKUP_I_MASK; a=((COS_LOOKUP_I[i]<> (COS_LOOKUP_I_SHIFT-LSP_FRACBITS+14); } return(a); } static const int barklook[28]={ 0,100,200,301, 405,516,635,766, 912,1077,1263,1476, 1720,2003,2333,2721, 3184,3742,4428,5285, 6376,7791,9662,12181, 15624,20397,27087,36554 }; /* used in init only; interpolate the long way */ STIN ogg_int32_t toBARK(int n){ int i; for(i=0;i<27;i++) if(n>=barklook[i] && n>10)*0x517d)>>14; #endif /* safeguard against a malicious stream */ if(val<0 || (val>>COS_LOOKUP_I_SHIFT)>=COS_LOOKUP_I_SZ){ memset(curve,0,sizeof(*curve)*n); return; } ilsp[i]=vorbis_coslook_i(val); } i=0; while(i>16); qi=((qi*qi)>>16); if(m&1){ qexp= qexp*2-28*((m+1)>>1)+m; pi*=(1<<14)-((wi*wi)>>14); qi+=pi>>14; }else{ qexp= qexp*2-13*m; pi*=(1<<14)-wi; qi*=(1<<14)+wi; qi=(qi+pi)>>14; } if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */ qi>>=1; qexp++; }else lsp_norm_asm(&qi,&qexp); #else qi*=labs(ilsp[0]-wi); pi*=labs(ilsp[1]-wi); for(j=3;j>25])) if(!(shift=MLOOP_2[(pi|qi)>>19])) shift=MLOOP_3[(pi|qi)>>16]; qi=(qi>>shift)*labs(ilsp[j-1]-wi); pi=(pi>>shift)*labs(ilsp[j]-wi); qexp+=shift; } if(!(shift=MLOOP_1[(pi|qi)>>25])) if(!(shift=MLOOP_2[(pi|qi)>>19])) shift=MLOOP_3[(pi|qi)>>16]; /* pi,qi normalized collectively, both tracked using qexp */ if(m&1){ /* odd order filter; slightly assymetric */ /* the last coefficient */ qi=(qi>>shift)*labs(ilsp[j-1]-wi); pi=(pi>>shift)<<14; qexp+=shift; if(!(shift=MLOOP_1[(pi|qi)>>25])) if(!(shift=MLOOP_2[(pi|qi)>>19])) shift=MLOOP_3[(pi|qi)>>16]; pi>>=shift; qi>>=shift; qexp+=shift-14*((m+1)>>1); pi=((pi*pi)>>16); qi=((qi*qi)>>16); qexp=qexp*2+m; pi*=(1<<14)-((wi*wi)>>14); qi+=pi>>14; }else{ /* even order filter; still symmetric */ /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't worth tracking step by step */ pi>>=shift; qi>>=shift; qexp+=shift-7*m; pi=((pi*pi)>>16); qi=((qi*qi)>>16); qexp=qexp*2+m; pi*=(1<<14)-wi; qi*=(1<<14)+wi; qi=(qi+pi)>>14; } /* we've let the normalization drift because it wasn't important; however, for the lookup, things must be normalized again. We need at most one right shift or a number of left shifts */ if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */ qi>>=1; qexp++; }else while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/ qi<<=1; qexp--; } #endif amp=vorbis_fromdBlook_i(ampi* /* n.4 */ vorbis_invsqlook_i(qi,qexp)- /* m.8, m+n<=8 */ ampoffseti); /* 8.12[0] */ #ifdef _LOW_ACCURACY_ amp>>=9; #endif curve[i]= MULT31_SHIFT15(curve[i],amp); while(map[++i]==k) curve[i]= MULT31_SHIFT15(curve[i],amp); } } /*************** vorbis decode glue ************/ static void floor0_free_info(vorbis_info_floor *i){ vorbis_info_floor0 *info=(vorbis_info_floor0 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } static void floor0_free_look(vorbis_look_floor *i){ vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; if(look){ if(look->linearmap)_ogg_free(look->linearmap); if(look->lsp_look)_ogg_free(look->lsp_look); memset(look,0,sizeof(*look)); _ogg_free(look); } } static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; int j; vorbis_info_floor0 *info=(vorbis_info_floor0 *)_ogg_malloc(sizeof(*info)); info->order=oggpack_read(opb,8); info->rate=oggpack_read(opb,16); info->barkmap=oggpack_read(opb,16); info->ampbits=oggpack_read(opb,6); info->ampdB=oggpack_read(opb,8); info->numbooks=oggpack_read(opb,4)+1; if(info->order<1)goto err_out; if(info->rate<1)goto err_out; if(info->barkmap<1)goto err_out; if(info->numbooks<1)goto err_out; for(j=0;jnumbooks;j++){ info->books[j]=oggpack_read(opb,8); if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out; } return(info); err_out: floor0_free_info(info); return(NULL); } /* initialize Bark scale and normalization lookups. We could do this with static tables, but Vorbis allows a number of possible combinations, so it's best to do it computationally. The below is authoritative in terms of defining scale mapping. Note that the scale depends on the sampling rate as well as the linear block and mapping sizes */ static vorbis_look_floor *floor0_look (vorbis_dsp_state *vd,vorbis_info_mode *mi, vorbis_info_floor *i){ int j; vorbis_info *vi=vd->vi; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; vorbis_info_floor0 *info=(vorbis_info_floor0 *)i; vorbis_look_floor0 *look=(vorbis_look_floor0 *)_ogg_calloc(1,sizeof(*look)); look->m=info->order; look->n=ci->blocksizes[mi->blockflag]/2; look->ln=info->barkmap; look->vi=info; /* the mapping from a linear scale to a smaller bark scale is straightforward. We do *not* make sure that the linear mapping does not skip bark-scale bins; the decoder simply skips them and the encoder may do what it wishes in filling them. They're necessary in some mapping combinations to keep the scale spacing accurate */ look->linearmap=(int *)_ogg_malloc((look->n+1)*sizeof(*look->linearmap)); for(j=0;jn;j++){ int val=(look->ln* ((toBARK(info->rate/2*j/look->n)<<11)/toBARK(info->rate/2)))>>11; if(val>=look->ln)val=look->ln-1; /* guard against the approximation */ look->linearmap[j]=val; } look->linearmap[j]=-1; look->lsp_look=(ogg_int32_t *)_ogg_malloc(look->ln*sizeof(*look->lsp_look)); for(j=0;jln;j++) look->lsp_look[j]=vorbis_coslook2_i(0x10000*j/look->ln); return look; } static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){ vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; vorbis_info_floor0 *info=look->vi; int j,k; int ampraw=oggpack_read(&vb->opb,info->ampbits); if(ampraw>0){ /* also handles the -1 out of data case */ long maxval=(1<ampbits)-1; int amp=((ampraw*info->ampdB)<<4)/maxval; int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks)); if(booknum!=-1 && booknumnumbooks){ /* be paranoid */ codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; codebook *b=ci->fullbooks+info->books[booknum]; ogg_int32_t last=0; ogg_int32_t *lsp=(ogg_int32_t *)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+1)); for(j=0;jm;j+=b->dim) if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim,-24)==-1)goto eop; for(j=0;jm;){ for(k=0;kdim;k++,j++)lsp[j]+=last; last=lsp[j-1]; } lsp[look->m]=amp; return(lsp); } } eop: return(NULL); } static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i, void *memo,ogg_int32_t *out){ vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; vorbis_info_floor0 *info=look->vi; if(memo){ ogg_int32_t *lsp=(ogg_int32_t *)memo; ogg_int32_t amp=lsp[look->m]; /* take the coefficients back to a spectral envelope curve */ vorbis_lsp_to_curve(out,look->linearmap,look->n,look->ln, lsp,look->m,amp,info->ampdB,look->lsp_look); return(1); } memset(out,0,sizeof(*out)*look->n); return(0); } /* export hooks */ vorbis_func_floor floor0_exportbundle={ &floor0_unpack,&floor0_look,&floor0_free_info, &floor0_free_look,&floor0_inverse1,&floor0_inverse2 }; bcmatroska2-5.3.101/mkclean/tremor/floor1.c000066400000000000000000000335761462133141200203740ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: floor backend 1 implementation ********************************************************************/ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "codebook.h" #include "misc.h" #include "block.h" #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */ typedef struct { int forward_index[VIF_POSIT+2]; int hineighbor[VIF_POSIT]; int loneighbor[VIF_POSIT]; int posts; int n; int quant_q; vorbis_info_floor1 *vi; } vorbis_look_floor1; /***********************************************/ static void floor1_free_info(vorbis_info_floor *i){ vorbis_info_floor1 *info=(vorbis_info_floor1 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } static void floor1_free_look(vorbis_look_floor *i){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)i; if(look){ memset(look,0,sizeof(*look)); _ogg_free(look); } } static int ilog(unsigned int v){ int ret=0; while(v){ ret++; v>>=1; } return(ret); } static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; int j,k,count=0,maxclass=-1,rangebits; vorbis_info_floor1 *info=(vorbis_info_floor1 *)_ogg_calloc(1,sizeof(*info)); /* read partitions */ info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */ for(j=0;jpartitions;j++){ info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */ if(maxclasspartitionclass[j])maxclass=info->partitionclass[j]; } /* read partition classes */ for(j=0;jclass_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */ info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */ if(info->class_subs[j]<0) goto err_out; if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8); if(info->class_book[j]<0 || info->class_book[j]>=ci->books) goto err_out; for(k=0;k<(1<class_subs[j]);k++){ info->class_subbook[j][k]=oggpack_read(opb,8)-1; if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books) goto err_out; } } /* read the post list */ info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */ rangebits=oggpack_read(opb,4); for(j=0,k=0;jpartitions;j++){ count+=info->class_dim[info->partitionclass[j]]; for(;kpostlist[k+2]=oggpack_read(opb,rangebits); if(t<0 || t>=(1<postlist[0]=0; info->postlist[1]=1<vi=info; look->n=info->postlist[1]; /* we drop each position value in-between already decoded values, and use linear interpolation to predict each new value past the edges. The positions are read in the order of the position list... we precompute the bounding positions in the lookup. Of course, the neighbors can change (if a position is declined), but this is an initial mapping */ for(i=0;ipartitions;i++)n+=info->class_dim[info->partitionclass[i]]; n+=2; look->posts=n; /* also store a sorted position index */ for(i=0;ipostlist+i; qsort(sortpointer,n,sizeof(*sortpointer),icomp); /* points from sort order back to range number */ for(i=0;iforward_index[i]=sortpointer[i]-info->postlist; /* quantize values to multiplier spec */ switch(info->mult){ case 1: /* 1024 -> 256 */ look->quant_q=256; break; case 2: /* 1024 -> 128 */ look->quant_q=128; break; case 3: /* 1024 -> 86 */ look->quant_q=86; break; case 4: /* 1024 -> 64 */ look->quant_q=64; break; } /* discover our neighbors for decode where we don't use fit flags (that would push the neighbors outward) */ for(i=0;in; int currentx=info->postlist[i+2]; for(j=0;jpostlist[j]; if(x>lx && xcurrentx){ hi=j; hx=x; } } look->loneighbor[i]=lo; look->hineighbor[i]=hi; } return(look); } static int render_point(int x0,int x1,int y0,int y1,int x){ y0&=0x7fff; /* mask off flag */ y1&=0x7fff; { int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int err=ady*(x-x0); int off=err/adx; if(dy<0)return(y0-off); return(y0+off); } } #ifdef _LOW_ACCURACY_ # define XdB(n) ((((n)>>8)+1)>>1) #else # define XdB(n) (n) #endif static const ogg_int32_t FLOOR_fromdB_LOOKUP[256]={ XdB(0x000000e5), XdB(0x000000f4), XdB(0x00000103), XdB(0x00000114), XdB(0x00000126), XdB(0x00000139), XdB(0x0000014e), XdB(0x00000163), XdB(0x0000017a), XdB(0x00000193), XdB(0x000001ad), XdB(0x000001c9), XdB(0x000001e7), XdB(0x00000206), XdB(0x00000228), XdB(0x0000024c), XdB(0x00000272), XdB(0x0000029b), XdB(0x000002c6), XdB(0x000002f4), XdB(0x00000326), XdB(0x0000035a), XdB(0x00000392), XdB(0x000003cd), XdB(0x0000040c), XdB(0x00000450), XdB(0x00000497), XdB(0x000004e4), XdB(0x00000535), XdB(0x0000058c), XdB(0x000005e8), XdB(0x0000064a), XdB(0x000006b3), XdB(0x00000722), XdB(0x00000799), XdB(0x00000818), XdB(0x0000089e), XdB(0x0000092e), XdB(0x000009c6), XdB(0x00000a69), XdB(0x00000b16), XdB(0x00000bcf), XdB(0x00000c93), XdB(0x00000d64), XdB(0x00000e43), XdB(0x00000f30), XdB(0x0000102d), XdB(0x0000113a), XdB(0x00001258), XdB(0x0000138a), XdB(0x000014cf), XdB(0x00001629), XdB(0x0000179a), XdB(0x00001922), XdB(0x00001ac4), XdB(0x00001c82), XdB(0x00001e5c), XdB(0x00002055), XdB(0x0000226f), XdB(0x000024ac), XdB(0x0000270e), XdB(0x00002997), XdB(0x00002c4b), XdB(0x00002f2c), XdB(0x0000323d), XdB(0x00003581), XdB(0x000038fb), XdB(0x00003caf), XdB(0x000040a0), XdB(0x000044d3), XdB(0x0000494c), XdB(0x00004e10), XdB(0x00005323), XdB(0x0000588a), XdB(0x00005e4b), XdB(0x0000646b), XdB(0x00006af2), XdB(0x000071e5), XdB(0x0000794c), XdB(0x0000812e), XdB(0x00008993), XdB(0x00009283), XdB(0x00009c09), XdB(0x0000a62d), XdB(0x0000b0f9), XdB(0x0000bc79), XdB(0x0000c8b9), XdB(0x0000d5c4), XdB(0x0000e3a9), XdB(0x0000f274), XdB(0x00010235), XdB(0x000112fd), XdB(0x000124dc), XdB(0x000137e4), XdB(0x00014c29), XdB(0x000161bf), XdB(0x000178bc), XdB(0x00019137), XdB(0x0001ab4a), XdB(0x0001c70e), XdB(0x0001e4a1), XdB(0x0002041f), XdB(0x000225aa), XdB(0x00024962), XdB(0x00026f6d), XdB(0x000297f0), XdB(0x0002c316), XdB(0x0002f109), XdB(0x000321f9), XdB(0x00035616), XdB(0x00038d97), XdB(0x0003c8b4), XdB(0x000407a7), XdB(0x00044ab2), XdB(0x00049218), XdB(0x0004de23), XdB(0x00052f1e), XdB(0x0005855c), XdB(0x0005e135), XdB(0x00064306), XdB(0x0006ab33), XdB(0x00071a24), XdB(0x0007904b), XdB(0x00080e20), XdB(0x00089422), XdB(0x000922da), XdB(0x0009bad8), XdB(0x000a5cb6), XdB(0x000b091a), XdB(0x000bc0b1), XdB(0x000c8436), XdB(0x000d5471), XdB(0x000e3233), XdB(0x000f1e5f), XdB(0x001019e4), XdB(0x001125c1), XdB(0x00124306), XdB(0x001372d5), XdB(0x0014b663), XdB(0x00160ef7), XdB(0x00177df0), XdB(0x001904c1), XdB(0x001aa4f9), XdB(0x001c603d), XdB(0x001e384f), XdB(0x00202f0f), XdB(0x0022467a), XdB(0x002480b1), XdB(0x0026dff7), XdB(0x002966b3), XdB(0x002c1776), XdB(0x002ef4fc), XdB(0x0032022d), XdB(0x00354222), XdB(0x0038b828), XdB(0x003c67c2), XdB(0x004054ae), XdB(0x004482e8), XdB(0x0048f6af), XdB(0x004db488), XdB(0x0052c142), XdB(0x005821ff), XdB(0x005ddc33), XdB(0x0063f5b0), XdB(0x006a74a7), XdB(0x00715faf), XdB(0x0078bdce), XdB(0x0080967f), XdB(0x0088f1ba), XdB(0x0091d7f9), XdB(0x009b5247), XdB(0x00a56a41), XdB(0x00b02a27), XdB(0x00bb9ce2), XdB(0x00c7ce12), XdB(0x00d4ca17), XdB(0x00e29e20), XdB(0x00f15835), XdB(0x0101074b), XdB(0x0111bb4e), XdB(0x01238531), XdB(0x01367704), XdB(0x014aa402), XdB(0x016020a7), XdB(0x017702c3), XdB(0x018f6190), XdB(0x01a955cb), XdB(0x01c4f9cf), XdB(0x01e269a8), XdB(0x0201c33b), XdB(0x0223265a), XdB(0x0246b4ea), XdB(0x026c9302), XdB(0x0294e716), XdB(0x02bfda13), XdB(0x02ed9793), XdB(0x031e4e09), XdB(0x03522ee4), XdB(0x03896ed0), XdB(0x03c445e2), XdB(0x0402efd6), XdB(0x0445ac4b), XdB(0x048cbefc), XdB(0x04d87013), XdB(0x05290c67), XdB(0x057ee5ca), XdB(0x05da5364), XdB(0x063bb204), XdB(0x06a36485), XdB(0x0711d42b), XdB(0x0787710e), XdB(0x0804b299), XdB(0x088a17ef), XdB(0x0918287e), XdB(0x09af747c), XdB(0x0a50957e), XdB(0x0afc2f19), XdB(0x0bb2ef7f), XdB(0x0c759034), XdB(0x0d44d6ca), XdB(0x0e2195bc), XdB(0x0f0cad0d), XdB(0x10070b62), XdB(0x1111aeea), XdB(0x122da66c), XdB(0x135c120f), XdB(0x149e24d9), XdB(0x15f525b1), XdB(0x176270e3), XdB(0x18e7794b), XdB(0x1a85c9ae), XdB(0x1c3f06d1), XdB(0x1e14f07d), XdB(0x200963d7), XdB(0x221e5ccd), XdB(0x2455f870), XdB(0x26b2770b), XdB(0x29363e2b), XdB(0x2be3db5c), XdB(0x2ebe06b6), XdB(0x31c7a55b), XdB(0x3503ccd4), XdB(0x3875c5aa), XdB(0x3c210f44), XdB(0x4009632b), XdB(0x4432b8cf), XdB(0x48a149bc), XdB(0x4d59959e), XdB(0x52606733), XdB(0x57bad899), XdB(0x5d6e593a), XdB(0x6380b298), XdB(0x69f80e9a), XdB(0x70dafda8), XdB(0x78307d76), XdB(0x7fffffff), }; static void render_line(int n, int x0,int x1,int y0,int y1,ogg_int32_t *d){ int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int base=dy/adx; int sy=(dy<0?base-1:base+1); int x=x0; int y=y0; int err=0; if(n>x1)n=x1; ady-=abs(base*adx); if(x=adx){ err-=adx; y+=sy; }else{ y+=base; } d[x]= MULT31_SHIFT15(d[x],FLOOR_fromdB_LOOKUP[y]); } } static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; vorbis_info_floor1 *info=look->vi; codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; int i,j,k; codebook *books=ci->fullbooks; /* unpack wrapped/predicted values from stream */ if(oggpack_read(&vb->opb,1)==1){ int *fit_value=(int *)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value)); fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); /* partition by partition */ /* partition by partition */ for(i=0,j=2;ipartitions;i++){ int classv=info->partitionclass[i]; int cdim=info->class_dim[classv]; int csubbits=info->class_subs[classv]; int csub=1<class_book[classv],&vb->opb); if(cval==-1)goto eop; } for(k=0;kclass_subbook[classv][cval&(csub-1)]; cval>>=csubbits; if(book>=0){ if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1) goto eop; }else{ fit_value[j+k]=0; } } j+=cdim; } /* unwrap positive values and reconsitute via linear interpolation */ for(i=2;iposts;i++){ int predicted=render_point(info->postlist[look->loneighbor[i-2]], info->postlist[look->hineighbor[i-2]], fit_value[look->loneighbor[i-2]], fit_value[look->hineighbor[i-2]], info->postlist[i]); int hiroom=look->quant_q-predicted; int loroom=predicted; int room=(hiroom=room){ if(hiroom>loroom){ val = val-loroom; }else{ val = -1-(val-hiroom); } }else{ if(val&1){ val= -((val+1)>>1); }else{ val>>=1; } } fit_value[i]=val+predicted; fit_value[look->loneighbor[i-2]]&=0x7fff; fit_value[look->hineighbor[i-2]]&=0x7fff; }else{ fit_value[i]=predicted|0x8000; } } return(fit_value); } eop: return(NULL); } static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo, ogg_int32_t *out){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; vorbis_info_floor1 *info=look->vi; codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; int n=ci->blocksizes[vb->W]/2; int j; if(memo){ /* render the lines */ int *fit_value=(int *)memo; int hx=0; int lx=0; int ly=fit_value[0]*info->mult; for(j=1;jposts;j++){ int current=look->forward_index[j]; int hy=fit_value[current]&0x7fff; if(hy==fit_value[current]){ hy*=info->mult; hx=info->postlist[current]; render_line(n,lx,hx,ly,hy,out); lx=hx; ly=hy; } } for(j=hx;j #include #include "ogg.h" #include "misc.h" /* A complete description of Ogg framing exists in docs/framing.html */ /* basic, centralized Ogg memory management based on linked lists of references to refcounted memory buffers. References and buffers are both recycled. Buffers are passed around and consumed in reference form. */ static ogg_buffer_state *ogg_buffer_create(void){ ogg_buffer_state *bs=_ogg_calloc(1,sizeof(*bs)); return bs; } /* destruction is 'lazy'; there may be memory references outstanding, and yanking the buffer state out from underneath would be antisocial. Dealloc what is currently unused and have _release_one watch for the stragglers to come in. When they do, finish destruction. */ /* call the helper while holding lock */ static void _ogg_buffer_destroy(ogg_buffer_state *bs){ ogg_buffer *bt; ogg_reference *rt; if(bs->shutdown){ bt=bs->unused_buffers; rt=bs->unused_references; while(bt){ ogg_buffer *b=bt; bt=b->ptr.next; if(b->data)_ogg_free(b->data); _ogg_free(b); } bs->unused_buffers=0; while(rt){ ogg_reference *r=rt; rt=r->next; _ogg_free(r); } bs->unused_references=0; if(!bs->outstanding) _ogg_free(bs); } } static void ogg_buffer_destroy(ogg_buffer_state *bs){ bs->shutdown=1; _ogg_buffer_destroy(bs); } static ogg_buffer *_fetch_buffer(ogg_buffer_state *bs,long bytes){ ogg_buffer *ob; bs->outstanding++; /* do we have an unused buffer sitting in the pool? */ if(bs->unused_buffers){ ob=bs->unused_buffers; bs->unused_buffers=ob->ptr.next; /* if the unused buffer is too small, grow it */ if(ob->sizedata=_ogg_realloc(ob->data,bytes); ob->size=bytes; } }else{ /* allocate a new buffer */ ob=_ogg_malloc(sizeof(*ob)); ob->data=_ogg_malloc(bytes<16?16:bytes); ob->size=bytes; } ob->refcount=1; ob->ptr.owner=bs; return ob; } static ogg_reference *_fetch_ref(ogg_buffer_state *bs){ ogg_reference *or; bs->outstanding++; /* do we have an unused reference sitting in the pool? */ if(bs->unused_references){ or=bs->unused_references; bs->unused_references=or->next; }else{ /* allocate a new reference */ or=_ogg_malloc(sizeof(*or)); } or->begin=0; or->length=0; or->next=0; return or; } /* fetch a reference pointing to a fresh, initially continguous buffer of at least [bytes] length */ static ogg_reference *ogg_buffer_alloc(ogg_buffer_state *bs,long bytes){ ogg_buffer *ob=_fetch_buffer(bs,bytes); ogg_reference *or=_fetch_ref(bs); or->buffer=ob; return or; } /* enlarge the data buffer in the current link */ static void ogg_buffer_realloc(ogg_reference *or,long bytes){ ogg_buffer *ob=or->buffer; /* if the unused buffer is too small, grow it */ if(ob->sizedata=_ogg_realloc(ob->data,bytes); ob->size=bytes; } } static void _ogg_buffer_mark_one(ogg_reference *or){ or->buffer->refcount++; } /* increase the refcount of the buffers to which the reference points */ static void ogg_buffer_mark(ogg_reference *or){ while(or){ _ogg_buffer_mark_one(or); or=or->next; } } /* duplicate a reference (pointing to the same actual buffer memory) and increment buffer refcount. If the desired segment begins out of range, NULL is returned; if the desired segment is simply zero length, a zero length ref is returned. Partial range overlap returns the overlap of the ranges */ static ogg_reference *ogg_buffer_sub(ogg_reference *or,long begin,long length){ ogg_reference *ret=0,*head=0; /* walk past any preceeding fragments we don't want */ while(or && begin>=or->length){ begin-=or->length; or=or->next; } /* duplicate the reference chain; increment refcounts */ while(or && length){ ogg_reference *temp=_fetch_ref(or->buffer->ptr.owner); if(head) head->next=temp; else ret=temp; head=temp; head->buffer=or->buffer; head->begin=or->begin+begin; head->length=length; if(head->length>or->length-begin) head->length=or->length-begin; begin=0; length-=head->length; or=or->next; } ogg_buffer_mark(ret); return ret; } ogg_reference *ogg_buffer_dup(ogg_reference *or){ ogg_reference *ret=0,*head=0; /* duplicate the reference chain; increment refcounts */ while(or){ ogg_reference *temp=_fetch_ref(or->buffer->ptr.owner); if(head) head->next=temp; else ret=temp; head=temp; head->buffer=or->buffer; head->begin=or->begin; head->length=or->length; or=or->next; } ogg_buffer_mark(ret); return ret; } /* split a reference into two references; 'return' is a reference to the buffer preceeding pos and 'head'/'tail' are the buffer past the split. If pos is at or past the end of the passed in segment, 'head/tail' are NULL */ static ogg_reference *ogg_buffer_split(ogg_reference **tail, ogg_reference **head,long pos){ /* walk past any preceeding fragments to one of: a) the exact boundary that seps two fragments b) the fragment that needs split somewhere in the middle */ ogg_reference *ret=*tail; ogg_reference *or=*tail; while(or && pos>or->length){ pos-=or->length; or=or->next; } if(!or || pos==0){ return 0; }else{ if(pos>=or->length){ /* exact split, or off the end? */ if(or->next){ /* a split */ *tail=or->next; or->next=0; }else{ /* off or at the end */ *tail=*head=0; } }else{ /* split within a fragment */ long lengthA=pos; long beginB=or->begin+pos; long lengthB=or->length-pos; /* make a new reference to tail the second piece */ *tail=_fetch_ref(or->buffer->ptr.owner); (*tail)->buffer=or->buffer; (*tail)->begin=beginB; (*tail)->length=lengthB; (*tail)->next=or->next; _ogg_buffer_mark_one(*tail); if(head && or==*head)*head=*tail; /* update the first piece */ or->next=0; or->length=lengthA; } } return ret; } static void ogg_buffer_release_one(ogg_reference *or){ ogg_buffer *ob=or->buffer; ogg_buffer_state *bs=ob->ptr.owner; ob->refcount--; if(ob->refcount==0){ bs->outstanding--; /* for the returned buffer */ ob->ptr.next=bs->unused_buffers; bs->unused_buffers=ob; } bs->outstanding--; /* for the returned reference */ or->next=bs->unused_references; bs->unused_references=or; _ogg_buffer_destroy(bs); /* lazy cleanup (if needed) */ } /* release the references, decrease the refcounts of buffers to which they point, release any buffers with a refcount that drops to zero */ static void ogg_buffer_release(ogg_reference *or){ while(or){ ogg_reference *next=or->next; ogg_buffer_release_one(or); or=next; } } static ogg_reference *ogg_buffer_pretruncate(ogg_reference *or,long pos){ /* release preceeding fragments we don't want */ while(or && pos>=or->length){ ogg_reference *next=or->next; pos-=or->length; ogg_buffer_release_one(or); or=next; } if (or) { or->begin+=pos; or->length-=pos; } return or; } static ogg_reference *ogg_buffer_walk(ogg_reference *or){ if(!or)return NULL; while(or->next){ or=or->next; } return(or); } /* *head is appended to the front end (head) of *tail; both continue to be valid pointers, with *tail at the tail and *head at the head */ static ogg_reference *ogg_buffer_cat(ogg_reference *tail, ogg_reference *head){ if(!tail)return head; while(tail->next){ tail=tail->next; } tail->next=head; return ogg_buffer_walk(head); } static void _positionB(oggbyte_buffer *b,int pos){ if(pospos){ /* start at beginning, scan forward */ b->ref=b->baseref; b->pos=0; b->end=b->pos+b->ref->length; b->ptr=b->ref->buffer->data+b->ref->begin; } } static void _positionF(oggbyte_buffer *b,int pos){ /* scan forward for position */ while(pos>=b->end){ /* just seek forward */ b->pos+=b->ref->length; b->ref=b->ref->next; b->end=b->ref->length+b->pos; b->ptr=b->ref->buffer->data+b->ref->begin; } } static int oggbyte_init(oggbyte_buffer *b,ogg_reference *or){ memset(b,0,sizeof(*b)); if(or){ b->ref=b->baseref=or; b->pos=0; b->end=b->ref->length; b->ptr=b->ref->buffer->data+b->ref->begin; return 0; }else return -1; } static void oggbyte_set4(oggbyte_buffer *b,ogg_uint32_t val,int pos){ int i; _positionB(b,pos); for(i=0;i<4;i++){ _positionF(b,pos); b->ptr[pos-b->pos]=val; val>>=8; ++pos; } } static unsigned char oggbyte_read1(oggbyte_buffer *b,int pos){ _positionB(b,pos); _positionF(b,pos); return b->ptr[pos-b->pos]; } static ogg_uint32_t oggbyte_read4(oggbyte_buffer *b,int pos){ ogg_uint32_t ret; _positionB(b,pos); _positionF(b,pos); ret=b->ptr[pos-b->pos]; _positionF(b,++pos); ret|=b->ptr[pos-b->pos]<<8; _positionF(b,++pos); ret|=b->ptr[pos-b->pos]<<16; _positionF(b,++pos); ret|=b->ptr[pos-b->pos]<<24; return ret; } static ogg_int64_t oggbyte_read8(oggbyte_buffer *b,int pos){ ogg_int64_t ret; unsigned char t[7]; int i; _positionB(b,pos); for(i=0;i<7;i++){ _positionF(b,pos); t[i]=b->ptr[pos++ -b->pos]; } _positionF(b,pos); ret=b->ptr[pos-b->pos]; for(i=6;i>=0;--i) ret= ret<<8 | t[i]; return ret; } /* Now we get to the actual framing code */ int ogg_page_version(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read1(&ob,4); } int ogg_page_continued(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read1(&ob,5)&0x01; } int ogg_page_bos(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read1(&ob,5)&0x02; } int ogg_page_eos(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read1(&ob,5)&0x04; } ogg_int64_t ogg_page_granulepos(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read8(&ob,6); } ogg_uint32_t ogg_page_serialno(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read4(&ob,14); } ogg_uint32_t ogg_page_pageno(ogg_page *og){ oggbyte_buffer ob; oggbyte_init(&ob,og->header); return oggbyte_read4(&ob,18); } /* returns the number of packets that are completed on this page (if the leading packet is begun on a previous page, but ends on this page, it's counted */ /* NOTE: If a page consists of a packet begun on a previous page, and a new packet begun (but not completed) on this page, the return will be: ogg_page_packets(page) ==1, ogg_page_continued(page) !=0 If a page happens to be a single packet that was begun on a previous page, and spans to the next page (in the case of a three or more page packet), the return will be: ogg_page_packets(page) ==0, ogg_page_continued(page) !=0 */ int ogg_page_packets(ogg_page *og){ int i; int n; int count=0; oggbyte_buffer ob; oggbyte_init(&ob,og->header); n=oggbyte_read1(&ob,26); for(i=0;ibufferpool=ogg_buffer_create(); return oy; } int ogg_sync_destroy(ogg_sync_state *oy){ if(oy){ ogg_sync_reset(oy); ogg_buffer_destroy(oy->bufferpool); memset(oy,0,sizeof(*oy)); _ogg_free(oy); } return OGG_SUCCESS; } unsigned char *ogg_sync_bufferin(ogg_sync_state *oy, long bytes){ /* [allocate and] expose a buffer for data submission. If there is no head fragment allocate one and expose it else if the current head fragment has sufficient unused space expose it else if the current head fragment is unused resize and expose it else allocate new fragment and expose it */ /* base case; fifo uninitialized */ if(!oy->fifo_head){ oy->fifo_head=oy->fifo_tail=ogg_buffer_alloc(oy->bufferpool,bytes); return oy->fifo_head->buffer->data; } /* space left in current fragment case */ if(oy->fifo_head->buffer->size- oy->fifo_head->length- oy->fifo_head->begin >= bytes) return oy->fifo_head->buffer->data+ oy->fifo_head->length+oy->fifo_head->begin; /* current fragment is unused, but too small */ if(!oy->fifo_head->length){ ogg_buffer_realloc(oy->fifo_head,bytes); return oy->fifo_head->buffer->data+oy->fifo_head->begin; } /* current fragment used/full; get new fragment */ { ogg_reference *new=ogg_buffer_alloc(oy->bufferpool,bytes); oy->fifo_head->next=new; oy->fifo_head=new; } return oy->fifo_head->buffer->data; } int ogg_sync_wrote(ogg_sync_state *oy, long bytes){ if(!oy->fifo_head)return OGG_EINVAL; if(oy->fifo_head->buffer->size-oy->fifo_head->length-oy->fifo_head->begin < bytes)return OGG_EINVAL; oy->fifo_head->length+=bytes; oy->fifo_fill+=bytes; return OGG_SUCCESS; } static ogg_uint32_t _checksum(ogg_reference *or, int bytes){ ogg_uint32_t crc_reg=0; int j,post; while(or){ unsigned char *data=or->buffer->data+or->begin; post=(byteslength?bytes:or->length); for(j=0;j> 24)&0xff)^data[j]]; bytes-=j; or=or->next; } return crc_reg; } /* sync the stream. This is meant to be useful for finding page boundaries. return values for this: -n) skipped n bytes 0) page not ready; more data (no bytes skipped) n) page synced at current location; page length n bytes */ long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){ oggbyte_buffer page; long bytes,ret=0; ogg_page_release(og); bytes=oy->fifo_fill; oggbyte_init(&page,oy->fifo_tail); if(oy->headerbytes==0){ if(bytes<27)goto sync_out; /* not enough for even a minimal header */ /* verify capture pattern */ if(oggbyte_read1(&page,0)!=(int)'O' || oggbyte_read1(&page,1)!=(int)'g' || oggbyte_read1(&page,2)!=(int)'g' || oggbyte_read1(&page,3)!=(int)'S' ) goto sync_fail; oy->headerbytes=oggbyte_read1(&page,26)+27; } if(bytesheaderbytes)goto sync_out; /* not enough for header + seg table */ if(oy->bodybytes==0){ int i; /* count up body length in the segment table */ for(i=0;iheaderbytes-27;i++) oy->bodybytes+=oggbyte_read1(&page,27+i); } if(oy->bodybytes+oy->headerbytes>bytes)goto sync_out; /* we have what appears to be a complete page; last test: verify checksum */ { ogg_uint32_t chksum=oggbyte_read4(&page,22); oggbyte_set4(&page,0,22); /* Compare checksums; memory continues to be common access */ if(chksum!=_checksum(oy->fifo_tail,oy->bodybytes+oy->headerbytes)){ /* D'oh. Mismatch! Corrupt page (or miscapture and not a page at all). replace the computed checksum with the one actually read in; remember all the memory is common access */ oggbyte_set4(&page,chksum,22); goto sync_fail; } oggbyte_set4(&page,chksum,22); } /* We have a page. Set up page return. */ if(og){ /* set up page output */ og->header=ogg_buffer_split(&oy->fifo_tail,&oy->fifo_head,oy->headerbytes); og->header_len=oy->headerbytes; og->body=ogg_buffer_split(&oy->fifo_tail,&oy->fifo_head,oy->bodybytes); og->body_len=oy->bodybytes; }else{ /* simply advance */ oy->fifo_tail= ogg_buffer_pretruncate(oy->fifo_tail,oy->headerbytes+oy->bodybytes); if(!oy->fifo_tail)oy->fifo_head=0; } ret=oy->headerbytes+oy->bodybytes; oy->unsynced=0; oy->headerbytes=0; oy->bodybytes=0; oy->fifo_fill-=ret; return ret; sync_fail: oy->headerbytes=0; oy->bodybytes=0; oy->fifo_tail=ogg_buffer_pretruncate(oy->fifo_tail,1); ret--; /* search forward through fragments for possible capture */ while(oy->fifo_tail){ /* invariant: fifo_cursor points to a position in fifo_tail */ unsigned char *now=oy->fifo_tail->buffer->data+oy->fifo_tail->begin; unsigned char *next=memchr(now, 'O', oy->fifo_tail->length); if(next){ /* possible capture in this segment */ long bytes=next-now; oy->fifo_tail=ogg_buffer_pretruncate(oy->fifo_tail,bytes); ret-=bytes; break; }else{ /* no capture. advance to next segment */ long bytes=oy->fifo_tail->length; ret-=bytes; oy->fifo_tail=ogg_buffer_pretruncate(oy->fifo_tail,bytes); } } if(!oy->fifo_tail)oy->fifo_head=0; oy->fifo_fill+=ret; sync_out: return ret; } /* sync the stream and get a page. Keep trying until we find a page. Supress 'sync errors' after reporting the first. return values: OGG_HOLE) recapture (hole in data) 0) need more data 1) page returned Returns pointers into buffered data; invalidated by next call to _stream, _clear, _init, or _buffer */ int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){ /* all we need to do is verify a page at the head of the stream buffer. If it doesn't verify, we look for the next potential frame */ while(1){ long ret=ogg_sync_pageseek(oy,og); if(ret>0){ /* have a page */ return 1; } if(ret==0){ /* need more data */ return 0; } /* head did not start a synced page... skipped some bytes */ if(!oy->unsynced){ oy->unsynced=1; return OGG_HOLE; } /* loop. keep looking */ } } /* clear things to an initial state. Good to call, eg, before seeking */ int ogg_sync_reset(ogg_sync_state *oy){ ogg_buffer_release(oy->fifo_tail); oy->fifo_tail=0; oy->fifo_head=0; oy->fifo_fill=0; oy->unsynced=0; oy->headerbytes=0; oy->bodybytes=0; return OGG_SUCCESS; } ogg_stream_state *ogg_stream_create(int serialno){ ogg_stream_state *os=_ogg_calloc(1,sizeof(*os)); os->serialno=serialno; os->pageno=-1; return os; } int ogg_stream_destroy(ogg_stream_state *os){ if(os){ ogg_buffer_release(os->header_tail); ogg_buffer_release(os->body_tail); memset(os,0,sizeof(*os)); _ogg_free(os); } return OGG_SUCCESS; } #define FINFLAG 0x80000000UL #define FINMASK 0x7fffffffUL static void _next_lace(oggbyte_buffer *ob,ogg_stream_state *os){ /* search ahead one lace */ os->body_fill_next=0; while(os->laceptrlacing_fill){ int val=oggbyte_read1(ob,27+os->laceptr++); os->body_fill_next+=val; if(val<255){ os->body_fill_next|=FINFLAG; os->clearflag=1; break; } } } static void _span_queued_page(ogg_stream_state *os){ while( !(os->body_fill&FINFLAG) ){ if(!os->header_tail)break; /* first flush out preceeding page header (if any). Body is flushed as it's consumed, so that's not done here. */ if(os->lacing_fill>=0) os->header_tail=ogg_buffer_pretruncate(os->header_tail, os->lacing_fill+27); os->lacing_fill=0; os->laceptr=0; os->clearflag=0; if(!os->header_tail){ os->header_head=0; break; }else{ /* process/prepare next page, if any */ long pageno; oggbyte_buffer ob; ogg_page og; /* only for parsing header values */ og.header=os->header_tail; /* only for parsing header values */ pageno=ogg_page_pageno(&og); oggbyte_init(&ob,os->header_tail); os->lacing_fill=oggbyte_read1(&ob,26); /* are we in sequence? */ if(pageno!=os->pageno){ if(os->pageno==-1) /* indicates seek or reset */ os->holeflag=1; /* set for internal use */ else os->holeflag=2; /* set for external reporting */ os->body_tail=ogg_buffer_pretruncate(os->body_tail, os->body_fill); if(os->body_tail==0)os->body_head=0; os->body_fill=0; } if(ogg_page_continued(&og)){ if(os->body_fill==0){ /* continued packet, but no preceeding data to continue */ /* dump the first partial packet on the page */ _next_lace(&ob,os); os->body_tail= ogg_buffer_pretruncate(os->body_tail,os->body_fill_next&FINMASK); if(os->body_tail==0)os->body_head=0; /* set span flag */ if(!os->spanflag && !os->holeflag)os->spanflag=2; } }else{ if(os->body_fill>0){ /* preceeding data to continue, but not a continued page */ /* dump body_fill */ os->body_tail=ogg_buffer_pretruncate(os->body_tail, os->body_fill); if(os->body_tail==0)os->body_head=0; os->body_fill=0; /* set espan flag */ if(!os->spanflag && !os->holeflag)os->spanflag=2; } } if(os->laceptrlacing_fill){ os->granulepos=ogg_page_granulepos(&og); /* get current packet size & flag */ _next_lace(&ob,os); os->body_fill+=os->body_fill_next; /* addition handles the flag fine; unsigned on purpose */ /* ...and next packet size & flag */ _next_lace(&ob,os); } os->pageno=pageno+1; os->e_o_s=ogg_page_eos(&og); os->b_o_s=ogg_page_bos(&og); } } } /* add the incoming page to the stream state; we decompose the page into packet segments here as well. */ int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){ int serialno=ogg_page_serialno(og); int version=ogg_page_version(og); /* check the serial number */ if(serialno!=os->serialno){ ogg_page_release(og); return OGG_ESERIAL; } if(version>0){ ogg_page_release(og); return OGG_EVERSION; } /* add to fifos */ if(!os->body_tail){ os->body_tail=og->body; os->body_head=ogg_buffer_walk(og->body); }else{ os->body_head=ogg_buffer_cat(os->body_head,og->body); } if(!os->header_tail){ os->header_tail=og->header; os->header_head=ogg_buffer_walk(og->header); os->lacing_fill=-27; }else{ os->header_head=ogg_buffer_cat(os->header_head,og->header); } memset(og,0,sizeof(*og)); return OGG_SUCCESS; } int ogg_stream_reset(ogg_stream_state *os){ ogg_buffer_release(os->header_tail); ogg_buffer_release(os->body_tail); os->header_tail=os->header_head=0; os->body_tail=os->body_head=0; os->e_o_s=0; os->b_o_s=0; os->pageno=-1; os->packetno=0; os->granulepos=0; os->body_fill=0; os->lacing_fill=0; os->holeflag=0; os->spanflag=0; os->clearflag=0; os->laceptr=0; os->body_fill_next=0; return OGG_SUCCESS; } int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){ ogg_stream_reset(os); os->serialno=serialno; return OGG_SUCCESS; } static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){ ogg_packet_release(op); _span_queued_page(os); if(os->holeflag){ int temp=os->holeflag; if(os->clearflag) os->holeflag=0; else os->holeflag=1; if(temp==2){ os->packetno++; return OGG_HOLE; } } if(os->spanflag){ int temp=os->spanflag; if(os->clearflag) os->spanflag=0; else os->spanflag=1; if(temp==2){ os->packetno++; return OGG_SPAN; } } if(!(os->body_fill&FINFLAG)) return 0; if(!op && !adv)return 1; /* just using peek as an inexpensive way to ask if there's a whole packet waiting */ if(op){ op->b_o_s=os->b_o_s; if(os->e_o_s && os->body_fill_next==0) op->e_o_s=os->e_o_s; else op->e_o_s=0; if( (os->body_fill&FINFLAG) && !(os->body_fill_next&FINFLAG) ) op->granulepos=os->granulepos; else op->granulepos=-1; op->packetno=os->packetno; } if(adv){ oggbyte_buffer ob; oggbyte_init(&ob,os->header_tail); /* split the body contents off */ if(op){ op->packet=ogg_buffer_split(&os->body_tail,&os->body_head, os->body_fill&FINMASK); op->bytes=os->body_fill&FINMASK; }else{ os->body_tail=ogg_buffer_pretruncate(os->body_tail, os->body_fill&FINMASK); if(os->body_tail==0)os->body_head=0; } /* update lacing pointers */ os->body_fill=os->body_fill_next; _next_lace(&ob,os); }else{ if(op){ op->packet=ogg_buffer_sub(os->body_tail,0,os->body_fill&FINMASK); op->bytes=os->body_fill&FINMASK; } } if(adv){ os->packetno++; os->b_o_s=0; } return 1; } int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){ return _packetout(os,op,1); } int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){ return _packetout(os,op,0); } int ogg_packet_release(ogg_packet *op) { if(op){ ogg_buffer_release(op->packet); memset(op, 0, sizeof(*op)); } return OGG_SUCCESS; } int ogg_page_release(ogg_page *og) { if(og){ ogg_buffer_release(og->header); ogg_buffer_release(og->body); memset(og, 0, sizeof(*og)); } return OGG_SUCCESS; } void ogg_page_dup(ogg_page *dup,ogg_page *orig){ dup->header_len=orig->header_len; dup->body_len=orig->body_len; dup->header=ogg_buffer_dup(orig->header); dup->body=ogg_buffer_dup(orig->body); } bcmatroska2-5.3.101/mkclean/tremor/info.c000066400000000000000000000266121462133141200201160ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2003 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: maintain the info structure, info <-> header packets ********************************************************************/ /* general handling of the header and the vorbis_info structure (and substructures) */ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "codebook.h" #include "registry.h" #include "window.h" #include "misc.h" /* helpers */ static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){ while(bytes--){ *buf++=oggpack_read(o,8); } } void vorbis_comment_init(vorbis_comment *vc){ memset(vc,0,sizeof(*vc)); } /* This is more or less the same as strncasecmp - but that doesn't exist * everywhere, and this is a fairly trivial function, so we include it */ static int tagcompare(const char *s1, const char *s2, int n){ int c=0; while(c < n){ if(toupper(s1[c]) != toupper(s2[c])) return !0; c++; } return 0; } char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){ long i; int found = 0; int taglen = strlen(tag)+1; /* +1 for the = we append */ char *fulltag = (char *)alloca(taglen+ 1); strcpy(fulltag, tag); strcat(fulltag, "="); for(i=0;icomments;i++){ if(!tagcompare(vc->user_comments[i], fulltag, taglen)){ if(count == found) /* We return a pointer to the data, not a copy */ return vc->user_comments[i] + taglen; else found++; } } return NULL; /* didn't find anything */ } int vorbis_comment_query_count(vorbis_comment *vc, char *tag){ int i,count=0; int taglen = strlen(tag)+1; /* +1 for the = we append */ char *fulltag = (char *)alloca(taglen+1); strcpy(fulltag,tag); strcat(fulltag, "="); for(i=0;icomments;i++){ if(!tagcompare(vc->user_comments[i], fulltag, taglen)) count++; } return count; } void vorbis_comment_clear(vorbis_comment *vc){ if(vc){ long i; for(i=0;icomments;i++) if(vc->user_comments[i])_ogg_free(vc->user_comments[i]); if(vc->user_comments)_ogg_free(vc->user_comments); if(vc->comment_lengths)_ogg_free(vc->comment_lengths); if(vc->vendor)_ogg_free(vc->vendor); memset(vc,0,sizeof(*vc)); } } /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long. They may be equal, but short will never ge greater than long */ int vorbis_info_blocksize(vorbis_info *vi,int zo){ codec_setup_info *ci = (codec_setup_info *)vi->codec_setup; return ci ? ci->blocksizes[zo] : -1; } /* used by synthesis, which has a full, alloced vi */ void vorbis_info_init(vorbis_info *vi){ memset(vi,0,sizeof(*vi)); vi->codec_setup=(codec_setup_info *)_ogg_calloc(1,sizeof(codec_setup_info)); } void vorbis_info_clear(vorbis_info *vi){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; int i; if(ci){ for(i=0;imodes;i++) if(ci->mode_param[i])_ogg_free(ci->mode_param[i]); for(i=0;imaps;i++) /* unpack does the range checking */ if(ci->map_param[i]) _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]); for(i=0;ifloors;i++) /* unpack does the range checking */ if(ci->floor_param[i]) _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]); for(i=0;iresidues;i++) /* unpack does the range checking */ if(ci->residue_param[i]) _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]); for(i=0;ibooks;i++){ if(ci->book_param[i]){ /* knows if the book was not alloced */ vorbis_staticbook_destroy(ci->book_param[i]); } if(ci->fullbooks) vorbis_book_clear(ci->fullbooks+i); } if(ci->fullbooks) _ogg_free(ci->fullbooks); _ogg_free(ci); } memset(vi,0,sizeof(*vi)); } /* Header packing/unpacking ********************************************/ static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; if(!ci)return(OV_EFAULT); vi->version=oggpack_read(opb,32); if(vi->version!=0)return(OV_EVERSION); vi->channels=oggpack_read(opb,8); vi->rate=oggpack_read(opb,32); vi->bitrate_upper=oggpack_read(opb,32); vi->bitrate_nominal=oggpack_read(opb,32); vi->bitrate_lower=oggpack_read(opb,32); ci->blocksizes[0]=1<blocksizes[1]=1<rate<1)goto err_out; if(vi->channels<1)goto err_out; if(ci->blocksizes[0]<64)goto err_out; if(ci->blocksizes[1]blocksizes[0])goto err_out; if(ci->blocksizes[1]>8192)goto err_out; if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */ return(0); err_out: vorbis_info_clear(vi); return(OV_EBADHEADER); } static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){ int i; int vendorlen=oggpack_read(opb,32); if(vendorlen<0)goto err_out; vc->vendor=(char *)_ogg_calloc(vendorlen+1,1); _v_readstring(opb,vc->vendor,vendorlen); vc->comments=oggpack_read(opb,32); if(vc->comments<0)goto err_out; vc->user_comments=(char **)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments)); vc->comment_lengths=(int *)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths)); for(i=0;icomments;i++){ int len=oggpack_read(opb,32); if(len<0)goto err_out; vc->comment_lengths[i]=len; vc->user_comments[i]=(char *)_ogg_calloc(len+1,1); _v_readstring(opb,vc->user_comments[i],len); } if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */ return(0); err_out: vorbis_comment_clear(vc); return(OV_EBADHEADER); } /* all of the real encoding details are here. The modes, books, everything */ static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; int i; if(!ci)return(OV_EFAULT); /* codebooks */ ci->books=oggpack_read(opb,8)+1; /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/ for(i=0;ibooks;i++){ ci->book_param[i]=(static_codebook *)_ogg_calloc(1,sizeof(*ci->book_param[i])); if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out; } /* time backend settings */ ci->times=oggpack_read(opb,6)+1; /*ci->time_type=_ogg_malloc(ci->times*sizeof(*ci->time_type));*/ /*ci->time_param=_ogg_calloc(ci->times,sizeof(void *));*/ for(i=0;itimes;i++){ ci->time_type[i]=oggpack_read(opb,16); if(ci->time_type[i]<0 || ci->time_type[i]>=VI_TIMEB)goto err_out; /* ci->time_param[i]=_time_P[ci->time_type[i]]->unpack(vi,opb); Vorbis I has no time backend */ /*if(!ci->time_param[i])goto err_out;*/ } /* floor backend settings */ ci->floors=oggpack_read(opb,6)+1; /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/ /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/ for(i=0;ifloors;i++){ ci->floor_type[i]=oggpack_read(opb,16); if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out; ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb); if(!ci->floor_param[i])goto err_out; } /* residue backend settings */ ci->residues=oggpack_read(opb,6)+1; /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/ /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/ for(i=0;iresidues;i++){ ci->residue_type[i]=oggpack_read(opb,16); if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out; ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb); if(!ci->residue_param[i])goto err_out; } /* map backend settings */ ci->maps=oggpack_read(opb,6)+1; /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/ /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/ for(i=0;imaps;i++){ ci->map_type[i]=oggpack_read(opb,16); if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out; ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb); if(!ci->map_param[i])goto err_out; } /* mode settings */ ci->modes=oggpack_read(opb,6)+1; /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/ for(i=0;imodes;i++){ ci->mode_param[i]=(vorbis_info_mode *)_ogg_calloc(1,sizeof(*ci->mode_param[i])); ci->mode_param[i]->blockflag=oggpack_read(opb,1); ci->mode_param[i]->windowtype=oggpack_read(opb,16); ci->mode_param[i]->transformtype=oggpack_read(opb,16); ci->mode_param[i]->mapping=oggpack_read(opb,8); if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out; if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out; if(ci->mode_param[i]->mapping>=ci->maps)goto err_out; } if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */ return(0); err_out: vorbis_info_clear(vi); return(OV_EBADHEADER); } /* Is this packet a vorbis ID header? */ int vorbis_synthesis_idheader(ogg_packet *op){ oggpack_buffer opb; char buffer[6]; if(op){ oggpack_readinit(&opb,op->packet); if(!op->b_o_s) return(0); /* Not the initial packet */ if(oggpack_read(&opb,8) != 1) return 0; /* not an ID header */ memset(buffer,0,6); _v_readstring(&opb,buffer,6); if(memcmp(buffer,"vorbis",6)) return 0; /* not vorbis */ return 1; } return 0; } /* The Vorbis header is in three packets; the initial small packet in the first page that identifies basic parameters, a second packet with bitstream comments and a third packet that holds the codebook. */ int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){ oggpack_buffer opb; if(op){ oggpack_readinit(&opb,op->packet); /* Which of the three types of header is this? */ /* Also verify header-ness, vorbis */ { char buffer[6]; int packtype=oggpack_read(&opb,8); memset(buffer,0,6); _v_readstring(&opb,buffer,6); if(memcmp(buffer,"vorbis",6)){ /* not a vorbis header */ return(OV_ENOTVORBIS); } switch(packtype){ case 0x01: /* least significant *bit* is read first */ if(!op->b_o_s){ /* Not the initial packet */ return(OV_EBADHEADER); } if(vi->rate!=0){ /* previously initialized info header */ return(OV_EBADHEADER); } return(_vorbis_unpack_info(vi,&opb)); case 0x03: /* least significant *bit* is read first */ if(vi->rate==0){ /* um... we didn't get the initial header */ return(OV_EBADHEADER); } return(_vorbis_unpack_comment(vc,&opb)); case 0x05: /* least significant *bit* is read first */ if(vi->rate==0 || vc->vendor==NULL){ /* um... we didn;t get the initial header or comments yet */ return(OV_EBADHEADER); } return(_vorbis_unpack_books(vi,&opb)); default: /* Not a valid vorbis header type */ return(OV_EBADHEADER); break; } } } return(OV_EBADHEADER); } bcmatroska2-5.3.101/mkclean/tremor/iseeking_example.c000066400000000000000000000164721462133141200224770ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2009 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: illustrate seeking, and test it too last mod: $Id: iseeking_example.c 16037 2009-05-26 21:10:58Z xiphmont $ ********************************************************************/ #include #include #include #include #ifdef _WIN32 /* We need the following two to set stdin/stdout to binary */ # include # include #endif void _verify(OggVorbis_File *ov, ogg_int64_t val, ogg_int64_t pcmval, ogg_int64_t timeval, ogg_int64_t pcmlength, char *bigassbuffer){ int j; long bread; char buffer[4096]; int dummy; ogg_int64_t pos; /* verify the raw position, the pcm position and position decode */ if(val!=-1 && ov_raw_tell(ov)pcmval){ fprintf(stderr,"pcm position out of tolerance: requested %ld, got %ld\n", (long)pcmval,(long)ov_pcm_tell(ov)); exit(1); } if(timeval!=-1 && ov_time_tell(ov)>timeval){ fprintf(stderr,"time position out of tolerance: requested %ld, got %ld\n", (long)timeval,(long)ov_time_tell(ov)); exit(1); } pos=ov_pcm_tell(ov); if(pos<0 || pos>pcmlength){ fprintf(stderr,"pcm position out of bounds: got %ld\n",(long)pos); exit(1); } bread=ov_read(ov,buffer,4096,&dummy); for(j=0;jchannels!=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*4); /* w00t */ i=0; while(ival+1){ fprintf(stderr,"Declared position didn't perfectly match request: %ld != %ld\n", (long)val,(long)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; } bcmatroska2-5.3.101/mkclean/tremor/ivorbiscodec.h000066400000000000000000000153221462133141200216370ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: libvorbis codec headers ********************************************************************/ #ifndef _vorbis_codec_h_ #define _vorbis_codec_h_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "ogg.h" typedef struct vorbis_info{ int version; int channels; long rate; /* The below bitrate declarations are *hints*. Combinations of the three values carry the following implications: all three set to the same value: implies a fixed rate bitstream only nominal set: implies a VBR stream that averages the nominal bitrate. No hard upper/lower limit upper and or lower set: implies a VBR bitstream that obeys the bitrate limits. nominal may also be set to give a nominal rate. none set: the coder does not care to speculate. */ long bitrate_upper; long bitrate_nominal; long bitrate_lower; long bitrate_window; void *codec_setup; } vorbis_info; /* vorbis_dsp_state buffers the current vorbis audio analysis/synthesis state. The DSP state belongs to a specific logical bitstream ****************************************************/ typedef struct vorbis_dsp_state{ int analysisp; vorbis_info *vi; ogg_int32_t **pcm; ogg_int32_t **pcmret; int pcm_storage; int pcm_current; int pcm_returned; int preextrapolate; int eofflag; long lW; long W; long nW; long centerW; ogg_int64_t granulepos; ogg_int64_t sequence; void *backend_state; } vorbis_dsp_state; typedef struct vorbis_block{ /* necessary stream state for linking to the framing abstraction */ ogg_int32_t **pcm; /* this is a pointer into local storage */ oggpack_buffer opb; long lW; long W; long nW; int pcmend; int mode; int eofflag; ogg_int64_t granulepos; ogg_int64_t sequence; vorbis_dsp_state *vd; /* For read-only access of configuration */ /* local storage to avoid remallocing; it's up to the mapping to structure it */ void *localstore; long localtop; long localalloc; long totaluse; struct alloc_chain *reap; } vorbis_block; /* vorbis_block is a single block of data to be processed as part of the analysis/synthesis stream; it belongs to a specific logical bitstream, but is independant from other vorbis_blocks belonging to that logical bitstream. *************************************************/ struct alloc_chain{ void *ptr; struct alloc_chain *next; }; /* vorbis_info contains all the setup information specific to the specific compression/decompression mode in progress (eg, psychoacoustic settings, channel setup, options, codebook etc). vorbis_info and substructures are in backends.h. *********************************************************************/ /* the comments are not part of vorbis_info so that vorbis_info can be static storage */ typedef struct vorbis_comment{ /* unlimited user comment fields. libvorbis writes 'libvorbis' whatever vendor is set to in encode */ char **user_comments; int *comment_lengths; int comments; char *vendor; } vorbis_comment; /* libvorbis encodes in two abstraction layers; first we perform DSP and produce a packet (see docs/analysis.txt). The packet is then coded into a framed OggSquish bitstream by the second layer (see docs/framing.txt). Decode is the reverse process; we sync/frame the bitstream and extract individual packets, then decode the packet back into PCM audio. The extra framing/packetizing is used in streaming formats, such as files. Over the net (such as with UDP), the framing and packetization aren't necessary as they're provided by the transport and the streaming layer is not used */ /* Vorbis PRIMITIVES: general ***************************************/ extern void vorbis_info_init(vorbis_info *vi); extern void vorbis_info_clear(vorbis_info *vi); extern int vorbis_info_blocksize(vorbis_info *vi,int zo); extern void vorbis_comment_init(vorbis_comment *vc); extern void vorbis_comment_add(vorbis_comment *vc, char *comment); extern void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents); extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count); extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag); extern void vorbis_comment_clear(vorbis_comment *vc); extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb); extern int vorbis_block_clear(vorbis_block *vb); extern void vorbis_dsp_clear(vorbis_dsp_state *v); /* Vorbis PRIMITIVES: synthesis layer *******************************/ extern int vorbis_synthesis_idheader(ogg_packet *op); extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc, ogg_packet *op); extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi); extern int vorbis_synthesis_restart(vorbis_dsp_state *v); extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op); extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op); extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb); extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,ogg_int32_t ***pcm); extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples); extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op); /* Vorbis ERRORS and return codes ***********************************/ #define OV_FALSE -1 #define OV_EOF -2 #define OV_HOLE -3 #define OV_EREAD -128 #define OV_EFAULT -129 #define OV_EIMPL -130 #define OV_EINVAL -131 #define OV_ENOTVORBIS -132 #define OV_EBADHEADER -133 #define OV_EVERSION -134 #define OV_ENOTAUDIO -135 #define OV_EBADPACKET -136 #define OV_EBADLINK -137 #define OV_ENOSEEK -138 #ifdef __cplusplus } #endif /* __cplusplus */ #endif bcmatroska2-5.3.101/mkclean/tremor/ivorbisfile.h000066400000000000000000000112241462133141200214760ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: stdio-based convenience library for opening/seeking/decoding ********************************************************************/ #ifndef _OV_FILE_H_ #define _OV_FILE_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include #include "ivorbiscodec.h" #define CHUNKSIZE 1024 /* The function prototypes for the callbacks are basically the same as for * the stdio functions fread, fseek, fclose, ftell. * The one difference is that the FILE * arguments have been replaced with * a void * - this is to be used as a pointer to whatever internal data these * functions might need. In the stdio case, it's just a FILE * cast to a void * * * If you use other functions, check the docs for these functions and return * the right values. For seek_func(), you *MUST* return -1 if the stream is * unseekable */ typedef struct { size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource); int (*seek_func) (void *datasource, ogg_int64_t offset, int whence); int (*close_func) (void *datasource); long (*tell_func) (void *datasource); } ov_callbacks; #define NOTOPEN 0 #define PARTOPEN 1 #define OPENED 2 #define STREAMSET 3 #define INITSET 4 typedef struct OggVorbis_File { void *datasource; /* Pointer to a FILE *, etc. */ int seekable; ogg_int64_t offset; ogg_int64_t end; ogg_sync_state *oy; /* If the FILE handle isn't seekable (eg, a pipe), only the current stream appears */ int links; ogg_int64_t *offsets; ogg_int64_t *dataoffsets; ogg_uint32_t *serialnos; ogg_int64_t *pcmlengths; vorbis_info *vi; vorbis_comment *vc; /* Decoding working state local storage */ ogg_int64_t pcm_offset; int ready_state; ogg_uint32_t current_serialno; int current_link; ogg_int64_t bittrack; ogg_int64_t samptrack; ogg_stream_state *os; /* take physical pages, weld into a logical stream of packets */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ ov_callbacks callbacks; } OggVorbis_File; extern int ov_clear(OggVorbis_File *vf); extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes); extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks); extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes); extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks); extern int ov_test_open(OggVorbis_File *vf); extern long ov_bitrate(OggVorbis_File *vf,int i); extern long ov_bitrate_instant(OggVorbis_File *vf); extern long ov_streams(OggVorbis_File *vf); extern long ov_seekable(OggVorbis_File *vf); extern long ov_serialnumber(OggVorbis_File *vf,int i); extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i); extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i); extern ogg_int64_t ov_time_total(OggVorbis_File *vf,int i); extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos); extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos); extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos); extern int ov_time_seek(OggVorbis_File *vf,ogg_int64_t pos); extern int ov_time_seek_page(OggVorbis_File *vf,ogg_int64_t pos); extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf); extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf); extern ogg_int64_t ov_time_tell(OggVorbis_File *vf); extern vorbis_info *ov_info(OggVorbis_File *vf,int link); extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link); extern long ov_read(OggVorbis_File *vf,char *buffer,int length, int *bitstream); #ifdef __cplusplus } #endif /* __cplusplus */ #endif bcmatroska2-5.3.101/mkclean/tremor/ivorbisfile_example.c000066400000000000000000000056041462133141200232110ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: simple example decoder using vorbisidec ********************************************************************/ /* Takes a vorbis bitstream from stdin and writes raw stereo PCM to stdout using vorbisfile. Using vorbisfile is much simpler than dealing with libvorbis. */ #include #include #include #include #ifdef _WIN32 /* We need the following two to set stdin/stdout to binary */ #include #include #endif char pcmout[4096]; /* take 4k out of the data segment, not the stack */ int main(){ OggVorbis_File vf; int eof=0; int current_section; #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */ /* Beware the evil ifdef. We avoid these where we can, but this one we cannot. Don't add any more, you'll probably go to hell if you do. */ _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); #endif if(ov_open(stdin, &vf, NULL, 0) < 0) { fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n"); exit(1); } /* Throw the comments plus a few lines about the bitstream we're decoding */ { char **ptr=ov_comment(&vf,-1)->user_comments; vorbis_info *vi=ov_info(&vf,-1); while(*ptr){ fprintf(stderr,"%s\n",*ptr); ++ptr; } fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi->channels,vi->rate); fprintf(stderr,"\nDecoded length: %ld samples\n", (long)ov_pcm_total(&vf,-1)); fprintf(stderr,"Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor); } while(!eof){ long ret=ov_read(&vf,pcmout,sizeof(pcmout),¤t_section); if (ret == 0) { /* EOF */ eof=1; } else if (ret < 0) { /* error in the stream. Not a problem, just reporting it in case we (the app) cares. In this case, we don't. */ } else { /* we don't bother dealing with sample rate changes, etc, but you'll have to*/ fwrite(pcmout,1,ret,stdout); } } /* cleanup */ ov_clear(&vf); fprintf(stderr,"Done.\n"); return(0); } bcmatroska2-5.3.101/mkclean/tremor/lsp_lookup.h000066400000000000000000000115771462133141200213630ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: lookup data ********************************************************************/ #ifndef _V_LOOKUP_DATA_H_ #define _V_LOOKUP_DATA_H_ #include "os_types.h" #define FROMdB_LOOKUP_SZ 35 #define FROMdB2_LOOKUP_SZ 32 #define FROMdB_SHIFT 5 #define FROMdB2_SHIFT 3 #define FROMdB2_MASK 31 static const ogg_int32_t FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={ 0x003fffff, 0x0028619b, 0x00197a96, 0x0010137a, 0x000a24b0, 0x00066666, 0x000409c3, 0x00028c42, 0x00019b8c, 0x000103ab, 0x0000a3d7, 0x00006760, 0x0000413a, 0x00002928, 0x000019f8, 0x00001062, 0x00000a56, 0x00000686, 0x0000041e, 0x00000299, 0x000001a3, 0x00000109, 0x000000a7, 0x00000069, 0x00000042, 0x0000002a, 0x0000001a, 0x00000011, 0x0000000b, 0x00000007, 0x00000004, 0x00000003, 0x00000002, 0x00000001, 0x00000001}; static const ogg_int32_t FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={ 0x000001fc, 0x000001f5, 0x000001ee, 0x000001e7, 0x000001e0, 0x000001d9, 0x000001d2, 0x000001cc, 0x000001c5, 0x000001bf, 0x000001b8, 0x000001b2, 0x000001ac, 0x000001a6, 0x000001a0, 0x0000019a, 0x00000194, 0x0000018e, 0x00000188, 0x00000183, 0x0000017d, 0x00000178, 0x00000172, 0x0000016d, 0x00000168, 0x00000163, 0x0000015e, 0x00000159, 0x00000154, 0x0000014f, 0x0000014a, 0x00000145, }; #define INVSQ_LOOKUP_I_SHIFT 10 #define INVSQ_LOOKUP_I_MASK 1023 static const long INVSQ_LOOKUP_I[64+1]={ 92682, 91966, 91267, 90583, 89915, 89261, 88621, 87995, 87381, 86781, 86192, 85616, 85051, 84497, 83953, 83420, 82897, 82384, 81880, 81385, 80899, 80422, 79953, 79492, 79039, 78594, 78156, 77726, 77302, 76885, 76475, 76072, 75674, 75283, 74898, 74519, 74146, 73778, 73415, 73058, 72706, 72359, 72016, 71679, 71347, 71019, 70695, 70376, 70061, 69750, 69444, 69141, 68842, 68548, 68256, 67969, 67685, 67405, 67128, 66855, 66585, 66318, 66054, 65794, 65536, }; static const long INVSQ_LOOKUP_IDel[64]={ 716, 699, 684, 668, 654, 640, 626, 614, 600, 589, 576, 565, 554, 544, 533, 523, 513, 504, 495, 486, 477, 469, 461, 453, 445, 438, 430, 424, 417, 410, 403, 398, 391, 385, 379, 373, 368, 363, 357, 352, 347, 343, 337, 332, 328, 324, 319, 315, 311, 306, 303, 299, 294, 292, 287, 284, 280, 277, 273, 270, 267, 264, 260, 258, }; #define COS_LOOKUP_I_SHIFT 9 #define COS_LOOKUP_I_MASK 511 #define COS_LOOKUP_I_SZ 128 static const ogg_int32_t COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={ 16384, 16379, 16364, 16340, 16305, 16261, 16207, 16143, 16069, 15986, 15893, 15791, 15679, 15557, 15426, 15286, 15137, 14978, 14811, 14635, 14449, 14256, 14053, 13842, 13623, 13395, 13160, 12916, 12665, 12406, 12140, 11866, 11585, 11297, 11003, 10702, 10394, 10080, 9760, 9434, 9102, 8765, 8423, 8076, 7723, 7366, 7005, 6639, 6270, 5897, 5520, 5139, 4756, 4370, 3981, 3590, 3196, 2801, 2404, 2006, 1606, 1205, 804, 402, 0, -401, -803, -1204, -1605, -2005, -2403, -2800, -3195, -3589, -3980, -4369, -4755, -5138, -5519, -5896, -6269, -6638, -7004, -7365, -7722, -8075, -8422, -8764, -9101, -9433, -9759, -10079, -10393, -10701, -11002, -11296, -11584, -11865, -12139, -12405, -12664, -12915, -13159, -13394, -13622, -13841, -14052, -14255, -14448, -14634, -14810, -14977, -15136, -15285, -15425, -15556, -15678, -15790, -15892, -15985, -16068, -16142, -16206, -16260, -16304, -16339, -16363, -16378, -16383, }; #endif bcmatroska2-5.3.101/mkclean/tremor/mapping0.c000066400000000000000000000221471462133141200206750ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: channel mapping 0 implementation ********************************************************************/ #include #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "mdct.h" #include "codec_internal.h" #include "codebook.h" #include "window.h" #include "registry.h" #include "misc.h" /* simplistic, wasteful way of doing this (unique lookup for each mode/submapping); there should be a central repository for identical lookups. That will require minor work, so I'm putting it off as low priority. Why a lookup for each backend in a given mode? Because the blocksize is set by the mode, and low backend lookups may require parameters from other areas of the mode/mapping */ typedef struct { vorbis_info_mode *mode; vorbis_info_mapping0 *map; vorbis_look_floor **floor_look; vorbis_look_residue **residue_look; vorbis_func_floor **floor_func; vorbis_func_residue **residue_func; int ch; long lastframe; /* if a different mode is called, we need to invalidate decay */ } vorbis_look_mapping0; static void mapping0_free_info(vorbis_info_mapping *i){ vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } static void mapping0_free_look(vorbis_look_mapping *look){ int i; vorbis_look_mapping0 *l=(vorbis_look_mapping0 *)look; if(l){ for(i=0;imap->submaps;i++){ l->floor_func[i]->free_look(l->floor_look[i]); l->residue_func[i]->free_look(l->residue_look[i]); } _ogg_free(l->floor_func); _ogg_free(l->residue_func); _ogg_free(l->floor_look); _ogg_free(l->residue_look); memset(l,0,sizeof(*l)); _ogg_free(l); } } static vorbis_look_mapping *mapping0_look(vorbis_dsp_state *vd,vorbis_info_mode *vm, vorbis_info_mapping *m){ int i; vorbis_info *vi=vd->vi; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; vorbis_look_mapping0 *look=(vorbis_look_mapping0 *)_ogg_calloc(1,sizeof(*look)); vorbis_info_mapping0 *info=look->map=(vorbis_info_mapping0 *)m; look->mode=vm; look->floor_look=(vorbis_look_floor **)_ogg_calloc(info->submaps,sizeof(*look->floor_look)); look->residue_look=(vorbis_look_residue **)_ogg_calloc(info->submaps,sizeof(*look->residue_look)); look->floor_func=(vorbis_func_floor **)_ogg_calloc(info->submaps,sizeof(*look->floor_func)); look->residue_func=(vorbis_func_residue **)_ogg_calloc(info->submaps,sizeof(*look->residue_func)); for(i=0;isubmaps;i++){ int floornum=info->floorsubmap[i]; int resnum=info->residuesubmap[i]; look->floor_func[i]=_floor_P[ci->floor_type[floornum]]; look->floor_look[i]=look->floor_func[i]-> look(vd,vm,ci->floor_param[floornum]); look->residue_func[i]=_residue_P[ci->residue_type[resnum]]; look->residue_look[i]=look->residue_func[i]-> look(vd,vm,ci->residue_param[resnum]); } look->ch=vi->channels; return(look); } static int ilog(unsigned int v){ int ret=0; if(v)--v; while(v){ ret++; v>>=1; } return(ret); } /* also responsible for range checking */ static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){ int i; vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)_ogg_calloc(1,sizeof(*info)); codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; memset(info,0,sizeof(*info)); if(oggpack_read(opb,1)) info->submaps=oggpack_read(opb,4)+1; else info->submaps=1; if(oggpack_read(opb,1)){ info->coupling_steps=oggpack_read(opb,8)+1; for(i=0;icoupling_steps;i++){ int testM=info->coupling_mag[i]=oggpack_read(opb,ilog(vi->channels)); int testA=info->coupling_ang[i]=oggpack_read(opb,ilog(vi->channels)); if(testM<0 || testA<0 || testM==testA || testM>=vi->channels || testA>=vi->channels) goto err_out; } } if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */ if(info->submaps>1){ for(i=0;ichannels;i++){ info->chmuxlist[i]=oggpack_read(opb,4); if(info->chmuxlist[i]>=info->submaps)goto err_out; } } for(i=0;isubmaps;i++){ int temp=oggpack_read(opb,8); if(temp>=ci->times)goto err_out; info->floorsubmap[i]=oggpack_read(opb,8); if(info->floorsubmap[i]>=ci->floors)goto err_out; info->residuesubmap[i]=oggpack_read(opb,8); if(info->residuesubmap[i]>=ci->residues)goto err_out; } return info; err_out: mapping0_free_info(info); return(NULL); } static int seq=0; static int mapping0_inverse(vorbis_block *vb,vorbis_look_mapping *l){ vorbis_dsp_state *vd=vb->vd; vorbis_info *vi=vd->vi; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; private_state *b=(private_state *)vd->backend_state; vorbis_look_mapping0 *look=(vorbis_look_mapping0 *)l; vorbis_info_mapping0 *info=look->map; int i,j; long n=vb->pcmend=ci->blocksizes[vb->W]; ogg_int32_t **pcmbundle=(ogg_int32_t **)alloca(sizeof(*pcmbundle)*vi->channels); int *zerobundle=(int *)alloca(sizeof(*zerobundle)*vi->channels); int *nonzero =(int *)alloca(sizeof(*nonzero)*vi->channels); void **floormemo=(void **)alloca(sizeof(*floormemo)*vi->channels); /* time domain information decode (note that applying the information would have to happen later; we'll probably add a function entry to the harness for that later */ /* NOT IMPLEMENTED */ /* recover the spectral envelope; store it in the PCM vector for now */ for(i=0;ichannels;i++){ int submap=info->chmuxlist[i]; floormemo[i]=look->floor_func[submap]-> inverse1(vb,look->floor_look[submap]); if(floormemo[i]) nonzero[i]=1; else nonzero[i]=0; memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2); } /* channel coupling can 'dirty' the nonzero listing */ for(i=0;icoupling_steps;i++){ if(nonzero[info->coupling_mag[i]] || nonzero[info->coupling_ang[i]]){ nonzero[info->coupling_mag[i]]=1; nonzero[info->coupling_ang[i]]=1; } } /* recover the residue into our working vectors */ for(i=0;isubmaps;i++){ int ch_in_bundle=0; for(j=0;jchannels;j++){ if(info->chmuxlist[j]==i){ if(nonzero[j]) zerobundle[ch_in_bundle]=1; else zerobundle[ch_in_bundle]=0; pcmbundle[ch_in_bundle++]=vb->pcm[j]; } } look->residue_func[i]->inverse(vb,look->residue_look[i], pcmbundle,zerobundle,ch_in_bundle); } //for(j=0;jchannels;j++) //_analysis_output("coupled",seq+j,vb->pcm[j],-8,n/2,0,0); /* channel coupling */ for(i=info->coupling_steps-1;i>=0;i--){ ogg_int32_t *pcmM=vb->pcm[info->coupling_mag[i]]; ogg_int32_t *pcmA=vb->pcm[info->coupling_ang[i]]; for(j=0;j0) if(ang>0){ pcmM[j]=mag; pcmA[j]=mag-ang; }else{ pcmA[j]=mag; pcmM[j]=mag+ang; } else if(ang>0){ pcmM[j]=mag; pcmA[j]=mag+ang; }else{ pcmA[j]=mag; pcmM[j]=mag-ang; } } } //for(j=0;jchannels;j++) //_analysis_output("residue",seq+j,vb->pcm[j],-8,n/2,0,0); /* compute and apply spectral envelope */ for(i=0;ichannels;i++){ ogg_int32_t *pcm=vb->pcm[i]; int submap=info->chmuxlist[i]; look->floor_func[submap]-> inverse2(vb,look->floor_look[submap],floormemo[i],pcm); } //for(j=0;jchannels;j++) //_analysis_output("mdct",seq+j,vb->pcm[j],-24,n/2,0,1); /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */ /* only MDCT right now.... */ for(i=0;ichannels;i++){ ogg_int32_t *pcm=vb->pcm[i]; mdct_backward(n,pcm,pcm); } //for(j=0;jchannels;j++) //_analysis_output("imdct",seq+j,vb->pcm[j],-24,n,0,0); /* window the data */ for(i=0;ichannels;i++){ ogg_int32_t *pcm=vb->pcm[i]; if(nonzero[i]) _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW); else for(j=0;jchannels;j++) //_analysis_output("window",seq+j,vb->pcm[j],-24,n,0,0); seq+=vi->channels; /* all done! */ return(0); } /* export hooks */ vorbis_func_mapping mapping0_exportbundle={ &mapping0_unpack, &mapping0_look, &mapping0_free_info, &mapping0_free_look, &mapping0_inverse }; bcmatroska2-5.3.101/mkclean/tremor/mdct.c000066400000000000000000000330651462133141200201120ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: normalized modified discrete cosine transform power of two length transform only [64 <= n ] last mod: $Id: mdct.c,v 1.9 2002/10/16 09:17:39 xiphmont Exp $ Original algorithm adapted long ago from _The use of multirate filter banks for coding of high quality digital audio_, by T. Sporer, K. Brandenburg and B. Edler, collection of the European Signal Processing Conference (EUSIPCO), Amsterdam, June 1992, Vol.1, pp 211-214 The below code implements an algorithm that no longer looks much like that presented in the paper, but the basic structure remains if you dig deep enough to see it. This module DOES NOT INCLUDE code to generate/apply the window function. Everybody has their own weird favorite including me... I happen to like the properties of y=sin(.5PI*sin^2(x)), but others may vehemently disagree. ********************************************************************/ #include "ivorbiscodec.h" #include "codebook.h" #include "misc.h" #include "mdct.h" #include "mdct_lookup.h" /* 8 point butterfly (in place) */ STIN void mdct_butterfly_8(DATA_TYPE *x){ REG_TYPE r0 = x[4] + x[0]; REG_TYPE r1 = x[4] - x[0]; REG_TYPE r2 = x[5] + x[1]; REG_TYPE r3 = x[5] - x[1]; REG_TYPE r4 = x[6] + x[2]; REG_TYPE r5 = x[6] - x[2]; REG_TYPE r6 = x[7] + x[3]; REG_TYPE r7 = x[7] - x[3]; x[0] = r5 + r3; x[1] = r7 - r1; x[2] = r5 - r3; x[3] = r7 + r1; x[4] = r4 - r0; x[5] = r6 - r2; x[6] = r4 + r0; x[7] = r6 + r2; MB(); } /* 16 point butterfly (in place, 4 register) */ STIN void mdct_butterfly_16(DATA_TYPE *x){ REG_TYPE r0, r1; r0 = x[ 0] - x[ 8]; x[ 8] += x[ 0]; r1 = x[ 1] - x[ 9]; x[ 9] += x[ 1]; x[ 0] = MULT31((r0 + r1) , cPI2_8); x[ 1] = MULT31((r1 - r0) , cPI2_8); MB(); r0 = x[10] - x[ 2]; x[10] += x[ 2]; r1 = x[ 3] - x[11]; x[11] += x[ 3]; x[ 2] = r1; x[ 3] = r0; MB(); r0 = x[12] - x[ 4]; x[12] += x[ 4]; r1 = x[13] - x[ 5]; x[13] += x[ 5]; x[ 4] = MULT31((r0 - r1) , cPI2_8); x[ 5] = MULT31((r0 + r1) , cPI2_8); MB(); r0 = x[14] - x[ 6]; x[14] += x[ 6]; r1 = x[15] - x[ 7]; x[15] += x[ 7]; x[ 6] = r0; x[ 7] = r1; MB(); mdct_butterfly_8(x); mdct_butterfly_8(x+8); } /* 32 point butterfly (in place, 4 register) */ STIN void mdct_butterfly_32(DATA_TYPE *x){ REG_TYPE r0, r1; r0 = x[30] - x[14]; x[30] += x[14]; r1 = x[31] - x[15]; x[31] += x[15]; x[14] = r0; x[15] = r1; MB(); r0 = x[28] - x[12]; x[28] += x[12]; r1 = x[29] - x[13]; x[29] += x[13]; XNPROD31( r0, r1, cPI1_8, cPI3_8, &x[12], &x[13] ); MB(); r0 = x[26] - x[10]; x[26] += x[10]; r1 = x[27] - x[11]; x[27] += x[11]; x[10] = MULT31((r0 - r1) , cPI2_8); x[11] = MULT31((r0 + r1) , cPI2_8); MB(); r0 = x[24] - x[ 8]; x[24] += x[ 8]; r1 = x[25] - x[ 9]; x[25] += x[ 9]; XNPROD31( r0, r1, cPI3_8, cPI1_8, &x[ 8], &x[ 9] ); MB(); r0 = x[22] - x[ 6]; x[22] += x[ 6]; r1 = x[ 7] - x[23]; x[23] += x[ 7]; x[ 6] = r1; x[ 7] = r0; MB(); r0 = x[ 4] - x[20]; x[20] += x[ 4]; r1 = x[ 5] - x[21]; x[21] += x[ 5]; XPROD31 ( r0, r1, cPI3_8, cPI1_8, &x[ 4], &x[ 5] ); MB(); r0 = x[ 2] - x[18]; x[18] += x[ 2]; r1 = x[ 3] - x[19]; x[19] += x[ 3]; x[ 2] = MULT31((r1 + r0) , cPI2_8); x[ 3] = MULT31((r1 - r0) , cPI2_8); MB(); r0 = x[ 0] - x[16]; x[16] += x[ 0]; r1 = x[ 1] - x[17]; x[17] += x[ 1]; XPROD31 ( r0, r1, cPI1_8, cPI3_8, &x[ 0], &x[ 1] ); MB(); mdct_butterfly_16(x); mdct_butterfly_16(x+16); } /* N/stage point generic N stage butterfly (in place, 2 register) */ STIN void mdct_butterfly_generic(DATA_TYPE *x,int points,int step){ LOOKUP_T *T = sincos_lookup0; DATA_TYPE *x1 = x + points - 8; DATA_TYPE *x2 = x + (points>>1) - 8; REG_TYPE r0; REG_TYPE r1; do{ r0 = x1[6] - x2[6]; x1[6] += x2[6]; r1 = x2[7] - x1[7]; x1[7] += x2[7]; XPROD31( r1, r0, T[0], T[1], &x2[6], &x2[7] ); T+=step; r0 = x1[4] - x2[4]; x1[4] += x2[4]; r1 = x2[5] - x1[5]; x1[5] += x2[5]; XPROD31( r1, r0, T[0], T[1], &x2[4], &x2[5] ); T+=step; r0 = x1[2] - x2[2]; x1[2] += x2[2]; r1 = x2[3] - x1[3]; x1[3] += x2[3]; XPROD31( r1, r0, T[0], T[1], &x2[2], &x2[3] ); T+=step; r0 = x1[0] - x2[0]; x1[0] += x2[0]; r1 = x2[1] - x1[1]; x1[1] += x2[1]; XPROD31( r1, r0, T[0], T[1], &x2[0], &x2[1] ); T+=step; x1-=8; x2-=8; }while(Tsincos_lookup0); do{ r0 = x2[6] - x1[6]; x1[6] += x2[6]; r1 = x2[7] - x1[7]; x1[7] += x2[7]; XPROD31( r0, r1, T[0], T[1], &x2[6], &x2[7] ); T+=step; r0 = x2[4] - x1[4]; x1[4] += x2[4]; r1 = x2[5] - x1[5]; x1[5] += x2[5]; XPROD31( r0, r1, T[0], T[1], &x2[4], &x2[5] ); T+=step; r0 = x2[2] - x1[2]; x1[2] += x2[2]; r1 = x2[3] - x1[3]; x1[3] += x2[3]; XPROD31( r0, r1, T[0], T[1], &x2[2], &x2[3] ); T+=step; r0 = x2[0] - x1[0]; x1[0] += x2[0]; r1 = x2[1] - x1[1]; x1[1] += x2[1]; XPROD31( r0, r1, T[0], T[1], &x2[0], &x2[1] ); T+=step; x1-=8; x2-=8; }while(Tsincos_lookup0); } STIN void mdct_butterflies(DATA_TYPE *x,int points,int shift){ int stages=8-shift; int i,j; for(i=0;--stages>0;i++){ for(j=0;j<(1<>i)*j,points>>i,4<<(i+shift)); } for(j=0;j>8]|(bitrev[(x&0x0f0)>>4]<<4)|(((int)bitrev[x&0x00f])<<8); } STIN void mdct_bitreverse(DATA_TYPE *x,int n,int step,int shift){ int bit = 0; DATA_TYPE *w0 = x; DATA_TYPE *w1 = x = w0+(n>>1); LOOKUP_T *T = (step>=4)?(sincos_lookup0+(step>>1)):sincos_lookup1; LOOKUP_T *Ttop = T+1024; DATA_TYPE r2; do{ DATA_TYPE r3 = bitrev12(bit++); DATA_TYPE *x0 = x + ((r3 ^ 0xfff)>>shift) -1; DATA_TYPE *x1 = x + (r3>>shift); REG_TYPE r0 = x0[0] + x1[0]; REG_TYPE r1 = x1[1] - x0[1]; XPROD32( r0, r1, T[1], T[0], &r2, &r3 ); T+=step; w1 -= 4; r0 = (x0[1] + x1[1])>>1; r1 = (x0[0] - x1[0])>>1; w0[0] = r0 + r2; w0[1] = r1 + r3; w1[2] = r0 - r2; w1[3] = r3 - r1; r3 = bitrev12(bit++); x0 = x + ((r3 ^ 0xfff)>>shift) -1; x1 = x + (r3>>shift); r0 = x0[0] + x1[0]; r1 = x1[1] - x0[1]; XPROD32( r0, r1, T[1], T[0], &r2, &r3 ); T+=step; r0 = (x0[1] + x1[1])>>1; r1 = (x0[0] - x1[0])>>1; w0[2] = r0 + r2; w0[3] = r1 + r3; w1[0] = r0 - r2; w1[1] = r3 - r1; w0 += 4; }while(T>shift) -1; DATA_TYPE *x1 = x + (r3>>shift); REG_TYPE r0 = x0[0] + x1[0]; REG_TYPE r1 = x1[1] - x0[1]; T-=step; XPROD32( r0, r1, T[0], T[1], &r2, &r3 ); w1 -= 4; r0 = (x0[1] + x1[1])>>1; r1 = (x0[0] - x1[0])>>1; w0[0] = r0 + r2; w0[1] = r1 + r3; w1[2] = r0 - r2; w1[3] = r3 - r1; r3 = bitrev12(bit++); x0 = x + ((r3 ^ 0xfff)>>shift) -1; x1 = x + (r3>>shift); r0 = x0[0] + x1[0]; r1 = x1[1] - x0[1]; T-=step; XPROD32( r0, r1, T[0], T[1], &r2, &r3 ); r0 = (x0[1] + x1[1])>>1; r1 = (x0[0] - x1[0])>>1; w0[2] = r0 + r2; w0[3] = r1 + r3; w1[0] = r0 - r2; w1[1] = r3 - r1; w0 += 4; }while(w0>1; int n4=n>>2; DATA_TYPE *iX; DATA_TYPE *oX; LOOKUP_T *T; LOOKUP_T *V; int shift; int step; for (shift=6;!(n&(1<=in+n4); do{ oX-=4; XPROD31( iX[4], iX[6], T[1], T[0], &oX[2], &oX[3] ); T-=step; XPROD31( iX[0], iX[2], T[1], T[0], &oX[0], &oX[1] ); T-=step; iX-=8; }while(iX>=in); iX = in+n2-8; oX = out+n2+n4; T = sincos_lookup0; do{ T+=step; XNPROD31( iX[6], iX[4], T[0], T[1], &oX[0], &oX[1] ); T+=step; XNPROD31( iX[2], iX[0], T[0], T[1], &oX[2], &oX[3] ); iX-=8; oX+=4; }while(iX>=in+n4); do{ T-=step; XNPROD31( iX[6], iX[4], T[1], T[0], &oX[0], &oX[1] ); T-=step; XNPROD31( iX[2], iX[0], T[1], T[0], &oX[2], &oX[3] ); iX-=8; oX+=4; }while(iX>=in); mdct_butterflies(out+n2,n2,shift); mdct_bitreverse(out,n,step,shift); /* rotate + window */ step>>=2; { DATA_TYPE *oX1=out+n2+n4; DATA_TYPE *oX2=out+n2+n4; DATA_TYPE *iX =out; switch(step) { default: { T=(step>=4)?(sincos_lookup0+(step>>1)):sincos_lookup1; do{ oX1-=4; XPROD31( iX[0], -iX[1], T[0], T[1], &oX1[3], &oX2[0] ); T+=step; XPROD31( iX[2], -iX[3], T[0], T[1], &oX1[2], &oX2[1] ); T+=step; XPROD31( iX[4], -iX[5], T[0], T[1], &oX1[1], &oX2[2] ); T+=step; XPROD31( iX[6], -iX[7], T[0], T[1], &oX1[0], &oX2[3] ); T+=step; oX2+=4; iX+=8; }while(iX>1; t1 = (*T++)>>1; do{ oX1-=4; t0 += (v0 = (*V++)>>1); t1 += (v1 = (*V++)>>1); XPROD31( iX[0], -iX[1], t0, t1, &oX1[3], &oX2[0] ); v0 += (t0 = (*T++)>>1); v1 += (t1 = (*T++)>>1); XPROD31( iX[2], -iX[3], v0, v1, &oX1[2], &oX2[1] ); t0 += (v0 = (*V++)>>1); t1 += (v1 = (*V++)>>1); XPROD31( iX[4], -iX[5], t0, t1, &oX1[1], &oX2[2] ); v0 += (t0 = (*T++)>>1); v1 += (t1 = (*T++)>>1); XPROD31( iX[6], -iX[7], v0, v1, &oX1[0], &oX2[3] ); oX2+=4; iX+=8; }while(iX>2); t1 += (q1 = (v1-t1)>>2); XPROD31( iX[0], -iX[1], t0, t1, &oX1[3], &oX2[0] ); t0 = v0-q0; t1 = v1-q1; XPROD31( iX[2], -iX[3], t0, t1, &oX1[2], &oX2[1] ); t0 = *T++; t1 = *T++; v0 += (q0 = (t0-v0)>>2); v1 += (q1 = (t1-v1)>>2); XPROD31( iX[4], -iX[5], v0, v1, &oX1[1], &oX2[2] ); v0 = t0-q0; v1 = t1-q1; XPROD31( iX[6], -iX[7], v0, v1, &oX1[0], &oX2[3] ); oX2+=4; iX+=8; }while(iXoX2); } } bcmatroska2-5.3.101/mkclean/tremor/mdct.h000066400000000000000000000026761462133141200201230ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: modified discrete cosine transform prototypes ********************************************************************/ #ifndef _OGG_mdct_H_ #define _OGG_mdct_H_ #include "ivorbiscodec.h" #include "misc.h" #define DATA_TYPE ogg_int32_t #define REG_TYPE register ogg_int32_t #ifdef _LOW_ACCURACY_ #define cPI3_8 (0x0062) #define cPI2_8 (0x00b5) #define cPI1_8 (0x00ed) #else #define cPI3_8 (0x30fbc54d) #define cPI2_8 (0x5a82799a) #define cPI1_8 (0x7641af3d) #endif extern void mdct_forward(int n, DATA_TYPE *in, DATA_TYPE *out); extern void mdct_backward(int n, DATA_TYPE *in, DATA_TYPE *out); #endif bcmatroska2-5.3.101/mkclean/tremor/mdct_lookup.h000066400000000000000000001003211462133141200214760ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: sin,cos lookup tables ********************************************************************/ #include "os_types.h" /* {sin(2*i*PI/4096), cos(2*i*PI/4096)}, with i = 0 to 512 */ static LOOKUP_T sincos_lookup0[1026] = { X(0x00000000), X(0x7fffffff), X(0x003243f5), X(0x7ffff621), X(0x006487e3), X(0x7fffd886), X(0x0096cbc1), X(0x7fffa72c), X(0x00c90f88), X(0x7fff6216), X(0x00fb5330), X(0x7fff0943), X(0x012d96b1), X(0x7ffe9cb2), X(0x015fda03), X(0x7ffe1c65), X(0x01921d20), X(0x7ffd885a), X(0x01c45ffe), X(0x7ffce093), X(0x01f6a297), X(0x7ffc250f), X(0x0228e4e2), X(0x7ffb55ce), X(0x025b26d7), X(0x7ffa72d1), X(0x028d6870), X(0x7ff97c18), X(0x02bfa9a4), X(0x7ff871a2), X(0x02f1ea6c), X(0x7ff75370), X(0x03242abf), X(0x7ff62182), X(0x03566a96), X(0x7ff4dbd9), X(0x0388a9ea), X(0x7ff38274), X(0x03bae8b2), X(0x7ff21553), X(0x03ed26e6), X(0x7ff09478), X(0x041f6480), X(0x7feeffe1), X(0x0451a177), X(0x7fed5791), X(0x0483ddc3), X(0x7feb9b85), X(0x04b6195d), X(0x7fe9cbc0), X(0x04e8543e), X(0x7fe7e841), X(0x051a8e5c), X(0x7fe5f108), X(0x054cc7b1), X(0x7fe3e616), X(0x057f0035), X(0x7fe1c76b), X(0x05b137df), X(0x7fdf9508), X(0x05e36ea9), X(0x7fdd4eec), X(0x0615a48b), X(0x7fdaf519), X(0x0647d97c), X(0x7fd8878e), X(0x067a0d76), X(0x7fd6064c), X(0x06ac406f), X(0x7fd37153), X(0x06de7262), X(0x7fd0c8a3), X(0x0710a345), X(0x7fce0c3e), X(0x0742d311), X(0x7fcb3c23), X(0x077501be), X(0x7fc85854), X(0x07a72f45), X(0x7fc560cf), X(0x07d95b9e), X(0x7fc25596), X(0x080b86c2), X(0x7fbf36aa), X(0x083db0a7), X(0x7fbc040a), X(0x086fd947), X(0x7fb8bdb8), X(0x08a2009a), X(0x7fb563b3), X(0x08d42699), X(0x7fb1f5fc), X(0x09064b3a), X(0x7fae7495), X(0x09386e78), X(0x7faadf7c), X(0x096a9049), X(0x7fa736b4), X(0x099cb0a7), X(0x7fa37a3c), X(0x09cecf89), X(0x7f9faa15), X(0x0a00ece8), X(0x7f9bc640), X(0x0a3308bd), X(0x7f97cebd), X(0x0a6522fe), X(0x7f93c38c), X(0x0a973ba5), X(0x7f8fa4b0), X(0x0ac952aa), X(0x7f8b7227), X(0x0afb6805), X(0x7f872bf3), X(0x0b2d7baf), X(0x7f82d214), X(0x0b5f8d9f), X(0x7f7e648c), X(0x0b919dcf), X(0x7f79e35a), X(0x0bc3ac35), X(0x7f754e80), X(0x0bf5b8cb), X(0x7f70a5fe), X(0x0c27c389), X(0x7f6be9d4), X(0x0c59cc68), X(0x7f671a05), X(0x0c8bd35e), X(0x7f62368f), X(0x0cbdd865), X(0x7f5d3f75), X(0x0cefdb76), X(0x7f5834b7), X(0x0d21dc87), X(0x7f531655), X(0x0d53db92), X(0x7f4de451), X(0x0d85d88f), X(0x7f489eaa), X(0x0db7d376), X(0x7f434563), X(0x0de9cc40), X(0x7f3dd87c), X(0x0e1bc2e4), X(0x7f3857f6), X(0x0e4db75b), X(0x7f32c3d1), X(0x0e7fa99e), X(0x7f2d1c0e), X(0x0eb199a4), X(0x7f2760af), X(0x0ee38766), X(0x7f2191b4), X(0x0f1572dc), X(0x7f1baf1e), X(0x0f475bff), X(0x7f15b8ee), X(0x0f7942c7), X(0x7f0faf25), X(0x0fab272b), X(0x7f0991c4), X(0x0fdd0926), X(0x7f0360cb), X(0x100ee8ad), X(0x7efd1c3c), X(0x1040c5bb), X(0x7ef6c418), X(0x1072a048), X(0x7ef05860), X(0x10a4784b), X(0x7ee9d914), X(0x10d64dbd), X(0x7ee34636), X(0x11082096), X(0x7edc9fc6), X(0x1139f0cf), X(0x7ed5e5c6), X(0x116bbe60), X(0x7ecf1837), X(0x119d8941), X(0x7ec8371a), X(0x11cf516a), X(0x7ec14270), X(0x120116d5), X(0x7eba3a39), X(0x1232d979), X(0x7eb31e78), X(0x1264994e), X(0x7eabef2c), X(0x1296564d), X(0x7ea4ac58), X(0x12c8106f), X(0x7e9d55fc), X(0x12f9c7aa), X(0x7e95ec1a), X(0x132b7bf9), X(0x7e8e6eb2), X(0x135d2d53), X(0x7e86ddc6), X(0x138edbb1), X(0x7e7f3957), X(0x13c0870a), X(0x7e778166), X(0x13f22f58), X(0x7e6fb5f4), X(0x1423d492), X(0x7e67d703), X(0x145576b1), X(0x7e5fe493), X(0x148715ae), X(0x7e57dea7), X(0x14b8b17f), X(0x7e4fc53e), X(0x14ea4a1f), X(0x7e47985b), X(0x151bdf86), X(0x7e3f57ff), X(0x154d71aa), X(0x7e37042a), X(0x157f0086), X(0x7e2e9cdf), X(0x15b08c12), X(0x7e26221f), X(0x15e21445), X(0x7e1d93ea), X(0x16139918), X(0x7e14f242), X(0x16451a83), X(0x7e0c3d29), X(0x1676987f), X(0x7e0374a0), X(0x16a81305), X(0x7dfa98a8), X(0x16d98a0c), X(0x7df1a942), X(0x170afd8d), X(0x7de8a670), X(0x173c6d80), X(0x7ddf9034), X(0x176dd9de), X(0x7dd6668f), X(0x179f429f), X(0x7dcd2981), X(0x17d0a7bc), X(0x7dc3d90d), X(0x1802092c), X(0x7dba7534), X(0x183366e9), X(0x7db0fdf8), X(0x1864c0ea), X(0x7da77359), X(0x18961728), X(0x7d9dd55a), X(0x18c7699b), X(0x7d9423fc), X(0x18f8b83c), X(0x7d8a5f40), X(0x192a0304), X(0x7d808728), X(0x195b49ea), X(0x7d769bb5), X(0x198c8ce7), X(0x7d6c9ce9), X(0x19bdcbf3), X(0x7d628ac6), X(0x19ef0707), X(0x7d58654d), X(0x1a203e1b), X(0x7d4e2c7f), X(0x1a517128), X(0x7d43e05e), X(0x1a82a026), X(0x7d3980ec), X(0x1ab3cb0d), X(0x7d2f0e2b), X(0x1ae4f1d6), X(0x7d24881b), X(0x1b161479), X(0x7d19eebf), X(0x1b4732ef), X(0x7d0f4218), X(0x1b784d30), X(0x7d048228), X(0x1ba96335), X(0x7cf9aef0), X(0x1bda74f6), X(0x7ceec873), X(0x1c0b826a), X(0x7ce3ceb2), X(0x1c3c8b8c), X(0x7cd8c1ae), X(0x1c6d9053), X(0x7ccda169), X(0x1c9e90b8), X(0x7cc26de5), X(0x1ccf8cb3), X(0x7cb72724), X(0x1d00843d), X(0x7cabcd28), X(0x1d31774d), X(0x7ca05ff1), X(0x1d6265dd), X(0x7c94df83), X(0x1d934fe5), X(0x7c894bde), X(0x1dc4355e), X(0x7c7da505), X(0x1df5163f), X(0x7c71eaf9), X(0x1e25f282), X(0x7c661dbc), X(0x1e56ca1e), X(0x7c5a3d50), X(0x1e879d0d), X(0x7c4e49b7), X(0x1eb86b46), X(0x7c4242f2), X(0x1ee934c3), X(0x7c362904), X(0x1f19f97b), X(0x7c29fbee), X(0x1f4ab968), X(0x7c1dbbb3), X(0x1f7b7481), X(0x7c116853), X(0x1fac2abf), X(0x7c0501d2), X(0x1fdcdc1b), X(0x7bf88830), X(0x200d888d), X(0x7bebfb70), X(0x203e300d), X(0x7bdf5b94), X(0x206ed295), X(0x7bd2a89e), X(0x209f701c), X(0x7bc5e290), X(0x20d0089c), X(0x7bb9096b), X(0x21009c0c), X(0x7bac1d31), X(0x21312a65), X(0x7b9f1de6), X(0x2161b3a0), X(0x7b920b89), X(0x219237b5), X(0x7b84e61f), X(0x21c2b69c), X(0x7b77ada8), X(0x21f3304f), X(0x7b6a6227), X(0x2223a4c5), X(0x7b5d039e), X(0x225413f8), X(0x7b4f920e), X(0x22847de0), X(0x7b420d7a), X(0x22b4e274), X(0x7b3475e5), X(0x22e541af), X(0x7b26cb4f), X(0x23159b88), X(0x7b190dbc), X(0x2345eff8), X(0x7b0b3d2c), X(0x23763ef7), X(0x7afd59a4), X(0x23a6887f), X(0x7aef6323), X(0x23d6cc87), X(0x7ae159ae), X(0x24070b08), X(0x7ad33d45), X(0x243743fa), X(0x7ac50dec), X(0x24677758), X(0x7ab6cba4), X(0x2497a517), X(0x7aa8766f), X(0x24c7cd33), X(0x7a9a0e50), X(0x24f7efa2), X(0x7a8b9348), X(0x25280c5e), X(0x7a7d055b), X(0x2558235f), X(0x7a6e648a), X(0x2588349d), X(0x7a5fb0d8), X(0x25b84012), X(0x7a50ea47), X(0x25e845b6), X(0x7a4210d8), X(0x26184581), X(0x7a332490), X(0x26483f6c), X(0x7a24256f), X(0x26783370), X(0x7a151378), X(0x26a82186), X(0x7a05eead), X(0x26d809a5), X(0x79f6b711), X(0x2707ebc7), X(0x79e76ca7), X(0x2737c7e3), X(0x79d80f6f), X(0x27679df4), X(0x79c89f6e), X(0x27976df1), X(0x79b91ca4), X(0x27c737d3), X(0x79a98715), X(0x27f6fb92), X(0x7999dec4), X(0x2826b928), X(0x798a23b1), X(0x2856708d), X(0x797a55e0), X(0x288621b9), X(0x796a7554), X(0x28b5cca5), X(0x795a820e), X(0x28e5714b), X(0x794a7c12), X(0x29150fa1), X(0x793a6361), X(0x2944a7a2), X(0x792a37fe), X(0x29743946), X(0x7919f9ec), X(0x29a3c485), X(0x7909a92d), X(0x29d34958), X(0x78f945c3), X(0x2a02c7b8), X(0x78e8cfb2), X(0x2a323f9e), X(0x78d846fb), X(0x2a61b101), X(0x78c7aba2), X(0x2a911bdc), X(0x78b6fda8), X(0x2ac08026), X(0x78a63d11), X(0x2aefddd8), X(0x789569df), X(0x2b1f34eb), X(0x78848414), X(0x2b4e8558), X(0x78738bb3), X(0x2b7dcf17), X(0x786280bf), X(0x2bad1221), X(0x7851633b), X(0x2bdc4e6f), X(0x78403329), X(0x2c0b83fa), X(0x782ef08b), X(0x2c3ab2b9), X(0x781d9b65), X(0x2c69daa6), X(0x780c33b8), X(0x2c98fbba), X(0x77fab989), X(0x2cc815ee), X(0x77e92cd9), X(0x2cf72939), X(0x77d78daa), X(0x2d263596), X(0x77c5dc01), X(0x2d553afc), X(0x77b417df), X(0x2d843964), X(0x77a24148), X(0x2db330c7), X(0x7790583e), X(0x2de2211e), X(0x777e5cc3), X(0x2e110a62), X(0x776c4edb), X(0x2e3fec8b), X(0x775a2e89), X(0x2e6ec792), X(0x7747fbce), X(0x2e9d9b70), X(0x7735b6af), X(0x2ecc681e), X(0x77235f2d), X(0x2efb2d95), X(0x7710f54c), X(0x2f29ebcc), X(0x76fe790e), X(0x2f58a2be), X(0x76ebea77), X(0x2f875262), X(0x76d94989), X(0x2fb5fab2), X(0x76c69647), X(0x2fe49ba7), X(0x76b3d0b4), X(0x30133539), X(0x76a0f8d2), X(0x3041c761), X(0x768e0ea6), X(0x30705217), X(0x767b1231), X(0x309ed556), X(0x76680376), X(0x30cd5115), X(0x7654e279), X(0x30fbc54d), X(0x7641af3d), X(0x312a31f8), X(0x762e69c4), X(0x3158970e), X(0x761b1211), X(0x3186f487), X(0x7607a828), X(0x31b54a5e), X(0x75f42c0b), X(0x31e39889), X(0x75e09dbd), X(0x3211df04), X(0x75ccfd42), X(0x32401dc6), X(0x75b94a9c), X(0x326e54c7), X(0x75a585cf), X(0x329c8402), X(0x7591aedd), X(0x32caab6f), X(0x757dc5ca), X(0x32f8cb07), X(0x7569ca99), X(0x3326e2c3), X(0x7555bd4c), X(0x3354f29b), X(0x75419de7), X(0x3382fa88), X(0x752d6c6c), X(0x33b0fa84), X(0x751928e0), X(0x33def287), X(0x7504d345), X(0x340ce28b), X(0x74f06b9e), X(0x343aca87), X(0x74dbf1ef), X(0x3468aa76), X(0x74c7663a), X(0x34968250), X(0x74b2c884), X(0x34c4520d), X(0x749e18cd), X(0x34f219a8), X(0x7489571c), X(0x351fd918), X(0x74748371), X(0x354d9057), X(0x745f9dd1), X(0x357b3f5d), X(0x744aa63f), X(0x35a8e625), X(0x74359cbd), X(0x35d684a6), X(0x74208150), X(0x36041ad9), X(0x740b53fb), X(0x3631a8b8), X(0x73f614c0), X(0x365f2e3b), X(0x73e0c3a3), X(0x368cab5c), X(0x73cb60a8), X(0x36ba2014), X(0x73b5ebd1), X(0x36e78c5b), X(0x73a06522), X(0x3714f02a), X(0x738acc9e), X(0x37424b7b), X(0x73752249), X(0x376f9e46), X(0x735f6626), X(0x379ce885), X(0x73499838), X(0x37ca2a30), X(0x7333b883), X(0x37f76341), X(0x731dc70a), X(0x382493b0), X(0x7307c3d0), X(0x3851bb77), X(0x72f1aed9), X(0x387eda8e), X(0x72db8828), X(0x38abf0ef), X(0x72c54fc1), X(0x38d8fe93), X(0x72af05a7), X(0x39060373), X(0x7298a9dd), X(0x3932ff87), X(0x72823c67), X(0x395ff2c9), X(0x726bbd48), X(0x398cdd32), X(0x72552c85), X(0x39b9bebc), X(0x723e8a20), X(0x39e6975e), X(0x7227d61c), X(0x3a136712), X(0x7211107e), X(0x3a402dd2), X(0x71fa3949), X(0x3a6ceb96), X(0x71e35080), X(0x3a99a057), X(0x71cc5626), X(0x3ac64c0f), X(0x71b54a41), X(0x3af2eeb7), X(0x719e2cd2), X(0x3b1f8848), X(0x7186fdde), X(0x3b4c18ba), X(0x716fbd68), X(0x3b78a007), X(0x71586b74), X(0x3ba51e29), X(0x71410805), X(0x3bd19318), X(0x7129931f), X(0x3bfdfecd), X(0x71120cc5), X(0x3c2a6142), X(0x70fa74fc), X(0x3c56ba70), X(0x70e2cbc6), X(0x3c830a50), X(0x70cb1128), X(0x3caf50da), X(0x70b34525), X(0x3cdb8e09), X(0x709b67c0), X(0x3d07c1d6), X(0x708378ff), X(0x3d33ec39), X(0x706b78e3), X(0x3d600d2c), X(0x70536771), X(0x3d8c24a8), X(0x703b44ad), X(0x3db832a6), X(0x7023109a), X(0x3de4371f), X(0x700acb3c), X(0x3e10320d), X(0x6ff27497), X(0x3e3c2369), X(0x6fda0cae), X(0x3e680b2c), X(0x6fc19385), X(0x3e93e950), X(0x6fa90921), X(0x3ebfbdcd), X(0x6f906d84), X(0x3eeb889c), X(0x6f77c0b3), X(0x3f1749b8), X(0x6f5f02b2), X(0x3f430119), X(0x6f463383), X(0x3f6eaeb8), X(0x6f2d532c), X(0x3f9a5290), X(0x6f1461b0), X(0x3fc5ec98), X(0x6efb5f12), X(0x3ff17cca), X(0x6ee24b57), X(0x401d0321), X(0x6ec92683), X(0x40487f94), X(0x6eaff099), X(0x4073f21d), X(0x6e96a99d), X(0x409f5ab6), X(0x6e7d5193), X(0x40cab958), X(0x6e63e87f), X(0x40f60dfb), X(0x6e4a6e66), X(0x4121589b), X(0x6e30e34a), X(0x414c992f), X(0x6e174730), X(0x4177cfb1), X(0x6dfd9a1c), X(0x41a2fc1a), X(0x6de3dc11), X(0x41ce1e65), X(0x6dca0d14), X(0x41f93689), X(0x6db02d29), X(0x42244481), X(0x6d963c54), X(0x424f4845), X(0x6d7c3a98), X(0x427a41d0), X(0x6d6227fa), X(0x42a5311b), X(0x6d48047e), X(0x42d0161e), X(0x6d2dd027), X(0x42faf0d4), X(0x6d138afb), X(0x4325c135), X(0x6cf934fc), X(0x4350873c), X(0x6cdece2f), X(0x437b42e1), X(0x6cc45698), X(0x43a5f41e), X(0x6ca9ce3b), X(0x43d09aed), X(0x6c8f351c), X(0x43fb3746), X(0x6c748b3f), X(0x4425c923), X(0x6c59d0a9), X(0x4450507e), X(0x6c3f055d), X(0x447acd50), X(0x6c242960), X(0x44a53f93), X(0x6c093cb6), X(0x44cfa740), X(0x6bee3f62), X(0x44fa0450), X(0x6bd3316a), X(0x452456bd), X(0x6bb812d1), X(0x454e9e80), X(0x6b9ce39b), X(0x4578db93), X(0x6b81a3cd), X(0x45a30df0), X(0x6b66536b), X(0x45cd358f), X(0x6b4af279), X(0x45f7526b), X(0x6b2f80fb), X(0x4621647d), X(0x6b13fef5), X(0x464b6bbe), X(0x6af86c6c), X(0x46756828), X(0x6adcc964), X(0x469f59b4), X(0x6ac115e2), X(0x46c9405c), X(0x6aa551e9), X(0x46f31c1a), X(0x6a897d7d), X(0x471cece7), X(0x6a6d98a4), X(0x4746b2bc), X(0x6a51a361), X(0x47706d93), X(0x6a359db9), X(0x479a1d67), X(0x6a1987b0), X(0x47c3c22f), X(0x69fd614a), X(0x47ed5be6), X(0x69e12a8c), X(0x4816ea86), X(0x69c4e37a), X(0x48406e08), X(0x69a88c19), X(0x4869e665), X(0x698c246c), X(0x48935397), X(0x696fac78), X(0x48bcb599), X(0x69532442), X(0x48e60c62), X(0x69368bce), X(0x490f57ee), X(0x6919e320), X(0x49389836), X(0x68fd2a3d), X(0x4961cd33), X(0x68e06129), X(0x498af6df), X(0x68c387e9), X(0x49b41533), X(0x68a69e81), X(0x49dd282a), X(0x6889a4f6), X(0x4a062fbd), X(0x686c9b4b), X(0x4a2f2be6), X(0x684f8186), X(0x4a581c9e), X(0x683257ab), X(0x4a8101de), X(0x68151dbe), X(0x4aa9dba2), X(0x67f7d3c5), X(0x4ad2a9e2), X(0x67da79c3), X(0x4afb6c98), X(0x67bd0fbd), X(0x4b2423be), X(0x679f95b7), X(0x4b4ccf4d), X(0x67820bb7), X(0x4b756f40), X(0x676471c0), X(0x4b9e0390), X(0x6746c7d8), X(0x4bc68c36), X(0x67290e02), X(0x4bef092d), X(0x670b4444), X(0x4c177a6e), X(0x66ed6aa1), X(0x4c3fdff4), X(0x66cf8120), X(0x4c6839b7), X(0x66b187c3), X(0x4c9087b1), X(0x66937e91), X(0x4cb8c9dd), X(0x6675658c), X(0x4ce10034), X(0x66573cbb), X(0x4d092ab0), X(0x66390422), X(0x4d31494b), X(0x661abbc5), X(0x4d595bfe), X(0x65fc63a9), X(0x4d8162c4), X(0x65ddfbd3), X(0x4da95d96), X(0x65bf8447), X(0x4dd14c6e), X(0x65a0fd0b), X(0x4df92f46), X(0x65826622), X(0x4e210617), X(0x6563bf92), X(0x4e48d0dd), X(0x6545095f), X(0x4e708f8f), X(0x6526438f), X(0x4e984229), X(0x65076e25), X(0x4ebfe8a5), X(0x64e88926), X(0x4ee782fb), X(0x64c99498), X(0x4f0f1126), X(0x64aa907f), X(0x4f369320), X(0x648b7ce0), X(0x4f5e08e3), X(0x646c59bf), X(0x4f857269), X(0x644d2722), X(0x4faccfab), X(0x642de50d), X(0x4fd420a4), X(0x640e9386), X(0x4ffb654d), X(0x63ef3290), X(0x50229da1), X(0x63cfc231), X(0x5049c999), X(0x63b0426d), X(0x5070e92f), X(0x6390b34a), X(0x5097fc5e), X(0x637114cc), X(0x50bf031f), X(0x635166f9), X(0x50e5fd6d), X(0x6331a9d4), X(0x510ceb40), X(0x6311dd64), X(0x5133cc94), X(0x62f201ac), X(0x515aa162), X(0x62d216b3), X(0x518169a5), X(0x62b21c7b), X(0x51a82555), X(0x6292130c), X(0x51ced46e), X(0x6271fa69), X(0x51f576ea), X(0x6251d298), X(0x521c0cc2), X(0x62319b9d), X(0x524295f0), X(0x6211557e), X(0x5269126e), X(0x61f1003f), X(0x528f8238), X(0x61d09be5), X(0x52b5e546), X(0x61b02876), X(0x52dc3b92), X(0x618fa5f7), X(0x53028518), X(0x616f146c), X(0x5328c1d0), X(0x614e73da), X(0x534ef1b5), X(0x612dc447), X(0x537514c2), X(0x610d05b7), X(0x539b2af0), X(0x60ec3830), X(0x53c13439), X(0x60cb5bb7), X(0x53e73097), X(0x60aa7050), X(0x540d2005), X(0x60897601), X(0x5433027d), X(0x60686ccf), X(0x5458d7f9), X(0x604754bf), X(0x547ea073), X(0x60262dd6), X(0x54a45be6), X(0x6004f819), X(0x54ca0a4b), X(0x5fe3b38d), X(0x54efab9c), X(0x5fc26038), X(0x55153fd4), X(0x5fa0fe1f), X(0x553ac6ee), X(0x5f7f8d46), X(0x556040e2), X(0x5f5e0db3), X(0x5585adad), X(0x5f3c7f6b), X(0x55ab0d46), X(0x5f1ae274), X(0x55d05faa), X(0x5ef936d1), X(0x55f5a4d2), X(0x5ed77c8a), X(0x561adcb9), X(0x5eb5b3a2), X(0x56400758), X(0x5e93dc1f), X(0x566524aa), X(0x5e71f606), X(0x568a34a9), X(0x5e50015d), X(0x56af3750), X(0x5e2dfe29), X(0x56d42c99), X(0x5e0bec6e), X(0x56f9147e), X(0x5de9cc33), X(0x571deefa), X(0x5dc79d7c), X(0x5742bc06), X(0x5da5604f), X(0x57677b9d), X(0x5d8314b1), X(0x578c2dba), X(0x5d60baa7), X(0x57b0d256), X(0x5d3e5237), X(0x57d5696d), X(0x5d1bdb65), X(0x57f9f2f8), X(0x5cf95638), X(0x581e6ef1), X(0x5cd6c2b5), X(0x5842dd54), X(0x5cb420e0), X(0x58673e1b), X(0x5c9170bf), X(0x588b9140), X(0x5c6eb258), X(0x58afd6bd), X(0x5c4be5b0), X(0x58d40e8c), X(0x5c290acc), X(0x58f838a9), X(0x5c0621b2), X(0x591c550e), X(0x5be32a67), X(0x594063b5), X(0x5bc024f0), X(0x59646498), X(0x5b9d1154), X(0x598857b2), X(0x5b79ef96), X(0x59ac3cfd), X(0x5b56bfbd), X(0x59d01475), X(0x5b3381ce), X(0x59f3de12), X(0x5b1035cf), X(0x5a1799d1), X(0x5aecdbc5), X(0x5a3b47ab), X(0x5ac973b5), X(0x5a5ee79a), X(0x5aa5fda5), X(0x5a82799a), X(0x5a82799a) }; /* {sin((2*i+1)*PI/4096), cos((2*i+1)*PI/4096)}, with i = 0 to 511 */ static LOOKUP_T sincos_lookup1[1024] = { X(0x001921fb), X(0x7ffffd88), X(0x004b65ee), X(0x7fffe9cb), X(0x007da9d4), X(0x7fffc251), X(0x00afeda8), X(0x7fff8719), X(0x00e23160), X(0x7fff3824), X(0x011474f6), X(0x7ffed572), X(0x0146b860), X(0x7ffe5f03), X(0x0178fb99), X(0x7ffdd4d7), X(0x01ab3e97), X(0x7ffd36ee), X(0x01dd8154), X(0x7ffc8549), X(0x020fc3c6), X(0x7ffbbfe6), X(0x024205e8), X(0x7ffae6c7), X(0x027447b0), X(0x7ff9f9ec), X(0x02a68917), X(0x7ff8f954), X(0x02d8ca16), X(0x7ff7e500), X(0x030b0aa4), X(0x7ff6bcf0), X(0x033d4abb), X(0x7ff58125), X(0x036f8a51), X(0x7ff4319d), X(0x03a1c960), X(0x7ff2ce5b), X(0x03d407df), X(0x7ff1575d), X(0x040645c7), X(0x7fefcca4), X(0x04388310), X(0x7fee2e30), X(0x046abfb3), X(0x7fec7c02), X(0x049cfba7), X(0x7feab61a), X(0x04cf36e5), X(0x7fe8dc78), X(0x05017165), X(0x7fe6ef1c), X(0x0533ab20), X(0x7fe4ee06), X(0x0565e40d), X(0x7fe2d938), X(0x05981c26), X(0x7fe0b0b1), X(0x05ca5361), X(0x7fde7471), X(0x05fc89b8), X(0x7fdc247a), X(0x062ebf22), X(0x7fd9c0ca), X(0x0660f398), X(0x7fd74964), X(0x06932713), X(0x7fd4be46), X(0x06c5598a), X(0x7fd21f72), X(0x06f78af6), X(0x7fcf6ce8), X(0x0729bb4e), X(0x7fcca6a7), X(0x075bea8c), X(0x7fc9ccb2), X(0x078e18a7), X(0x7fc6df08), X(0x07c04598), X(0x7fc3dda9), X(0x07f27157), X(0x7fc0c896), X(0x08249bdd), X(0x7fbd9fd0), X(0x0856c520), X(0x7fba6357), X(0x0888ed1b), X(0x7fb7132b), X(0x08bb13c5), X(0x7fb3af4e), X(0x08ed3916), X(0x7fb037bf), X(0x091f5d06), X(0x7facac7f), X(0x09517f8f), X(0x7fa90d8e), X(0x0983a0a7), X(0x7fa55aee), X(0x09b5c048), X(0x7fa1949e), X(0x09e7de6a), X(0x7f9dbaa0), X(0x0a19fb04), X(0x7f99ccf4), X(0x0a4c1610), X(0x7f95cb9a), X(0x0a7e2f85), X(0x7f91b694), X(0x0ab0475c), X(0x7f8d8de1), X(0x0ae25d8d), X(0x7f895182), X(0x0b147211), X(0x7f850179), X(0x0b4684df), X(0x7f809dc5), X(0x0b7895f0), X(0x7f7c2668), X(0x0baaa53b), X(0x7f779b62), X(0x0bdcb2bb), X(0x7f72fcb4), X(0x0c0ebe66), X(0x7f6e4a5e), X(0x0c40c835), X(0x7f698461), X(0x0c72d020), X(0x7f64aabf), X(0x0ca4d620), X(0x7f5fbd77), X(0x0cd6da2d), X(0x7f5abc8a), X(0x0d08dc3f), X(0x7f55a7fa), X(0x0d3adc4e), X(0x7f507fc7), X(0x0d6cda53), X(0x7f4b43f2), X(0x0d9ed646), X(0x7f45f47b), X(0x0dd0d01f), X(0x7f409164), X(0x0e02c7d7), X(0x7f3b1aad), X(0x0e34bd66), X(0x7f359057), X(0x0e66b0c3), X(0x7f2ff263), X(0x0e98a1e9), X(0x7f2a40d2), X(0x0eca90ce), X(0x7f247ba5), X(0x0efc7d6b), X(0x7f1ea2dc), X(0x0f2e67b8), X(0x7f18b679), X(0x0f604faf), X(0x7f12b67c), X(0x0f923546), X(0x7f0ca2e7), X(0x0fc41876), X(0x7f067bba), X(0x0ff5f938), X(0x7f0040f6), X(0x1027d784), X(0x7ef9f29d), X(0x1059b352), X(0x7ef390ae), X(0x108b8c9b), X(0x7eed1b2c), X(0x10bd6356), X(0x7ee69217), X(0x10ef377d), X(0x7edff570), X(0x11210907), X(0x7ed94538), X(0x1152d7ed), X(0x7ed28171), X(0x1184a427), X(0x7ecbaa1a), X(0x11b66dad), X(0x7ec4bf36), X(0x11e83478), X(0x7ebdc0c6), X(0x1219f880), X(0x7eb6aeca), X(0x124bb9be), X(0x7eaf8943), X(0x127d7829), X(0x7ea85033), X(0x12af33ba), X(0x7ea1039b), X(0x12e0ec6a), X(0x7e99a37c), X(0x1312a230), X(0x7e922fd6), X(0x13445505), X(0x7e8aa8ac), X(0x137604e2), X(0x7e830dff), X(0x13a7b1bf), X(0x7e7b5fce), X(0x13d95b93), X(0x7e739e1d), X(0x140b0258), X(0x7e6bc8eb), X(0x143ca605), X(0x7e63e03b), X(0x146e4694), X(0x7e5be40c), X(0x149fe3fc), X(0x7e53d462), X(0x14d17e36), X(0x7e4bb13c), X(0x1503153a), X(0x7e437a9c), X(0x1534a901), X(0x7e3b3083), X(0x15663982), X(0x7e32d2f4), X(0x1597c6b7), X(0x7e2a61ed), X(0x15c95097), X(0x7e21dd73), X(0x15fad71b), X(0x7e194584), X(0x162c5a3b), X(0x7e109a24), X(0x165dd9f0), X(0x7e07db52), X(0x168f5632), X(0x7dff0911), X(0x16c0cef9), X(0x7df62362), X(0x16f2443e), X(0x7ded2a47), X(0x1723b5f9), X(0x7de41dc0), X(0x17552422), X(0x7ddafdce), X(0x17868eb3), X(0x7dd1ca75), X(0x17b7f5a3), X(0x7dc883b4), X(0x17e958ea), X(0x7dbf298d), X(0x181ab881), X(0x7db5bc02), X(0x184c1461), X(0x7dac3b15), X(0x187d6c82), X(0x7da2a6c6), X(0x18aec0db), X(0x7d98ff17), X(0x18e01167), X(0x7d8f4409), X(0x19115e1c), X(0x7d85759f), X(0x1942a6f3), X(0x7d7b93da), X(0x1973ebe6), X(0x7d719eba), X(0x19a52ceb), X(0x7d679642), X(0x19d669fc), X(0x7d5d7a74), X(0x1a07a311), X(0x7d534b50), X(0x1a38d823), X(0x7d4908d9), X(0x1a6a0929), X(0x7d3eb30f), X(0x1a9b361d), X(0x7d3449f5), X(0x1acc5ef6), X(0x7d29cd8c), X(0x1afd83ad), X(0x7d1f3dd6), X(0x1b2ea43a), X(0x7d149ad5), X(0x1b5fc097), X(0x7d09e489), X(0x1b90d8bb), X(0x7cff1af5), X(0x1bc1ec9e), X(0x7cf43e1a), X(0x1bf2fc3a), X(0x7ce94dfb), X(0x1c240786), X(0x7cde4a98), X(0x1c550e7c), X(0x7cd333f3), X(0x1c861113), X(0x7cc80a0f), X(0x1cb70f43), X(0x7cbcccec), X(0x1ce80906), X(0x7cb17c8d), X(0x1d18fe54), X(0x7ca618f3), X(0x1d49ef26), X(0x7c9aa221), X(0x1d7adb73), X(0x7c8f1817), X(0x1dabc334), X(0x7c837ad8), X(0x1ddca662), X(0x7c77ca65), X(0x1e0d84f5), X(0x7c6c06c0), X(0x1e3e5ee5), X(0x7c602fec), X(0x1e6f342c), X(0x7c5445e9), X(0x1ea004c1), X(0x7c4848ba), X(0x1ed0d09d), X(0x7c3c3860), X(0x1f0197b8), X(0x7c3014de), X(0x1f325a0b), X(0x7c23de35), X(0x1f63178f), X(0x7c179467), X(0x1f93d03c), X(0x7c0b3777), X(0x1fc4840a), X(0x7bfec765), X(0x1ff532f2), X(0x7bf24434), X(0x2025dcec), X(0x7be5ade6), X(0x205681f1), X(0x7bd9047c), X(0x208721f9), X(0x7bcc47fa), X(0x20b7bcfe), X(0x7bbf7860), X(0x20e852f6), X(0x7bb295b0), X(0x2118e3dc), X(0x7ba59fee), X(0x21496fa7), X(0x7b989719), X(0x2179f64f), X(0x7b8b7b36), X(0x21aa77cf), X(0x7b7e4c45), X(0x21daf41d), X(0x7b710a49), X(0x220b6b32), X(0x7b63b543), X(0x223bdd08), X(0x7b564d36), X(0x226c4996), X(0x7b48d225), X(0x229cb0d5), X(0x7b3b4410), X(0x22cd12bd), X(0x7b2da2fa), X(0x22fd6f48), X(0x7b1feee5), X(0x232dc66d), X(0x7b1227d3), X(0x235e1826), X(0x7b044dc7), X(0x238e646a), X(0x7af660c2), X(0x23beab33), X(0x7ae860c7), X(0x23eeec78), X(0x7ada4dd8), X(0x241f2833), X(0x7acc27f7), X(0x244f5e5c), X(0x7abdef25), X(0x247f8eec), X(0x7aafa367), X(0x24afb9da), X(0x7aa144bc), X(0x24dfdf20), X(0x7a92d329), X(0x250ffeb7), X(0x7a844eae), X(0x25401896), X(0x7a75b74f), X(0x25702cb7), X(0x7a670d0d), X(0x25a03b11), X(0x7a584feb), X(0x25d0439f), X(0x7a497feb), X(0x26004657), X(0x7a3a9d0f), X(0x26304333), X(0x7a2ba75a), X(0x26603a2c), X(0x7a1c9ece), X(0x26902b39), X(0x7a0d836d), X(0x26c01655), X(0x79fe5539), X(0x26effb76), X(0x79ef1436), X(0x271fda96), X(0x79dfc064), X(0x274fb3ae), X(0x79d059c8), X(0x277f86b5), X(0x79c0e062), X(0x27af53a6), X(0x79b15435), X(0x27df1a77), X(0x79a1b545), X(0x280edb23), X(0x79920392), X(0x283e95a1), X(0x79823f20), X(0x286e49ea), X(0x797267f2), X(0x289df7f8), X(0x79627e08), X(0x28cd9fc1), X(0x79528167), X(0x28fd4140), X(0x79427210), X(0x292cdc6d), X(0x79325006), X(0x295c7140), X(0x79221b4b), X(0x298bffb2), X(0x7911d3e2), X(0x29bb87bc), X(0x790179cd), X(0x29eb0957), X(0x78f10d0f), X(0x2a1a847b), X(0x78e08dab), X(0x2a49f920), X(0x78cffba3), X(0x2a796740), X(0x78bf56f9), X(0x2aa8ced3), X(0x78ae9fb0), X(0x2ad82fd2), X(0x789dd5cb), X(0x2b078a36), X(0x788cf94c), X(0x2b36ddf7), X(0x787c0a36), X(0x2b662b0e), X(0x786b088c), X(0x2b957173), X(0x7859f44f), X(0x2bc4b120), X(0x7848cd83), X(0x2bf3ea0d), X(0x7837942b), X(0x2c231c33), X(0x78264849), X(0x2c52478a), X(0x7814e9df), X(0x2c816c0c), X(0x780378f1), X(0x2cb089b1), X(0x77f1f581), X(0x2cdfa071), X(0x77e05f91), X(0x2d0eb046), X(0x77ceb725), X(0x2d3db928), X(0x77bcfc3f), X(0x2d6cbb10), X(0x77ab2ee2), X(0x2d9bb5f6), X(0x77994f11), X(0x2dcaa9d5), X(0x77875cce), X(0x2df996a3), X(0x7775581d), X(0x2e287c5a), X(0x776340ff), X(0x2e575af3), X(0x77511778), X(0x2e863267), X(0x773edb8b), X(0x2eb502ae), X(0x772c8d3a), X(0x2ee3cbc1), X(0x771a2c88), X(0x2f128d99), X(0x7707b979), X(0x2f41482e), X(0x76f5340e), X(0x2f6ffb7a), X(0x76e29c4b), X(0x2f9ea775), X(0x76cff232), X(0x2fcd4c19), X(0x76bd35c7), X(0x2ffbe95d), X(0x76aa670d), X(0x302a7f3a), X(0x76978605), X(0x30590dab), X(0x768492b4), X(0x308794a6), X(0x76718d1c), X(0x30b61426), X(0x765e7540), X(0x30e48c22), X(0x764b4b23), X(0x3112fc95), X(0x76380ec8), X(0x31416576), X(0x7624c031), X(0x316fc6be), X(0x76115f63), X(0x319e2067), X(0x75fdec60), X(0x31cc7269), X(0x75ea672a), X(0x31fabcbd), X(0x75d6cfc5), X(0x3228ff5c), X(0x75c32634), X(0x32573a3f), X(0x75af6a7b), X(0x32856d5e), X(0x759b9c9b), X(0x32b398b3), X(0x7587bc98), X(0x32e1bc36), X(0x7573ca75), X(0x330fd7e1), X(0x755fc635), X(0x333debab), X(0x754bafdc), X(0x336bf78f), X(0x7537876c), X(0x3399fb85), X(0x75234ce8), X(0x33c7f785), X(0x750f0054), X(0x33f5eb89), X(0x74faa1b3), X(0x3423d78a), X(0x74e63108), X(0x3451bb81), X(0x74d1ae55), X(0x347f9766), X(0x74bd199f), X(0x34ad6b32), X(0x74a872e8), X(0x34db36df), X(0x7493ba34), X(0x3508fa66), X(0x747eef85), X(0x3536b5be), X(0x746a12df), X(0x356468e2), X(0x74552446), X(0x359213c9), X(0x744023bc), X(0x35bfb66e), X(0x742b1144), X(0x35ed50c9), X(0x7415ece2), X(0x361ae2d3), X(0x7400b69a), X(0x36486c86), X(0x73eb6e6e), X(0x3675edd9), X(0x73d61461), X(0x36a366c6), X(0x73c0a878), X(0x36d0d746), X(0x73ab2ab4), X(0x36fe3f52), X(0x73959b1b), X(0x372b9ee3), X(0x737ff9ae), X(0x3758f5f2), X(0x736a4671), X(0x37864477), X(0x73548168), X(0x37b38a6d), X(0x733eaa96), X(0x37e0c7cc), X(0x7328c1ff), X(0x380dfc8d), X(0x7312c7a5), X(0x383b28a9), X(0x72fcbb8c), X(0x38684c19), X(0x72e69db7), X(0x389566d6), X(0x72d06e2b), X(0x38c278d9), X(0x72ba2cea), X(0x38ef821c), X(0x72a3d9f7), X(0x391c8297), X(0x728d7557), X(0x39497a43), X(0x7276ff0d), X(0x39766919), X(0x7260771b), X(0x39a34f13), X(0x7249dd86), X(0x39d02c2a), X(0x72333251), X(0x39fd0056), X(0x721c7580), X(0x3a29cb91), X(0x7205a716), X(0x3a568dd4), X(0x71eec716), X(0x3a834717), X(0x71d7d585), X(0x3aaff755), X(0x71c0d265), X(0x3adc9e86), X(0x71a9bdba), X(0x3b093ca3), X(0x71929789), X(0x3b35d1a5), X(0x717b5fd3), X(0x3b625d86), X(0x7164169d), X(0x3b8ee03e), X(0x714cbbeb), X(0x3bbb59c7), X(0x71354fc0), X(0x3be7ca1a), X(0x711dd220), X(0x3c143130), X(0x7106430e), X(0x3c408f03), X(0x70eea28e), X(0x3c6ce38a), X(0x70d6f0a4), X(0x3c992ec0), X(0x70bf2d53), X(0x3cc5709e), X(0x70a7589f), X(0x3cf1a91c), X(0x708f728b), X(0x3d1dd835), X(0x70777b1c), X(0x3d49fde1), X(0x705f7255), X(0x3d761a19), X(0x70475839), X(0x3da22cd7), X(0x702f2ccd), X(0x3dce3614), X(0x7016f014), X(0x3dfa35c8), X(0x6ffea212), X(0x3e262bee), X(0x6fe642ca), X(0x3e52187f), X(0x6fcdd241), X(0x3e7dfb73), X(0x6fb5507a), X(0x3ea9d4c3), X(0x6f9cbd79), X(0x3ed5a46b), X(0x6f841942), X(0x3f016a61), X(0x6f6b63d8), X(0x3f2d26a0), X(0x6f529d40), X(0x3f58d921), X(0x6f39c57d), X(0x3f8481dd), X(0x6f20dc92), X(0x3fb020ce), X(0x6f07e285), X(0x3fdbb5ec), X(0x6eeed758), X(0x40074132), X(0x6ed5bb10), X(0x4032c297), X(0x6ebc8db0), X(0x405e3a16), X(0x6ea34f3d), X(0x4089a7a8), X(0x6e89ffb9), X(0x40b50b46), X(0x6e709f2a), X(0x40e064ea), X(0x6e572d93), X(0x410bb48c), X(0x6e3daaf8), X(0x4136fa27), X(0x6e24175c), X(0x416235b2), X(0x6e0a72c5), X(0x418d6729), X(0x6df0bd35), X(0x41b88e84), X(0x6dd6f6b1), X(0x41e3abbc), X(0x6dbd1f3c), X(0x420ebecb), X(0x6da336dc), X(0x4239c7aa), X(0x6d893d93), X(0x4264c653), X(0x6d6f3365), X(0x428fbabe), X(0x6d551858), X(0x42baa4e6), X(0x6d3aec6e), X(0x42e584c3), X(0x6d20afac), X(0x43105a50), X(0x6d066215), X(0x433b2585), X(0x6cec03af), X(0x4365e65b), X(0x6cd1947c), X(0x43909ccd), X(0x6cb71482), X(0x43bb48d4), X(0x6c9c83c3), X(0x43e5ea68), X(0x6c81e245), X(0x44108184), X(0x6c67300b), X(0x443b0e21), X(0x6c4c6d1a), X(0x44659039), X(0x6c319975), X(0x449007c4), X(0x6c16b521), X(0x44ba74bd), X(0x6bfbc021), X(0x44e4d71c), X(0x6be0ba7b), X(0x450f2edb), X(0x6bc5a431), X(0x45397bf4), X(0x6baa7d49), X(0x4563be60), X(0x6b8f45c7), X(0x458df619), X(0x6b73fdae), X(0x45b82318), X(0x6b58a503), X(0x45e24556), X(0x6b3d3bcb), X(0x460c5cce), X(0x6b21c208), X(0x46366978), X(0x6b0637c1), X(0x46606b4e), X(0x6aea9cf8), X(0x468a624a), X(0x6acef1b2), X(0x46b44e65), X(0x6ab335f4), X(0x46de2f99), X(0x6a9769c1), X(0x470805df), X(0x6a7b8d1e), X(0x4731d131), X(0x6a5fa010), X(0x475b9188), X(0x6a43a29a), X(0x478546de), X(0x6a2794c1), X(0x47aef12c), X(0x6a0b7689), X(0x47d8906d), X(0x69ef47f6), X(0x48022499), X(0x69d3090e), X(0x482badab), X(0x69b6b9d3), X(0x48552b9b), X(0x699a5a4c), X(0x487e9e64), X(0x697dea7b), X(0x48a805ff), X(0x69616a65), X(0x48d16265), X(0x6944da10), X(0x48fab391), X(0x6928397e), X(0x4923f97b), X(0x690b88b5), X(0x494d341e), X(0x68eec7b9), X(0x49766373), X(0x68d1f68f), X(0x499f8774), X(0x68b5153a), X(0x49c8a01b), X(0x689823bf), X(0x49f1ad61), X(0x687b2224), X(0x4a1aaf3f), X(0x685e106c), X(0x4a43a5b0), X(0x6840ee9b), X(0x4a6c90ad), X(0x6823bcb7), X(0x4a957030), X(0x68067ac3), X(0x4abe4433), X(0x67e928c5), X(0x4ae70caf), X(0x67cbc6c0), X(0x4b0fc99d), X(0x67ae54ba), X(0x4b387af9), X(0x6790d2b6), X(0x4b6120bb), X(0x677340ba), X(0x4b89badd), X(0x67559eca), X(0x4bb24958), X(0x6737ecea), X(0x4bdacc28), X(0x671a2b20), X(0x4c034345), X(0x66fc596f), X(0x4c2baea9), X(0x66de77dc), X(0x4c540e4e), X(0x66c0866d), X(0x4c7c622d), X(0x66a28524), X(0x4ca4aa41), X(0x66847408), X(0x4ccce684), X(0x6666531d), X(0x4cf516ee), X(0x66482267), X(0x4d1d3b7a), X(0x6629e1ec), X(0x4d455422), X(0x660b91af), X(0x4d6d60df), X(0x65ed31b5), X(0x4d9561ac), X(0x65cec204), X(0x4dbd5682), X(0x65b0429f), X(0x4de53f5a), X(0x6591b38c), X(0x4e0d1c30), X(0x657314cf), X(0x4e34ecfc), X(0x6554666d), X(0x4e5cb1b9), X(0x6535a86b), X(0x4e846a60), X(0x6516dacd), X(0x4eac16eb), X(0x64f7fd98), X(0x4ed3b755), X(0x64d910d1), X(0x4efb4b96), X(0x64ba147d), X(0x4f22d3aa), X(0x649b08a0), X(0x4f4a4f89), X(0x647bed3f), X(0x4f71bf2e), X(0x645cc260), X(0x4f992293), X(0x643d8806), X(0x4fc079b1), X(0x641e3e38), X(0x4fe7c483), X(0x63fee4f8), X(0x500f0302), X(0x63df7c4d), X(0x50363529), X(0x63c0043b), X(0x505d5af1), X(0x63a07cc7), X(0x50847454), X(0x6380e5f6), X(0x50ab814d), X(0x63613fcd), X(0x50d281d5), X(0x63418a50), X(0x50f975e6), X(0x6321c585), X(0x51205d7b), X(0x6301f171), X(0x5147388c), X(0x62e20e17), X(0x516e0715), X(0x62c21b7e), X(0x5194c910), X(0x62a219aa), X(0x51bb7e75), X(0x628208a1), X(0x51e22740), X(0x6261e866), X(0x5208c36a), X(0x6241b8ff), X(0x522f52ee), X(0x62217a72), X(0x5255d5c5), X(0x62012cc2), X(0x527c4bea), X(0x61e0cff5), X(0x52a2b556), X(0x61c06410), X(0x52c91204), X(0x619fe918), X(0x52ef61ee), X(0x617f5f12), X(0x5315a50e), X(0x615ec603), X(0x533bdb5d), X(0x613e1df0), X(0x536204d7), X(0x611d66de), X(0x53882175), X(0x60fca0d2), X(0x53ae3131), X(0x60dbcbd1), X(0x53d43406), X(0x60bae7e1), X(0x53fa29ed), X(0x6099f505), X(0x542012e1), X(0x6078f344), X(0x5445eedb), X(0x6057e2a2), X(0x546bbdd7), X(0x6036c325), X(0x54917fce), X(0x601594d1), X(0x54b734ba), X(0x5ff457ad), X(0x54dcdc96), X(0x5fd30bbc), X(0x5502775c), X(0x5fb1b104), X(0x55280505), X(0x5f90478a), X(0x554d858d), X(0x5f6ecf53), X(0x5572f8ed), X(0x5f4d4865), X(0x55985f20), X(0x5f2bb2c5), X(0x55bdb81f), X(0x5f0a0e77), X(0x55e303e6), X(0x5ee85b82), X(0x5608426e), X(0x5ec699e9), X(0x562d73b2), X(0x5ea4c9b3), X(0x565297ab), X(0x5e82eae5), X(0x5677ae54), X(0x5e60fd84), X(0x569cb7a8), X(0x5e3f0194), X(0x56c1b3a1), X(0x5e1cf71c), X(0x56e6a239), X(0x5dfade20), X(0x570b8369), X(0x5dd8b6a7), X(0x5730572e), X(0x5db680b4), X(0x57551d80), X(0x5d943c4e), X(0x5779d65b), X(0x5d71e979), X(0x579e81b8), X(0x5d4f883b), X(0x57c31f92), X(0x5d2d189a), X(0x57e7afe4), X(0x5d0a9a9a), X(0x580c32a7), X(0x5ce80e41), X(0x5830a7d6), X(0x5cc57394), X(0x58550f6c), X(0x5ca2ca99), X(0x58796962), X(0x5c801354), X(0x589db5b3), X(0x5c5d4dcc), X(0x58c1f45b), X(0x5c3a7a05), X(0x58e62552), X(0x5c179806), X(0x590a4893), X(0x5bf4a7d2), X(0x592e5e19), X(0x5bd1a971), X(0x595265df), X(0x5bae9ce7), X(0x59765fde), X(0x5b8b8239), X(0x599a4c12), X(0x5b68596d), X(0x59be2a74), X(0x5b452288), X(0x59e1faff), X(0x5b21dd90), X(0x5a05bdae), X(0x5afe8a8b), X(0x5a29727b), X(0x5adb297d), X(0x5a4d1960), X(0x5ab7ba6c), X(0x5a70b258), X(0x5a943d5e), }; bcmatroska2-5.3.101/mkclean/tremor/misc.h000066400000000000000000000133231462133141200201160ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: miscellaneous math and prototypes ********************************************************************/ #ifndef _V_RANDOM_H_ #define _V_RANDOM_H_ #include "ivorbiscodec.h" #include "os.h" #include "asm_arm.h" #include /* for abs() */ #ifndef _V_WIDE_MATH #define _V_WIDE_MATH #ifndef _LOW_ACCURACY_ /* 64 bit multiply */ #if !(defined WIN32 && defined WINCE) #include #endif #if BYTE_ORDER==LITTLE_ENDIAN union magic { struct { ogg_int32_t lo; ogg_int32_t hi; } halves; ogg_int64_t whole; }; #endif #if BYTE_ORDER==BIG_ENDIAN union magic { struct { ogg_int32_t hi; ogg_int32_t lo; } halves; ogg_int64_t whole; }; #endif STIN ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { union magic magic; magic.whole = (ogg_int64_t)x * y; return magic.halves.hi; } STIN ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { return MULT32(x,y)<<1; } STIN ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { union magic magic; magic.whole = (ogg_int64_t)x * y; return ((ogg_uint32_t)(magic.halves.lo)>>15) | ((magic.halves.hi)<<17); } #else /* 32 bit multiply, more portable but less accurate */ /* * Note: Precision is biased towards the first argument therefore ordering * is important. Shift values were chosen for the best sound quality after * many listening tests. */ /* * For MULT32 and MULT31: The second argument is always a lookup table * value already preshifted from 31 to 8 bits. We therefore take the * opportunity to save on text space and use unsigned char for those * tables in this case. */ STIN ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { return (x >> 9) * y; /* y preshifted >>23 */ } STIN ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { return (x >> 8) * y; /* y preshifted >>23 */ } STIN ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { return (x >> 6) * y; /* y preshifted >>9 */ } #endif /* * This should be used as a memory barrier, forcing all cached values in * registers to wr writen back to memory. Might or might not be beneficial * depending on the architecture and compiler. */ #define MB() /* * The XPROD functions are meant to optimize the cross products found all * over the place in mdct.c by forcing memory operation ordering to avoid * unnecessary register reloads as soon as memory is being written to. * However this is only beneficial on CPUs with a sane number of general * purpose registers which exclude the Intel x86. On Intel, better let the * compiler actually reload registers directly from original memory by using * macros. */ #ifdef __i386__ #define XPROD32(_a, _b, _t, _v, _x, _y) \ { *(_x)=MULT32(_a,_t)+MULT32(_b,_v); \ *(_y)=MULT32(_b,_t)-MULT32(_a,_v); } #define XPROD31(_a, _b, _t, _v, _x, _y) \ { *(_x)=MULT31(_a,_t)+MULT31(_b,_v); \ *(_y)=MULT31(_b,_t)-MULT31(_a,_v); } #define XNPROD31(_a, _b, _t, _v, _x, _y) \ { *(_x)=MULT31(_a,_t)-MULT31(_b,_v); \ *(_y)=MULT31(_b,_t)+MULT31(_a,_v); } #else STIN void XPROD32(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { *x = MULT32(a, t) + MULT32(b, v); *y = MULT32(b, t) - MULT32(a, v); } STIN void XPROD31(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { *x = MULT31(a, t) + MULT31(b, v); *y = MULT31(b, t) - MULT31(a, v); } STIN void XNPROD31(ogg_int32_t a, ogg_int32_t b, ogg_int32_t t, ogg_int32_t v, ogg_int32_t *x, ogg_int32_t *y) { *x = MULT31(a, t) - MULT31(b, v); *y = MULT31(b, t) + MULT31(a, v); } #endif #endif #ifndef _V_CLIP_MATH #define _V_CLIP_MATH STIN ogg_int32_t CLIP_TO_15(ogg_int32_t x) { int ret=x; ret-= ((x<=32767)-1)&(x-32767); ret-= ((x>=-32768)-1)&(x+32768); return(ret); } #endif STIN ogg_int32_t VFLOAT_MULT(ogg_int32_t a,ogg_int32_t ap, ogg_int32_t b,ogg_int32_t bp, ogg_int32_t *p){ if(a && b){ #ifndef _LOW_ACCURACY_ *p=ap+bp+32; return MULT32(a,b); #else *p=ap+bp+31; return (a>>15)*(b>>16); #endif }else return 0; } int _ilog(unsigned int); STIN ogg_int32_t VFLOAT_MULTI(ogg_int32_t a,ogg_int32_t ap, ogg_int32_t i, ogg_int32_t *p){ int ip=_ilog(abs(i))-31; return VFLOAT_MULT(a,ap,i<<-ip,ip,p); } STIN ogg_int32_t VFLOAT_ADD(ogg_int32_t a,ogg_int32_t ap, ogg_int32_t b,ogg_int32_t bp, ogg_int32_t *p){ if(!a){ *p=bp; return b; }else if(!b){ *p=ap; return a; } /* yes, this can leak a bit. */ if(ap>bp){ int shift=ap-bp+1; *p=ap+1; a>>=1; if(shift<32){ b=(b+(1<<(shift-1)))>>shift; }else{ b=0; } }else{ int shift=bp-ap+1; *p=bp+1; b>>=1; if(shift<32){ a=(a+(1<<(shift-1)))>>shift; }else{ a=0; } } a+=b; if((a&0xc0000000)==0xc0000000 || (a&0xc0000000)==0){ a<<=1; (*p)--; } return(a); } #endif bcmatroska2-5.3.101/mkclean/tremor/ogg.h000066400000000000000000000150631462133141200177420ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2003 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: subsumed libogg includes ********************************************************************/ #ifndef _OGG_H #define _OGG_H #ifdef __cplusplus extern "C" { #endif #include "os_types.h" typedef struct ogg_buffer_state{ struct ogg_buffer *unused_buffers; struct ogg_reference *unused_references; int outstanding; int shutdown; } ogg_buffer_state; typedef struct ogg_buffer { unsigned char *data; long size; int refcount; union { ogg_buffer_state *owner; struct ogg_buffer *next; } ptr; } ogg_buffer; typedef struct ogg_reference { ogg_buffer *buffer; long begin; long length; struct ogg_reference *next; } ogg_reference; typedef struct oggpack_buffer { int headbit; unsigned char *headptr; long headend; /* memory management */ ogg_reference *head; ogg_reference *tail; /* render the byte/bit counter API constant time */ long count; /* doesn't count the tail */ } oggpack_buffer; typedef struct oggbyte_buffer { ogg_reference *baseref; ogg_reference *ref; unsigned char *ptr; long pos; long end; } oggbyte_buffer; typedef struct ogg_sync_state { /* decode memory management pool */ ogg_buffer_state *bufferpool; /* stream buffers */ ogg_reference *fifo_head; ogg_reference *fifo_tail; long fifo_fill; /* stream sync management */ int unsynced; int headerbytes; int bodybytes; } ogg_sync_state; typedef struct ogg_stream_state { ogg_reference *header_head; ogg_reference *header_tail; ogg_reference *body_head; ogg_reference *body_tail; int e_o_s; /* set when we have buffered the last packet in the logical bitstream */ int b_o_s; /* set after we've written the initial page of a logical bitstream */ long serialno; long pageno; ogg_int64_t packetno; /* sequence number for decode; the framing knows where there's a hole in the data, but we need coupling so that the codec (which is in a seperate abstraction layer) also knows about the gap */ ogg_int64_t granulepos; int lacing_fill; ogg_uint32_t body_fill; /* decode-side state data */ int holeflag; int spanflag; int clearflag; int laceptr; ogg_uint32_t body_fill_next; } ogg_stream_state; typedef struct { ogg_reference *packet; long bytes; long b_o_s; long e_o_s; ogg_int64_t granulepos; ogg_int64_t packetno; /* sequence number for decode; the framing knows where there's a hole in the data, but we need coupling so that the codec (which is in a seperate abstraction layer) also knows about the gap */ } ogg_packet; typedef struct { ogg_reference *header; int header_len; ogg_reference *body; long body_len; } ogg_page; /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/ extern void oggpack_readinit(oggpack_buffer *b,ogg_reference *r); extern long oggpack_look(oggpack_buffer *b,int bits); extern void oggpack_adv(oggpack_buffer *b,int bits); extern long oggpack_read(oggpack_buffer *b,int bits); extern long oggpack_bytes(oggpack_buffer *b); extern long oggpack_bits(oggpack_buffer *b); extern int oggpack_eop(oggpack_buffer *b); /* Ogg BITSTREAM PRIMITIVES: decoding **************************/ extern ogg_sync_state *ogg_sync_create(void); extern int ogg_sync_destroy(ogg_sync_state *oy); extern int ogg_sync_reset(ogg_sync_state *oy); extern unsigned char *ogg_sync_bufferin(ogg_sync_state *oy, long size); extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes); extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og); extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og); extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og); extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op); extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op); /* Ogg BITSTREAM PRIMITIVES: general ***************************/ extern ogg_stream_state *ogg_stream_create(int serialno); extern int ogg_stream_destroy(ogg_stream_state *os); extern int ogg_stream_reset(ogg_stream_state *os); extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno); extern int ogg_stream_eos(ogg_stream_state *os); extern int ogg_page_checksum_set(ogg_page *og); extern int ogg_page_version(ogg_page *og); extern int ogg_page_continued(ogg_page *og); extern int ogg_page_bos(ogg_page *og); extern int ogg_page_eos(ogg_page *og); extern ogg_int64_t ogg_page_granulepos(ogg_page *og); extern ogg_uint32_t ogg_page_serialno(ogg_page *og); extern ogg_uint32_t ogg_page_pageno(ogg_page *og); extern int ogg_page_packets(ogg_page *og); extern int ogg_page_getbuffer(ogg_page *og, unsigned char **buffer); extern int ogg_packet_release(ogg_packet *op); extern int ogg_page_release(ogg_page *og); extern void ogg_page_dup(ogg_page *d, ogg_page *s); /* Ogg BITSTREAM PRIMITIVES: return codes ***************************/ #define OGG_SUCCESS 0 #define OGG_HOLE -10 #define OGG_SPAN -11 #define OGG_EVERSION -12 #define OGG_ESERIAL -13 #define OGG_EINVAL -14 #define OGG_EEOS -15 #ifdef __cplusplus } #endif #endif /* _OGG_H */ bcmatroska2-5.3.101/mkclean/tremor/os.h000066400000000000000000000033371462133141200176100ustar00rootroot00000000000000#ifndef _OS_H #define _OS_H /******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: #ifdef jail to whip a few platforms into the UNIX ideal. ********************************************************************/ #include #include "os_types.h" #ifndef _V_IFDEFJAIL_H_ # define _V_IFDEFJAIL_H_ # ifdef __GNUC__ # define STIN static __inline__ # elif _WIN32 # define STIN static __inline # endif #else # define STIN static #endif #ifndef M_PI # define M_PI (3.1415926536f) #endif #ifdef _WIN32 # include # define rint(x) (floor((x)+0.5f)) # define NO_FLOAT_MATH_LIB # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b)) # define LITTLE_ENDIAN 1 # define BYTE_ORDER LITTLE_ENDIAN #endif #ifdef HAVE_ALLOCA_H # include #endif #ifdef USE_MEMORY_H # include #endif #ifndef min # define min(x,y) ((x)>(y)?(y):(x)) #endif #ifndef max # define max(x,y) ((x)<(y)?(y):(x)) #endif #endif /* _OS_H */ bcmatroska2-5.3.101/mkclean/tremor/os_types.h000066400000000000000000000050041462133141200210250ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: #ifdef jail to whip a few platforms into the UNIX ideal. ********************************************************************/ #ifndef _OS_TYPES_H #define _OS_TYPES_H #ifdef _LOW_ACCURACY_ # define X(n) (((((n)>>22)+1)>>1) - ((((n)>>22)+1)>>9)) # define LOOKUP_T const unsigned char #else # define X(n) (n) # define LOOKUP_T const ogg_int32_t #endif /* make it easy on the folks that want to compile the libs with a different malloc than stdlib */ #define _ogg_malloc malloc #define _ogg_calloc calloc #define _ogg_realloc realloc #define _ogg_free free #ifdef _WIN32 # ifndef __GNUC__ /* MSVC/Borland */ typedef __int64 ogg_int64_t; typedef __int32 ogg_int32_t; typedef unsigned __int32 ogg_uint32_t; typedef __int16 ogg_int16_t; # else /* Cygwin */ #include <_G_config.h> typedef _G_int64_t ogg_int64_t; typedef _G_int32_t ogg_int32_t; typedef _G_uint32_t ogg_uint32_t; typedef _G_int16_t ogg_int16_t; # endif #elif defined(__MACOS__) # include typedef SInt16 ogg_int16_t; typedef SInt32 ogg_int32_t; typedef UInt32 ogg_uint32_t; typedef SInt64 ogg_int64_t; #elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */ # include typedef int16_t ogg_int16_t; typedef int32_t ogg_int32_t; typedef u_int32_t ogg_uint32_t; typedef int64_t ogg_int64_t; #elif defined(__BEOS__) /* Be */ # include #elif defined (__EMX__) /* OS/2 GCC */ typedef short ogg_int16_t; typedef int ogg_int32_t; typedef unsigned int ogg_uint32_t; typedef long long ogg_int64_t; #else # include # include "config_types.h" #endif #endif /* _OS_TYPES_H */ bcmatroska2-5.3.101/mkclean/tremor/registry.c000066400000000000000000000033511462133141200210260ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: registry for floor, res backends and channel mappings ********************************************************************/ #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "misc.h" /* seems like major overkill now; the backend numbers will grow into the infrastructure soon enough */ extern vorbis_func_floor floor0_exportbundle; extern vorbis_func_floor floor1_exportbundle; extern vorbis_func_residue residue0_exportbundle; extern vorbis_func_residue residue1_exportbundle; extern vorbis_func_residue residue2_exportbundle; extern vorbis_func_mapping mapping0_exportbundle; vorbis_func_floor *_floor_P[]={ &floor0_exportbundle, &floor1_exportbundle, }; vorbis_func_residue *_residue_P[]={ &residue0_exportbundle, &residue1_exportbundle, &residue2_exportbundle, }; vorbis_func_mapping *_mapping_P[]={ &mapping0_exportbundle, }; bcmatroska2-5.3.101/mkclean/tremor/registry.h000066400000000000000000000026331462133141200210350ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: registry for time, floor, res backends and channel mappings ********************************************************************/ #ifndef _V_REG_H_ #define _V_REG_H_ #define VI_TRANSFORMB 1 #define VI_WINDOWB 1 #define VI_TIMEB 1 #define VI_FLOORB 2 #define VI_RESB 3 #define VI_MAPB 1 #include "backends.h" #if defined(_WIN32) && defined(VORBISDLL_IMPORT) # define EXTERN __declspec(dllimport) extern #else # define EXTERN extern #endif EXTERN vorbis_func_floor *_floor_P[]; EXTERN vorbis_func_residue *_residue_P[]; EXTERN vorbis_func_mapping *_mapping_P[]; #endif bcmatroska2-5.3.101/mkclean/tremor/res012.c000066400000000000000000000220651462133141200201750ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: residue backend 0, 1 and 2 implementation ********************************************************************/ #include #include #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "codebook.h" #include "misc.h" #include "os.h" #include "block.h" typedef struct { vorbis_info_residue0 *info; int map; int parts; int stages; codebook *fullbooks; codebook *phrasebook; codebook ***partbooks; int partvals; int **decodemap; } vorbis_look_residue0; void res0_free_info(vorbis_info_residue *i){ vorbis_info_residue0 *info=(vorbis_info_residue0 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } void res0_free_look(vorbis_look_residue *i){ int j; if(i){ vorbis_look_residue0 *look=(vorbis_look_residue0 *)i; for(j=0;jparts;j++) if(look->partbooks[j])_ogg_free(look->partbooks[j]); _ogg_free(look->partbooks); for(j=0;jpartvals;j++) _ogg_free(look->decodemap[j]); _ogg_free(look->decodemap); memset(look,0,sizeof(*look)); _ogg_free(look); } } static int ilog(unsigned int v){ int ret=0; while(v){ ret++; v>>=1; } return(ret); } static int icount(unsigned int v){ int ret=0; while(v){ ret+=v&1; v>>=1; } return(ret); } /* vorbis_info is for range checking */ vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){ int j,acc=0; vorbis_info_residue0 *info=(vorbis_info_residue0 *)_ogg_calloc(1,sizeof(*info)); codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; info->begin=oggpack_read(opb,24); info->end=oggpack_read(opb,24); info->grouping=oggpack_read(opb,24)+1; info->partitions=oggpack_read(opb,6)+1; info->groupbook=oggpack_read(opb,8); for(j=0;jpartitions;j++){ int cascade=oggpack_read(opb,3); if(oggpack_read(opb,1)) cascade|=(oggpack_read(opb,5)<<3); info->secondstages[j]=cascade; acc+=icount(cascade); } for(j=0;jbooklist[j]=oggpack_read(opb,8); if(info->groupbook>=ci->books)goto errout; for(j=0;jbooklist[j]>=ci->books)goto errout; return(info); errout: res0_free_info(info); return(NULL); } vorbis_look_residue *res0_look(vorbis_dsp_state *vd,vorbis_info_mode *vm, vorbis_info_residue *vr){ vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr; vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look)); codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; int j,k,acc=0; int dim; int maxstage=0; look->info=info; look->map=vm->mapping; look->parts=info->partitions; look->fullbooks=ci->fullbooks; look->phrasebook=ci->fullbooks+info->groupbook; dim=look->phrasebook->dim; look->partbooks=(codebook ***)_ogg_calloc(look->parts,sizeof(*look->partbooks)); for(j=0;jparts;j++){ int stages=ilog(info->secondstages[j]); if(stages){ if(stages>maxstage)maxstage=stages; look->partbooks[j]=(codebook **)_ogg_calloc(stages,sizeof(*look->partbooks[j])); for(k=0;ksecondstages[j]&(1<partbooks[j][k]=ci->fullbooks+info->booklist[acc++]; #ifdef TRAIN_RES look->training_data[k][j]=calloc(look->partbooks[j][k]->entries, sizeof(***look->training_data)); #endif } } } look->partvals=look->parts; for(j=1;jpartvals*=look->parts; look->stages=maxstage; look->decodemap=(int **)_ogg_malloc(look->partvals*sizeof(*look->decodemap)); for(j=0;jpartvals;j++){ long val=j; long mult=look->partvals/look->parts; look->decodemap[j]=(int *)_ogg_malloc(dim*sizeof(*look->decodemap[j])); for(k=0;kparts; look->decodemap[j][k]=deco; } } return(look); } /* a truncated packet here just means 'stop working'; it's not an error */ static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int ch, long (*decodepart)(codebook *, ogg_int32_t *, oggpack_buffer *,int,int)){ long i,j,k,l,s; vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl; vorbis_info_residue0 *info=look->info; /* move all this setup out later */ int samples_per_partition=info->grouping; int partitions_per_word=look->phrasebook->dim; int max=vb->pcmend>>1; int end=(info->endend:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; int ***partword=(int ***)alloca(ch*sizeof(*partword)); for(j=0;jstages;s++){ /* each loop decodes on partition codeword containing partitions_pre_word partitions */ for(i=0,l=0;iphrasebook,&vb->opb); if(temp==-1)goto eopbreak; partword[j][l]=look->decodemap[temp]; if(partword[j][l]==NULL)goto errout; } } /* now we decode residual values for the partitions */ for(k=0;kbegin+i*samples_per_partition; if(info->secondstages[partword[j][l][k]]&(1<partbooks[partword[j][l][k]][s]; if(stagebook){ if(decodepart(stagebook,in[j]+offset,&vb->opb, samples_per_partition,-8)==-1)goto eopbreak; } } } } } } errout: eopbreak: return(0); } int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl, ogg_int32_t **in,int *nonzero,int ch){ int i,used=0; for(i=0;iinfo; /* move all this setup out later */ int samples_per_partition=info->grouping; int partitions_per_word=look->phrasebook->dim; int max=(vb->pcmend*ch)>>1; int end=(info->endend:max); int n=end-info->begin; if(n>0){ int partvals=n/samples_per_partition; int partwords=(partvals+partitions_per_word-1)/partitions_per_word; int **partword=(int **)_vorbis_block_alloc(vb,partwords*sizeof(*partword)); int beginoff=info->begin/ch; for(i=0;istages;s++){ for(i=0,l=0;iphrasebook,&vb->opb); if(temp==-1)goto eopbreak; partword[l]=look->decodemap[temp]; if(partword[l]==NULL)goto errout; } /* now we decode residual values for the partitions */ for(k=0;ksecondstages[partword[l][k]]&(1<partbooks[partword[l][k]][s]; if(stagebook){ if(vorbis_book_decodevv_add(stagebook,in, i*samples_per_partition+beginoff,ch, &vb->opb, samples_per_partition,-8)==-1) goto eopbreak; } } } } } errout: eopbreak: return(0); } vorbis_func_residue residue0_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res0_inverse }; vorbis_func_residue residue1_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res1_inverse }; vorbis_func_residue residue2_exportbundle={ &res0_unpack, &res0_look, &res0_free_info, &res0_free_look, &res2_inverse }; bcmatroska2-5.3.101/mkclean/tremor/sharedbook.c000066400000000000000000000305011462133141200212740ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: basic shared codebook operations ********************************************************************/ #include #include #include #include "ogg.h" #include "misc.h" #include "ivorbiscodec.h" #include "codebook.h" /**** pack/unpack helpers ******************************************/ int _ilog(unsigned int v){ int ret=0; while(v){ ret++; v>>=1; } return(ret); } /* 32 bit float (not IEEE; nonnormalized mantissa + biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm Why not IEEE? It's just not that important here. */ #define VQ_FEXP 10 #define VQ_FMAN 21 #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */ static ogg_int32_t _float32_unpack(long val,int *point){ long mant=val&0x1fffff; int sign=val&0x80000000; long exp =(val&0x7fe00000L)>>VQ_FMAN; exp-=(VQ_FMAN-1)+VQ_FEXP_BIAS; if(mant){ while(!(mant&0x40000000)){ mant<<=1; exp-=1; } if(sign)mant= -mant; }else{ sign=0; exp=-9999; } *point=exp; return mant; } /* given a list of word lengths, generate a list of codewords. Works for length ordered or unordered, always assigns the lowest valued codewords first. Extended to handle unused entries (length 0) */ ogg_uint32_t *_make_words(long *l,long n,long sparsecount){ long i,j,count=0; ogg_uint32_t marker[33]; ogg_uint32_t *r=(ogg_uint32_t *)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r)); memset(marker,0,sizeof(marker)); for(i=0;i0){ ogg_uint32_t entry=marker[length]; /* when we claim a node for an entry, we also claim the nodes below it (pruning off the imagined tree that may have dangled from it) as well as blocking the use of any nodes directly above for leaves */ /* update ourself */ if(length<32 && (entry>>length)){ /* error condition; the lengths must specify an overpopulated tree */ _ogg_free(r); return(NULL); } r[count++]=entry; /* Look to see if the next shorter marker points to the node above. if so, update it and repeat. */ { for(j=length;j>0;j--){ if(marker[j]&1){ /* have to jump branches */ if(j==1) marker[1]++; else marker[j]=marker[j-1]<<1; break; /* invariant says next upper marker would already have been moved if it was on the same path */ } marker[j]++; } } /* prune the tree; the implicit invariant says all the longer markers were dangling from our just-taken node. Dangle them from our *new* node. */ for(j=length+1;j<33;j++) if((marker[j]>>1) == entry){ entry=marker[j]; marker[j]=marker[j-1]<<1; }else break; }else if(sparsecount==0)count++; } /* bitreverse the words because our bitwise packer/unpacker is LSb endian */ for(i=0,count=0;i>j)&1; } if(sparsecount){ if(l[i]) r[count++]=temp; }else r[count++]=temp; } return(r); } /* there might be a straightforward one-line way to do the below that's portable and totally safe against roundoff, but I haven't thought of it. Therefore, we opt on the side of caution */ long _book_maptype1_quantvals(const static_codebook *b){ /* get us a starting hint, we'll polish it below */ int bits=_ilog(b->entries); int vals=b->entries>>((bits-1)*(b->dim-1)/b->dim); while(1){ long acc=1; long acc1=1; int i; for(i=0;idim;i++){ acc*=vals; acc1*=vals+1; } if(acc<=b->entries && acc1>b->entries){ return(vals); }else{ if(acc>b->entries){ vals--; }else{ vals++; } } } } /* different than what _book_unquantize does for mainline: we repack the book in a fixed point format that shares the same binary point. Upon first use, we can shift point if needed */ /* we need to deal with two map types: in map type 1, the values are generated algorithmically (each column of the vector counts through the values in the quant vector). in map type 2, all the values came in in an explicit list. Both value lists must be unpacked */ ogg_int32_t *_book_unquantize(const static_codebook *b,int n,int *sparsemap, int *maxpoint){ long j,k,count=0; if(b->maptype==1 || b->maptype==2){ int quantvals; int minpoint,delpoint; ogg_int32_t mindel=_float32_unpack(b->q_min,&minpoint); ogg_int32_t delta=_float32_unpack(b->q_delta,&delpoint); ogg_int32_t *r=(ogg_int32_t *)_ogg_calloc(n*b->dim,sizeof(*r)); int *rp=(int *)_ogg_calloc(n*b->dim,sizeof(*rp)); *maxpoint=minpoint; /* maptype 1 and 2 both use a quantized value vector, but different sizes */ switch(b->maptype){ case 1: /* most of the time, entries%dimensions == 0, but we need to be well defined. We define that the possible vales at each scalar is values == entries/dim. If entries%dim != 0, we'll have 'too few' values (values*dimentries;j++){ if((sparsemap && b->lengthlist[j]) || !sparsemap){ ogg_int32_t last=0; int lastpoint=0; int indexdiv=1; for(k=0;kdim;k++){ int index= (j/indexdiv)%quantvals; int point=0; int val=VFLOAT_MULTI(delta,delpoint, abs(b->quantlist[index]),&point); val=VFLOAT_ADD(mindel,minpoint,val,point,&point); val=VFLOAT_ADD(last,lastpoint,val,point,&point); if(b->q_sequencep){ last=val; lastpoint=point; } if(sparsemap){ r[sparsemap[count]*b->dim+k]=val; rp[sparsemap[count]*b->dim+k]=point; }else{ r[count*b->dim+k]=val; rp[count*b->dim+k]=point; } if(*maxpointentries;j++){ if((sparsemap && b->lengthlist[j]) || !sparsemap){ ogg_int32_t last=0; int lastpoint=0; for(k=0;kdim;k++){ int point=0; int val=VFLOAT_MULTI(delta,delpoint, abs(b->quantlist[j*b->dim+k]),&point); val=VFLOAT_ADD(mindel,minpoint,val,point,&point); val=VFLOAT_ADD(last,lastpoint,val,point,&point); if(b->q_sequencep){ last=val; lastpoint=point; } if(sparsemap){ r[sparsemap[count]*b->dim+k]=val; rp[sparsemap[count]*b->dim+k]=point; }else{ r[count*b->dim+k]=val; rp[count*b->dim+k]=point; } if(*maxpointdim;j++) if(rp[j]<*maxpoint) r[j]>>=*maxpoint-rp[j]; _ogg_free(rp); return(r); } return(NULL); } void vorbis_staticbook_clear(static_codebook *b){ if(b->quantlist)_ogg_free(b->quantlist); if(b->lengthlist)_ogg_free(b->lengthlist); memset(b,0,sizeof(*b)); } void vorbis_staticbook_destroy(static_codebook *b){ vorbis_staticbook_clear(b); _ogg_free(b); } void vorbis_book_clear(codebook *b){ /* static book is not cleared; we're likely called on the lookup and the static codebook belongs to the info struct */ if(b->valuelist)_ogg_free(b->valuelist); if(b->codelist)_ogg_free(b->codelist); if(b->dec_index)_ogg_free(b->dec_index); if(b->dec_codelengths)_ogg_free(b->dec_codelengths); if(b->dec_firsttable)_ogg_free(b->dec_firsttable); memset(b,0,sizeof(*b)); } static ogg_uint32_t bitreverse(ogg_uint32_t x){ x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL); x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL); x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL); x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL); return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL); } static int sort32a(const void *a,const void *b){ return (**(ogg_uint32_t **)a>**(ogg_uint32_t **)b)- (**(ogg_uint32_t **)a<**(ogg_uint32_t **)b); } /* decode codebook arrangement is more heavily optimized than encode */ int vorbis_book_init_decode(codebook *c,const static_codebook *s){ int i,j,n=0,tabn; int *sortindex; memset(c,0,sizeof(*c)); /* count actually used entries */ for(i=0;ientries;i++) if(s->lengthlist[i]>0) n++; c->entries=s->entries; c->used_entries=n; c->dim=s->dim; if(n>0){ /* two different remappings go on here. First, we collapse the likely sparse codebook down only to actually represented values/words. This collapsing needs to be indexed as map-valueless books are used to encode original entry positions as integers. Second, we reorder all vectors, including the entry index above, by sorted bitreversed codeword to allow treeless decode. */ /* perform sort */ ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries); ogg_uint32_t **codep=(ogg_uint32_t **)alloca(sizeof(*codep)*n); if(codes==NULL)goto err_out; for(i=0;icodelist=(ogg_uint32_t *)_ogg_malloc(n*sizeof(*c->codelist)); /* the index is a reverse index */ for(i=0;icodelist[sortindex[i]]=codes[i]; _ogg_free(codes); c->valuelist=_book_unquantize(s,n,sortindex,&c->binarypoint); c->dec_index=(int *)_ogg_malloc(n*sizeof(*c->dec_index)); for(n=0,i=0;ientries;i++) if(s->lengthlist[i]>0) c->dec_index[sortindex[n++]]=i; c->dec_codelengths=(char *)_ogg_malloc(n*sizeof(*c->dec_codelengths)); for(n=0,i=0;ientries;i++) if(s->lengthlist[i]>0) c->dec_codelengths[sortindex[n++]]=s->lengthlist[i]; c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */ if(c->dec_firsttablen<5)c->dec_firsttablen=5; if(c->dec_firsttablen>8)c->dec_firsttablen=8; tabn=1<dec_firsttablen; c->dec_firsttable=(ogg_uint32_t *)_ogg_calloc(tabn,sizeof(*c->dec_firsttable)); c->dec_maxlength=0; for(i=0;idec_maxlengthdec_codelengths[i]) c->dec_maxlength=c->dec_codelengths[i]; if(c->dec_codelengths[i]<=c->dec_firsttablen){ ogg_uint32_t orig=bitreverse(c->codelist[i]); for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++) c->dec_firsttable[orig|(j<dec_codelengths[i])]=i+1; } } /* now fill in 'unused' entries in the firsttable with hi/lo search hints for the non-direct-hits */ { ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen); long lo=0,hi=0; for(i=0;idec_firsttablen); if(c->dec_firsttable[bitreverse(word)]==0){ while((lo+1)codelist[lo+1]<=word)lo++; while( hi=(c->codelist[hi]&mask))hi++; /* we only actually have 15 bits per hint to play with here. In order to overflow gracefully (nothing breaks, efficiency just drops), encode as the difference from the extremes. */ { unsigned long loval=lo; unsigned long hival=n-hi; if(loval>0x7fff)loval=0x7fff; if(hival>0x7fff)hival=0x7fff; c->dec_firsttable[bitreverse(word)]= 0x80000000UL | (loval<<15) | hival; } } } } } return(0); err_out: vorbis_book_clear(c); return(-1); } bcmatroska2-5.3.101/mkclean/tremor/synthesis.c000066400000000000000000000071371462133141200212150ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2003 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: single-block PCM synthesis last mod: $Id: synthesis.c,v 1.4 2003/03/29 03:07:21 xiphmont Exp $ ********************************************************************/ #include #include "ogg.h" #include "ivorbiscodec.h" #include "codec_internal.h" #include "registry.h" #include "misc.h" #include "block.h" static int _vorbis_synthesis1(vorbis_block *vb,ogg_packet *op,int decodep){ vorbis_dsp_state *vd=vb->vd; private_state *b=(private_state *)vd->backend_state; vorbis_info *vi=vd->vi; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; oggpack_buffer *opb=&vb->opb; int type,mode,i; /* first things first. Make sure decode is ready */ _vorbis_block_ripcord(vb); oggpack_readinit(opb,op->packet); /* Check the packet type */ if(oggpack_read(opb,1)!=0){ /* Oops. This is not an audio data packet */ return(OV_ENOTAUDIO); } /* read our mode and pre/post windowsize */ mode=oggpack_read(opb,b->modebits); if(mode==-1)return(OV_EBADPACKET); vb->mode=mode; vb->W=ci->mode_param[mode]->blockflag; if(vb->W){ vb->lW=oggpack_read(opb,1); vb->nW=oggpack_read(opb,1); if(vb->nW==-1) return(OV_EBADPACKET); }else{ vb->lW=0; vb->nW=0; } /* more setup */ vb->granulepos=op->granulepos; vb->sequence=op->packetno-3; /* first block is third packet */ vb->eofflag=op->e_o_s; if(decodep){ /* alloc pcm passback storage */ vb->pcmend=ci->blocksizes[vb->W]; vb->pcm=(ogg_int32_t **)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels); for(i=0;ichannels;i++) vb->pcm[i]=(ogg_int32_t *)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i])); /* unpack_header enforces range checking */ type=ci->map_type[ci->mode_param[mode]->mapping]; return(_mapping_P[type]->inverse(vb,b->mode[mode])); }else{ /* no pcm */ vb->pcmend=0; vb->pcm=NULL; return(0); } } int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){ return _vorbis_synthesis1(vb,op,1); } int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){ return _vorbis_synthesis1(vb,op,0); } long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){ codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; oggpack_buffer opb; int mode; oggpack_readinit(&opb,op->packet); /* Check the packet type */ if(oggpack_read(&opb,1)!=0){ /* Oops. This is not an audio data packet */ return(OV_ENOTAUDIO); } { int modebits=0; int v=ci->modes; while(v>1){ modebits++; v>>=1; } /* read our mode and pre/post windowsize */ mode=oggpack_read(&opb,modebits); } if(mode==-1)return(OV_EBADPACKET); return(ci->blocksizes[ci->mode_param[mode]->blockflag]); } bcmatroska2-5.3.101/mkclean/tremor/vorbisfile.c000066400000000000000000001563101462133141200213260ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2009 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: stdio-based convenience library for opening/seeking/decoding last mod: $Id: vorbisfile.c,v 1.6 2003/03/30 23:40:56 xiphmont Exp $ ********************************************************************/ #include #include #include #include #include #include "ivorbiscodec.h" #include "ivorbisfile.h" #include "misc.h" /* A 'chained bitstream' is a Vorbis bitstream that contains more than one logical bitstream arranged end to end (the only form of Ogg multiplexing allowed in a Vorbis bitstream; grouping [parallel multiplexing] is not allowed in Vorbis) */ /* A Vorbis file can be played beginning to end (streamed) without worrying ahead of time about chaining (see decoder_example.c). If we have the whole file, however, and want random access (seeking/scrubbing) or desire to know the total length/time of a file, we need to account for the possibility of chaining. */ /* We can handle things a number of ways; we can determine the entire bitstream structure right off the bat, or find pieces on demand. This example determines and caches structure for the entire bitstream, but builds a virtual decoder on the fly when moving between links in the chain. */ /* There are also different ways to implement seeking. Enough information exists in an Ogg bitstream to seek to sample-granularity positions in the output. Or, one can seek by picking some portion of the stream roughly in the desired area if we only want coarse navigation through the stream. */ /************************************************************************* * Many, many internal helpers. The intention is not to be confusing; * rampant duplication and monolithic function implementation would be * harder to understand anyway. The high level functions are last. Begin * grokking near the end of the file */ /* read a little more data from the file/pipe into the ogg_sync framer */ static long _get_data(OggVorbis_File *vf){ errno=0; if(vf->datasource){ unsigned char *buffer=ogg_sync_bufferin(vf->oy,CHUNKSIZE); long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource); if(bytes>0)ogg_sync_wrote(vf->oy,bytes); if(bytes==0 && errno)return(-1); return(bytes); }else return(0); } /* save a tiny smidge of verbosity to make the code more readable */ static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){ if(vf->datasource){ if(!(vf->callbacks.seek_func)|| (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1) return OV_EREAD; vf->offset=offset; ogg_sync_reset(vf->oy); }else{ /* shouldn't happen unless someone writes a broken callback */ return OV_EFAULT; } return 0; } /* The read/seek functions track absolute position within the stream */ /* from the head of the stream, get the next page. boundary specifies if the function is allowed to fetch more data from the stream (and how much) or only use internally buffered data. boundary: -1) unbounded search 0) read no additional data; use cached only n) search for a new page beginning for n bytes return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD) n) found a page at absolute offset n produces a refcounted page */ static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og, ogg_int64_t boundary){ if(boundary>0)boundary+=vf->offset; while(1){ long more; if(boundary>0 && vf->offset>=boundary)return(OV_FALSE); more=ogg_sync_pageseek(vf->oy,og); if(more<0){ /* skipped n bytes */ vf->offset-=more; }else{ if(more==0){ /* send more paramedics */ if(!boundary)return(OV_FALSE); { long ret=_get_data(vf); if(ret==0)return(OV_EOF); if(ret<0)return(OV_EREAD); } }else{ /* got a page. Return the offset at the page beginning, advance the internal offset past the page end */ ogg_int64_t ret=vf->offset; vf->offset+=more; return(ret); } } } } /* find the latest page beginning before the current stream cursor position. Much dirtier than the above as Ogg doesn't have any backward search linkage. no 'readp' as it will certainly have to read. */ /* returns offset or OV_EREAD, OV_FAULT and produces a refcounted page */ static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){ ogg_int64_t begin=vf->offset; ogg_int64_t end=begin; ogg_int64_t ret; ogg_int64_t offset=-1; while(offset==-1){ begin-=CHUNKSIZE; if(begin<0) begin=0; ret=_seek_helper(vf,begin); if(ret)return(ret); while(vf->offsetoffset); if(ret==OV_EREAD)return(OV_EREAD); if(ret<0){ break; }else{ offset=ret; } } } /* In a fully compliant, non-multiplexed stream, we'll still be holding the last page. In multiplexed (or noncompliant streams), we will probably have to re-read the last page we saw */ if(og->header_len==0){ ogg_page_release(og); ret=_seek_helper(vf,offset); if(ret)return(ret); ret=_get_next_page(vf,og,CHUNKSIZE); if(ret<0) /* this shouldn't be possible */ return(OV_EFAULT); } return(offset); } static void _add_serialno(ogg_page *og,ogg_uint32_t **serialno_list, int *n){ long s = ogg_page_serialno(og); (*n)++; if(*serialno_list){ *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n)); }else{ *serialno_list = _ogg_malloc(sizeof(**serialno_list)); } (*serialno_list)[(*n)-1] = s; } /* returns nonzero if found */ static int _lookup_serialno(long s, ogg_uint32_t *serialno_list, int n){ if(serialno_list){ while(n--){ if(*serialno_list == s) return 1; serialno_list++; } } return 0; } static int _lookup_page_serialno(ogg_page *og, ogg_uint32_t *serialno_list, int n){ long s = ogg_page_serialno(og); return _lookup_serialno(s,serialno_list,n); } /* performs the same search as _get_prev_page, but prefers pages of the specified serial number. If a page of the specified serialno is spotted during the seek-back-and-read-forward, it will return the info of last page of the matching serial number instead of the very last page. If no page of the specified serialno is seen, it will return the info of last page and alter *serialno. */ static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, ogg_uint32_t *serial_list, int serial_n, int *serialno, ogg_int64_t *granpos){ ogg_page og={0,0,0,0}; ogg_int64_t begin=vf->offset; ogg_int64_t end=begin; ogg_int64_t ret; ogg_int64_t prefoffset=-1; ogg_int64_t offset=-1; ogg_uint32_t ret_serialno=-1; ogg_int64_t ret_gran=-1; while(offset==-1){ begin-=CHUNKSIZE; if(begin<0) begin=0; ret=_seek_helper(vf,begin); if(ret)return(ret); while(vf->offsetoffset); if(ret==OV_EREAD)return(OV_EREAD); if(ret<0){ ogg_page_release(&og); break; }else{ ret_serialno=ogg_page_serialno(&og); ret_gran=ogg_page_granulepos(&og); offset=ret; ogg_page_release(&og); if(ret_serialno == *serialno){ prefoffset=ret; *granpos=ret_gran; } if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){ /* we fell off the end of the link, which means we seeked back too far and shouldn't have been looking in that link to begin with. If we found the preferred serial number, forget that we saw it. */ prefoffset=-1; } } } } /* we're not interested in the page... just the serialno and granpos. */ if(prefoffset>=0)return(prefoffset); *serialno = ret_serialno; *granpos = ret_gran; return(offset); } /* uses the local ogg_stream storage in vf; this is important for non-streaming input sources */ /* consumes the page that's passed in (if any) */ static int _fetch_headers(OggVorbis_File *vf, vorbis_info *vi, vorbis_comment *vc, ogg_uint32_t **serialno_list, int *serialno_n, ogg_page *og_ptr){ ogg_page og={0,0,0,0}; ogg_packet op={0,0,0,0,0,0}; int i,ret; int allbos=0; if(!og_ptr){ ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE); if(llret==OV_EREAD)return(OV_EREAD); if(llret<0)return OV_ENOTVORBIS; og_ptr=&og; } vorbis_info_init(vi); vorbis_comment_init(vc); vf->ready_state=OPENED; /* extract the serialnos of all BOS pages + the first set of vorbis headers we see in the link */ while(ogg_page_bos(og_ptr)){ if(serialno_list){ if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){ /* a dupe serialnumber in an initial header packet set == invalid stream */ if(*serialno_list)_ogg_free(*serialno_list); *serialno_list=0; *serialno_n=0; ret=OV_EBADHEADER; goto bail_header; } _add_serialno(og_ptr,serialno_list,serialno_n); } if(vf->ready_stateos,ogg_page_serialno(og_ptr)); ogg_stream_pagein(vf->os,og_ptr); if(ogg_stream_packetout(vf->os,&op) > 0 && vorbis_synthesis_idheader(&op)){ /* vorbis header; continue setup */ vf->ready_state=STREAMSET; if((ret=vorbis_synthesis_headerin(vi,vc,&op))){ ret=OV_EBADHEADER; goto bail_header; } } } /* get next page */ { ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE); if(llret==OV_EREAD){ ret=OV_EREAD; goto bail_header; } if(llret<0){ ret=OV_ENOTVORBIS; goto bail_header; } /* if this page also belongs to our vorbis stream, submit it and break */ if(vf->ready_state==STREAMSET && vf->os->serialno == ogg_page_serialno(og_ptr)){ ogg_stream_pagein(vf->os,og_ptr); break; } } } if(vf->ready_state!=STREAMSET){ ret = OV_ENOTVORBIS; goto bail_header; } while(1){ i=0; while(i<2){ /* get a page loop */ while(i<2){ /* get a packet loop */ int result=ogg_stream_packetout(vf->os,&op); if(result==0)break; if(result==-1){ ret=OV_EBADHEADER; goto bail_header; } if((ret=vorbis_synthesis_headerin(vi,vc,&op))) goto bail_header; i++; } while(i<2){ if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){ ret=OV_EBADHEADER; goto bail_header; } /* if this page belongs to the correct stream, go parse it */ if(vf->os->serialno == ogg_page_serialno(og_ptr)){ ogg_stream_pagein(vf->os,og_ptr); break; } /* if we never see the final vorbis headers before the link ends, abort */ if(ogg_page_bos(og_ptr)){ if(allbos){ ret = OV_EBADHEADER; goto bail_header; }else allbos=1; } /* otherwise, keep looking */ } } ogg_packet_release(&op); ogg_page_release(&og); return 0; } bail_header: ogg_packet_release(&op); ogg_page_release(&og); vorbis_info_clear(vi); vorbis_comment_clear(vc); vf->ready_state=OPENED; return ret; } /* Starting from current cursor position, get initial PCM offset of next page. Consumes the page in the process without decoding audio, however this is only called during stream parsing upon seekable open. */ static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){ ogg_page og={0,0,0,0}; ogg_int64_t accumulated=0,pos; long lastblock=-1; int result; int serialno = vf->os->serialno; while(1){ ogg_packet op={0,0,0,0,0,0}; if(_get_next_page(vf,&og,-1)<0) break; /* should not be possible unless the file is truncated/mangled */ if(ogg_page_bos(&og)) break; if(ogg_page_serialno(&og)!=serialno) continue; pos=ogg_page_granulepos(&og); /* count blocksizes of all frames in the page */ ogg_stream_pagein(vf->os,&og); while((result=ogg_stream_packetout(vf->os,&op))){ if(result>0){ /* ignore holes */ long thisblock=vorbis_packet_blocksize(vi,&op); if(lastblock!=-1) accumulated+=(lastblock+thisblock)>>2; lastblock=thisblock; } } ogg_packet_release(&op); if(pos!=-1){ /* pcm offset of last packet on the first audio page */ accumulated= pos-accumulated; break; } } /* less than zero? This is a stream with samples trimmed off the beginning, a normal occurrence; set the offset to zero */ if(accumulated<0)accumulated=0; ogg_page_release(&og); return accumulated; } /* finds each bitstream link one at a time using a bisection search (has to begin by knowing the offset of the lb's initial page). Recurses for each link so it can alloc the link storage after finding them all, then unroll and fill the cache at the same time */ static int _bisect_forward_serialno(OggVorbis_File *vf, ogg_int64_t begin, ogg_int64_t searched, ogg_int64_t end, ogg_int64_t endgran, int endserial, ogg_uint32_t *currentno_list, int currentnos, long m){ ogg_int64_t pcmoffset; ogg_int64_t dataoffset=searched; ogg_int64_t endsearched=end; ogg_int64_t next=end; ogg_int64_t searchgran=-1; ogg_int64_t ret,last; int serialno = vf->os->serialno; /* invariants: we have the headers and serialnos for the link beginning at 'begin' we have the offset and granpos of the last page in the file (potentially not a page we care about) */ /* Is the last page in our list of current serialnumbers? */ if(_lookup_serialno(endserial,currentno_list,currentnos)){ /* last page is in the starting serialno list, so we've bisected down to (or just started with) a single link. Now we need to find the last vorbis page belonging to the first vorbis stream for this link. */ while(endserial != serialno){ endserial = serialno; vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&endserial,&endgran); } vf->links=m+1; if(vf->offsets)_ogg_free(vf->offsets); if(vf->serialnos)_ogg_free(vf->serialnos); if(vf->dataoffsets)_ogg_free(vf->dataoffsets); vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets)); vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi)); vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc)); vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos)); vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets)); vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths)); vf->offsets[m+1]=end; vf->offsets[m]=begin; vf->pcmlengths[m*2+1]=endgran; }else{ ogg_uint32_t *next_serialno_list=NULL; int next_serialnos=0; vorbis_info vi; vorbis_comment vc; /* the below guards against garbage seperating the last and first pages of two links. */ while(searched=0)next=last; }else{ searched=last+og.header_len+og.body_len; } ogg_page_release(&og); } /* Bisection point found */ /* for the time being, fetch end PCM offset the simple way */ { int testserial = serialno+1; vf->offset = next; while(testserial != serialno){ testserial = serialno; vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&testserial,&searchgran); } } if(vf->offset!=next){ ret=_seek_helper(vf,next); if(ret)return(ret); } ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL); if(ret)return(ret); serialno = vf->os->serialno; dataoffset = vf->offset; /* this will consume a page, however the next bistection always starts with a raw seek */ pcmoffset = _initial_pcmoffset(vf,&vi); ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial, next_serialno_list,next_serialnos,m+1); if(ret)return(ret); if(next_serialno_list)_ogg_free(next_serialno_list); vf->offsets[m+1]=next; vf->serialnos[m+1]=serialno; vf->dataoffsets[m+1]=dataoffset; vf->vi[m+1]=vi; vf->vc[m+1]=vc; vf->pcmlengths[m*2+1]=searchgran; vf->pcmlengths[m*2+2]=pcmoffset; vf->pcmlengths[m*2+3]-=pcmoffset; } return(0); } static int _make_decode_ready(OggVorbis_File *vf){ if(vf->ready_state>STREAMSET)return 0; if(vf->ready_stateseekable){ if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link)) return OV_EBADLINK; }else{ if(vorbis_synthesis_init(&vf->vd,vf->vi)) return OV_EBADLINK; } vorbis_block_init(&vf->vd,&vf->vb); vf->ready_state=INITSET; vf->bittrack=0; vf->samptrack=0; return 0; } static int _open_seekable2(OggVorbis_File *vf){ ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1; int endserial=vf->os->serialno; int serialno=vf->os->serialno; /* we're partially open and have a first link header state in storage in vf */ /* fetch initial PCM offset */ ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi); /* we can seek, so set out learning all about this file */ if(vf->callbacks.seek_func && vf->callbacks.tell_func){ (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END); vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource); }else{ vf->offset=vf->end=-1; } /* If seek_func is implemented, tell_func must also be implemented */ if(vf->end==-1) return(OV_EINVAL); /* Get the offset of the last page of the physical bitstream, or, if we're lucky the last vorbis page of this link as most OggVorbis files will contain a single logical bitstream */ end=_get_prev_page_serial(vf,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran); if(end<0)return(end); /* now determine bitstream structure recursively */ if(_bisect_forward_serialno(vf,0,dataoffset,vf->offset,endgran,endserial, vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD); vf->offsets[0]=0; vf->serialnos[0]=serialno; vf->dataoffsets[0]=dataoffset; vf->pcmlengths[0]=pcmoffset; vf->pcmlengths[1]-=pcmoffset; return(ov_raw_seek(vf,dataoffset)); } /* clear out the current logical bitstream decoder */ static void _decode_clear(OggVorbis_File *vf){ vorbis_dsp_clear(&vf->vd); vorbis_block_clear(&vf->vb); vf->ready_state=OPENED; } /* fetch and process a packet. Handles the case where we're at a bitstream boundary and dumps the decoding machine. If the decoding machine is unloaded, it loads it. It also keeps pcm_offset up to date (seek and read both use this. seek uses a special hack with readp). return: <0) error, OV_HOLE (lost packet) or OV_EOF 0) need more data (only if readp==0) 1) got a packet */ static int _fetch_and_process_packet(OggVorbis_File *vf, int readp, int spanp){ ogg_page og={0,0,0,0}; ogg_packet op={0,0,0,0,0,0}; int ret=0; /* handle one packet. Try to fetch it from current stream state */ /* extract packets from page */ while(1){ if(vf->ready_state==STREAMSET){ ret=_make_decode_ready(vf); if(ret<0) goto cleanup; } /* process a packet if we can. If the machine isn't loaded, neither is a page */ if(vf->ready_state==INITSET){ while(1) { int result=ogg_stream_packetout(vf->os,&op); ogg_int64_t granulepos; if(result==-1){ ret=OV_HOLE; /* hole in the data. */ goto cleanup; } if(result>0){ /* got a packet. process it */ granulepos=op.granulepos; if(!vorbis_synthesis(&vf->vb,&op)){ /* lazy check for lazy header handling. The header packets aren't audio, so if/when we submit them, vorbis_synthesis will reject them */ /* suck in the synthesis data and track bitrate */ { int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL); /* for proper use of libvorbis within libvorbisfile, oldsamples will always be zero. */ if(oldsamples){ ret=OV_EFAULT; goto cleanup; } vorbis_synthesis_blockin(&vf->vd,&vf->vb); vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples; vf->bittrack+=op.bytes*8; } /* update the pcm offset. */ if(granulepos!=-1 && !op.e_o_s){ int link=(vf->seekable?vf->current_link:0); int i,samples; /* this packet has a pcm_offset on it (the last packet completed on a page carries the offset) After processing (above), we know the pcm position of the *last* sample ready to be returned. Find the offset of the *first* As an aside, this trick is inaccurate if we begin reading anew right at the last page; the end-of-stream granulepos declares the last frame in the stream, and the last packet of the last page may be a partial frame. So, we need a previous granulepos from an in-sequence page to have a reference point. Thus the !op.e_o_s clause above */ if(vf->seekable && link>0) granulepos-=vf->pcmlengths[link*2]; if(granulepos<0)granulepos=0; /* actually, this shouldn't be possible here unless the stream is very broken */ samples=vorbis_synthesis_pcmout(&vf->vd,NULL); granulepos-=samples; for(i=0;ipcmlengths[i*2+1]; vf->pcm_offset=granulepos; } ret=1; goto cleanup; } } else break; } } if(vf->ready_state>=OPENED){ ogg_int64_t lret; while(1){ /* the loop is not strictly necessary, but there's no sense in doing the extra checks of the larger loop for the common case in a multiplexed bistream where the page is simply part of a different logical bitstream; keep reading until we get one with the correct serialno */ if(!readp){ ret=0; goto cleanup; } if((lret=_get_next_page(vf,&og,-1))<0){ ret=OV_EOF; /* eof. leave unitialized */ goto cleanup; } /* bitrate tracking; add the header's bytes here, the body bytes are done by packet above */ vf->bittrack+=og.header_len*8; if(vf->ready_state==INITSET){ if(vf->current_serialno!=ogg_page_serialno(&og)){ /* two possibilities: 1) our decoding just traversed a bitstream boundary 2) another stream is multiplexed into this logical section */ if(ogg_page_bos(&og)){ /* boundary case */ if(!spanp){ ret=OV_EOF; goto cleanup; } _decode_clear(vf); if(!vf->seekable){ vorbis_info_clear(vf->vi); vorbis_comment_clear(vf->vc); } break; }else continue; /* possibility #2 */ } } break; } } /* Do we need to load a new machine before submitting the page? */ /* This is different in the seekable and non-seekable cases. In the seekable case, we already have all the header information loaded and cached; we just initialize the machine with it and continue on our merry way. In the non-seekable (streaming) case, we'll only be at a boundary if we just left the previous logical bitstream and we're now nominally at the header of the next bitstream */ if(vf->ready_state!=INITSET){ int link; if(vf->ready_stateseekable){ long serialno=ogg_page_serialno(&og); /* match the serialno to bitstream section. We use this rather than offset positions to avoid problems near logical bitstream boundaries */ for(link=0;linklinks;link++) if(vf->serialnos[link]==serialno)break; if(link==vf->links) continue; /* not the desired Vorbis bitstream section; keep trying */ vf->current_serialno=serialno; vf->current_link=link; ogg_stream_reset_serialno(vf->os,vf->current_serialno); vf->ready_state=STREAMSET; }else{ /* we're streaming */ /* fetch the three header packets, build the info struct */ int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og); if(ret) goto cleanup; vf->current_serialno=vf->os->serialno; vf->current_link++; link=0; } } } /* the buffered page is the data we want, and we're ready for it; add it to the stream state */ ogg_stream_pagein(vf->os,&og); } cleanup: ogg_packet_release(&op); ogg_page_release(&og); return ret; } /* if, eg, 64 bit stdio is configured by default, this will build with fseek64 */ static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){ if(f==NULL)return(-1); return fseek(f,off,whence); } static int _ov_open1(void *f,OggVorbis_File *vf,char *initial, long ibytes, ov_callbacks callbacks){ int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1); ogg_uint32_t *serialno_list=NULL; int serialno_list_size=0; int ret; memset(vf,0,sizeof(*vf)); vf->datasource=f; vf->callbacks = callbacks; /* init the framing state */ vf->oy=ogg_sync_create(); /* perhaps some data was previously read into a buffer for testing against other stream types. Allow initialization from this previously read data (especially as we may be reading from a non-seekable stream) */ if(initial){ unsigned char *buffer=ogg_sync_bufferin(vf->oy,ibytes); memcpy(buffer,initial,ibytes); ogg_sync_wrote(vf->oy,ibytes); } /* can we seek? Stevens suggests the seek test was portable */ if(offsettest!=-1)vf->seekable=1; /* No seeking yet; Set up a 'single' (current) logical bitstream entry for partial open */ vf->links=1; vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi)); vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc)); vf->os=ogg_stream_create(-1); /* fill in the serialno later */ /* Fetch all BOS pages, store the vorbis header and all seen serial numbers, load subsequent vorbis setup headers */ if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){ vf->datasource=NULL; ov_clear(vf); }else{ /* serial number list for first link needs to be held somewhere for second stage of seekable stream open; this saves having to seek/reread first link's serialnumber data then. */ vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos)); vf->serialnos[0]=vf->current_serialno; vf->serialnos[1]=serialno_list_size; memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos)); vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets)); vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets)); vf->offsets[0]=0; vf->dataoffsets[0]=vf->offset; vf->current_serialno=vf->os->serialno; vf->ready_state=PARTOPEN; } if(serialno_list)_ogg_free(serialno_list); return(ret); } static int _ov_open2(OggVorbis_File *vf){ if(vf->ready_state < OPENED) vf->ready_state=OPENED; if(vf->seekable){ int ret=_open_seekable2(vf); if(ret){ vf->datasource=NULL; ov_clear(vf); } return(ret); } return 0; } /* clear out the OggVorbis_File struct */ int ov_clear(OggVorbis_File *vf){ if(vf){ vorbis_block_clear(&vf->vb); vorbis_dsp_clear(&vf->vd); ogg_stream_destroy(vf->os); if(vf->vi && vf->links){ int i; for(i=0;ilinks;i++){ vorbis_info_clear(vf->vi+i); vorbis_comment_clear(vf->vc+i); } _ogg_free(vf->vi); _ogg_free(vf->vc); } if(vf->dataoffsets)_ogg_free(vf->dataoffsets); if(vf->pcmlengths)_ogg_free(vf->pcmlengths); if(vf->serialnos)_ogg_free(vf->serialnos); if(vf->offsets)_ogg_free(vf->offsets); ogg_sync_destroy(vf->oy); if(vf->datasource && vf->callbacks.close_func) (vf->callbacks.close_func)(vf->datasource); memset(vf,0,sizeof(*vf)); } #ifdef DEBUG_LEAKS _VDBG_dump(); #endif return(0); } /* inspects the OggVorbis file and finds/documents all the logical bitstreams contained in it. Tries to be tolerant of logical bitstream sections that are truncated/woogie. return: -1) error 0) OK */ int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes, ov_callbacks callbacks){ int ret=_ov_open1(f,vf,initial,ibytes,callbacks); if(ret)return ret; return _ov_open2(vf); } int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){ ov_callbacks callbacks = { (size_t (*)(void *, size_t, size_t, void *)) fread, (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, (int (*)(void *)) fclose, (long (*)(void *)) ftell }; return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks); } /* Only partially open the vorbis file; test for Vorbisness, and load the headers for the first chain. Do not seek (although test for seekability). Use ov_test_open to finish opening the file, else ov_clear to close/free it. Same return codes as open. */ int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes, ov_callbacks callbacks) { return _ov_open1(f,vf,initial,ibytes,callbacks); } int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){ ov_callbacks callbacks = { (size_t (*)(void *, size_t, size_t, void *)) fread, (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, (int (*)(void *)) fclose, (long (*)(void *)) ftell }; return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks); } int ov_test_open(OggVorbis_File *vf){ if(vf->ready_state!=PARTOPEN)return(OV_EINVAL); return _ov_open2(vf); } /* How many logical bitstreams in this physical bitstream? */ long ov_streams(OggVorbis_File *vf){ return vf->links; } /* Is the FILE * associated with vf seekable? */ long ov_seekable(OggVorbis_File *vf){ return vf->seekable; } /* returns the bitrate for a given logical bitstream or the entire physical bitstream. If the file is open for random access, it will find the *actual* average bitrate. If the file is streaming, it returns the nominal bitrate (if set) else the average of the upper/lower bounds (if set) else -1 (unset). If you want the actual bitrate field settings, get them from the vorbis_info structs */ long ov_bitrate(OggVorbis_File *vf,int i){ if(vf->ready_state=vf->links)return(OV_EINVAL); if(!vf->seekable && i!=0)return(ov_bitrate(vf,0)); if(i<0){ ogg_int64_t bits=0; int i; for(i=0;ilinks;i++) bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8; /* This once read: return(rint(bits/ov_time_total(vf,-1))); * gcc 3.x on x86 miscompiled this at optimisation level 2 and above, * so this is slightly transformed to make it work. */ return(bits*1000/ov_time_total(vf,-1)); }else{ if(vf->seekable){ /* return the actual bitrate */ return((vf->offsets[i+1]-vf->dataoffsets[i])*8000/ov_time_total(vf,i)); }else{ /* return nominal if set */ if(vf->vi[i].bitrate_nominal>0){ return vf->vi[i].bitrate_nominal; }else{ if(vf->vi[i].bitrate_upper>0){ if(vf->vi[i].bitrate_lower>0){ return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2; }else{ return vf->vi[i].bitrate_upper; } } return(OV_FALSE); } } } } /* returns the actual bitrate since last call. returns -1 if no additional data to offer since last call (or at beginning of stream), EINVAL if stream is only partially open */ long ov_bitrate_instant(OggVorbis_File *vf){ int link=(vf->seekable?vf->current_link:0); long ret; if(vf->ready_statesamptrack==0)return(OV_FALSE); ret=vf->bittrack/vf->samptrack*vf->vi[link].rate; vf->bittrack=0; vf->samptrack=0; return(ret); } /* Guess */ long ov_serialnumber(OggVorbis_File *vf,int i){ if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1)); if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1)); if(i<0){ return(vf->current_serialno); }else{ return(vf->serialnos[i]); } } /* returns: total raw (compressed) length of content if i==-1 raw (compressed) length of that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or if stream is only partially open */ ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){ if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); if(i<0){ ogg_int64_t acc=0; int i; for(i=0;ilinks;i++) acc+=ov_raw_total(vf,i); return(acc); }else{ return(vf->offsets[i+1]-vf->offsets[i]); } } /* returns: total PCM length (samples) of content if i==-1 PCM length (samples) of that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or only partially open */ ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){ if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); if(i<0){ ogg_int64_t acc=0; int i; for(i=0;ilinks;i++) acc+=ov_pcm_total(vf,i); return(acc); }else{ return(vf->pcmlengths[i*2+1]); } } /* returns: total milliseconds of content if i==-1 milliseconds in that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or only partially open */ ogg_int64_t ov_time_total(OggVorbis_File *vf,int i){ if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); if(i<0){ ogg_int64_t acc=0; int i; for(i=0;ilinks;i++) acc+=ov_time_total(vf,i); return(acc); }else{ return(((ogg_int64_t)vf->pcmlengths[i*2+1])*1000/vf->vi[i].rate); } } /* seek to an offset relative to the *compressed* data. This also scans packets to update the PCM cursor. It will cross a logical bitstream boundary, but only if it can't get any packets out of the tail of the bitstream we seek to (so no surprises). returns zero on success, nonzero on failure */ int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){ ogg_stream_state *work_os=NULL; ogg_page og={0,0,0,0}; ogg_packet op={0,0,0,0,0,0}; int ret; if(vf->ready_stateseekable) return(OV_ENOSEEK); /* don't dump machine if we can't seek */ if(pos<0 || pos>vf->end)return(OV_EINVAL); /* don't yet clear out decoding machine (if it's initialized), in the case we're in the same link. Restart the decode lapping, and let _fetch_and_process_packet deal with a potential bitstream boundary */ vf->pcm_offset=-1; ogg_stream_reset_serialno(vf->os, vf->current_serialno); /* must set serialno */ vorbis_synthesis_restart(&vf->vd); ret=_seek_helper(vf,pos); if(ret)goto seek_error; /* we need to make sure the pcm_offset is set, but we don't want to advance the raw cursor past good packets just to get to the first with a granulepos. That's not equivalent behavior to beginning decoding as immediately after the seek position as possible. So, a hack. We use two stream states; a local scratch state and the shared vf->os stream state. We use the local state to scan, and the shared state as a buffer for later decode. Unfortuantely, on the last page we still advance to last packet because the granulepos on the last page is not necessarily on a packet boundary, and we need to make sure the granpos is correct. */ { int lastblock=0; int accblock=0; int thisblock; int lastflag=0; int firstflag=0; ogg_int64_t pagepos=-1; work_os=ogg_stream_create(vf->current_serialno); /* get the memory ready */ while(1){ if(vf->ready_state>=STREAMSET){ /* snarf/scan a packet if we can */ int result=ogg_stream_packetout(work_os,&op); if(result>0){ if(vf->vi[vf->current_link].codec_setup){ thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); if(thisblock<0){ ogg_stream_packetout(vf->os,NULL); thisblock=0; }else{ /* We can't get a guaranteed correct pcm position out of the last page in a stream because it might have a 'short' granpos, which can only be detected in the presence of a preceeding page. However, if the last page is also the first page, the granpos rules of a first page take precedence. Not only that, but for first==last, the EOS page must be treated as if its a normal first page for the stream to open/play. */ if(lastflag && !firstflag) ogg_stream_packetout(vf->os,NULL); else if(lastblock)accblock+=(lastblock+thisblock)>>2; } if(op.granulepos!=-1){ int i,link=vf->current_link; ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2]; if(granulepos<0)granulepos=0; for(i=0;ipcmlengths[i*2+1]; vf->pcm_offset=granulepos-accblock; if(vf->pcm_offset<0)vf->pcm_offset=0; break; } lastblock=thisblock; continue; }else ogg_stream_packetout(vf->os,NULL); } } if(!lastblock){ pagepos=_get_next_page(vf,&og,-1); if(pagepos<0){ vf->pcm_offset=ov_pcm_total(vf,-1); break; } }else{ /* huh? Bogus stream with packets but no granulepos */ vf->pcm_offset=-1; break; } /* has our decoding just traversed a bitstream boundary? */ if(vf->ready_state>=STREAMSET){ if(vf->current_serialno!=ogg_page_serialno(&og)){ /* two possibilities: 1) our decoding just traversed a bitstream boundary 2) another stream is multiplexed into this logical section? */ if(ogg_page_bos(&og)){ /* we traversed */ _decode_clear(vf); /* clear out stream state */ ogg_stream_destroy(work_os); } /* else, do nothing; next loop will scoop another page */ } } if(vf->ready_statelinks;link++) if(vf->serialnos[link]==vf->current_serialno)break; if(link==vf->links) continue; /* not the desired Vorbis bitstream section; keep trying */ vf->current_link=link; vf->current_serialno=serialno; ogg_stream_reset_serialno(vf->os,vf->current_serialno); ogg_stream_reset_serialno(work_os,vf->current_serialno); vf->ready_state=STREAMSET; firstflag=(pagepos<=vf->dataoffsets[link]); } { ogg_page dup; ogg_page_dup(&dup,&og); lastflag=ogg_page_eos(&og); ogg_stream_pagein(vf->os,&og); ogg_stream_pagein(work_os,&dup); } } } ogg_packet_release(&op); ogg_page_release(&og); ogg_stream_destroy(work_os); vf->bittrack=0; vf->samptrack=0; return(0); seek_error: ogg_packet_release(&op); ogg_page_release(&og); /* dump the machine so we're in a known state */ vf->pcm_offset=-1; ogg_stream_destroy(work_os); _decode_clear(vf); return OV_EBADLINK; } /* Page granularity seek (faster than sample granularity because we don't do the last bit of decode to find a specific sample). Seek to the last [granule marked] page preceeding the specified pos location, such that decoding past the returned point will quickly arrive at the requested position. */ int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){ int link=-1; ogg_int64_t result=0; ogg_int64_t total=ov_pcm_total(vf,-1); ogg_page og={0,0,0,0}; ogg_packet op={0,0,0,0,0,0}; if(vf->ready_stateseekable)return(OV_ENOSEEK); if(pos<0 || pos>total)return(OV_EINVAL); /* which bitstream section does this pcm offset occur in? */ for(link=vf->links-1;link>=0;link--){ total-=vf->pcmlengths[link*2+1]; if(pos>=total)break; } /* search within the logical bitstream for the page with the highest pcm_pos preceeding (or equal to) pos. There is a danger here; missing pages or incorrect frame number information in the bitstream could make our task impossible. Account for that (it would be an error condition) */ /* new search algorithm by HB (Nicholas Vinen) */ { ogg_int64_t end=vf->offsets[link+1]; ogg_int64_t begin=vf->offsets[link]; ogg_int64_t begintime = vf->pcmlengths[link*2]; ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime; ogg_int64_t target=pos-total+begintime; ogg_int64_t best=begin; while(beginoffset); if(result==OV_EREAD) goto seek_error; if(result<0){ if(bisect<=begin+1) end=begin; /* found it */ else{ if(bisect==0) goto seek_error; bisect-=CHUNKSIZE; if(bisect<=begin)bisect=begin+1; _seek_helper(vf,bisect); } }else{ ogg_int64_t granulepos=ogg_page_granulepos(&og); if(granulepos==-1)continue; if(granuleposoffset; /* raw offset of next page */ begintime=granulepos; if(target-begintime>44100)break; bisect=begin; /* *not* begin + 1 */ }else{ if(bisect<=begin+1) end=begin; /* found it */ else{ if(end==vf->offset){ /* we're pretty close - we'd be stuck in */ end=result; bisect-=CHUNKSIZE; /* an endless loop otherwise. */ if(bisect<=begin)bisect=begin+1; _seek_helper(vf,bisect); }else{ end=result; endtime=granulepos; break; } } } } } } /* found our page. seek to it, update pcm offset. Easier case than raw_seek, don't keep packets preceeding granulepos. */ { /* seek */ result=_seek_helper(vf,best); vf->pcm_offset=-1; if(result) goto seek_error; result=_get_next_page(vf,&og,-1); if(result<0) goto seek_error; if(link!=vf->current_link){ /* Different link; dump entire decode machine */ _decode_clear(vf); vf->current_link=link; vf->current_serialno=ogg_page_serialno(&og); vf->ready_state=STREAMSET; }else{ vorbis_synthesis_restart(&vf->vd); } ogg_stream_reset_serialno(vf->os,vf->current_serialno); ogg_stream_pagein(vf->os,&og); /* pull out all but last packet; the one with granulepos */ while(1){ result=ogg_stream_packetpeek(vf->os,&op); if(result==0){ /* !!! the packet finishing this page originated on a preceeding page. Keep fetching previous pages until we get one with a granulepos or without the 'continued' flag set. Then just use raw_seek for simplicity. */ result=_seek_helper(vf,best); if(result<0) goto seek_error; while(1){ result=_get_prev_page(vf,&og); if(result<0) goto seek_error; if(ogg_page_serialno(&og)==vf->current_serialno && (ogg_page_granulepos(&og)>-1 || !ogg_page_continued(&og))){ return ov_raw_seek(vf,result); } vf->offset=result; } } if(result<0){ result = OV_EBADPACKET; goto seek_error; } if(op.granulepos!=-1){ vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; if(vf->pcm_offset<0)vf->pcm_offset=0; vf->pcm_offset+=total; break; }else result=ogg_stream_packetout(vf->os,NULL); } } } /* verify result */ if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){ result=OV_EFAULT; goto seek_error; } vf->bittrack=0; vf->samptrack=0; ogg_page_release(&og); ogg_packet_release(&op); return(0); seek_error: ogg_page_release(&og); ogg_packet_release(&op); /* dump machine so we're in a known state */ vf->pcm_offset=-1; _decode_clear(vf); return (int)result; } /* seek to a sample offset relative to the decompressed pcm stream returns zero on success, nonzero on failure */ int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){ ogg_packet op={0,0,0,0,0,0}; ogg_page og={0,0,0,0}; int thisblock,lastblock=0; int ret=ov_pcm_seek_page(vf,pos); if(ret<0)return(ret); _make_decode_ready(vf); /* discard leading packets we don't need for the lapping of the position we want; don't decode them */ while(1){ int ret=ogg_stream_packetpeek(vf->os,&op); if(ret>0){ thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); if(thisblock<0){ ogg_stream_packetout(vf->os,NULL); continue; /* non audio packet */ } if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2; if(vf->pcm_offset+((thisblock+ vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break; /* remove the packet from packet queue and track its granulepos */ ogg_stream_packetout(vf->os,NULL); vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with only tracking, no pcm_decode */ vorbis_synthesis_blockin(&vf->vd,&vf->vb); /* end of logical stream case is hard, especially with exact length positioning. */ if(op.granulepos>-1){ int i; /* always believe the stream markers */ vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; if(vf->pcm_offset<0)vf->pcm_offset=0; for(i=0;icurrent_link;i++) vf->pcm_offset+=vf->pcmlengths[i*2+1]; } lastblock=thisblock; }else{ if(ret<0 && ret!=OV_HOLE)break; /* suck in a new page */ if(_get_next_page(vf,&og,-1)<0)break; if(ogg_page_bos(&og))_decode_clear(vf); if(vf->ready_statelinks;link++) if(vf->serialnos[link]==serialno)break; if(link==vf->links) continue; vf->current_link=link; vf->ready_state=STREAMSET; vf->current_serialno=ogg_page_serialno(&og); ogg_stream_reset_serialno(vf->os,serialno); ret=_make_decode_ready(vf); if(ret){ ogg_page_release(&og); ogg_packet_release(&op); return ret; } lastblock=0; } ogg_stream_pagein(vf->os,&og); } } vf->bittrack=0; vf->samptrack=0; /* discard samples until we reach the desired position. Crossing a logical bitstream boundary with abandon is OK. */ while(vf->pcm_offsetpcm_offset; long samples=vorbis_synthesis_pcmout(&vf->vd,NULL); if(samples>target)samples=target; vorbis_synthesis_read(&vf->vd,samples); vf->pcm_offset+=samples; if(samplespcm_offset=ov_pcm_total(vf,-1); /* eof */ } ogg_page_release(&og); ogg_packet_release(&op); return 0; } /* seek to a playback time relative to the decompressed pcm stream returns zero on success, nonzero on failure */ int ov_time_seek(OggVorbis_File *vf,ogg_int64_t milliseconds){ /* translate time to PCM position and call ov_pcm_seek */ int link=-1; ogg_int64_t pcm_total=0; ogg_int64_t time_total=0; if(vf->ready_stateseekable)return(OV_ENOSEEK); if(milliseconds<0)return(OV_EINVAL); /* which bitstream section does this time offset occur in? */ for(link=0;linklinks;link++){ ogg_int64_t addsec = ov_time_total(vf,link); if(millisecondspcmlengths[link*2+1]; } if(link==vf->links)return(OV_EINVAL); /* enough information to convert time offset to pcm offset */ { ogg_int64_t target=pcm_total+(milliseconds-time_total)*vf->vi[link].rate/1000; return(ov_pcm_seek(vf,target)); } } /* page-granularity version of ov_time_seek returns zero on success, nonzero on failure */ int ov_time_seek_page(OggVorbis_File *vf,ogg_int64_t milliseconds){ /* translate time to PCM position and call ov_pcm_seek */ int link=-1; ogg_int64_t pcm_total=0; ogg_int64_t time_total=0; if(vf->ready_stateseekable)return(OV_ENOSEEK); if(milliseconds<0)return(OV_EINVAL); /* which bitstream section does this time offset occur in? */ for(link=0;linklinks;link++){ ogg_int64_t addsec = ov_time_total(vf,link); if(millisecondspcmlengths[link*2+1]; } if(link==vf->links)return(OV_EINVAL); /* enough information to convert time offset to pcm offset */ { ogg_int64_t target=pcm_total+(milliseconds-time_total)*vf->vi[link].rate/1000; return(ov_pcm_seek_page(vf,target)); } } /* tell the current stream offset cursor. Note that seek followed by tell will likely not give the set offset due to caching */ ogg_int64_t ov_raw_tell(OggVorbis_File *vf){ if(vf->ready_stateoffset); } /* return PCM offset (sample) of next PCM sample to be read */ ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){ if(vf->ready_statepcm_offset); } /* return time offset (milliseconds) of next PCM sample to be read */ ogg_int64_t ov_time_tell(OggVorbis_File *vf){ int link=0; ogg_int64_t pcm_total=0; ogg_int64_t time_total=0; if(vf->ready_stateseekable){ pcm_total=ov_pcm_total(vf,-1); time_total=ov_time_total(vf,-1); /* which bitstream section does this time offset occur in? */ for(link=vf->links-1;link>=0;link--){ pcm_total-=vf->pcmlengths[link*2+1]; time_total-=ov_time_total(vf,link); if(vf->pcm_offset>=pcm_total)break; } } return(time_total+(1000*vf->pcm_offset-pcm_total)/vf->vi[link].rate); } /* link: -1) return the vorbis_info struct for the bitstream section currently being decoded 0-n) to request information for a specific bitstream section In the case of a non-seekable bitstream, any call returns the current bitstream. NULL in the case that the machine is not initialized */ vorbis_info *ov_info(OggVorbis_File *vf,int link){ if(vf->seekable){ if(link<0) if(vf->ready_state>=STREAMSET) return vf->vi+vf->current_link; else return vf->vi; else if(link>=vf->links) return NULL; else return vf->vi+link; }else{ return vf->vi; } } vorbis_comment *ov_comment(OggVorbis_File *vf,int link){ if(vf->seekable){ if(link<0) if(vf->ready_state>=STREAMSET) return vf->vc+vf->current_link; else return vf->vc; else if(link>=vf->links) return NULL; else return vf->vc+link; }else{ return vf->vc; } } /* up to this point, everything could more or less hide the multiple logical bitstream nature of chaining from the toplevel application if the toplevel application didn't particularly care. However, at the point that we actually read audio back, the multiple-section nature must surface: Multiple bitstream sections do not necessarily have to have the same number of channels or sampling rate. ov_read returns the sequential logical bitstream number currently being decoded along with the PCM data in order that the toplevel application can take action on channel/sample rate changes. This number will be incremented even for streamed (non-seekable) streams (for seekable streams, it represents the actual logical bitstream index within the physical bitstream. Note that the accessor functions above are aware of this dichotomy). input values: buffer) a buffer to hold packed PCM data for return length) the byte length requested to be placed into buffer return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL) 0) EOF n) number of bytes of PCM actually returned. The below works on a packet-by-packet basis, so the return length is not related to the 'length' passed in, just guaranteed to fit. *section) set to the logical bitstream number */ long ov_read(OggVorbis_File *vf,char *buffer,int bytes_req,int *bitstream){ int i,j; ogg_int32_t **pcm; long samples; if(vf->ready_stateready_state==INITSET){ samples=vorbis_synthesis_pcmout(&vf->vd,&pcm); if(samples)break; } /* suck in another packet */ { int ret=_fetch_and_process_packet(vf,1,1); if(ret==OV_EOF) return(0); if(ret<=0) return(ret); } } if(samples>0){ /* yay! proceed to pack data into the byte buffer */ long channels=ov_info(vf,-1)->channels; if(samples>(bytes_req/(2*channels))) samples=bytes_req/(2*channels); for(i=0;i>9); dest+=channels; } } vorbis_synthesis_read(&vf->vd,samples); vf->pcm_offset+=samples; if(bitstream)*bitstream=vf->current_link; return(samples*2*channels); }else{ return(samples); } } bcmatroska2-5.3.101/mkclean/tremor/vorbisidec.pc.in000066400000000000000000000004551462133141200220760ustar00rootroot00000000000000# libvorbisidec pkg-config source file prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: vorbisidec Description: vorbisidec is the integer Ogg Vorbis library Version: @VERSION@ Requires: ogg Conflicts: Libs: -L${libdir} -lvorbisidec -lm Cflags: -I${includedir} bcmatroska2-5.3.101/mkclean/tremor/win32/000077500000000000000000000000001462133141200177525ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/win32/VS2005/000077500000000000000000000000001462133141200206115ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/win32/VS2005/libtremor/000077500000000000000000000000001462133141200226105ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/win32/VS2005/libtremor/libtremor.vcproj000066400000000000000000000340001462133141200260310ustar00rootroot00000000000000 bcmatroska2-5.3.101/mkclean/tremor/win32/VS2008/000077500000000000000000000000001462133141200206145ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/win32/VS2008/libtremor/000077500000000000000000000000001462133141200226135ustar00rootroot00000000000000bcmatroska2-5.3.101/mkclean/tremor/win32/VS2008/libtremor/libtremor.vcproj000066400000000000000000000341151462133141200260430ustar00rootroot00000000000000 bcmatroska2-5.3.101/mkclean/tremor/window.c000066400000000000000000000041071462133141200204650ustar00rootroot00000000000000/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: window functions ********************************************************************/ #include #include #include "misc.h" #include "window.h" #include "window_lookup.h" const void *_vorbis_window(int type, int left){ switch(type){ case 0: switch(left){ case 32: return vwin64; case 64: return vwin128; case 128: return vwin256; case 256: return vwin512; case 512: return vwin1024; case 1024: return vwin2048; case 2048: return vwin4096; case 4096: return vwin8192; default: return(0); } break; default: return(0); } } void _vorbis_apply_window(ogg_int32_t *d,const void *window_p[2], long *blocksizes, int lW,int W,int nW){ LOOKUP_T *window[2]={window_p[0],window_p[1]}; long n=blocksizes[W]; long ln=blocksizes[lW]; long rn=blocksizes[nW]; long leftbegin=n/4-ln/4; long leftend=leftbegin+ln/2; long rightbegin=n/2+n/4-rn/4; long rightend=rightbegin+rn/2; int i,p; for(i=0;i/corec/tools/coremake/coremake.c with your C compiler. - run coremake from the root of the source : * "coremake.exe vs9_win32" to generate the project files for Visual Studio 2008 * "coremake gcc_linux" to generate the project files for GNU make building with gcc * "coremake gcc_linux_x64" for GNU make building with gcc on Linux 64 bits * "coremake xcode_uni" to generate the project files for XCode for a universal OS X binary * look in the coremake folder for all the platforms supported The Makefile/mkparts.sln will end up in the mkparts folder. You just have to build from there and it will create mkparts(.exe) under /release/ To delete all the project files run "coremake(.exe) clean" from the root of the sources. bcmatroska2-5.3.101/mkparts/configure000066400000000000000000000004561462133141200174600ustar00rootroot00000000000000#!/bin/sh %%BEGIN SCRIPT %%END make -s -C corec/tools/coremake mv -f corec/tools/coremake/coremake . coremake_param=`corec/tools/coremake/system_output.sh` echo "Running ./coremake" $coremake_param ./coremake $coremake_param echo "Now you can run make -C %(PROJECT_NAME) or gmake -C %(PROJECT_NAME)"bcmatroska2-5.3.101/mkparts/default_config.h000066400000000000000000000005301462133141200206670ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE //#define CONFIG_EBML_WRITING #undef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #define HAVE_EBML2 #define CONFIG_MATROSKA2 #define USE_PRECOMPILED_HEADERS #define CONFIG_DEBUGCHECKS #define CONFIG_STDIO #define CONFIG_FILEPOS_64 #define COREMAKE_CONFIG_HELPER //#define CONFIG_DEBUG_LEAKS bcmatroska2-5.3.101/mkparts/mkparts.c000066400000000000000000000311511462133141200173750ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mkparts_stdafx.h" #include "mkparts_project.h" #ifndef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #endif #include "matroska/matroska.h" #include "matroska/matroska_sem.h" static textwriter *StdErr = NULL; static bool_t Split = 1; static bool_t Quiet = 0; static uint8_t Data[8*1024]; // some macros for code readability #define EL_Pos(elt) EBML_ElementPosition((const ebml_element*)elt) #define EL_Int(elt) EBML_IntegerValue((const ebml_integer*)elt) #define EL_Type(elt, type) EBML_ElementIsType((const ebml_element*)elt, type) #define EL_DataSize(elt) EBML_ElementDataSize((const ebml_element*)elt, 1) typedef struct track_info { int Num; int Kind; ebml_string *CodecID; filepos_t DataLength; } track_info; #ifdef TARGET_WIN #include void DebugMessage(const tchar_t* Msg,...) { #if !defined(NDEBUG) || defined(LOGFILE) || defined(LOGTIME) va_list Args; tchar_t Buffer[1024],*s=Buffer; va_start(Args,Msg); vstprintf_s(Buffer,TSIZEOF(Buffer), Msg, Args); va_end(Args); tcscat_s(Buffer,TSIZEOF(Buffer),T("\r\n")); #endif #ifdef LOGTIME { tchar_t timed[1024]; SysTickToString(timed,TSIZEOF(timed),GetTimeTick(),1,1,0); stcatprintf_s(timed,TSIZEOF(timed),T(" %s"),s); s = timed; } #endif #if !defined(NDEBUG) OutputDebugString(s); #endif #if defined(LOGFILE) { static FILE* f=NULL; static char s8[1024]; size_t i; if (!f) #if defined(TARGET_WINCE) { tchar_t DocPath[MAXPATH]; char LogPath[MAXPATH]; charconv *ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); GetDocumentPath(NULL,DocPath,TSIZEOF(DocPath),FTYPE_LOG); // more visible via ActiveSync if (!DocPath[0]) tcscpy_s(DocPath,TSIZEOF(DocPath),T("\\My Documents")); if (!PathIsFolder(NULL,DocPath)) FolderCreate(NULL,DocPath); tcscat_s(DocPath,TSIZEOF(DocPath),T("\\corelog.txt")); CharConvST(ToStr,LogPath,sizeof(LogPath),DocPath); CharConvClose(ToStr); f=fopen(LogPath,"a+b"); if (!f) f=fopen("\\corelog.txt","a+b"); } #else f=fopen("\\corelog.txt","a+b"); #endif for (i=0;s[i];++i) s8[i]=(char)s[i]; s8[i]=0; fputs(s8,f); fflush(f); } #endif } #endif static int OutputError(int ErrCode, const tchar_t *ErrString, ...) { tchar_t Buffer[MAXLINE]; va_list Args; va_start(Args,ErrString); vstprintf_s(Buffer,TSIZEOF(Buffer), ErrString, Args); va_end(Args); TextPrintf(StdErr,T("\rERR%03X: %s\r\n"),ErrCode,Buffer); return -ErrCode; } static int OutputWarning(int ErrCode, const tchar_t *ErrString, ...) { tchar_t Buffer[MAXLINE]; va_list Args; va_start(Args,ErrString); vstprintf_s(Buffer,TSIZEOF(Buffer), ErrString, Args); va_end(Args); TextPrintf(StdErr,T("\rWRN%03X: %s\r\n"),ErrCode,Buffer); return -ErrCode; } typedef struct { filepos_t EbmlHeadPos; filepos_t EbmlSize; filepos_t SegmentPos; filepos_t SegmentSize; } SegmentStart; static void CopyTo(stream *Input, stream *Output, filepos_t StartPos, filepos_t Size) { filepos_t SizeToCopy = Size; size_t readSize; err_t Err; Stream_Seek(Input, StartPos, SEEK_SET); while (SizeToCopy) { Err = Stream_ReadOneOrMore(Input, Data, min(SizeToCopy, sizeof(Data)), &readSize); if (Err==ERR_NONE || Err == ERR_NEED_MORE_DATA) { if (!Quiet) TextWrite(StdErr,T(".")); Stream_Write(Output, Data, readSize, NULL); SizeToCopy -= readSize; } } if (!Quiet) TextWrite(StdErr,T("\r\n")); } int main(int argc, const char *argv[]) { int Result = 0; int ShowUsage = 0; int ShowVersion = 0; parsercontext p; textwriter _StdErr; stream *Input = NULL, *Output = NULL; tchar_t Path[MAXPATHFULL]; ebml_master *EbmlHead = NULL; ebml_parser_context RContext; int i,UpperElement; array SegmentStarts; // Core-C init phase ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); ProjectSettings((nodecontext*)&p); // EBML & Matroska Init MATROSKA_Init((nodecontext*)&p); ArrayInit(&SegmentStarts); StdErr = &_StdErr; memset(StdErr,0,sizeof(_StdErr)); StdErr->Stream = (stream*)NodeSingleton(&p,STDERR_ID); assert(StdErr->Stream!=NULL); for (i=1;i")); TextWrite(StdErr,T("Options:\r\n")); TextWrite(StdErr,T(" --split split concatenated segments into different files\r\n")); TextWrite(StdErr,T(" --quiet don't ouput progress and file info\r\n")); TextWrite(StdErr,T(" --version show the version of mkparts\r\n")); TextWrite(StdErr,T(" --help show this screen\r\n")); } goto exit; } Node_FromStr(&p,Path,TSIZEOF(Path),argv[argc-1]); Input = StreamOpen(&p,Path,SFLAG_RDONLY/*|SFLAG_BUFFERED*/); if (!Input) { TextPrintf(StdErr,T("Could not open file \"%s\" for reading\r\n"),Path); Result = -2; goto exit; } if (!Split) { TextPrintf(StdErr,T("Only the --split option is supported for the moment\r\n")); Result = -3; goto exit; } // parse the source file to determine if it's a Matroska file and determine the location of the key parts RContext.Context = &MATROSKA_ContextStream; RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = NULL; RContext.Profile = 0; EbmlHead = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 0); while (EbmlHead!=NULL) { // parse the list of EBML header+segment start points in memory ebml_master *Segment = NULL; if (EL_Type(EbmlHead, &MATROSKA_ContextSegment)) { Result |= OutputWarning(3,T("Matroska Segment at %") TPRId64 T(" in %s without an EBML header"),EbmlHead->Base.ElementPosition, Path); // TODO: if there is an existing EBML head before in the file, use it // otherwise create an EBML head with best guess } else if (!EL_Type(EbmlHead, &EBML_ContextHead)) { Result |= OutputWarning(3,T("Unknown element %x at %") TPRId64 T(" in %s"), EbmlHead->Base.Context->Id, EbmlHead->Base.ElementPosition, Path); // TODO: if there is an existing EBML head before in the file, use it // otherwise create an EBML head with best guess } if (!Quiet) TextWrite(StdErr,T(".")); do { Segment = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 0); if (EL_Type(Segment, &EBML_ContextHead)) { Result |= OutputWarning(3,T("Found a new EBML header at %") TPRId64 T(" instead of a segment after EBML Header at %") TPRId64 T(" in %s"), Segment->Base.ElementPosition, EbmlHead->Base.ElementPosition, Path); EbmlHead = Segment; } } while (Segment!=NULL && !EL_Type(Segment, &MATROSKA_ContextSegment)); if (Segment!=NULL && EL_Type(Segment, &MATROSKA_ContextSegment) && EbmlHead!=NULL && EL_Type(EbmlHead, &EBML_ContextHead)) { SegmentStart currSegment; currSegment.EbmlHeadPos = EbmlHead->Base.ElementPosition; currSegment.SegmentPos = Segment->Base.ElementPosition; if (EBML_ElementIsFiniteSize(EbmlHead)) currSegment.EbmlSize = EBML_ElementFullSize(EbmlHead, 1); else currSegment.EbmlSize = Segment->Base.ElementPosition - EbmlHead->Base.ElementPosition; // TODO: we should write the proper size in the header if there is enough room NodeDelete(EbmlHead); EbmlHead = EBML_ElementSkipData(Segment, Input, &RContext, NULL, 1); if (EBML_ElementIsFiniteSize(Segment)) currSegment.SegmentSize = EBML_ElementFullSize(Segment, 1); else { // TODO: we should write the proper size in the segment if there is enough room if (EbmlHead!=NULL) currSegment.SegmentSize = EbmlHead->Base.ElementPosition - Segment->Base.ElementPosition; else currSegment.SegmentSize = Stream_Seek(Input,0,SEEK_CUR); } NodeDelete(Segment); ArrayAppend(&SegmentStarts, &currSegment, sizeof(currSegment), 0); } if (EbmlHead==NULL) EbmlHead = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 0); } if (!Quiet) TextWrite(StdErr,T("\r\n")); if (ARRAYCOUNT(SegmentStarts, SegmentStart)==0) Result = OutputError(3,T("No segment found in %s"), Path); else if (ARRAYCOUNT(SegmentStarts, SegmentStart)==1) Result = OutputWarning(3,T("Only one segment found in %s, do nothing"), Path); else { tchar_t OutPath[MAXPATHFULL]; tchar_t Original[MAXLINE], String[MAXLINE], Ext[MAXDATA]; // TODO: copy each segment in a separate file for (i=0; iEbmlHeadPos, seg->EbmlSize+seg->SegmentSize, Path); SplitPath(Path,Original,TSIZEOF(Original),String,TSIZEOF(String),Ext,TSIZEOF(Ext)); if (!Original[0]) OutPath[0] = 0; else { tcscpy_s(OutPath,TSIZEOF(OutPath),Original); AddPathDelimiter(OutPath,TSIZEOF(OutPath)); } if (Ext[0]) stcatprintf_s(OutPath,TSIZEOF(OutPath),T("%s.%d.%s"),String,i,Ext); else stcatprintf_s(OutPath,TSIZEOF(OutPath),T("%d.%s"),i,String); Output = StreamOpen(&p,OutPath,SFLAG_WRONLY|SFLAG_CREATE); if (!Output) { Result = OutputError(5,T("Could not open file \"%s\" for writing\r\n"),OutPath); goto exit; } CopyTo(Input, Output, seg->EbmlHeadPos, seg->EbmlSize); CopyTo(Input, Output, seg->SegmentPos, seg->SegmentSize); StreamClose(Output); } } exit: ArrayClear(&SegmentStarts); if (Input) StreamClose(Input); if (Output) StreamClose(Output); // EBML & Matroska ending MATROSKA_Done((nodecontext*)&p); // Core-C ending StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return Result; } bcmatroska2-5.3.101/mkparts/mkparts.proj000066400000000000000000000003371462133141200201270ustar00rootroot00000000000000CON mkparts { PROJECT_NAME "mkparts" PROJECT_VERSION 0.1.0 PROJECT_VENDOR "Matroska" USE matroska2 SOURCE mkparts.c COMPILE src.br COMPILE configure COMPILE pkg.sh } WORKSPACE mkparts { USE mkparts } bcmatroska2-5.3.101/mkparts/pkg.sh000066400000000000000000000003411462133141200166620ustar00rootroot00000000000000#!/bin/sh %%BEGIN SCRIPT %%END rm -rf %(PROJECT_NAME)-%(PROJECT_VERSION) branch src.br rm -rf %(PROJECT_NAME)-%(PROJECT_VERSION).tar.bz2 tar cvfj %(PROJECT_NAME)-%(PROJECT_VERSION).tar.bz2 %(PROJECT_NAME)-%(PROJECT_VERSION) bcmatroska2-5.3.101/mkparts/src.br000066400000000000000000000015501462133141200166640ustar00rootroot00000000000000# corec %(!ROOTPATH)corec %(PROJECT_NAME)-%(PROJECT_VERSION)/corec # libebml2 %(!ROOTPATH)libebml2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libebml2 # libmatroska2 %(!ROOTPATH)libmatroska2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libmatroska2 # %(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME) %(PROJECT_NAME)-%(PROJECT_VERSION)/%(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME)/default_config.h %(PROJECT_NAME)-%(PROJECT_VERSION)/config.h %(!ROOTPATH)%(PROJECT_NAME)/ChangeLog.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ChangeLog.txt %(!ROOTPATH)%(PROJECT_NAME)/ReadMe.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ReadMe.txt %(!ROOTPATH)root.proj %(PROJECT_NAME)-%(PROJECT_VERSION)/root.proj %(¯!BASE)configure %(PROJECT_NAME)-%(PROJECT_VERSION)/configure %(!ROOTPATH)corec/tools/coremake/coremake - *.br - *.vs - Makefile - *.vcproj - *.sln - *_project.h - *_stdafx.* - bcmatroska2-5.3.101/mkvalidator/000077500000000000000000000000001462133141200164035ustar00rootroot00000000000000bcmatroska2-5.3.101/mkvalidator/ChangeLog.txt000066400000000000000000000117571462133141200210060ustar00rootroot000000000000002012-xx-xx version 0.4.2: - add support for Matroska v4 elements like CueDuration and CueRelativePosition 2012-08-26 version 0.4.1: - handle non-latin command-line characters on windows - detect elements with bogus sizes 2012-05-13 version 0.4.0: - better differentiation between errors (will not play/not following specs) and warnings - don't warn about a Cluster not starting with a keyframe if it has no keyframe 2011-09-25 version 0.3.7: - allow TrueHD to have non-keyframes in the audio stream - issue a warning when an aspect ratio unit seems to be in pixel values 2011-08-15 version 0.3.6: - verify that the audio sampling freq is not 0 2011-07-10 version 0.3.5: - fix the keyframe detection for WebM alt-ref frames (0 duration = non keyframe) - More detailed error messages 2011-04-03 version 0.3.4: - FlagForced, BlockVirtual and Slices should not be found multiple times at their level - VideoFrameRate is not used in any profile - add some support for some experimental elements from the generated specs 2011-03-06 version 0.3.3: - add support for Matroska v3 - fix some mismatches with the specifications (especially WebM) 2010-12-12 version 0.3.2: - header/zlib compression is not allowed in WebM 2010-11-21 version 0.3.1: - fix some files reported as fine even though it contains hidden junk (not seen by libebml2 so far) - fix return an error code when the Cue entries was reported as broken - a warning on the aspect ratio should not result in an error code 2010-11-14 version 0.3.0: - allow StereoMode for WebM - internal code shuffling 2010-11-01 version 0.2.4: - add a --quiet option 2010-09-02 version 0.2.3: - fix the UNIX source package 2010-08-22 version 0.2.2: - better error reporting for damaged files - fix a potential crash when the last level1 encountered wasn't a legal element - check the CRC-32 in the EBML head too - don't crash when a Block with an invalid ID is found 2010-08-14 version 0.2.1: - check if the CRC-32 is valid - don't complain about a missing Cue if there is only one Cluster 2010-08-05 version 0.2.0: - add --help and --version CLI options - verify that the cropping values are correct - verify that display values of 0 are not used - check that the codec IDs are uppercase - check that codec IDs are in the format (A|V|S|B)_xxx - a display value can't be implied if it's not in pixels 2010-07-19 version 0.1.12: - fix a crash when the DisplayWidth/DisplayHeight was not written in the file - check that the Segment size matches the size of the data inside - reject files that don't have an EBML header 2010-07-17 version 0.1.11: - bootstrap.sh should now call the correct coremake config depending on the host platform - rename boostrap.sh to configure - read the track info even if there were errors before in the file - check that track attachment links point to valid attachments - add an option to accept DivX extensions (TrickTrack and font start/stop) with --divx 2010-07-12 version 0.1.10: - display the 64 bits integers correctly on all platforms - output a warning/error when incorrect aspect ratio values are detected - output a warning when there is more than 4 KB of void data 2010-06-24 version 0.1.9: - add a --details parameter to show the various tracks and bitrate of valid files - add a warning when a track is defined but has no frame defined - verify that timecodes of clusters are increasing - fix keyframe checking of the first video frame of each cluster 2010-05-27 version 0.1.8: - add a --live parameter to only check errors and warnings relevant to live streams - fix some default values in chapters - fix the end of reading of a master when the size is unknown/infinite - adjust the severe/benign warnings and errors 2010-05-23 version 0.1.7: - very that the Cluster PrevSize and Position are valid - check when unique elements are found twice - warn when a secondary SeekHead is found (useless) - make sure audio frames are all keyframes (no known codec so far are not) - warn when a Cluster's first video track is not a keyframe - fix issues with live streams - warn when a top level element is not present in the main SeekHead - disable warnings with --no-warn 2010-05-20 version 0.1.6: - unobfuscate the 'webm' and 'V_VP8' strings - fix a crash when reading Sorenson Squeeze files (Ebml Void in the header) 2010-05-18 version 0.1.5: - new package due to a bug in libmatroska2 0.9.6 2010-05-17 version 0.1.4: - better profile handling 2010-05-16 version 0.1.3: - verify that no lacing is used when lacing is disabled in the Track 2010-05-15 version 0.1.2: - check the Cue entries for erroneous entries - check if the Track entries are properly defined 2010-05-14 version 0.1.1: - check the validity of (primary and secondary) SeekHead entries 2010-05-13 version 0.1.0: - basic EBML/mandatory/profile checking bcmatroska2-5.3.101/mkvalidator/ReadMe.txt000066400000000000000000000030151462133141200203000ustar00rootroot00000000000000mkvalidator is a command line tool to verify Matroska files for spec conformance. It currently checks for missing mandatory element, EBML "junk" data (use of unknown IDs), bad track or cues (index) entries, and profile violation (like a v1 file using v2 features). ** LICENSE ** The program is licensed with the BSD license. So you can modify it in any way you want. However we ask that you generously give back your enhancements to the community if you think it can help. Contact: slhomme@matroska.org mkclean depends on libebml2 (BSD) and libmatroska2 (BSD) that themselves rely on Core-C (BSD) which adds an object API on top of the C language. ** BUILDING ** To build mkvalidator you have to build coremake first: You can either run ./configure on Linux/OS X or - Just compile /corec/tools/coremake/coremake.c with your C compiler. - run coremake from the root of the source : * "coremake.exe vs9_win32" to generate the project files for Visual Studio 2008 * "coremake gcc_linux" to generate the project files for GNU make building with gcc * "coremake gcc_linux_x64" for GNU make building with gcc on Linux 64 bits * "coremake xcode_uni" to generate the project files for XCode for a universal OS X binary * look in the coremake folder for all the platforms supported The Makefile/mkvalidator.sln will end up in the mkvalidator folder. You just have to build from there and it will create mkvalidator(.exe) under /release/ To delete all the project files run "coremake(.exe) clean" from the root of the sources. bcmatroska2-5.3.101/mkvalidator/configure000066400000000000000000000004561462133141200203140ustar00rootroot00000000000000#!/bin/sh %%BEGIN SCRIPT %%END make -s -C corec/tools/coremake mv -f corec/tools/coremake/coremake . coremake_param=`corec/tools/coremake/system_output.sh` echo "Running ./coremake" $coremake_param ./coremake $coremake_param echo "Now you can run make -C %(PROJECT_NAME) or gmake -C %(PROJECT_NAME)"bcmatroska2-5.3.101/mkvalidator/default_config.h000066400000000000000000000005301462133141200215230ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE //#define CONFIG_EBML_WRITING #undef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #define HAVE_EBML2 #define CONFIG_MATROSKA2 #define USE_PRECOMPILED_HEADERS #define CONFIG_DEBUGCHECKS #define CONFIG_STDIO #define CONFIG_FILEPOS_64 #define COREMAKE_CONFIG_HELPER //#define CONFIG_DEBUG_LEAKS bcmatroska2-5.3.101/mkvalidator/mkvalidator.c000066400000000000000000001664751462133141200211070ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2010-2012, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mkvalidator_stdafx.h" #include "mkvalidator_project.h" #ifndef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #endif #include "matroska/matroska.h" #include "matroska/matroska_sem.h" /*! * \todo verify the track timecode scale is not null * \todo verify that the size of frames inside a lace is legit (ie the remaining size for the last must be > 0) * \todo verify that items with a limited set of values don't use other values * \todo verify that timecodes for each track are increasing (for keyframes and p frames) * \todo optionally show the use of deprecated elements * \todo support concatenated segments */ static textwriter *StdErr = NULL; static ebml_master *RSegmentInfo = NULL, *RTrackInfo = NULL, *RChapters = NULL, *RTags = NULL, *RCues = NULL, *RAttachments = NULL, *RSeekHead = NULL, *RSeekHead2 = NULL; static array RClusters; static array Tracks; static size_t TrackMax=0; static bool_t Warnings = 1; static bool_t Live = 0; static bool_t Details = 0; static bool_t DivX = 0; static bool_t Quiet = 0; static timecode_t MinTime = INVALID_TIMECODE_T, MaxTime = INVALID_TIMECODE_T; static timecode_t ClusterTime = INVALID_TIMECODE_T; // some macros for code readability #define EL_Pos(elt) EBML_ElementPosition((const ebml_element*)elt) #define EL_Int(elt) EBML_IntegerValue((const ebml_integer*)elt) #define EL_Type(elt, type) EBML_ElementIsType((const ebml_element*)elt, type) #define EL_DataSize(elt) EBML_ElementDataSize((const ebml_element*)elt, 1) typedef struct track_info { int Num; int Kind; filepos_t DataLength; ebml_string *CodecID; } track_info; #ifdef TARGET_WIN #include void DebugMessage(const tchar_t* Msg,...) { #if !defined(NDEBUG) || defined(LOGFILE) || defined(LOGTIME) va_list Args; tchar_t Buffer[1024],*s=Buffer; va_start(Args,Msg); vstprintf_s(Buffer,TSIZEOF(Buffer), Msg, Args); va_end(Args); tcscat_s(Buffer,TSIZEOF(Buffer),T("\r\n")); #endif #ifdef LOGTIME { tchar_t timed[1024]; SysTickToString(timed,TSIZEOF(timed),GetTimeTick(),1,1,0); stcatprintf_s(timed,TSIZEOF(timed),T(" %s"),s); s = timed; } #endif #if !defined(NDEBUG) OutputDebugString(s); #endif #if defined(LOGFILE) { static FILE* f=NULL; static char s8[1024]; size_t i; if (!f) #if defined(TARGET_WINCE) { tchar_t DocPath[MAXPATH]; char LogPath[MAXPATH]; charconv *ToStr = CharConvOpen(NULL,CHARSET_DEFAULT); GetDocumentPath(NULL,DocPath,TSIZEOF(DocPath),FTYPE_LOG); // more visible via ActiveSync if (!DocPath[0]) tcscpy_s(DocPath,TSIZEOF(DocPath),T("\\My Documents")); if (!PathIsFolder(NULL,DocPath)) FolderCreate(NULL,DocPath); tcscat_s(DocPath,TSIZEOF(DocPath),T("\\corelog.txt")); CharConvST(ToStr,LogPath,sizeof(LogPath),DocPath); CharConvClose(ToStr); f=fopen(LogPath,"a+b"); if (!f) f=fopen("\\corelog.txt","a+b"); } #else f=fopen("\\corelog.txt","a+b"); #endif for (i=0;s[i];++i) s8[i]=(char)s[i]; s8[i]=0; fputs(s8,f); fflush(f); } #endif } #endif static const tchar_t *GetProfileName(size_t ProfileNum) { static const tchar_t *Profile[7] = {T("unknown"), T("matroska v1"), T("matroska v2"), T("matroska v3"), T("webm"), T("matroska+DivX"), T("matroska v4")}; switch (ProfileNum) { default: return Profile[0]; case PROFILE_MATROSKA_V1: return Profile[1]; case PROFILE_MATROSKA_V2: return Profile[2]; case PROFILE_MATROSKA_V3: return Profile[3]; case PROFILE_WEBM: return Profile[4]; case PROFILE_DIVX: return Profile[5]; case PROFILE_MATROSKA_V4: return Profile[6]; } } static int OutputError(int ErrCode, const tchar_t *ErrString, ...) { tchar_t Buffer[MAXLINE]; va_list Args; va_start(Args,ErrString); vstprintf_s(Buffer,TSIZEOF(Buffer), ErrString, Args); va_end(Args); TextPrintf(StdErr,T("\rERR%03X: %s\r\n"),ErrCode,Buffer); return -ErrCode; } static void OutputWarning(int ErrCode, const tchar_t *ErrString, ...) { if (Warnings) { tchar_t Buffer[MAXLINE]; va_list Args; va_start(Args,ErrString); vstprintf_s(Buffer,TSIZEOF(Buffer), ErrString, Args); va_end(Args); TextPrintf(StdErr,T("\rWRN%03X: %s\r\n"),ErrCode,Buffer); } } static filepos_t CheckUnknownElements(ebml_element *Elt) { tchar_t IdStr[32], String[MAXPATH]; ebml_element *SubElt; filepos_t VoidAmount = 0; for (SubElt = EBML_MasterChildren(Elt); SubElt; SubElt = EBML_MasterNext(SubElt)) { if (Node_IsPartOf(SubElt,EBML_DUMMY_ID)) { EBML_ElementGetName(Elt,String,TSIZEOF(String)); EBML_IdToString(IdStr,TSIZEOF(IdStr),EBML_ElementClassID(SubElt)); OutputWarning(12,T("Unknown element in %s %s at %") TPRId64 T(" (size %") TPRId64 T(" total %") TPRId64 T(")"),String,IdStr,EL_Pos(SubElt),EL_DataSize(SubElt), EBML_ElementFullSize(SubElt, 0)); } else if (Node_IsPartOf(SubElt,EBML_VOID_CLASS)) { VoidAmount = EBML_ElementFullSize(SubElt,0); } else if (Node_IsPartOf(SubElt,EBML_MASTER_CLASS)) { VoidAmount += CheckUnknownElements(SubElt); } } return VoidAmount; } static int64_t gcd(int64_t a, int64_t b) { for (;;) { int64_t c = a % b; if(!c) return b; a = b; b = c; } } static int CheckVideoTrack(ebml_master *Track, int TrackNum, int ProfileNum) { int Result = 0; ebml_element *Elt, *PixelW, *PixelH; ebml_integer *Unit; ebml_master *Video; Video = (ebml_master*)EBML_MasterFindChild(Track,&MATROSKA_ContextVideo); if (!Video) Result = OutputError(0xE0,T("Video track at %") TPRId64 T(" is missing a Video element"),EL_Pos(Track)); // check the DisplayWidth and DisplayHeight are correct else { int64_t DisplayW = 0,DisplayH = 0; PixelW = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelWidth); if (!PixelW) Result |= OutputError(0xE1,T("Video track #%d at %") TPRId64 T(" has no pixel width"),TrackNum,EL_Pos(Track)); PixelH = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelHeight); if (!PixelH) Result |= OutputError(0xE2,T("Video track #%d at %") TPRId64 T(" has no pixel height"),TrackNum,EL_Pos(Track)); Unit = (ebml_integer*)EBML_MasterGetChild(Video,&MATROSKA_ContextDisplayUnit); assert(Unit!=NULL); Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextDisplayWidth); if (Elt) DisplayW = EL_Int(Elt); else if (EL_Int(Unit)!=MATROSKA_DISPLAY_UNIT_PIXEL) Result |= OutputError(0xE2,T("Video track #%d at %") TPRId64 T(" has an implied non pixel width"),TrackNum,EL_Pos(Track)); else if (PixelW) DisplayW = EL_Int(PixelW); Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextDisplayHeight); if (Elt) DisplayH = EL_Int(Elt); else if (EL_Int(Unit)!=MATROSKA_DISPLAY_UNIT_PIXEL) Result |= OutputError(0xE2,T("Video track #%d at %") TPRId64 T(" has an implied non pixel height"),TrackNum,EL_Pos(Track)); else if (PixelH) DisplayH = EL_Int(PixelH); if (DisplayH==0) Result |= OutputError(0xE7,T("Video track #%d at %") TPRId64 T(" has a null display height"),TrackNum,EL_Pos(Track)); if (DisplayW==0) Result |= OutputError(0xE7,T("Video track #%d at %") TPRId64 T(" has a null display width"),TrackNum,EL_Pos(Track)); if (EL_Int(Unit)==MATROSKA_DISPLAY_UNIT_PIXEL && PixelW && PixelH) { // check if the pixel sizes appear valid if (DisplayW < EL_Int(PixelW) && DisplayH < EL_Int(PixelH)) { int Serious = gcd(DisplayW,DisplayH)==1; // the DAR values were reduced as much as possible if (DisplayW*EL_Int(PixelH) == DisplayH*EL_Int(PixelW)) Serious++; // same aspect ratio as the source if (8*DisplayW <= EL_Int(PixelW) && 8*DisplayH <= EL_Int(PixelH)) Serious+=2; // too much shrinking compared to the original pixels if (ProfileNum!=PROFILE_WEBM) --Serious; // in Matroska it's tolerated as it's been operating like that for a while if (Serious>2) Result |= OutputError(0xE3,T("The output pixels for Video track #%d seem wrong %") TPRId64 T("x%") TPRId64 T("px from %") TPRId64 T("x%") TPRId64,TrackNum,DisplayW,DisplayH,EL_Int(PixelW),EL_Int(PixelH)); else if (Serious) OutputWarning(0xE3,T("The output pixels for Video track #%d seem wrong %") TPRId64 T("x%") TPRId64 T("px from %") TPRId64 T("x%") TPRId64,TrackNum,DisplayW,DisplayH,EL_Int(PixelW),EL_Int(PixelH)); } } if (EL_Int(Unit)==MATROSKA_DISPLAY_UNIT_DAR) { // crop values should never exist Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextPixelCropTop); if (Elt) Result |= OutputError(0xE4,T("Video track #%d is using unconstrained aspect ratio and has top crop at %") TPRId64,TrackNum,EL_Pos(Elt)); Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextPixelCropBottom); if (Elt) Result |= OutputError(0xE4,T("Video track #%d is using unconstrained aspect ratio and has bottom crop at %") TPRId64,TrackNum,EL_Pos(Elt)); Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextPixelCropLeft); if (Elt) Result |= OutputError(0xE4,T("Video track #%d is using unconstrained aspect ratio and has left crop at %") TPRId64,TrackNum,EL_Pos(Elt)); Elt = EBML_MasterFindChild(Video,&MATROSKA_ContextPixelCropRight); if (Elt) Result |= OutputError(0xE4,T("Video track #%d is using unconstrained aspect ratio and has right crop at %") TPRId64,TrackNum,EL_Pos(Elt)); if (PixelW && DisplayW == EL_Int(PixelW)) OutputWarning(0xE7,T("DisplayUnit seems to be pixels not aspect-ratio for Video track #%d %") TPRId64 T("px width from %") TPRId64,TrackNum,DisplayW,EL_Int(PixelW)); if (PixelH && DisplayH == EL_Int(PixelH)) OutputWarning(0xE7,T("DisplayUnit seems to be pixels not aspect-ratio for Video track #%d %") TPRId64 T("px height from %") TPRId64,TrackNum,DisplayH,EL_Int(PixelH)); } else { // crop values should be less than the extended value PixelW = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelCropTop); PixelH = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelCropBottom); if (EL_Int(PixelW) + EL_Int(PixelH) >= DisplayH) Result |= OutputError(0xE5,T("Video track #%d is cropping too many vertical pixels %") TPRId64 T(" vs %") TPRId64 T(" + %") TPRId64,TrackNum, DisplayH, EL_Int(PixelW), EL_Int(PixelH)); PixelW = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelCropLeft); PixelH = EBML_MasterGetChild(Video,&MATROSKA_ContextPixelCropRight); if (EL_Int(PixelW) + EL_Int(PixelH) >= DisplayW) Result |= OutputError(0xE6,T("Video track #%d is cropping too many horizontal pixels %") TPRId64 T(" vs %") TPRId64 T(" + %") TPRId64,TrackNum, DisplayW, EL_Int(PixelW), EL_Int(PixelH)); } } return Result; } static int CheckTracks(ebml_master *Tracks, int ProfileNum) { ebml_master *Track; ebml_element *TrackType, *TrackNum, *Elt, *Elt2; ebml_string *CodecID; tchar_t CodecName[MAXPATH],String[MAXPATH]; int Result = 0; Track = (ebml_master*)EBML_MasterFindChild(Tracks, &MATROSKA_ContextTrackEntry); while (Track) { // check if the codec is valid for the profile TrackNum = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackNumber); if (TrackNum) { TrackType = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackType); CodecID = (ebml_string*)EBML_MasterGetChild(Track, &MATROSKA_ContextCodecID); if (!CodecID) Result |= OutputError(0x300,T("Track #%d has no CodecID defined"),(int)EL_Int(TrackNum)); else if (!TrackType) Result |= OutputError(0x301,T("Track #%d has no type defined"),(int)EL_Int(TrackNum)); else { EBML_StringGet(CodecID,CodecName,TSIZEOF(CodecName)); tcscpy_s(String,TSIZEOF(String),CodecName); if (tcscmp(tcsupr(String),CodecName)!=0) OutputWarning(0x307,T("Track #%d codec '%s' should be uppercase"),(int)EL_Int(TrackNum),CodecName); if (tcslen(String)<3 || String[1]!='_' || (String[0]!='A' && String[0]!='V' && String[0]!='S' && String[0]!='B')) OutputWarning(0x308,T("Track #%d codec '%s' doesn't appear to be valid"),(int)EL_Int(TrackNum),String); // check that the audio frequencies are not 0 if (EL_Int(TrackType) == TRACK_TYPE_AUDIO) { Elt = EBML_MasterGetChild(Track, &MATROSKA_ContextAudio); if (Elt==NULL) Result |= OutputError(0x309,T("Audio Track #%d has no audio settings"),(int)EL_Int(TrackNum)); else { Elt2 = EBML_MasterFindChild(Elt, &MATROSKA_ContextOutputSamplingFrequency); if (Elt2 && EBML_FloatValue((ebml_float*)Elt2)==0) Result |= OutputError(0x30A,T("Audio Track #%d has a null output sampling frequency"),(int)EL_Int(TrackNum)); Elt2 = EBML_MasterFindChild(Elt, &MATROSKA_ContextSamplingFrequency); if (Elt2 && EBML_FloatValue((ebml_float*)Elt2)==0) Result |= OutputError(0x30A,T("Audio Track #%d has a null sampling frequency"),(int)EL_Int(TrackNum)); } } if (ProfileNum==PROFILE_WEBM) { if (EL_Int(TrackType) != TRACK_TYPE_AUDIO && EL_Int(TrackType) != TRACK_TYPE_VIDEO) Result |= OutputError(0x302,T("Track #%d type %d not supported for profile '%s'"),(int)EL_Int(TrackNum),(int)EL_Int(TrackType),GetProfileName(ProfileNum)); if (CodecID) { if (EL_Int(TrackType) == TRACK_TYPE_AUDIO) { if (!tcsisame_ascii(CodecName,T("A_VORBIS"))) Result |= OutputError(0x303,T("Track #%d codec %s not supported for profile '%s'"),(int)EL_Int(TrackNum),CodecName,GetProfileName(ProfileNum)); } else if (EL_Int(TrackType) == TRACK_TYPE_VIDEO) { if (!tcsisame_ascii(CodecName,T("V_VP8"))) Result |= OutputError(0x304,T("Track #%d codec %s not supported for profile '%s'"),(int)EL_Int(TrackNum),CodecName,GetProfileName(ProfileNum)); } } } } } // check if the AttachmentLink values match existing attachments TrackType = EBML_MasterFindChild(Track, &MATROSKA_ContextAttachmentLink); while (TrackType) { if (!RAttachments) { if (TrackNum) Result |= OutputError(0x305,T("Track #%d has attachment links but not attachments in the file"),(int)EL_Int(TrackNum)); else Result |= OutputError(0x305,T("Track at %") TPRId64 T(" has attachment links but not attachments in the file"),EL_Pos(Track)); break; } for (Elt=EBML_MasterChildren(RAttachments);Elt;Elt=EBML_MasterNext(Elt)) { if (EL_Type(Elt, &MATROSKA_ContextAttachedFile)) { Elt2 = EBML_MasterFindChild((ebml_master*)Elt, &MATROSKA_ContextFileUID); if (Elt2 && EL_Int(Elt2) == EL_Int(TrackType)) break; } } if (!Elt) { if (TrackNum) Result |= OutputError(0x306,T("Track #%d attachment link UID 0x%") TPRIx64 T(" not found in attachments"),(int)EL_Int(TrackNum),EL_Int(TrackType)); else Result |= OutputError(0x306,T("Track at %") TPRId64 T(" attachment link UID 0x%") TPRIx64 T(" not found in attachments"),EL_Pos(Track),EL_Int(TrackType)); } TrackType = EBML_MasterFindNextElt(Track, TrackType, 0, 0); } Track = (ebml_master*)EBML_MasterFindNextElt(Tracks, (ebml_element*)Track, 0, 0); } return Result; } struct profile_check { int *Result; const ebml_element *Parent; const tchar_t *EltName; int ProfileMask; }; static bool_t ProfileCallback(struct profile_check *check, int type, const tchar_t *ClassName, const ebml_element* Elt) { if (type==MASTER_CHECK_PROFILE_INVALID) *check->Result |= OutputError(0x201,T("Invalid '%s' for profile '%s' in %s at %") TPRId64,ClassName,GetProfileName(check->ProfileMask),check->EltName,EL_Pos(check->Parent)); else if (type==MASTER_CHECK_MISSING_MANDATORY) *check->Result |= OutputError(0x200,T("Missing element '%s' in %s at %") TPRId64, ClassName,check->EltName,EL_Pos(check->Parent)); else if (type==MASTER_CHECK_MULTIPLE_UNIQUE) *check->Result |= OutputError(0x202,T("Unique element '%s' in %s at %") TPRId64 T(" found more than once at %") TPRId64, ClassName,check->EltName,EL_Pos(check->Parent),EL_Pos(Elt)); return 0; // don't remove anything } static int CheckProfileViolation(ebml_element *Elt, int ProfileMask) { int Result = 0; tchar_t String[MAXPATH]; ebml_element *SubElt; struct profile_check Checker; if (Node_IsPartOf(Elt,EBML_MASTER_CLASS)) { EBML_ElementGetName(Elt,String,TSIZEOF(String)); if (!EBML_MasterIsChecksumValid((ebml_master*)Elt)) Result |= OutputError(0x203,T("Invalid checksum for element '%s' at %") TPRId64,String,EL_Pos(Elt)); Checker.EltName = String; Checker.ProfileMask = ProfileMask; Checker.Parent = Elt; Checker.Result = &Result; EBML_MasterCheckContext((ebml_master*)Elt, ProfileMask, ProfileCallback, &Checker); for (SubElt = EBML_MasterChildren(Elt); SubElt; SubElt = EBML_MasterNext(SubElt)) if (Node_IsPartOf(SubElt,EBML_MASTER_CLASS)) Result |= CheckProfileViolation(SubElt,ProfileMask); } return Result; } static int CheckSeekHead(ebml_master *SeekHead) { int Result = 0; matroska_seekpoint *RLevel1 = (matroska_seekpoint*)EBML_MasterFindChild(SeekHead, &MATROSKA_ContextSeek); bool_t BSegmentInfo = 0, BTrackInfo = 0, BCues = 0, BTags = 0, BChapters = 0, BAttachments = 0, BSecondSeek = 0; while (RLevel1) { filepos_t Pos = MATROSKA_MetaSeekAbsolutePos(RLevel1); fourcc_t SeekId = MATROSKA_MetaSeekID(RLevel1); tchar_t IdString[32]; EBML_IdToString(IdString,TSIZEOF(IdString),SeekId); if (Pos == INVALID_FILEPOS_T) Result |= OutputError(0x60,T("The SeekPoint at %") TPRId64 T(" has an unknown position (ID %s)"),EL_Pos(RLevel1),IdString); else if (SeekId==0) Result |= OutputError(0x61,T("The SeekPoint at %") TPRId64 T(" has no ID defined (position %") TPRId64 T(")"),EL_Pos(RLevel1),Pos); else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextInfo)) { if (!RSegmentInfo) Result |= OutputError(0x62,T("The SeekPoint at %") TPRId64 T(" references an unknown SegmentInfo at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RSegmentInfo) != Pos) Result |= OutputError(0x63,T("The SeekPoint at %") TPRId64 T(" references a SegmentInfo at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RSegmentInfo)); BSegmentInfo = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextTracks)) { if (!RTrackInfo) Result |= OutputError(0x64,T("The SeekPoint at %") TPRId64 T(" references an unknown TrackInfo at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RTrackInfo) != Pos) Result |= OutputError(0x65,T("The SeekPoint at %") TPRId64 T(" references a TrackInfo at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RTrackInfo)); BTrackInfo = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextCues)) { if (!RCues) Result |= OutputError(0x66,T("The SeekPoint at %") TPRId64 T(" references an unknown Cues at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RCues) != Pos) Result |= OutputError(0x67,T("The SeekPoint at %") TPRId64 T(" references a Cues at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RCues)); BCues = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextTags)) { if (!RTags) Result |= OutputError(0x68,T("The SeekPoint at %") TPRId64 T(" references an unknown Tags at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RTags) != Pos) Result |= OutputError(0x69,T("The SeekPoint at %") TPRId64 T(" references a Tags at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RTags)); BTags = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextChapters)) { if (!RChapters) Result |= OutputError(0x6A,T("The SeekPoint at %") TPRId64 T(" references an unknown Chapters at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RChapters) != Pos) Result |= OutputError(0x6B,T("The SeekPoint at %") TPRId64 T(" references a Chapters at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RChapters)); BChapters = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextAttachments)) { if (!RAttachments) Result |= OutputError(0x6C,T("The SeekPoint at %") TPRId64 T(" references an unknown Attachments at %") TPRId64,EL_Pos(RLevel1),Pos); else if (EL_Pos(RAttachments) != Pos) Result |= OutputError(0x6D,T("The SeekPoint at %") TPRId64 T(" references a Attachments at wrong position %") TPRId64 T(" (real %") TPRId64 T(")"),EL_Pos(RLevel1),Pos,EL_Pos(RAttachments)); BAttachments = 1; } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextSeekHead)) { if (EL_Pos(SeekHead) == Pos) Result |= OutputError(0x6E,T("The SeekPoint at %") TPRId64 T(" references references its own SeekHead"),EL_Pos(RLevel1)); else if (SeekHead == RSeekHead) { if (!RSeekHead2) Result |= OutputError(0x6F,T("The SeekPoint at %") TPRId64 T(" references an unknown secondary SeekHead at %") TPRId64,EL_Pos(RLevel1),Pos); BSecondSeek = 1; } else if (SeekHead == RSeekHead2 && Pos!=EL_Pos(RSeekHead)) Result |= OutputError(0x70,T("The SeekPoint at %") TPRId64 T(" references an unknown extra SeekHead at %") TPRId64,EL_Pos(RLevel1),Pos); } else if (MATROSKA_MetaSeekIsClass(RLevel1, &MATROSKA_ContextCluster)) { ebml_element **Cluster; for (Cluster = ARRAYBEGIN(RClusters,ebml_element*);Cluster != ARRAYEND(RClusters,ebml_element*); ++Cluster) { if (EL_Pos(*Cluster) == Pos) break; } if (Cluster == ARRAYEND(RClusters,ebml_element*) && Cluster != ARRAYBEGIN(RClusters,ebml_element*)) Result |= OutputError(0x71,T("The SeekPoint at %") TPRId64 T(" references a Cluster not found at %") TPRId64,EL_Pos(RLevel1),Pos); } else OutputWarning(0x860,T("The SeekPoint at %") TPRId64 T(" references an element that is not a known level 1 ID %s at %") TPRId64 T(")"),EL_Pos(RLevel1),IdString,Pos); RLevel1 = (matroska_seekpoint*)EBML_MasterFindNextElt(SeekHead, (ebml_element*)RLevel1, 0, 0); } if (SeekHead == RSeekHead) { if (!BSegmentInfo && RSegmentInfo) OutputWarning(0x861,T("The SegmentInfo is not referenced in the main SeekHead")); if (!BTrackInfo && RTrackInfo) OutputWarning(0x861,T("The TrackInfo is not referenced in the main SeekHead")); if (!BCues && RCues) OutputWarning(0x861,T("The Cues is not referenced in the main SeekHead")); if (!BTags && RTags) OutputWarning(0x861,T("The Tags is not referenced in the main SeekHead")); if (!BChapters && RChapters) OutputWarning(0x861,T("The Chapters is not referenced in the main SeekHead")); if (!BAttachments && RAttachments) OutputWarning(0x861,T("The Attachments is not referenced in the main SeekHead")); if (!BSecondSeek && RSeekHead2) OutputWarning(0x861,T("The secondary SeekHead is not referenced in the main SeekHead")); } return Result; } static void LinkClusterBlocks(void) { matroska_cluster **Cluster; for (Cluster=ARRAYBEGIN(RClusters,matroska_cluster*);Cluster!=ARRAYEND(RClusters,matroska_cluster*);++Cluster) MATROSKA_LinkClusterBlocks(*Cluster, RSegmentInfo, RTrackInfo, 1); } static bool_t TrackIsLaced(int16_t TrackNum) { ebml_element *TrackData; ebml_master *Track = (ebml_master*)EBML_MasterFindChild(RTrackInfo, &MATROSKA_ContextTrackEntry); while (Track) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackNumber); if (EL_Int(TrackData) == TrackNum) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextFlagLacing); return EL_Int(TrackData) != 0; } Track = (ebml_master*)EBML_MasterFindNextElt(RTrackInfo, (ebml_element*)Track, 0, 0); } return 1; } static bool_t TrackIsVideo(int16_t TrackNum) { ebml_element *TrackData; ebml_master *Track = (ebml_master*)EBML_MasterFindChild(RTrackInfo, &MATROSKA_ContextTrackEntry); while (Track) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackNumber); if (EL_Int(TrackData) == TrackNum) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackType); return EL_Int(TrackData) == TRACK_TYPE_VIDEO; } // look for TrackNum in the next Track Track = (ebml_master*)EBML_MasterFindNextElt(RTrackInfo, (ebml_element*)Track, 0, 0); } return 0; } static bool_t TrackNeedsKeyframe(int16_t TrackNum) { ebml_element *TrackData; ebml_master *Track = (ebml_master*)EBML_MasterFindChild(RTrackInfo, &MATROSKA_ContextTrackEntry); while (Track) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackNumber); if (EL_Int(TrackData) == TrackNum) { TrackData = EBML_MasterGetChild(Track, &MATROSKA_ContextTrackType); switch (EL_Int(TrackData)) { case TRACK_TYPE_VIDEO: return 0; case TRACK_TYPE_AUDIO: { tchar_t CodecName[MAXDATA]; ebml_string *CodecID = (ebml_string*)EBML_MasterGetChild(Track, &MATROSKA_ContextCodecID); EBML_StringGet(CodecID,CodecName,TSIZEOF(CodecName)); return !tcsisame_ascii(CodecName,T("A_TRUEHD")); } default: return 1; } } // look for TrackNum in the next Track Track = (ebml_master*)EBML_MasterFindNextElt(RTrackInfo, (ebml_element*)Track, 0, 0); } return 0; } static int CheckVideoStart(void) { int Result = 0; ebml_master **Cluster; ebml_element *Block, *GBlock; int16_t BlockNum; timecode_t ClusterTimecode; array TrackKeyframe; array TrackFirstKeyframePos; for (Cluster=ARRAYBEGIN(RClusters,ebml_master*);Cluster!=ARRAYEND(RClusters,ebml_master*);++Cluster) { ArrayInit(&TrackKeyframe); ArrayResize(&TrackKeyframe,sizeof(bool_t)*(TrackMax+1),256); ArrayZero(&TrackKeyframe); ArrayInit(&TrackFirstKeyframePos); ArrayResize(&TrackFirstKeyframePos,sizeof(filepos_t)*(TrackMax+1),256); ArrayZero(&TrackFirstKeyframePos); ClusterTimecode = MATROSKA_ClusterTimecode((matroska_cluster*)*Cluster); if (ClusterTimecode==INVALID_TIMECODE_T) Result |= OutputError(0xC1,T("The Cluster at %") TPRId64 T(" has no timecode"),EL_Pos(*Cluster)); else if (ClusterTime!=INVALID_TIMECODE_T && ClusterTime >= ClusterTimecode) OutputWarning(0xC2,T("The timecode of the Cluster at %") TPRId64 T(" is not incrementing (may be intentional)"),EL_Pos(*Cluster)); ClusterTime = ClusterTimecode; for (Block = EBML_MasterChildren(*Cluster);Block;Block=EBML_MasterNext(Block)) { if (EL_Type(Block, &MATROSKA_ContextBlockGroup)) { for (GBlock = EBML_MasterChildren(Block);GBlock;GBlock=EBML_MasterNext(GBlock)) { if (EL_Type(GBlock, &MATROSKA_ContextBlock)) { BlockNum = MATROSKA_BlockTrackNum((matroska_block*)GBlock); if (BlockNum > ARRAYCOUNT(TrackKeyframe,bool_t)) OutputError(0xC3,T("Unknown track #%d in Cluster at %") TPRId64 T(" in Block at %") TPRId64,(int)BlockNum,EL_Pos(*Cluster),EL_Pos(GBlock)); else if (TrackIsVideo(BlockNum)) { if (!ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] && MATROSKA_BlockKeyframe((matroska_block*)GBlock)) ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] = 1; if (!ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] && ARRAYBEGIN(TrackFirstKeyframePos,filepos_t)[BlockNum]==0) ARRAYBEGIN(TrackFirstKeyframePos,filepos_t)[BlockNum] = EL_Pos(*Cluster); } break; } } } else if (EL_Type(Block, &MATROSKA_ContextSimpleBlock)) { BlockNum = MATROSKA_BlockTrackNum((matroska_block*)Block); if (BlockNum > ARRAYCOUNT(TrackKeyframe,bool_t)) OutputError(0xC3,T("Unknown track #%d in Cluster at %") TPRId64 T(" in SimpleBlock at %") TPRId64,(int)BlockNum,EL_Pos(*Cluster),EL_Pos(Block)); else if (TrackIsVideo(BlockNum)) { if (!ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] && MATROSKA_BlockKeyframe((matroska_block*)Block)) ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] = 1; if (!ARRAYBEGIN(TrackKeyframe,bool_t)[BlockNum] && ARRAYBEGIN(TrackFirstKeyframePos,filepos_t)[BlockNum]==0) ARRAYBEGIN(TrackFirstKeyframePos,filepos_t)[BlockNum] = EL_Pos(*Cluster); } } } for (BlockNum=0;BlockNumBlockTime) MinTime = BlockTime; if (MaxTime==INVALID_TIMECODE_T || MaxTimeBlockTime) MinTime = BlockTime; if (MaxTime==INVALID_TIMECODE_T || MaxTimeStream = (stream*)NodeSingleton(&p,STDERR_ID); assert(StdErr->Stream!=NULL); for (i=1;i")); TextWrite(StdErr,T("Options:\r\n")); TextWrite(StdErr,T(" --no-warn only output errors, no warnings\r\n")); TextWrite(StdErr,T(" --live only output errors/warnings relevant to live streams\r\n")); TextWrite(StdErr,T(" --details show details for valid files\r\n")); TextWrite(StdErr,T(" --divx assume the file is using DivX specific extensions\r\n")); TextWrite(StdErr,T(" --quiet don't ouput progress and file info\r\n")); TextWrite(StdErr,T(" --version show the version of mkvalidator\r\n")); TextWrite(StdErr,T(" --help show this screen\r\n")); } goto exit; } #if defined(TARGET_WIN) && defined(UNICODE) Node_FromWcs(&p,Path,TSIZEOF(Path),argv[argc-1]); #else Node_FromStr(&p,Path,TSIZEOF(Path),argv[argc-1]); #endif Input = StreamOpen(&p,Path,SFLAG_RDONLY/*|SFLAG_BUFFERED*/); if (!Input) { TextPrintf(StdErr,T("Could not open file \"%s\" for reading\r\n"),Path); Result = -2; goto exit; } // parse the source file to determine if it's a Matroska file and determine the location of the key parts RContext.Context = &MATROSKA_ContextStream; RContext.EndPosition = INVALID_FILEPOS_T; RContext.UpContext = NULL; RContext.Profile = 0; EbmlHead = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 0); if (!EbmlHead || !EL_Type(EbmlHead, &EBML_ContextHead)) { Result = OutputError(3,T("EBML head not found! Are you sure it's a matroska/webm file?")); goto exit; } if (!Quiet) TextWrite(StdErr,T(".")); if (EBML_ElementReadData(EbmlHead,Input,&RContext,0,SCOPE_ALL_DATA, 1)!=ERR_NONE) { Result = OutputError(4,T("Could not read the EBML head")); goto exit; } if (!EBML_MasterIsChecksumValid(EbmlHead)) { Result = OutputError(12,T("The EBML header is damaged (invalid CheckSum)")); goto exit; } VoidAmount += CheckUnknownElements((ebml_element*)EbmlHead); RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextReadVersion); if (EL_Int(RLevel1) > EBML_MAX_VERSION) OutputError(5,T("The EBML read version is not supported: %d"),(int)EL_Int(RLevel1)); RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextMaxIdLength); if (EL_Int(RLevel1) > EBML_MAX_ID) OutputError(6,T("The EBML max ID length is not supported: %d"),(int)EL_Int(RLevel1)); RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextMaxSizeLength); if (EL_Int(RLevel1) > EBML_MAX_SIZE) OutputError(7,T("The EBML max size length is not supported: %d"),(int)EL_Int(RLevel1)); RLevel1 = (ebml_master*)EBML_MasterGetChild(EbmlHead,&EBML_ContextDocType); EBML_StringGet((ebml_string*)RLevel1,String,TSIZEOF(String)); if (tcscmp(String,T("matroska"))!=0 && tcscmp(String,T("webm"))!=0) { Result = OutputError(8,T("The EBML doctype is not supported: %s"),String); goto exit; } EbmlDocVer = EBML_MasterGetChild(EbmlHead,&EBML_ContextDocTypeVersion); EbmlReadDocVer = EBML_MasterGetChild(EbmlHead,&EBML_ContextDocTypeReadVersion); if (EL_Int(EbmlDocVer) > EL_Int(EbmlReadDocVer)) OutputError(9,T("The read DocType version %d is higher than the Doctype version %d"),(int)EL_Int(EbmlReadDocVer),(int)EL_Int(EbmlDocVer)); if (tcscmp(String,T("matroska"))==0) { if (DivX) MatroskaProfile = PROFILE_DIVX; else if (EL_Int(EbmlReadDocVer)==4) MatroskaProfile = PROFILE_MATROSKA_V4; else if (EL_Int(EbmlReadDocVer)==3) MatroskaProfile = PROFILE_MATROSKA_V3; else if (EL_Int(EbmlReadDocVer)==2) MatroskaProfile = PROFILE_MATROSKA_V2; else if (EL_Int(EbmlReadDocVer)==1) MatroskaProfile = PROFILE_MATROSKA_V1; else OutputError(10,T("Unknown Matroska profile %d/%d"),(int)EL_Int(EbmlDocVer),(int)EL_Int(EbmlReadDocVer)); } else if (tcscmp(String,T("webm"))==0) MatroskaProfile = PROFILE_WEBM; if (!Quiet) TextWrite(StdErr,T(".")); // find the segment RSegment = (ebml_master*)EBML_FindNextElement(Input, &RContext, &UpperElement, 1); RSegmentContext.Context = &MATROSKA_ContextSegment; RSegmentContext.EndPosition = EBML_ElementPositionEnd((ebml_element*)RSegment); RSegmentContext.UpContext = &RContext; RSegmentContext.Profile = MatroskaProfile; RContext.EndPosition = EBML_ElementPositionEnd((ebml_element*)RSegment); UpperElement = 0; DotCount = 0; Prev = NULL; RLevel1 = (ebml_master*)EBML_FindNextElement(Input, &RSegmentContext, &UpperElement, 1); while (RLevel1) { RLevelX = NULL; if (EL_Type(RLevel1, &MATROSKA_ContextCluster)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,0,SCOPE_PARTIAL_DATA,4)==ERR_NONE) { ArrayAppend(&RClusters,&RLevel1,sizeof(RLevel1),256); NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); } else { Result = OutputError(0x180,T("Failed to read the Cluster at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextSeekHead)) { if (Live) { OutputWarning(0x170,T("The live stream has a SeekHead at %") TPRId64,EL_Pos(RLevel1)); RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); NodeDelete((node*)RLevel1); RLevel1 = NULL; } else if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,2)==ERR_NONE) { if (!RSeekHead) RSeekHead = RLevel1; else if (!RSeekHead2) { OutputWarning(0x103,T("Unnecessary secondary SeekHead was found at %") TPRId64,EL_Pos(RLevel1)); RSeekHead2 = RLevel1; } else OutputWarning(0x101,T("Extra SeekHead found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); } else { Result = OutputError(0x100,T("Failed to read the SeekHead at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextInfo)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,1)==ERR_NONE) { if (RSegmentInfo != NULL) OutputWarning(0x110,T("Extra SegmentInfo found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { RSegmentInfo = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); if (Live) { ebml_master *Elt = (ebml_master*)EBML_MasterFindChild(RLevel1,&MATROSKA_ContextDuration); if (Elt) OutputWarning(0x112,T("The live Segment has a duration set at %") TPRId64,EL_Pos(Elt)); } } } else { Result = OutputError(0x111,T("Failed to read the SegmentInfo at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextTracks)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,4)==ERR_NONE) { if (RTrackInfo != NULL) OutputWarning(0x120,T("Extra TrackInfo found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { size_t TrackCount; ebml_master *Elt; RTrackInfo = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); Elt = (ebml_master*)EBML_MasterFindChild(RTrackInfo,&MATROSKA_ContextTrackEntry); TrackCount = 0; while (Elt) { Elt = (ebml_master*)EBML_MasterNextChild(RTrackInfo,Elt); ++TrackCount; } ArrayResize(&Tracks,TrackCount*sizeof(track_info),256); ArrayZero(&Tracks); Elt = (ebml_master*)EBML_MasterFindChild(RTrackInfo,&MATROSKA_ContextTrackEntry); TrackCount = 0; while (Elt) { EbmlDocVer = EBML_MasterFindChild(Elt,&MATROSKA_ContextTrackNumber); assert(EbmlDocVer!=NULL); if (EbmlDocVer) { TrackMax = max(TrackMax,(size_t)EL_Int(EbmlDocVer)); ARRAYBEGIN(Tracks,track_info)[TrackCount].Num = (int)EL_Int(EbmlDocVer); } EbmlDocVer = EBML_MasterFindChild(Elt,&MATROSKA_ContextTrackType); assert(EbmlDocVer!=NULL); if (EbmlDocVer) { if (EL_Int(EbmlDocVer)==TRACK_TYPE_VIDEO) { Result |= CheckVideoTrack(Elt, ARRAYBEGIN(Tracks,track_info)[TrackCount].Num, MatroskaProfile); HasVideo = 1; } ARRAYBEGIN(Tracks,track_info)[TrackCount].Kind = (int)EL_Int(EbmlDocVer); } ARRAYBEGIN(Tracks,track_info)[TrackCount].CodecID = (ebml_string*)EBML_MasterFindChild(Elt,&MATROSKA_ContextCodecID); Elt = (ebml_master*)EBML_MasterNextChild(RTrackInfo,Elt); ++TrackCount; } EbmlDocVer = NULL; Elt = NULL; } } else { Result = OutputError(0x121,T("Failed to read the TrackInfo at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextCues)) { if (Live) { OutputWarning(0x171,T("The live stream has Cues at %") TPRId64,EL_Pos(RLevel1)); RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); NodeDelete((node*)RLevel1); RLevel1 = NULL; } else if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,3)==ERR_NONE) { if (RCues != NULL) OutputWarning(0x130,T("Extra Cues found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { RCues = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); } } else { Result = OutputError(0x131,T("Failed to read the Cues at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextChapters)) { if (Live) { Result |= OutputError(0x172,T("The live stream has Chapters at %") TPRId64,EL_Pos(RLevel1)); RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); NodeDelete((node*)RLevel1); RLevel1 = NULL; } else if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,16)==ERR_NONE) { if (RChapters != NULL) OutputWarning(0x140,T("Extra Chapters found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { RChapters = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); } } else { Result = OutputError(0x141,T("Failed to read the Chapters at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextTags)) { if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,4)==ERR_NONE) { if (RTags != NULL) Result |= OutputError(0x150,T("Extra Tags found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { RTags = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); } } else { Result = OutputError(0x151,T("Failed to read the Tags at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else if (EL_Type(RLevel1, &MATROSKA_ContextAttachments)) { if (Live) { Result |= OutputError(0x173,T("The live stream has a Attachments at %") TPRId64,EL_Pos(RLevel1)); RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); NodeDelete((node*)RLevel1); RLevel1 = NULL; } else if (EBML_ElementReadData(RLevel1,Input,&RSegmentContext,1,SCOPE_ALL_DATA,3)==ERR_NONE) { if (RAttachments != NULL) Result |= OutputError(0x160,T("Extra Attachments found at %") TPRId64 T(" (size %") TPRId64 T(")"),EL_Pos(RLevel1),EL_DataSize(RLevel1)); else { RAttachments = RLevel1; NodeTree_SetParent(RLevel1, RSegment, NULL); VoidAmount += CheckUnknownElements((ebml_element*)RLevel1); Result |= CheckProfileViolation((ebml_element*)RLevel1, MatroskaProfile); } } else { Result = OutputError(0x161,T("Failed to read the Attachments at %") TPRId64 T(" size %") TPRId64,EL_Pos(RLevel1),EL_DataSize(RLevel1)); goto exit; } } else { if (Node_IsPartOf(RLevel1,EBML_DUMMY_ID)) { tchar_t Id[32]; EBML_IdToString(Id,TSIZEOF(Id),EBML_ElementClassID((ebml_element*)RLevel1)); OutputWarning(0x80,T("Unknown element %s at %") TPRId64 T(" size %") TPRId64,Id,EL_Pos(RLevel1),EL_DataSize(RLevel1)); } if (Node_IsPartOf(RLevel1,EBML_VOID_CLASS)) { VoidAmount += EBML_ElementFullSize((ebml_element*)RLevel1,0); } RLevelX = (ebml_master*)EBML_ElementSkipData((ebml_element*)RLevel1, Input, &RSegmentContext, NULL, 1); NodeDelete((node*)RLevel1); RLevel1 = NULL; } if (!Quiet) { TextWrite(StdErr,T(".")); ++DotCount; if (!(DotCount % 60)) TextWrite(StdErr,T("\r \r")); } Prev = RLevel1; if (RLevelX) RLevel1 = RLevelX; else RLevel1 = (ebml_master*)EBML_FindNextElement(Input, &RSegmentContext, &UpperElement, 1); } if (!RSegmentInfo) { Result = OutputError(0x40,T("The segment is missing a SegmentInfo")); goto exit; } if (Prev) { if (EBML_ElementPositionEnd((ebml_element*)RSegment)!=INVALID_FILEPOS_T && EBML_ElementPositionEnd((ebml_element*)RSegment)!=EBML_ElementPositionEnd((ebml_element*)Prev)) Result |= OutputError(0x42,T("The segment's size %") TPRId64 T(" doesn't match the position where it ends %") TPRId64,EBML_ElementPositionEnd((ebml_element*)RSegment),EBML_ElementPositionEnd((ebml_element*)Prev)); } if (!RSeekHead) { if (!Live) OutputWarning(0x801,T("The segment has no SeekHead section")); } else Result |= CheckSeekHead(RSeekHead); if (RSeekHead2) Result |= CheckSeekHead(RSeekHead2); if (ARRAYCOUNT(RClusters,ebml_element*)) { if (!Quiet) TextWrite(StdErr,T(".")); LinkClusterBlocks(); if (HasVideo) Result |= CheckVideoStart(); Result |= CheckLacingKeyframe(); Result |= CheckPosSize((ebml_element*)RSegment); if (!RCues) { if (!Live && ARRAYCOUNT(RClusters,ebml_element*)>1) OutputWarning(0x800,T("The segment has Clusters but no Cues section (bad for seeking)")); } else Result |= CheckCueEntries(RCues); if (!RTrackInfo) { Result = OutputError(0x41,T("The segment has Clusters but no TrackInfo section")); goto exit; } } if (!Quiet) TextWrite(StdErr,T(".")); if (RTrackInfo) CheckTracks(RTrackInfo, MatroskaProfile); for (TI=ARRAYBEGIN(Tracks,track_info); TI!=ARRAYEND(Tracks,track_info); ++TI) { if (TI->DataLength==0) OutputWarning(0xB8,T("Track #%d is defined but has no frame"),TI->Num); } if (VoidAmount > 4*1024) OutputWarning(0xD0,T("There are %") TPRId64 T(" bytes of void data\r\n"),VoidAmount); if (!Quiet && Result==0) { TextPrintf(StdErr,T("\r%s %s: the file appears to be valid\r\n"),PROJECT_NAME,PROJECT_VERSION); if (Details) { track_info *TI; for (TI=ARRAYBEGIN(Tracks,track_info); TI!=ARRAYEND(Tracks,track_info); ++TI) { EBML_StringGet(TI->CodecID,String,TSIZEOF(String)); TextPrintf(StdErr,T("Track #%d %18s %") TPRId64 T(" bits/s\r\n"),TI->Num,String,Scale64(TI->DataLength,8000000000,MaxTime-MinTime)); } } } exit: if (!Quiet && RSegmentInfo) { tchar_t App[MAXPATH]; App[0] = 0; LibName = (ebml_string*)EBML_MasterFindChild(RSegmentInfo,&MATROSKA_ContextMuxingApp); AppName = (ebml_string*)EBML_MasterFindChild(RSegmentInfo,&MATROSKA_ContextWritingApp); if (LibName) { EBML_StringGet(LibName,String,TSIZEOF(String)); tcscat_s(App,TSIZEOF(App),String); } if (AppName) { EBML_StringGet(AppName,String,TSIZEOF(String)); if (App[0]) tcscat_s(App,TSIZEOF(App),T(" / ")); tcscat_s(App,TSIZEOF(App),String); } if (App[0]==0) tcscat_s(App,TSIZEOF(App),T("")); TextPrintf(StdErr,T("\r\tfile created with %s\r\n"),App); } for (Cluster = ARRAYBEGIN(RClusters,ebml_master*);Cluster != ARRAYEND(RClusters,ebml_master*); ++Cluster) NodeDelete((node*)*Cluster); ArrayClear(&RClusters); if (RAttachments) NodeDelete((node*)RAttachments); if (RTags) NodeDelete((node*)RTags); if (RCues) NodeDelete((node*)RCues); if (RChapters) NodeDelete((node*)RChapters); if (RTrackInfo) NodeDelete((node*)RTrackInfo); if (RSegmentInfo) NodeDelete((node*)RSegmentInfo); if (RLevel1) NodeDelete((node*)RLevel1); if (RSegment) NodeDelete((node*)RSegment); if (EbmlHead) NodeDelete((node*)EbmlHead); ArrayClear(&Tracks); if (Input) StreamClose(Input); // EBML & Matroska ending MATROSKA_Done((nodecontext*)&p); // Core-C ending StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return Result; } bcmatroska2-5.3.101/mkvalidator/mkvalidator.proj000066400000000000000000000003631462133141200216160ustar00rootroot00000000000000CON mkvalidator { PROJECT_NAME "mkvalidator" PROJECT_VERSION 0.4.2 PROJECT_VENDOR "Matroska" USE matroska2 SOURCE mkvalidator.c COMPILE src.br COMPILE configure COMPILE pkg.sh } WORKSPACE mkvalidator { USE mkvalidator } bcmatroska2-5.3.101/mkvalidator/pkg.sh000066400000000000000000000003411462133141200175160ustar00rootroot00000000000000#!/bin/sh %%BEGIN SCRIPT %%END rm -rf %(PROJECT_NAME)-%(PROJECT_VERSION) branch src.br rm -rf %(PROJECT_NAME)-%(PROJECT_VERSION).tar.bz2 tar cvfj %(PROJECT_NAME)-%(PROJECT_VERSION).tar.bz2 %(PROJECT_NAME)-%(PROJECT_VERSION) bcmatroska2-5.3.101/mkvalidator/src.br000066400000000000000000000015501462133141200175200ustar00rootroot00000000000000# corec %(!ROOTPATH)corec %(PROJECT_NAME)-%(PROJECT_VERSION)/corec # libebml2 %(!ROOTPATH)libebml2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libebml2 # libmatroska2 %(!ROOTPATH)libmatroska2 %(PROJECT_NAME)-%(PROJECT_VERSION)/libmatroska2 # %(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME) %(PROJECT_NAME)-%(PROJECT_VERSION)/%(PROJECT_NAME) %(!ROOTPATH)%(PROJECT_NAME)/default_config.h %(PROJECT_NAME)-%(PROJECT_VERSION)/config.h %(!ROOTPATH)%(PROJECT_NAME)/ChangeLog.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ChangeLog.txt %(!ROOTPATH)%(PROJECT_NAME)/ReadMe.txt %(PROJECT_NAME)-%(PROJECT_VERSION)/ReadMe.txt %(!ROOTPATH)root.proj %(PROJECT_NAME)-%(PROJECT_VERSION)/root.proj %(¯!BASE)configure %(PROJECT_NAME)-%(PROJECT_VERSION)/configure %(!ROOTPATH)corec/tools/coremake/coremake - *.br - *.vs - Makefile - *.vcproj - *.sln - *_project.h - *_stdafx.* - bcmatroska2-5.3.101/root.proj000066400000000000000000000003471462133141200157510ustar00rootroot00000000000000CONFIG_FILE config.h PLATFORM_FILES corec/tools/coremake WORKSPACE ebml { USE ebml2 USE ebmltests } WORKSPACE(CONFIG_MATROSKA2) matroska { USE matroska2 USE mkvtests USE mkclean USE mkvalidator } #include "*/*.proj" bcmatroska2-5.3.101/spectool/000077500000000000000000000000001462133141200157165ustar00rootroot00000000000000bcmatroska2-5.3.101/spectool/data2lib.c000066400000000000000000000572461462133141200175620ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A tool to generate the libmatroska semantic files * input: specdata.xml * output: KaxSemantic.cpp / KaxSemantic.h */ #include "data2lib2_stdafx.h" #include "spec_element.h" typedef struct table_extras { bool_t StartedGlobal; bool_t PassedEBML; bool_t IsLast; bool_t InTags; int CurrLevel; int CurrProfile; } table_extras; static const tchar_t *GetCppName(const SpecElement *elt) { if (elt->CppName[0]) return elt->CppName; return elt->Name; } static const tchar_t *GetClassName(const SpecElement *elt) { if (elt->Id==0x61A7) return T("Attached"); if (elt->Id==0x4660) return T("MimeType"); if (elt->Id==0x447A) return T("TagLangue"); if (elt->Id!=0x114D9B74 && elt->Id!=0x4DBB && elt->Id!=0xFA) { if (elt->CppName[0]) return elt->CppName; } return elt->Name; } static bool_t IsValidElement(const SpecElement *elt) { return elt->InWebM || elt->MinVersion || elt->InDivX; } static void AddElementSemantic(textwriter *CFile, const SpecElement *elt, bool_t InRecursive) { TextPrintf(CFile, T("DEFINE_SEMANTIC_ITEM(%s, %s, Kax%s)"), InRecursive?T("false"):(elt->Mandatory?T("true"):T("false")), elt->Multiple?T("false"):T("true"), GetClassName(elt)); if (!IsValidElement(elt)) TextWrite(CFile, T(" // not supported\n")); else if (!elt->MinVersion && elt->InDivX) TextWrite(CFile, T(" // DivX specific\n")); else if (InRecursive) TextWrite(CFile, T(" // recursive\n")); else TextWrite(CFile, T("\n")); } static const tchar_t *GetClassType(const SpecElement *elt, bool_t Define) { if (elt->Id==0x3CB923 || elt->Id==0x3EB923 || elt->Id==0xA3 || elt->Id==0xA1 || elt->Id==0xA2) return T("BINARY_CONS"); else if (elt->Id==0x1F43B675 || elt->Id==0xA0 || elt->Id==0xAE) return T("MASTER_CONS"); else if (Define && (elt->Id==0x61A7 || elt->Id==0x1941A469)) return T("MASTER_CONS"); else if (elt->Id==0xFB) return T("SINTEGER_CONS"); else switch (elt->Type) { case EBML_MASTER: return T("MASTER"); break; case EBML_INTEGER: return T("SINTEGER"); break; case EBML_UNSIGNED_INTEGER: return T("UINTEGER"); break; case EBML_DATE: return T("DATE "); break; case EBML_FLOAT: return T("FLOAT"); break; case EBML_STRING: return T("STRING"); break; case EBML_UNICODE_STRING: return T("UNISTRING"); break; case EBML_BINARY: return T("BINARY "); break; } return NULL; } static void OutputElementDefinition(const SpecElement **pElt, const SpecElement *parent, const SpecElement **EltEnd, textwriter *CFile, table_extras *Extras) { const SpecElement *elt = *pElt; if (pElt==EltEnd) return; //if (!IsValidElement(elt)) TextWrite(CFile, T("// not supported ")); if (elt->Type != EBML_unknown && elt->Name[0]) { const SpecElement **sub; if (elt->Level==-1 && !Extras->StartedGlobal) { Extras->StartedGlobal = 1; } if (elt->Level>=0 && Extras->StartedGlobal) { Extras->StartedGlobal = 0; } if (elt->Level==0 || (elt->Level==1 && Extras->PassedEBML)) { Extras->InTags = 0; } Extras->CurrLevel = elt->Level; if (Extras->PassedEBML) { const tchar_t *s; intptr_t value; if (!IsValidElement(elt)) { if (Extras->CurrProfile != 2) { Extras->CurrProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), Extras->CurrProfile); } } else if (!elt->MinVersion || Extras->CurrProfile < elt->MinVersion) { if (Extras->CurrProfile != 2) { Extras->CurrProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), Extras->CurrProfile); } } if (elt->Type==EBML_MASTER) { // write the semantic int minProfile = Extras->CurrProfile; TextPrintf(CFile, T("\nDEFINE_START_SEMANTIC(Kax%s)\n"), GetClassName(elt)); if (elt->Recursive) AddElementSemantic(CFile, elt, 1); for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level) break; if ((*sub)->Level== elt->Level+1) { if (!IsValidElement(*sub)) { if (minProfile != 2) { minProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), minProfile); } } else if (!(*sub)->MinVersion || minProfile < (*sub)->MinVersion) { if (minProfile != 2) { minProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), minProfile); } } else if (minProfile > (*sub)->MinVersion) { minProfile = (*sub)->MinVersion; TextPrintf(CFile, T("#endif // MATROSKA_VERSION\n")); } //if (!IsValidElement(*sub)) TextWrite(CFile, T("// ")); AddElementSemantic(CFile, *sub, 0); } } if (minProfile > 1 && Extras->CurrProfile < 2) { minProfile = 1; TextPrintf(CFile, T("#endif // MATROSKA_VERSION\n")); } TextPrintf(CFile, T("DEFINE_END_SEMANTIC(Kax%s)\n\n"), GetClassName(elt)); } TextWrite(CFile, T("DEFINE_MKX_")); TextWrite(CFile, GetClassType(elt, 1)); switch (elt->Type) { case EBML_INTEGER: case EBML_UNSIGNED_INTEGER: case EBML_DATE: s = elt->DefaultValue; if (!elt->DefaultValue[0]) TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); else if (ExprIsInt(&s,&value)) TextPrintf(CFile, T("_DEF(Kax%s, 0x%X, %d, Kax%s, \"%s\", %d);\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt), value); else TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); break; case EBML_FLOAT: s = elt->DefaultValue; if (!elt->DefaultValue[0]) TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); else if (ExprIsInt(&s,&value)) TextPrintf(CFile, T("_DEF(Kax%s, 0x%X, %d, Kax%s, \"%s\", %d);\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt), value); else TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); break; case EBML_STRING: case EBML_UNICODE_STRING: if (!elt->DefaultValue[0]) TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); else TextPrintf(CFile, T("_DEF(Kax%s, 0x%X, %d, Kax%s, \"%s\", \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt), elt->DefaultValue); break; default: if (parent==NULL) TextPrintf(CFile, T("_ORPHAN(Kax%s, 0x%X, %d, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetCppName(elt)); else TextPrintf(CFile, T("(Kax%s, 0x%X, %d, Kax%s, \"%s\");\n"), GetClassName(elt), elt->Id, elt->Id<0x100 ? 1 : (elt->Id<0x10000 ? 2 : (elt->Id<0x1000000 ? 3 : 4)), GetClassName(parent), GetCppName(elt)); break; } } sub = pElt+1; if (sub!=EltEnd && (*sub)->MinVersion && Extras->CurrProfile > (*sub)->MinVersion) { Extras->CurrProfile = (*sub)->MinVersion; TextPrintf(CFile, T("#endif\n")); } } if (elt->Type==EBML_MASTER) { const SpecElement **sub; for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level && (*sub)->Level>=0) break; if ((*sub)->Level== elt->Level+1) OutputElementDefinition(sub, elt, EltEnd, CFile, Extras); } } } static void OutputElementDeclaration(const SpecElement **pElt, const SpecElement **EltEnd, textwriter *CFile, table_extras *Extras) { const SpecElement *elt = *pElt; const SpecElement **sub; if (pElt==EltEnd) return; if (elt->Type != EBML_unknown && elt->Name[0]) { if (elt->Level==-1 && !Extras->StartedGlobal) { Extras->StartedGlobal = 1; } if (elt->Level>=0 && Extras->StartedGlobal) { Extras->StartedGlobal = 0; } if (elt->Level==0 || (elt->Level==1 && Extras->PassedEBML)) { Extras->InTags = 0; } Extras->CurrLevel = elt->Level; if (Extras->PassedEBML && elt->Id!=0xAE && elt->Id!=0xA0 && elt->Id!=0xA1 && elt->Id!=0xA2 && elt->Id!=0xA3 && elt->Id!=0xFB && elt->Id!=0x1C53BB6B && elt->Id!=0x1F43B675 && elt->Id!=0x18538067 && elt->Id!=0xBB && elt->Id!=0xB7 && elt->Id!=0xDB && elt->Id!=0x3CB923 && elt->Id!=0x3EB923 && elt->Id!=0x114D9B74 && elt->Id!=0x4DBB) { if (!IsValidElement(elt)) { if (Extras->CurrProfile != 2) { Extras->CurrProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), Extras->CurrProfile); } } else if (!elt->MinVersion || Extras->CurrProfile < elt->MinVersion) { if (Extras->CurrProfile != 2) { Extras->CurrProfile = 2; TextPrintf(CFile, T("#if MATROSKA_VERSION >= %d\n"), Extras->CurrProfile); } } TextWrite(CFile, T("DECLARE_MKX_")); TextWrite(CFile, GetClassType(elt, 0)); TextPrintf(CFile, T("(Kax%s)\n"), GetClassName(elt)); switch (elt->Id) { case 0x53AB: TextWrite(CFile, T("public:\n")); TextWrite(CFile, T("\tvirtual bool ValidateSize() const {return IsFiniteSize() && GetSize() <= 4;}\n")); break; case 0x73A4: TextWrite(CFile, T("#if defined(HAVE_EBML2) || defined(HAS_EBML2)\n")); TextWrite(CFile, T("public:\n")); TextWrite(CFile, T("\tKaxSegmentUID(EBML_DEF_CONS EBML_DEF_SEP EBML_EXTRA_PARAM);\n")); TextWrite(CFile, T("#endif\n")); break; } if (elt->ByteSize) { TextWrite(CFile, T("public:\n")); TextPrintf(CFile, T("\tvirtual bool ValidateSize() const {return IsFiniteSize() && GetSize() == %d;}\n"), elt->ByteSize); } if (!IsValidElement(elt) || elt->MaxVersion!=0) { TextWrite(CFile, T("public:\n")); TextWrite(CFile, T("\tfilepos_t RenderData(IOCallback & output, bool bForceRender, bool bSaveDefault);\n")); } TextWrite(CFile, T("};\n")); sub = pElt+1; if (sub!=EltEnd && (*sub)->MinVersion && Extras->CurrProfile > (*sub)->MinVersion) { Extras->CurrProfile = (*sub)->MinVersion; TextPrintf(CFile, T("#endif\n\n")); } else if (elt->Type==EBML_MASTER) TextWrite(CFile, T("\n\n")); else TextWrite(CFile, T("\n")); } } if (elt->Type==EBML_MASTER) { const SpecElement **sub; for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level && (*sub)->Level>=0) break; if ((*sub)->Level== elt->Level+1) OutputElementDeclaration(sub, EltEnd, CFile, Extras); } } } static void ReadLevel(parser *p, array *Elements) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { if (tcsisame_ascii(Element,T("element"))) { SpecElement *Dumper = (SpecElement*)NodeCreate(p->Context, SPEC_ELEMENT_CLASS); ReadSpecElement(Dumper, p); ArrayAppend(Elements, &Dumper, sizeof(Dumper), 128); } else { while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { if (tcsisame_ascii(String,T("id"))) tcsreplace(Value,TSIZEOF(Value),T(" "),T("_")); } } if (p->ElementEof) p->ElementEof = 0; else ReadLevel(p, Elements); } } else { ParserSkipAfter(p,'>'); break; } } } META_START(SpecElement_Class,SPEC_ELEMENT_CLASS) META_CLASS(SIZE,sizeof(SpecElement)) META_END(NODE_CLASS) static void OutputCHeader(textwriter *CFile, bool_t WithInclude) { TextWrite(CFile, T("/**********************************************************************\n")); TextWrite(CFile, T("** DO NOT EDIT, GENERATED WITH DATA2LIB\n")); TextWrite(CFile, T("** \n")); TextWrite(CFile, T("** libmatroska : parse Matroska files, see http://www.matroska.org/\n")); TextWrite(CFile, T("** \n")); TextWrite(CFile, T("** Copyright (c) 2002-2010, Matroska (non-profit organisation)\n")); TextWrite(CFile, T("** All rights reserved.\n")); TextWrite(CFile, T("** \n")); TextWrite(CFile, T("** This file is part of libmatroska.\n")); TextWrite(CFile, T("**\n")); TextWrite(CFile, T("** This library is free software; you can redistribute it and/or\n")); TextWrite(CFile, T("** modify it under the terms of the GNU Lesser General Public\n")); TextWrite(CFile, T("** License as published by the Free Software Foundation; either\n")); TextWrite(CFile, T("** version 2.1 of the License, or (at your option) any later version.\n")); TextWrite(CFile, T("** \n")); TextWrite(CFile, T("** This library is distributed in the hope that it will be useful,\n")); TextWrite(CFile, T("** but WITHOUT ANY WARRANTY; without even the implied warranty of\n")); TextWrite(CFile, T("** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n")); TextWrite(CFile, T("** Lesser General Public License for more details.\n")); TextWrite(CFile, T("** \n")); TextWrite(CFile, T("** You should have received a copy of the GNU Lesser General Public\n")); TextWrite(CFile, T("** License along with this library; if not, write to the Free Software\n")); TextWrite(CFile, T("** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n")); TextWrite(CFile, T("**\n")); TextWrite(CFile, T("** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.**\n")); TextWrite(CFile, T("** Contact license@matroska.org if any conditions of this licensing are\n")); TextWrite(CFile, T("** not clear to you.\n")); TextWrite(CFile, T("**\n")); TextWrite(CFile, T("**********************************************************************/\n\n")); if (WithInclude) { TextWrite(CFile, T("#include \"matroska/KaxContexts.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxSemantic.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxSegment.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxSeekHead.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxCluster.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxTracks.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxCues.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxInfoData.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxBlockData.h\"\n")); TextWrite(CFile, T("#include \"matroska/KaxCuesData.h\"\n")); } TextWrite(CFile, T("\n")); } int main(void) { parsercontext p; parser parseIn; stream *Input = NULL,*OutputC = NULL,*OutputH = NULL; array Elements; SpecElement **element; //tchar_t Element[MAXLINE], String[MAXLINE], Value[MAXLINE]; ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); Input = StreamOpen(&p,T("specdata.xml"),SFLAG_RDONLY/*|SFLAG_BUFFERED*/); OutputC = StreamOpen(&p,T("KaxSemantic.cpp"),SFLAG_WRONLY|SFLAG_CREATE); OutputH = StreamOpen(&p,T("KaxSemantic.h"),SFLAG_WRONLY|SFLAG_CREATE); memset(&parseIn, 0, sizeof(parseIn)); ArrayInit(&Elements); if (ParserStreamXML(&parseIn, Input, &p, T("table"), 0)==ERR_NONE) { textwriter CFile; table_extras Extras; ReadLevel(&parseIn, &Elements); memset(&Extras,0,sizeof(Extras)); memset(&CFile,0,sizeof(CFile)); Extras.CurrLevel = -1; Extras.CurrProfile = 1; CFile.Stream = OutputC; OutputCHeader(&CFile, 1); TextWrite(&CFile, T("START_LIBMATROSKA_NAMESPACE\n")); for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; if ((*element)->Id == 0x18538067) { Extras.PassedEBML = 1; OutputElementDefinition(element, NULL, ARRAYEND(Elements,SpecElement*), &CFile, &Extras); break; } } memset(&Extras,0,sizeof(Extras)); Extras.CurrLevel = -1; Extras.CurrProfile = 1; for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; if ((*element)->Id == 0x18538067) // Segment Extras.PassedEBML = 1; if (Extras.PassedEBML) { if (!IsValidElement(*element) || (*element)->MaxVersion!=0) { TextPrintf(&CFile, T("\nfilepos_t Kax%s::RenderData(IOCallback & /* output */, bool /* bForceRender */, bool /* bSaveDefault */) {\n"), GetClassName(*element)); TextWrite(&CFile, T("\tassert(false); // no you are not allowed to use this element !\n")); TextWrite(&CFile, T("\treturn 0;\n")); TextWrite(&CFile, T("}\n")); } } } TextWrite(&CFile, T("\nEND_LIBMATROSKA_NAMESPACE\n")); memset(&Extras,0,sizeof(Extras)); Extras.CurrLevel = -1; #if 1 CFile.Stream = OutputH; OutputCHeader(&CFile, 0); TextWrite(&CFile, T("#ifndef LIBMATROSKA_SEMANTIC_H\n")); TextWrite(&CFile, T("#define LIBMATROSKA_SEMANTIC_H\n\n")); TextWrite(&CFile, T("#include \"matroska/KaxTypes.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlUInteger.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlSInteger.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlDate.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlFloat.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlString.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlUnicodeString.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlBinary.h\"\n")); TextWrite(&CFile, T("#include \"ebml/EbmlMaster.h\"\n")); TextWrite(&CFile, T("#include \"matroska/KaxDefines.h\"\n")); TextWrite(&CFile, T("\nusing namespace LIBEBML_NAMESPACE;\n")); TextWrite(&CFile, T("\nSTART_LIBMATROSKA_NAMESPACE\n\n")); for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; if ((*element)->Id == 0x18538067) { Extras.PassedEBML = 1; Extras.CurrProfile = 1; OutputElementDeclaration(element, ARRAYEND(Elements,SpecElement*), &CFile, &Extras); break; } } TextWrite(&CFile, T("END_LIBMATROSKA_NAMESPACE\n")); TextWrite(&CFile, T("\n#endif // LIBMATROSKA_SEMANTIC_H\n")); #endif } for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) NodeDelete((node*)*element); ArrayClear(&Elements); StreamClose(Input); StreamClose(OutputC); //StreamClose(OutputH); StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return 0; } bcmatroska2-5.3.101/spectool/data2lib2.c000066400000000000000000000424161462133141200176350ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A tool to generate the libmatroska2 semantic files * input: specdata.xml * output: matroska_sem.c / matroska_sem.h */ #include "data2lib2_stdafx.h" #include "spec_element.h" typedef struct table_extras { bool_t StartedGlobal; bool_t PassedEBML; bool_t IsLast; bool_t InTags; int CurrLevel; } table_extras; static void AddElementSemantic(textwriter *CFile, const SpecElement *elt, bool_t InRecursive) { TextPrintf(CFile, T(" {%d, %d, &MATROSKA_Context%s, "), InRecursive?0:(elt->Mandatory?1:0), elt->Multiple?0:1, elt->Name); if (elt->InWebM && elt->MinVersion==1 && !elt->MaxVersion && elt->InDivX) TextWrite(CFile, T("0")); else { bool_t hasData = 0; if (!elt->MinVersion || elt->MinVersion>1) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_MATROSKA_V1")); } if (!elt->MinVersion || elt->MinVersion>2 || (elt->MaxVersion && elt->MaxVersion<2)) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_MATROSKA_V2")); } if (!elt->MinVersion || elt->MinVersion>3 || (elt->MaxVersion && elt->MaxVersion<3)) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_MATROSKA_V3")); } if (!elt->MinVersion || elt->MinVersion>4 || (elt->MaxVersion && elt->MaxVersion<4)) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_MATROSKA_V4")); } if (!elt->InDivX) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_DIVX")); } if (!elt->InWebM) { if (hasData) TextWrite(CFile, T("|")); hasData = 1; TextWrite(CFile, T("PROFILE_WEBM")); } } if (InRecursive) TextWrite(CFile, T("}, // recursive\n")); else TextWrite(CFile, T("},\n")); } static bool_t IsValidElement(const SpecElement *elt) { return elt->InWebM || elt->MinVersion || elt->InDivX; } static void OutputElementDefinition(const SpecElement **pElt, const SpecElement **EltEnd, textwriter *CFile, table_extras *Extras) { const SpecElement *elt = *pElt; if (pElt==EltEnd) return; if (elt->Type==EBML_MASTER) { const SpecElement **sub; for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level && (*sub)->Level>=0) break; if ((*sub)->Level== elt->Level+1) OutputElementDefinition(sub, EltEnd, CFile, Extras); } } //if (!IsValidElement(elt)) TextWrite(CFile, T("// not supported ")); if (elt->Type != EBML_unknown && elt->Name[0]) { if (elt->Level==-1 && !Extras->StartedGlobal) { Extras->StartedGlobal = 1; } if (elt->Level>=0 && Extras->StartedGlobal) { Extras->StartedGlobal = 0; } if (elt->Level==0 || (elt->Level==1 && Extras->PassedEBML)) { Extras->InTags = 0; } Extras->CurrLevel = elt->Level; if (Extras->PassedEBML) { const tchar_t *s; intptr_t value; if (elt->Type==EBML_MASTER) { const SpecElement **sub; // write the semantic TextPrintf(CFile, T("\nconst ebml_semantic EBML_Semantic%s[] = {\n"), elt->Name); if (elt->Recursive) AddElementSemantic(CFile, elt, 1); for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level) break; if ((*sub)->Level== elt->Level+1) { //if (!IsValidElement(*sub)) TextWrite(CFile, T("// ")); AddElementSemantic(CFile, *sub, 0); } } TextWrite(CFile, T(" {0, 0, NULL ,0} // end of the table\n};\n")); } TextPrintf(CFile, T("const ebml_context MATROSKA_Context%s = {0x%X, "), elt->Name, elt->Id); if (elt->Id==0x4DBB) TextWrite(CFile, T("MATROSKA_SEEKPOINT_CLASS, ")); else if (elt->Id==0xAE) TextWrite(CFile, T("MATROSKA_TRACKENTRY_CLASS, ")); else if (elt->Id==0x73A4 || elt->Id==0x3CB923 || elt->Id==0x3EB923) TextWrite(CFile, T("MATROSKA_SEGMENTUID_CLASS, ")); else if (elt->Id==0xA3 || elt->Id==0xA1) TextWrite(CFile, T("MATROSKA_BLOCK_CLASS, ")); else if (elt->Id==0xA0) TextWrite(CFile, T("MATROSKA_BLOCKGROUP_CLASS, ")); else if (elt->Id==0x1F43B675) TextWrite(CFile, T("MATROSKA_CLUSTER_CLASS, ")); else if (elt->Id==0xBB) TextWrite(CFile, T("MATROSKA_CUEPOINT_CLASS, ")); else if (elt->Id==0x465C) TextWrite(CFile, T("MATROSKA_BIGBINARY_CLASS, ")); else if (elt->Id==0x61A7) TextWrite(CFile, T("MATROSKA_ATTACHMENT_CLASS, ")); else switch (elt->Type) { case EBML_MASTER: TextWrite(CFile, T("EBML_MASTER_CLASS, ")); break; case EBML_INTEGER: TextWrite(CFile, T("EBML_SINTEGER_CLASS, ")); break; case EBML_UNSIGNED_INTEGER: if (tcsisame_ascii(elt->Range,T("0-1"))) TextWrite(CFile, T("EBML_BOOLEAN_CLASS, ")); else TextWrite(CFile, T("EBML_INTEGER_CLASS, ")); break; case EBML_DATE: TextWrite(CFile, T("EBML_DATE_CLASS, ")); break; case EBML_FLOAT: TextWrite(CFile, T("EBML_FLOAT_CLASS, ")); break; case EBML_STRING: TextWrite(CFile, T("EBML_STRING_CLASS, ")); break; case EBML_UNICODE_STRING: TextWrite(CFile, T("EBML_UNISTRING_CLASS, ")); break; case EBML_BINARY: TextWrite(CFile, T("EBML_BINARY_CLASS, ")); break; } switch (elt->Type) { case EBML_INTEGER: case EBML_UNSIGNED_INTEGER: case EBML_DATE: s = elt->DefaultValue; if (!elt->DefaultValue[0]) TextWrite(CFile, T("0, 0, ")); // no default value else if (ExprIsInt(&s,&value)) TextPrintf(CFile, T("1, (intptr_t)%d, "), value); else TextPrintf(CFile, T("0, 0, "), s); // not supported break; case EBML_FLOAT: s = elt->DefaultValue; if (!elt->DefaultValue[0]) TextWrite(CFile, T("0, 0, ")); // no default value else if (ExprIsInt(&s,&value)) TextPrintf(CFile, T("1, (intptr_t)%s, "), elt->DefaultValue); else TextPrintf(CFile, T("0, 0, "), s); // not supported break; case EBML_STRING: case EBML_UNICODE_STRING: if (!elt->DefaultValue[0]) TextWrite(CFile, T("0, 0, ")); // no default value else TextPrintf(CFile, T("1, (intptr_t)\"%s\", "), elt->DefaultValue); break; default: TextPrintf(CFile, T("0, 0, "), elt->DefaultValue); break; } TextPrintf(CFile, T("\"%s\", "), elt->Name); if (elt->Type!=EBML_MASTER) TextWrite(CFile, T("NULL, ")); else TextPrintf(CFile, T("EBML_Semantic%s, "), elt->Name); TextWrite(CFile, T("EBML_SemanticGlobals, ")); TextWrite(CFile, T("NULL};\n")); } } } static void OutputElementDeclaration(const SpecElement **pElt, const SpecElement **EltEnd, textwriter *CFile, table_extras *Extras) { const SpecElement *elt = *pElt; if (pElt==EltEnd) return; if (elt->Type==EBML_MASTER) { const SpecElement **sub; for (sub = pElt+1; sub!=EltEnd; ++sub) { if ((*sub)->Level<= elt->Level && (*sub)->Level>=0) break; if ((*sub)->Level== elt->Level+1) OutputElementDeclaration(sub, EltEnd, CFile, Extras); } } if (elt->Type != EBML_unknown && elt->Name[0]) { if (elt->Level==-1 && !Extras->StartedGlobal) { Extras->StartedGlobal = 1; } if (elt->Level>=0 && Extras->StartedGlobal) { Extras->StartedGlobal = 0; } if (elt->Level==0 || (elt->Level==1 && Extras->PassedEBML)) { Extras->InTags = 0; } Extras->CurrLevel = elt->Level; if (Extras->PassedEBML) { TextPrintf(CFile, T("extern const ebml_context MATROSKA_Context%s;\n"), elt->Name); if (elt->Type==EBML_MASTER) TextWrite(CFile, T("\n")); } } } static void ReadLevel(parser *p, array *Elements) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { if (tcsisame_ascii(Element,T("element"))) { SpecElement *Dumper = (SpecElement*)NodeCreate(p->Context, SPEC_ELEMENT_CLASS); ReadSpecElement(Dumper, p); ArrayAppend(Elements, &Dumper, sizeof(Dumper), 128); } else { while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { if (tcsisame_ascii(String,T("id"))) tcsreplace(Value,TSIZEOF(Value),T(" "),T("_")); } } if (p->ElementEof) p->ElementEof = 0; else ReadLevel(p, Elements); } } else { ParserSkipAfter(p,'>'); break; } } } META_START(SpecElement_Class,SPEC_ELEMENT_CLASS) META_CLASS(SIZE,sizeof(SpecElement)) META_END(NODE_CLASS) static void OutputCHeader(textwriter *CFile, bool_t WithInclude) { TextWrite(CFile, T("/*\n")); TextWrite(CFile, T(" * DO NOT EDIT, GENERATED WITH DATA2LIB2\n")); TextWrite(CFile, T(" *\n")); TextPrintf(CFile, T(" * $Id$\n")); TextWrite(CFile, T(" * Copyright (c) 2008-2011, Matroska (non-profit organisation)\n")); TextWrite(CFile, T(" * All rights reserved.\n")); TextWrite(CFile, T(" *\n")); TextWrite(CFile, T(" * Redistribution and use in source and binary forms, with or without\n")); TextWrite(CFile, T(" * modification, are permitted provided that the following conditions are met:\n")); TextWrite(CFile, T(" * * Redistributions of source code must retain the above copyright\n")); TextWrite(CFile, T(" * notice, this list of conditions and the following disclaimer.\n")); TextWrite(CFile, T(" * * Redistributions in binary form must reproduce the above copyright\n")); TextWrite(CFile, T(" * notice, this list of conditions and the following disclaimer in the\n")); TextWrite(CFile, T(" * documentation and/or other materials provided with the distribution.\n")); TextWrite(CFile, T(" * * Neither the name of the Matroska assocation nor the\n")); TextWrite(CFile, T(" * names of its contributors may be used to endorse or promote products\n")); TextWrite(CFile, T(" * derived from this software without specific prior written permission.\n")); TextWrite(CFile, T(" *\n")); TextWrite(CFile, T(" * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY\n")); TextWrite(CFile, T(" * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n")); TextWrite(CFile, T(" * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n")); TextWrite(CFile, T(" * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY\n")); TextWrite(CFile, T(" * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n")); TextWrite(CFile, T(" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n")); TextWrite(CFile, T(" * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n")); TextWrite(CFile, T(" * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n")); TextWrite(CFile, T(" * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n")); TextWrite(CFile, T(" * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n")); TextWrite(CFile, T(" */\n")); TextWrite(CFile, T("#include \"matroska/matroska.h\"\n")); if (WithInclude) TextWrite(CFile, T("#include \"matroska/matroska_sem.h\"\n")); TextWrite(CFile, T("#include \"matroska/matroska_internal.h\"\n")); TextWrite(CFile, T("\n")); } int main(void) { parsercontext p; parser parseIn; stream *Input = NULL,*OutputC = NULL,*OutputH = NULL; array Elements; SpecElement **element; //tchar_t Element[MAXLINE], String[MAXLINE], Value[MAXLINE]; ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); Input = StreamOpen(&p,T("specdata.xml"),SFLAG_RDONLY/*|SFLAG_BUFFERED*/); OutputC = StreamOpen(&p,T("matroska_sem.c"),SFLAG_WRONLY|SFLAG_CREATE); OutputH = StreamOpen(&p,T("matroska_sem.h"),SFLAG_WRONLY|SFLAG_CREATE); memset(&parseIn, 0, sizeof(parseIn)); ArrayInit(&Elements); if (ParserStreamXML(&parseIn, Input, &p, T("table"), 0)==ERR_NONE) { textwriter CFile; table_extras Extras; ReadLevel(&parseIn, &Elements); memset(&Extras,0,sizeof(Extras)); memset(&CFile,0,sizeof(CFile)); Extras.CurrLevel = -1; CFile.Stream = OutputC; OutputCHeader(&CFile, 1); for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; if ((*element)->Id == 0x18538067) { Extras.PassedEBML = 1; OutputElementDefinition(element, ARRAYEND(Elements,SpecElement*), &CFile, &Extras); break; } } memset(&Extras,0,sizeof(Extras)); Extras.CurrLevel = -1; CFile.Stream = OutputH; OutputCHeader(&CFile, 0); TextWrite(&CFile, T("#ifndef MATROSKA_SEMANTIC_H\n")); TextWrite(&CFile, T("#define MATROSKA_SEMANTIC_H\n\n")); for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; if ((*element)->Id == 0x18538067) { Extras.PassedEBML = 1; OutputElementDeclaration(element, ARRAYEND(Elements,SpecElement*), &CFile, &Extras); break; } } TextWrite(&CFile, T("#endif // MATROSKA_SEMANTIC_H\n")); } for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) NodeDelete((node*)*element); ArrayClear(&Elements); StreamClose(Input); StreamClose(OutputC); StreamClose(OutputH); StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return 0; } bcmatroska2-5.3.101/spectool/data2spec.c000066400000000000000000000514631462133141200177410ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A tool to format the table in the specs * input: specdata.xml * output: spec.xml */ #include "data2spec_stdafx.h" #include "spec_element.h" #define WITH_V4 0 typedef struct table_extras { bool_t StartedGlobal; bool_t PassedEBML; bool_t IsLast; bool_t InTags; int CurrLevel; } table_extras; static void AddColumnHeader(textwriter *TBody) { textwriter Tr, Th, Abbr; TextElementBegin(&Tr, TBody, T("tr")); TextAttribEx(&Tr, T("class"), T("toptitle"), 0, TYPE_STRING); TextElementBegin(&Th, &Tr, T("th")); TextAttribEx(&Th, T("style"), T("white-space: nowrap"), 0, TYPE_STRING); TextElementEndData(&Th, T("Element Name")); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Level"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Level"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("L")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); TextAttribEx(&Th, T("style"), T("white-space: nowrap"), 0, TYPE_STRING); TextElementEndData(&Th, T("EBML ID")); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Mandatory"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Mandatory"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("Ma")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Multiple"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Multiple"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("Mu")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Range"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Range"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("Rng")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); TextElementEndData(&Th, T("Default")); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Element Type"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Element Type"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("T")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Version 1"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Version 1"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("1")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Version 2"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Version 2"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("2")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Version 3"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Version 3"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("3")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); #if defined(WITH_V4) TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("Version 4"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("Version 4"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("4")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); #endif TextElementBegin(&Th, &Tr, T("th")); Th.InsideContent = 1; TextAttribEx(&Th, T("title"), T("WebM"), 0, TYPE_STRING); TextElementBegin(&Abbr, &Th, T("abbr")); Abbr.InsideContent = 1; TextAttribEx(&Abbr, T("title"), T("WebM"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("W")); TextElementEnd(&Abbr); Th.InsideContent = 0; Th.Deep = 0; TextElementEnd(&Th); TextElementBegin(&Th, &Tr, T("th")); TextElementEndData(&Th, T("Description")); TextElementEnd(&Tr); } static void CleanHTML(tchar_t *Out, size_t OutLen) { if (Out[0]) tcsreplace(Out,OutLen,T("\n"),T(" ")); if (Out[0]) tcsreplace(Out,OutLen,T(" "),T(" ")); if (Out[0]) tcsreplace(Out,OutLen,T(" "),T(" ")); if (Out[0]) tcsreplace(Out,OutLen,T(" "),T(" ")); if (Out[0]) tcsreplace(Out,OutLen,T(" "),T(" ")); if (Out[0]) tcsreplace(Out,OutLen,T("
    "),T("
    ")); // Drupal doesn't like
    if (Out[0]) tcsreplace(Out,OutLen,T("& "),T("& ")); if (Out[0]) tcsreplace(Out,OutLen,T("\""),T(""")); if (Out[0]) tcsreplace(Out,OutLen,T(">"),T(">")); if (Out[0]) tcsreplace(Out,OutLen,T("<"),T("<")); } static void OutputElement(SpecElement *elt, textwriter *TBody, table_extras *Extras) { if (elt->Type != EBML_unknown && elt->Name[0]) { tchar_t IdString[32]; textwriter Tr, Td, Abbr; if (elt->Level==0/*!Extras->HadColumnHeader*/) { //Extras->HadColumnHeader = 1; AddColumnHeader(TBody); } if (elt->Level==-1 && !Extras->StartedGlobal) { Extras->StartedGlobal = 1; TextElementBegin(&Tr, TBody, T("tr")); TextElementBegin(&Td, &Tr, T("th")); #if defined(WITH_V4) TextAttribEx(&Td, T("colspan"), T("14"), 0, TYPE_STRING); #else TextAttribEx(&Td, T("colspan"), T("13"), 0, TYPE_STRING); #endif TextElementAppendData(&Td, T("Global elements (used everywhere in the format)")); TextElementEnd(&Td); TextElementEnd(&Tr); } if (elt->Level>=0 && Extras->StartedGlobal) { Extras->StartedGlobal = 0; } if (elt->Level==0 || (elt->Level==1 && Extras->PassedEBML)) { Extras->InTags = 0; TextElementBegin(&Tr, TBody, T("tr")); TextElementBegin(&Td, &Tr, T("th")); #if defined(WITH_V4) TextAttribEx(&Td, T("colspan"), T("14"), 0, TYPE_STRING); #else TextAttribEx(&Td, T("colspan"), T("13"), 0, TYPE_STRING); #endif if (elt->Id == 0x1A45DFA3) { TextAttribEx(&Td, T("id"), T("LevelEBML"), 0, TYPE_STRING); TextElementAppendData(&Td, T("EBML Header")); } else if (elt->Id == 0x18538067) { TextAttribEx(&Td, T("id"), T("LevelSegment"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Segment")); } else if (elt->Id == 0x114D9B74) { TextAttribEx(&Td, T("id"), T("MetaSeekInformation"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Meta Seek Information")); } else if (elt->Id == 0x1549A966) { TextAttribEx(&Td, T("id"), T("SegmentInformation"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Segment Information")); } else if (elt->Id == 0x1F43B675) { TextAttribEx(&Td, T("id"), T("LevelCluster"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Cluster")); } else if (elt->Id == 0x1654AE6B) { TextAttribEx(&Td, T("id"), T("LevelTrack"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Track")); } else if (elt->Id == 0x1C53BB6B) { TextAttribEx(&Td, T("id"), T("CueingData"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Cueing Data")); } else if (elt->Id == 0x1941A469) { TextAttribEx(&Td, T("id"), T("Attachment"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Attachment")); } else if (elt->Id == 0x1254C367) { Extras->InTags = 1; TextAttribEx(&Td, T("id"), T("Tagging"), 0, TYPE_STRING); TextElementAppendData(&Td, T("Tagging")); } TextElementEnd(&Td); TextElementEnd(&Tr); } Extras->CurrLevel = elt->Level; if (elt->Id == 0x18538067) Extras->PassedEBML = 1; TextElementBegin(&Tr, TBody, T("tr")); #if 0 if (Extras->InTags && tcsstr(elt->Name,T("UID"))) { stprintf_s(IdString,TSIZEOF(IdString), T("T%s"),elt->Name); TextAttribEx(&Tr, T("id"), IdString, 0, TYPE_STRING); } else #endif TextAttribEx(&Tr, T("id"), elt->Name, 0, TYPE_STRING); if (elt->MaxVersion || (!elt->MinVersion && !elt->InWebM)) stprintf_s(IdString,TSIZEOF(IdString),T("version2")); else if (elt->Level < 0) stprintf_s(IdString,TSIZEOF(IdString),T("level1")); else stprintf_s(IdString,TSIZEOF(IdString),T("level%d"), elt->Level); TextAttribEx(&Tr, T("class"), IdString, 0, TYPE_STRING); TextElementBegin(&Td, &Tr, T("td")); TextElementEndData(&Td, elt->Name); TextElementBegin(&Td, &Tr, T("td")); if (elt->Level < 0) stprintf_s(IdString,TSIZEOF(IdString),T("g")); else stprintf_s(IdString,TSIZEOF(IdString),T("%d%s"), elt->Level, elt->Recursive?T("+"):T("")); TextElementEndData(&Td, IdString); TextElementBegin(&Td, &Tr, T("td")); if (elt->Level==0) TextAttribEx(&Td, T("style"), T("white-space: nowrap"), 0, TYPE_STRING); if (elt->Id > 0x00FFFFFF) stprintf_s(IdString,TSIZEOF(IdString),T("[%02X][%02X][%02X][%02X]"),((elt->Id)>>24)&0xFF,((elt->Id)>>16)&0xFF,((elt->Id)>>8)&0xFF,elt->Id&0xFF); else if (elt->Id > 0x0000FFFF) stprintf_s(IdString,TSIZEOF(IdString),T("[%02X][%02X][%02X]"),((elt->Id)>>16)&0xFF,((elt->Id)>>8)&0xFF,elt->Id&0xFF); else if (elt->Id > 0x000000FF) stprintf_s(IdString,TSIZEOF(IdString),T("[%02X][%02X]"),((elt->Id)>>8)&0xFF,elt->Id&0xFF); else stprintf_s(IdString,TSIZEOF(IdString),T("[%02X]"),elt->Id&0xFF); TextElementEndData(&Td, IdString); TextElementBegin(&Td, &Tr, T("td")); if (elt->Mandatory) TextElementEndData(&Td, T("*")); else { TextAttribEx(&Tr, T("class"), T("unset"), 0, TYPE_STRING); TextElementEndData(&Td, T("-")); } TextElementBegin(&Td, &Tr, T("td")); if (elt->Multiple) TextElementEndData(&Td, T("*")); else { TextAttribEx(&Tr, T("class"), T("unset"), 0, TYPE_STRING); TextElementEndData(&Td, T("-")); } TextElementBegin(&Td, &Tr, T("td")); if (elt->Range[0]) { CleanHTML(elt->Range, TSIZEOF(elt->Range)); TextElementEndData(&Td, elt->Range); } else { TextAttribEx(&Tr, T("class"), T("unset"), 0, TYPE_STRING); TextElementEndData(&Td, T("-")); } TextElementBegin(&Td, &Tr, T("td")); if (elt->DefaultValue[0]) { CleanHTML(elt->DefaultValue, TSIZEOF(elt->DefaultValue)); TextElementEndData(&Td, elt->DefaultValue); } else { TextAttribEx(&Tr, T("class"), T("unset"), 0, TYPE_STRING); TextElementEndData(&Td, T("-")); } TextElementBegin(&Td, &Tr, T("td")); Td.InsideContent = 1; TextElementBegin(&Abbr, &Td, T("abbr")); Abbr.InsideContent = 1; switch (elt->Type) { case EBML_MASTER: TextAttribEx(&Abbr, T("title"), T("Master Elements"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("m")); break; case EBML_INTEGER: TextAttribEx(&Abbr, T("title"), T("Signed Integer"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("i")); break; case EBML_UNSIGNED_INTEGER: TextAttribEx(&Abbr, T("title"), T("Unsigned Integer"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("u")); break; case EBML_DATE: TextAttribEx(&Abbr, T("title"), T("Date"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("d")); break; case EBML_FLOAT: TextAttribEx(&Abbr, T("title"), T("Float"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("f")); break; case EBML_STRING: TextAttribEx(&Abbr, T("title"), T("String"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("s")); break; case EBML_UNICODE_STRING: TextAttribEx(&Abbr, T("title"), T("UTF-8"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("8")); break; case EBML_BINARY: TextAttribEx(&Abbr, T("title"), T("Binary"), 0, TYPE_STRING); TextElementAppendData(&Abbr, T("b")); break; } TextElementEnd(&Abbr); Td.InsideContent = 0; Td.Deep = 0; TextElementEnd(&Td); // v1 TextElementBegin(&Td, &Tr, T("td")); if (!elt->MinVersion && !elt->MaxVersion && !elt->InWebM) { TextElementEnd(&Td); } else if (!elt->MinVersion || elt->MinVersion > 1) { TextAttribEx(&Tr, T("class"), T("flagnot"), 0, TYPE_STRING); TextElementEnd(&Td); } else TextElementEndData(&Td, T("*")); // v2 TextElementBegin(&Td, &Tr, T("td")); if (!elt->MinVersion && !elt->MaxVersion && !elt->InWebM) { TextElementEnd(&Td); } else if (!elt->MinVersion || elt->MinVersion > 2 || (elt->MaxVersion && elt->MaxVersion < 2)) { TextAttribEx(&Tr, T("class"), T("flagnot"), 0, TYPE_STRING); TextElementEnd(&Td); } else TextElementEndData(&Td, T("*")); // v3 TextElementBegin(&Td, &Tr, T("td")); if (!elt->MinVersion && !elt->MaxVersion && !elt->InWebM) { TextElementEnd(&Td); } else if (!elt->MinVersion || elt->MinVersion > 3 || (elt->MaxVersion && elt->MaxVersion < 3)) { TextAttribEx(&Tr, T("class"), T("flagnot"), 0, TYPE_STRING); TextElementEnd(&Td); } else TextElementEndData(&Td, T("*")); #if defined(WITH_V4) // v4 TextElementBegin(&Td, &Tr, T("td")); if (!elt->MinVersion && !elt->MaxVersion && !elt->InWebM) { TextElementEnd(&Td); } else if (!elt->MinVersion || elt->MinVersion > 4 || (elt->MaxVersion && elt->MaxVersion < 4)) { TextAttribEx(&Tr, T("class"), T("flagnot"), 0, TYPE_STRING); TextElementEnd(&Td); } else TextElementEndData(&Td, T("*")); #endif // webm TextElementBegin(&Td, &Tr, T("td")); if (!elt->MinVersion && !elt->MaxVersion && !elt->InWebM) { TextElementEnd(&Td); } else if (!elt->InWebM) { TextAttribEx(&Tr, T("class"), T("flagnot"), 0, TYPE_STRING); TextElementEnd(&Td); } else TextElementEndData(&Td, T("*")); TextElementBegin(&Td, &Tr, T("td")); if (elt->Description[0]) tcsreplace(elt->Description,TSIZEOF(elt->Description),T("& "),T("& ")); if (elt->Description[0]) tcsreplace(elt->Description,TSIZEOF(elt->Description),T("
    "),T("
    \n")); // Drupal doesn't like
    if (elt->Description[0]) tcsreplace(elt->Description,TSIZEOF(elt->Description),T("http://www.matroska.org/technical/specs/"),T("")); TextElementEndData(&Td, elt->Description); TextElementEnd(&Tr); if (Extras->IsLast) AddColumnHeader(TBody); } } static void ReadLevel(parser *p, array *Elements) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { if (tcsisame_ascii(Element,T("element"))) { SpecElement *Dumper = (SpecElement*)NodeCreate(p->Context, SPEC_ELEMENT_CLASS); ReadSpecElement(Dumper, p); ArrayAppend(Elements, &Dumper, sizeof(Dumper), 128); } else { while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { if (tcsisame_ascii(String,T("id"))) tcsreplace(Value,TSIZEOF(Value),T(" "),T("_")); } } if (p->ElementEof) p->ElementEof = 0; else ReadLevel(p, Elements); } } else { ParserSkipAfter(p,'>'); break; } } } META_START(SpecElement_Class,SPEC_ELEMENT_CLASS) META_CLASS(SIZE,sizeof(SpecElement)) META_END(NODE_CLASS) int main(void) { parsercontext p; parser parseIn; stream *Input = NULL,*Output = NULL; array Elements; SpecElement **element; //tchar_t Element[MAXLINE], String[MAXLINE], Value[MAXLINE]; ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); Input = StreamOpen(&p,T("specdata.xml"),SFLAG_RDONLY/*|SFLAG_BUFFERED*/); Output = StreamOpen(&p,T("spec.xml"),SFLAG_WRONLY|SFLAG_CREATE); memset(&parseIn, 0, sizeof(parseIn)); ArrayInit(&Elements); if (ParserStreamXML(&parseIn, Input, &p, T("table"), 0)==ERR_NONE) { textwriter Table, TBody; table_extras Extras; memset(&Extras,0,sizeof(Extras)); memset(&Table,0,sizeof(Table)); memset(&TBody,0,sizeof(TBody)); Extras.CurrLevel = -1; ReadLevel(&parseIn, &Elements); Table.Stream = Output; TextElementXML(&p, &Table, T("table")); TextElementBegin(&TBody, &Table, T("tbody")); TBody.SafeFormat = 1; for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) { if ((element+1) == ARRAYEND(Elements,SpecElement*)) Extras.IsLast = 1; OutputElement(*element, &TBody, &Extras); } TextElementEnd(&TBody); TextElementEnd(&Table); } for (element=ARRAYBEGIN(Elements,SpecElement*); element!=ARRAYEND(Elements,SpecElement*);++element) NodeDelete((node*)*element); ArrayClear(&Elements); StreamClose(Input); StreamClose(Output); StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return 0; } bcmatroska2-5.3.101/spectool/default_config.h000066400000000000000000000004521462133141200210410ustar00rootroot00000000000000#define COREMAKE_STATIC #define COREMAKE_UNICODE #define CONFIG_EBML_WRITING #undef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #define USE_PRECOMPILED_HEADERS #define CONFIG_DEBUGCHECKS #define CONFIG_STDIO #define CONFIG_FILEPOS_64 #define COREMAKE_CONFIG_HELPER //#define CONFIG_DEBUG_LEAKS bcmatroska2-5.3.101/spectool/spec2data.c000066400000000000000000000271441462133141200177400ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spec2data_stdafx.h" #include "spec_element.h" static void SkipLevel(parser *p) { // TODO: move this in parser2.c when it's stable ParserElementSkipNested(p); ParserSkipAfter(p,'>'); } static void FillSpecElement(SpecElement *elt, parser *p) { tchar_t Element[MAXDATA], /*String[MAXDATA], */Value[MAXLINE]; int EltCount = 0; bool_t hasV1 = 0, hasV2 = 0; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\n"),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("
    "),T("
    ")); // Drupal doesn't like
    if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("& "),T("& ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\""),T(""")); } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { if (elt==NULL || tcsisame_ascii(Element,T("th"))) { SkipLevel(p); elt = NULL; // we don't fill any element as it's not a correct one } else { if (tcsisame_ascii(Element,T("td"))) { intptr_t id0,id1,id2,id3; const tchar_t *s = Value; ParserElementSkip(p); // we don't care about the td attributes ReadElementText(p, Value, TSIZEOF(Value)); switch (EltCount++) { case 0: tcscpy_s(elt->Name, TSIZEOF(elt->Name), Value); break; case 1: if (tcsisame_ascii(Value,T("global")) || tcsisame_ascii(Value,T("g"))) { elt->Level = -1; } else { ExprIsInt(&s,&id0); elt->Level = id0; if (s[0]=='+') elt->Recursive = 1; } break; case 2: if (ExprIsTokenEx(&s,T("[%x][%x][%x][%x]"),&id0,&id1,&id2,&id3)) elt->Id = FOURCCBE(id0, id1, id2, id3); else if (ExprIsTokenEx(&s,T("[%x][%x][%x]"),&id0,&id1,&id2)) elt->Id = FOURCCBE(0, id0, id1, id2); else if (ExprIsTokenEx(&s,T("[%x][%x]"),&id0,&id1)) elt->Id = FOURCCBE(0, 0, id0, id1); else if (ExprIsTokenEx(&s,T("[%x]"),&id0)) elt->Id = FOURCCBE(0, 0, 0, id0); else elt->Id = 0; break; case 3: elt->Mandatory = tcschr(Value,'*')!=NULL; break; case 4: elt->Multiple = tcschr(Value,'*')!=NULL; break; case 5: tcscpy_s(elt->Range, TSIZEOF(elt->Range), Value); break; case 6: tcscpy_s(elt->DefaultValue, TSIZEOF(elt->DefaultValue), Value); break; case 7: // handle s = tcschr(Value,'>'); if (s==NULL) s = Value; else ++s; switch (s[0]) { case 'm': elt->Type = EBML_MASTER; break; case 'u': elt->Type = EBML_UNSIGNED_INTEGER; break; case 'i': elt->Type = EBML_INTEGER; break; case 'd': elt->Type = EBML_DATE; break; case 's': elt->Type = EBML_STRING; break; case 'b': elt->Type = EBML_BINARY; break; case '8': elt->Type = EBML_UNICODE_STRING; break; case 'f': elt->Type = EBML_FLOAT; break; default: elt->Type = EBML_unknown; break; } break; case 8: hasV1 = tcschr(Value,'*')!=NULL; break; case 9: hasV2 = tcschr(Value,'*')!=NULL; break; case 10: elt->InWebM = tcschr(Value,'*')!=NULL; break; case 11: tcscpy_s(elt->Description, TSIZEOF(elt->Description), Value); break; } } else SkipLevel(p); } } else { ParserSkipAfter(p,'>'); break; } } if (elt!=NULL) { elt->MinVersion = hasV1 ? 1 : (hasV2 ? 2 : 0); elt->MaxVersion = hasV2 ? 2 : (hasV1 ? 1 : 0); } } static const tchar_t *GetTypeString(ebml_type Type) { switch (Type) { case EBML_MASTER: return T("master"); case EBML_INTEGER: return T("integer"); case EBML_UNSIGNED_INTEGER: return T("uinteger"); case EBML_DATE: return T("date"); case EBML_FLOAT: return T("float"); case EBML_STRING: return T("string"); case EBML_BINARY: return T("binary"); case EBML_UNICODE_STRING: return T("utf-8"); default: return NULL; } } static void OutputElement(SpecElement *elt, textwriter *parent) { if (elt->Type != EBML_unknown && elt->Name[0]) { tchar_t IdString[16]; textwriter child; TextElementBegin(&child, parent, T("element")); TextAttribEx(&child, T("name"), elt->Name, 0, TYPE_STRING); TextAttribEx(&child, T("level"), &elt->Level, sizeof(elt->Level), TYPE_INT); if (elt->Recursive) TextAttribEx(&child, T("recursive"), &elt->Recursive, sizeof(elt->Recursive), TYPE_BOOLEAN); stprintf_s(IdString,TSIZEOF(IdString), T("0x%X"),elt->Id); TextAttribEx(&child, T("id"), IdString, 0, TYPE_STRING); TextAttribEx(&child, T("type"), GetTypeString(elt->Type), 0, TYPE_STRING); if (elt->Mandatory) TextAttribEx(&child, T("mandatory"), &elt->Mandatory, sizeof(elt->Mandatory), TYPE_BOOLEAN); if (elt->Multiple) TextAttribEx(&child, T("multiple"), &elt->Multiple, sizeof(elt->Multiple), TYPE_BOOLEAN); if (elt->MinVersion) TextAttribEx(&child, T("minver"), &elt->MinVersion, sizeof(elt->MinVersion), TYPE_INT); if (elt->MaxVersion) TextAttribEx(&child, T("maxver"), &elt->MaxVersion, sizeof(elt->MaxVersion), TYPE_INT); TextAttribEx(&child, T("webm"), &elt->InWebM, sizeof(elt->InWebM), TYPE_BOOLEAN); if (elt->DefaultValue[0] && elt->DefaultValue[0]!='-') TextAttribEx(&child, T("default"), elt->DefaultValue, 0, TYPE_STRING); if (elt->Range[0] && elt->Range[0]!='-') TextAttribEx(&child, T("range"), elt->Range, 0, TYPE_STRING); tcsreplace(elt->Description, TSIZEOF(elt->Description), T("& "), T("& ")); TextElementAppendData(&child, elt->Description); TextElementEnd(&child); } } static void ReadLevel(parser *p, textwriter *current) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; bool_t isSpecData; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\n"),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("
    "),T("
    ")); // Drupal doesn't like
    if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\""),T(""")); if (Value[0]) TextElementAppendData(current,Value); } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { isSpecData = tcsisame_ascii(Element,T("tr")); if (isSpecData) { SpecElement *Dumper = (SpecElement*)NodeCreate(p->Context, SPEC_ELEMENT_CLASS); ParserElementSkip(p); // we don't care about the tr attributes FillSpecElement(Dumper, p); OutputElement(Dumper, current); NodeDelete((node*)Dumper); } else { while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { if (tcsisame_ascii(String,T("id"))) tcsreplace(Value,TSIZEOF(Value),T(" "),T("_")); } } if (p->ElementEof) p->ElementEof = 0; else ReadLevel(p, current); } //TextElementEnd(&child); } else { ParserSkipAfter(p,'>'); break; } } } META_START(SpecElement_Class,SPEC_ELEMENT_CLASS) META_CLASS(SIZE,sizeof(SpecElement)) META_END(NODE_CLASS) /** * A tool to format the table in the specs * input: spec.xml * output: table_spec.xml */ int main(void) { parsercontext p; parser parseIn; stream *Input = NULL,*Output = NULL; //tchar_t Element[MAXLINE], String[MAXLINE], Value[MAXLINE]; ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); Input = StreamOpen(&p,T("spec.xml"),SFLAG_RDONLY/*|SFLAG_BUFFERED*/); Output = StreamOpen(&p,T("specdata.xml"),SFLAG_WRONLY|SFLAG_CREATE); memset(&parseIn, 0, sizeof(parseIn)); if (ParserStreamXML(&parseIn, Input, &p, T("table"), 0)==ERR_NONE) { textwriter outFile; memset(&outFile,0,sizeof(outFile)); outFile.Stream = Output; TextElementXML(&p, &outFile, T("table")); ReadLevel(&parseIn, &outFile); TextElementEnd(&outFile); // /table } StreamClose(Input); StreamClose(Output); StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return 0; } bcmatroska2-5.3.101/spectool/spec_element.c000066400000000000000000000157061462133141200205360ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spec_element.h" void ReadElementText(parser *p, tchar_t *Out, size_t OutLen) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; size_t len = 0; Out[0] = 0; for (;;) { if (ParserElementContent(p, Out+len, OutLen-len) && Out[len]) { if (Out[0]) tcsreplace(Out+len, OutLen-len, T("\n"),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T(" "),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T(" "),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T(" "),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T(" "),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T(" "),T(" ")); if (Out[0]) tcsreplace(Out+len, OutLen-len, T("""),T("\"")); ParserHTMLChars(p, Out+len, OutLen-len); len += tcslen(Out+len); } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { if (len) tcscat_s(Out+len, OutLen-len,T(" ")); stprintf_s(Out+len, OutLen-len, T("<%s"), Element); while (ParserIsAttrib(p, String, TSIZEOF(String))) if (ParserAttribString(p, Value, TSIZEOF(Value))) stcatprintf_s(Out+len, OutLen-len, T(" %s=\"%s\""), String, Value); if (p->ElementEof) { stcatprintf_s(Out+len, OutLen-len, T("/>")); p->ElementEof = 0; } else { stcatprintf_s(Out+len, OutLen-len, T(">")); len += tcslen(Out+len); ReadElementText(p, Out+len, OutLen-len); len += tcslen(Out+len); stprintf_s(Out+len, OutLen-len, T(""), Element); } len += tcslen(Out+len); } else { ParserSkipAfter(p,'>'); break; } } } void ReadSpecElement(SpecElement *elt, parser *p) { tchar_t String[MAXDATA], Value[MAXLINE]; elt->InDivX = -1; elt->InWebM = -1; while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { const tchar_t *s = Value; intptr_t intval; if (tcsisame_ascii(String,T("name"))) tcscpy_s(elt->Name, TSIZEOF(elt->Name), Value); else if (tcsisame_ascii(String,T("cppname"))) tcscpy_s(elt->CppName, TSIZEOF(elt->CppName), Value); else if (tcsisame_ascii(String,T("level"))) { ExprIsInt(&s,&intval); elt->Level = intval; } else if (tcsisame_ascii(String,T("recursive"))) { ExprIsInt(&s,&intval); elt->Recursive = intval!=0; } else if (tcsisame_ascii(String,T("id"))) { ExprIsHex(&s,&intval); elt->Id = intval; } else if (tcsisame_ascii(String,T("type"))) { if (tcsisame_ascii(Value,T("master"))) elt->Type = EBML_MASTER; else if (tcsisame_ascii(Value,T("integer"))) elt->Type = EBML_INTEGER; else if (tcsisame_ascii(Value,T("uinteger"))) elt->Type = EBML_UNSIGNED_INTEGER; else if (tcsisame_ascii(Value,T("date"))) elt->Type = EBML_DATE; else if (tcsisame_ascii(Value,T("float"))) elt->Type = EBML_FLOAT; else if (tcsisame_ascii(Value,T("string"))) elt->Type = EBML_STRING; else if (tcsisame_ascii(Value,T("utf-8"))) elt->Type = EBML_UNICODE_STRING; else if (tcsisame_ascii(Value,T("binary"))) elt->Type = EBML_BINARY; else elt->Type = EBML_unknown; } else if (tcsisame_ascii(String,T("mandatory"))) { ExprIsInt(&s,&intval); elt->Mandatory = intval!=0; } else if (tcsisame_ascii(String,T("multiple"))) { ExprIsInt(&s,&intval); elt->Multiple = intval!=0; } else if (tcsisame_ascii(String,T("default"))) tcscpy_s(elt->DefaultValue, TSIZEOF(elt->DefaultValue), Value); else if (tcsisame_ascii(String,T("range"))) tcscpy_s(elt->Range, TSIZEOF(elt->Range), Value); else if (tcsisame_ascii(String,T("minver"))) { ExprIsInt(&s,&intval); elt->MinVersion = intval; } else if (tcsisame_ascii(String,T("maxver"))) { ExprIsInt(&s,&intval); elt->MaxVersion = intval; } else if (tcsisame_ascii(String,T("bytesize"))) { ExprIsInt(&s,&intval); elt->ByteSize = intval; } else if (tcsisame_ascii(String,T("webm"))) { ExprIsInt(&s,&intval); elt->InWebM = intval!=0; } else if (tcsisame_ascii(String,T("divx"))) { ExprIsInt(&s,&intval); elt->InDivX = intval!=0; } } } if (elt->InDivX==-1) { if (elt->MinVersion==1) elt->InDivX = 1; else elt->InDivX=0; } if (elt->InWebM==-1) { if (elt->MinVersion==1) elt->InWebM = 1; else elt->InWebM=0; } ReadElementText(p, elt->Description, TSIZEOF(elt->Description)); } bcmatroska2-5.3.101/spectool/spec_element.h000066400000000000000000000047671462133141200205500ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEC_ELEMENT_H #define SPEC_ELEMENT_H #ifndef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #endif #include "parser/parser.h" #define SPEC_ELEMENT_CLASS FOURCC('S','P','E','C') typedef enum { EBML_unknown, EBML_MASTER, EBML_INTEGER, EBML_UNSIGNED_INTEGER, EBML_DATE, EBML_FLOAT, EBML_STRING, EBML_UNICODE_STRING, EBML_BINARY, } ebml_type; typedef struct SpecElement { node Base; tchar_t Name[MAXPATH]; tchar_t CppName[MAXPATH]; int Level; bool_t Recursive; int32_t Id; ebml_type Type; bool_t Mandatory; bool_t Multiple; tchar_t Range[MAXPATH]; tchar_t DefaultValue[32]; int MinVersion, MaxVersion; int ByteSize; bool_t InWebM; bool_t InDivX; tchar_t Description[MAXLINE]; } SpecElement; void ReadElementText(parser *p, tchar_t *Out, size_t OutLen); void ReadSpecElement(SpecElement *elt, parser *p); #endif /* SPEC_ELEMENT_H */ bcmatroska2-5.3.101/spectool/specdata.xml000066400000000000000000001477521462133141200202440ustar00rootroot00000000000000 Set the EBML characteristics of the data to follow. Each EBML document has to start with this.The version of EBML parser used to create the file.The minimum EBML version a parser has to support to read this file.The maximum length of the IDs you'll find in this file (4 or less in Matroska).The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid.A string that describes the type of document that follows this EBML header. 'matroska' in our case or 'webm' for webm files.The version of DocType interpreter used to create the file.The minimum DocType version an interpreter has to support to read this file.Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use.The CRC is computed on all the data of the Master element it's in. The CRC element should be the first in it's parent master for easier reading. All level 1 elements should include a CRC-32. The CRC in use is the IEEE CRC32 Little EndianContain signature of some (coming) elements in the stream.Signature algorithm used (1=RSA, 2=elliptic).Hash algorithm used (1=SHA1-160, 2=MD5).The public key to use with the algorithm (in the case of a PKI-based signature).The signature of the data (until a new.Contains elements that will be used to compute the signature.A list consists of a number of consecutive elements that represent one case where data is used in signature. Ex: Cluster|Block|BlockAdditional means that the BlockAdditional of all Blocks in all Clusters is used for encryption.An element ID whose data will be used to compute the signature.This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment.Contains the position of other level 1 elements.Contains a single seek entry to an EBML element.The binary ID corresponding to the element name.The position of the element in the segment in octets (0 = first level 1 element).Contains miscellaneous general information and statistics on the file.A randomly generated unique ID to identify the current segment between many others (128 bits).A filename corresponding to this segment.A unique ID to identify the previous chained segment (128 bits).An escaped filename corresponding to the previous segment.A unique ID to identify the next chained segment (128 bits).An escaped filename corresponding to the next segment.A randomly generated unique ID that all segments related to each other must use (128 bits).A tuple of corresponding ID used by chapter codecs to represent this segment.Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment.The chapter codec using this ID (0: Matroska Script, 1: DVD-menu).The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used.Timestamp scale in nanoseconds (1.000.000 means all timestamps in the segment are expressed in milliseconds).Duration of the segment (based on TimecodeScale).Date of the origin of timestamp (value 0), i.e. production date.General name of the segment.Muxing application or library ("libmatroska-0.4.3").Writing application ("mkvmerge-0.3.3").The lower level element containing the (monolithic) Block structure.Absolute timestamp of the cluster (based on TimecodeScale).The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use.One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster.The Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams.Size of the previous Cluster, in octets. Can be useful for backward playing.Similar to Block but without all the extra information, mostly used to reduced overhead when no extra feature is needed. (see SimpleBlock Structure)Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock.Block containing the actual data to be rendered and a timestamp relative to the Cluster Timecode. (see Block Structure)A Block with no data. It must be stored in the stream at the place the real Block should be in display order. (see Block Virtual)Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data.Contain the BlockAdditional and some parameters.An ID to identify the BlockAdditional level.Interpreted by the codec as it wishes (using the BlockAddID).The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track (but can be omitted as other default values). When not written and with no DefaultDuration, the value is assumed to be the difference between the timestamp of this Block and the timestamp of the next Block in "display" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks. When set to 0 that means the frame is not a keyframe.This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced.Timestamp of another frame used as a reference (ie: B or P frame). The timestamp is relative to the block it's attached to.Relative position of the data that should be in position of the virtual block.The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry.Duration in nanoseconds of the silent data added to the Block (padding at the end of the Block for positive value, at the beginning of the Block for negative value). The duration of DiscardPadding is not calculated in the duration of the TrackEntry and should be discarded during playback.Contains slices description.Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback.The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback.The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame).The ID of the BlockAdditional element (0 is the main Block).The (scaled) delay to apply to the element.The (scaled) duration to apply to the element.DivX trick track extenstionsDivX trick track extenstionsDivX trick track extenstionsSimilar to SimpleBlock but the data inside the Block are Transformed (encrypt and/or signed). (see EncryptedBlock Structure)A top-level block of information with many tracks described.Describes a track with all elements.The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number).A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file.A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control).Set if the track is usable. (1 bit)Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference. (1 bit)Set if that track MUST be active during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. (1 bit)Set if the track may contain blocks using lacing. (1 bit)The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used.The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed.Number of nanoseconds (not scaled via TimecodeScale) per frame ('frame' in the Matroska sense -- one element put into a (Simple)Block).The period in nanoseconds (not scaled by TimcodeScale) between two successive fields at the output of the decoding process (see the notes)DEPRECATED, DO NOT USE. The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs).A value to add to the Block's Timestamp. This can be used to adjust the playback offset of a track.The maximum value of BlockAddID. A value 0 means there is no BlockAdditions for this track.A human-readable track name.Specifies the language of the track in the Matroska languages form.An ID corresponding to the codec, see the codec page for more info.Private data only known to the codec.A human-readable string specifying the codec.The UID of an attachment that is used by this codec.A string describing the encoding setting used.A URL to find information about the codec used.A URL to download about the codec used.The codec can decode potentially damaged data (1 bit).Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc.CodecDelay is The codec-built-in delay in nanoseconds. This value must be subtracted from each block timestamp in order to get the actual timestamp. The value should be small so the muxing of tracks with the same actual timestamp are in the same Cluster.After a discontinuity, SeekPreRoll is the duration in nanoseconds of the data the decoder must decode before the decoded data is valid.The track identification for the given Chapter Codec.Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment.The chapter codec using this ID (0: Matroska Script, 1: DVD-menu).The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used.Video settings.Set if the video is interlaced. (1 bit)Stereo-3D video mode (0: mono, 1: side by side (left eye is first), 2: top-bottom (right eye is first), 3: top-bottom (left eye is first), 4: checkboard (right is first), 5: checkboard (left is first), 6: row interleaved (right is first), 7: row interleaved (left is first), 8: column interleaved (right is first), 9: column interleaved (left is first), 10: anaglyph (cyan/red), 11: side by side (right eye is first), 12: anaglyph (green/magenta), 13 both eyes laced in one Block (left eye is first), 14 both eyes laced in one Block (right eye is first)) . There are some more details on 3D support in the Specification Notes.Alpha Video Mode. Presence of this element indicates that the BlockAdditional element could contain Alpha data.DEPRECATED, DO NOT USE. Bogus StereoMode value used in old versions of libmatroska. (0: mono, 1: right eye, 2: left eye, 3: both eyes).Width of the encoded video frames in pixels.Height of the encoded video frames in pixels.The number of video pixels to remove at the bottom of the image (for HDTV content).The number of video pixels to remove at the top of the image.The number of video pixels to remove on the left of the image.The number of video pixels to remove on the right of the image.Width of the video frames to display. The default value is only valid when DisplayUnit is 0.Height of the video frames to display. The default value is only valid when DisplayUnit is 0.How DisplayWidth & DisplayHeight should be interpreted (0: pixels, 1: centimeters, 2: inches, 3: Display Aspect Ratio).Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed).Same value as in AVI (32 bits).Gamma Value.Number of frames per second. Informational only.Audio settings.Sampling frequency in Hz.Real output sampling frequency in Hz (used for SBR techniques).Numbers of channels in the track.Table of horizontal angles for each successive channel, see appendix.Bits per sample, mostly used for PCM.Operation that needs to be applied on tracks to create this virtual track. For more details look at the Specification Notes on the subject.Contains the list of all video plane tracks that need to be combined to create this 3D trackContains a video plane track that need to be combined to create this 3D trackThe trackUID number of the track representing the plane.The kind of plane this track corresponds to (0: left eye, 1: right eye, 2: background).Contains the list of all tracks whose Blocks need to be combined to create this virtual trackThe trackUID number of a track whose blocks are used to create this virtual track.DivX trick track extenstionsDivX trick track extenstionsDivX trick track extenstionsDivX trick track extenstionsDivX trick track extenstionsSettings for several content encoding mechanisms like compression or encryption.Settings for one content encoding like compression or encryption.Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment.A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values:
    1 - all frame contents,
    2 - the track's private data,
    4 - the next ContentEncoding (next ContentEncodingOrder. Either the data inside ContentCompression and/or ContentEncryption)
    A value describing what kind of transformation has been done. Possible values:
    0 - compression,
    1 - encryption
    Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking.The compression algorithm used. Algorithms that have been specified so far are:
    0 - zlib,
    1 - bzlib,
    2 - lzo1x
    3 - Header Stripping
    Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track.Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise.The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values:
    1 - DES, 2 - 3DES, 3 - Twofish, 4 - Blowfish, 5 - AES
    For public key algorithms this is the ID of the public key the the data was encrypted with.A cryptographic signature of the contents.This is the ID of the private key the data was signed with.The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values:
    1 - RSA
    The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values:
    1 - SHA1-160
    2 - MD5
    A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams.Contains all information relative to a seek point in the segment.Absolute timestamp according to the segment time base.Contain positions for different tracks corresponding to the timestamp.The track for which a position is given.The position of the Cluster containing the required Block.The relative position of the referenced block inside the cluster with 0 being the first possible position for an element inside that cluster.The duration of the block according to the segment time base. If missing the track's DefaultDuration does not apply and no duration information is available in terms of the cues.Number of the Block in the specified Cluster.The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry.The Clusters containing the required referenced Blocks.Timestamp of the referenced Block.The Position of the Cluster containing the referenced Block.Number of the referenced Block of Track X in the specified Cluster.The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry.Contain attached files.An attached file.A human-friendly name for the attached file.Filename of the attached file.MIME type of the file.The data of the file.Unique ID representing the file, as random as possible.A binary value that a track/codec can refer to when the attachment is needed.DivX font extensionDivX font extensionA system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation.Contains all information about a segment edition.A unique ID to identify the edition. It's useful for tagging an edition.If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)If a flag is set (1) the edition should be used as the default one. (1 bit)Specify if the chapters can be defined multiple times and the order to play them is enforced. (1 bit)Contains the atom information to use as the chapter atom (apply to all tracks).A unique ID to identify the Chapter.A unique string ID to identify the Chapter. Use for WebVTT cue identifier storage.Timestamp of the start of Chapter (not scaled).Timestamp of the end of Chapter (timestamp excluded, not scaled).If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter (see flag notes). (1 bit)A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used.The EditionUID to play from the segment linked in ChapterSegmentUID.Specify the physical equivalent of this ChapterAtom like "DVD" (60) or "SIDE" (50), see complete list of values.List of tracks on which the chapter applies. If this element is not present, all tracks applyUID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks.Contains all possible strings to use for the chapter display.Contains the string to use as the chapter atom.The languages corresponding to the string, in the bibliographic ISO-639-2 form.The countries corresponding to the string, same 2 octets as in Internet domains.Contains all the commands associated to the Atom.Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later.Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent.Contains all the commands associated to the Atom.Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter).Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands.Element containing elements specific to Tracks/Chapters. A list of valid tags can be found here.Element containing elements specific to Tracks/Chapters.Contain all UIDs where the specified meta data apply. It is empty to describe everything in the segment.A number to indicate the logical level of the target (see TargetType).An informational string that can be used to display the logical level of the target like "ALBUM", "TRACK", "MOVIE", "CHAPTER", etc (see TargetType).A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment.A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment.A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment.A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment.Contains general information about the target.The name of the Tag that is going to be stored.Specifies the language of the tag specified, in the Matroska languages form.Indication to know if this is the default/original language to use for the given tag. (1 bit)The value of the Tag.The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString.
    bcmatroska2-5.3.101/spectool/spectool.proj000066400000000000000000000012131462133141200204370ustar00rootroot00000000000000CON tabler { USE parser SOURCE tabler.c } CON spec2data { USE parser SOURCE spec2data.c {class SpecElement_Class} SOURCE spec_element.c HEADER spec_element.h } CON data2spec { USE parser SOURCE data2spec.c {class SpecElement_Class} SOURCE spec_element.c HEADER spec_element.h } CON data2lib { USE parser SOURCE data2lib.c {class SpecElement_Class} SOURCE spec_element.c HEADER spec_element.h } CON data2lib2 { USE parser SOURCE data2lib2.c {class SpecElement_Class} SOURCE spec_element.c HEADER spec_element.h } WORKSPACE spectool { USE tabler USE spec2data USE data2spec USE data2lib USE data2lib2 }bcmatroska2-5.3.101/spectool/tabler.c000066400000000000000000000114451462133141200173400ustar00rootroot00000000000000/* * $Id$ * Copyright (c) 2011, Matroska (non-profit organisation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Matroska assocation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * A tool to format the table in the specs * input: spec.xml * output: table_spec.xml */ #include "tabler_stdafx.h" #ifndef CONFIG_EBML_UNICODE #define CONFIG_EBML_UNICODE #endif #include "parser/parser.h" static void DumpLevel(parser *p, textwriter *parent) { tchar_t Element[MAXDATA], String[MAXDATA], Value[MAXLINE]; for (;;) { if (ParserElementContent(p,Value,TSIZEOF(Value)) && Value[0]) { if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\n"),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T(" "),T(" ")); if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("
    "),T("
    ")); // Drupal doesn't like
    if (Value[0]) tcsreplace(Value,TSIZEOF(Value),T("\""),T(""")); if (Value[0]) TextElementAppendData(parent,Value); } else if (ParserIsElementNested(p, Element, TSIZEOF(Element))) { textwriter child; TextElementBegin(&child, parent, Element); while (ParserIsAttrib(p, String, TSIZEOF(String))) { if (ParserAttribString(p, Value, TSIZEOF(Value))) { if (tcsisame_ascii(String,T("href")) && tcsstr(Value,T("http://www.matroska.org/technical/specs/"))==Value) { tchar_t *Val = Value+40; if (tcsstr(Val,T("index.html"))==Val) Val += 10; TextAttribEx(&child, String, Val, 0, TYPE_STRING); } else { if (tcsisame_ascii(String,T("id"))) tcsreplace(Value,TSIZEOF(Value),T(" "),T("_")); TextAttribEx(&child, String, Value, 0, TYPE_STRING); } } } if (p->ElementEof) p->ElementEof = 0; else DumpLevel(p, &child); TextElementEnd(&child); } else { ParserSkipAfter(p,'>'); break; } } } int main(void) { parsercontext p; parser parseIn; stream *Input = NULL,*Output = NULL; //tchar_t Element[MAXLINE], String[MAXLINE], Value[MAXLINE]; ParserContext_Init(&p,NULL,NULL,NULL); StdAfx_Init((nodemodule*)&p); Input = StreamOpen(&p,T("spec.xml"),SFLAG_RDONLY/*|SFLAG_BUFFERED*/); Output = StreamOpen(&p,T("table_spec.xml"),SFLAG_WRONLY|SFLAG_CREATE); memset(&parseIn, 0, sizeof(parseIn)); if (ParserStreamXML(&parseIn, Input, &p, T("table"), 0)==ERR_NONE) { textwriter outFile; memset(&outFile,0,sizeof(outFile)); outFile.Stream = Output; TextElementXML(&p, &outFile, T("table")); outFile.SafeFormat = 1; // Drupal doesn't like DumpLevel(&parseIn, &outFile); TextElementEnd(&outFile); // /table } StreamClose(Input); StreamClose(Output); StdAfx_Done((nodemodule*)&p); ParserContext_Done(&p); return 0; }